Skip to content

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

Agent Messages on desktop: the tab's ⇄, Show Agent Messages, pane marks; Swarm's views removed (#1161)

Dee16569f3d27e1
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index b568083b0..3065dc9a3 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -294,7 +294,15 @@ Experimental switches are account state. `AppNotifier.experimentalFeatures` bind
identifies the account, clears on sign-out/account change, and rejects stale responses. It uses
`/api/experimental-settings`, refreshes on account invalidations and a 30-second fallback poll, and
shows changes only after server acknowledgement. Do not restore the old unscoped local keys at startup.
-Swarm collaboration keeps its existing account settings RPC. The creature switch opens the account's
+Agent Messages (docs/design/2026-10-10-agent-messages.md) replaced Swarm collaboration: its
+flag is per tab, not an Experimental switch — `GET /api/agent-messages` and
+`PATCH /api/agent-messages/tabs/:tabId` through the CLI like the desk, read after sign-in, after a
+toggle, on `desk_changed`, the desk safety-net poll and the backend coming back; a 404 (an older CLI
+or backend) offers no ⇄ at all, and the ⇄ waits for the first answer (`agentMessagesOffered`, which
+also needs a desk tab). Traffic arrives as `messages_changed` — but a daemon sends that only to its
+own computer's windows, so `AgentMessagesRemoteWatch` reads the last messages of each tab that is on
+from its other machines every 15 s while the window is in front. A tab's log is the
+`agent_messages` `history` request to every daemon with a pane in it, merged by message id. The creature switch opens the account's
`ZooController` collection; disabling it hides the creature without deleting eggs, individuals or progress.
Window-only preview collections are test/render fixtures, not a user setting.
@@ -414,9 +422,13 @@ add a kind there, not at the call site.
repaint on a theme flip.
- The [workspace status bar](design/workspace-status-bar.md) places system-font tabs and global actions at the top,
with harness, machine and installed local model counts plus subscription allowance remaining at the bottom left and focused machine/repo/branch/PR at the bottom right.
- Tabs center their name/status group without permanent number prefixes; Command replaces
- the status with the resolved shortcut beside the name. Tab and pane close marks are small
- and quiet, with larger click targets. Terminal panes end with matching
+ Tabs center their name/status group without permanent number prefixes. One revealed state
+ — hovering a tab, or holding Command for every tab — replaces the status with the resolved
+ shortcut and shows Agent Messages' ⇄ just left of ×; at rest only a tab whose agents are
+ messaging keeps a bright ⇄ (`lib/agent_messages/`, `AgentMessagesController` on
+ `AppNotifier.agentMessages`, its own notifier so traffic never rebuilds the workspace;
+ `SwarmTabButton` mirrors it natively). Revealing never moves the title. Tab and pane close
+ marks are small and quiet, with larger click targets. Terminal panes end with matching
plain-text agent/model selectors and close at every width. Hovering the right
or bottom edge reveals its split icon; zoom stays in commands, menus and keyboard
shortcuts. Only distinct domain-harness icons stay on the left.
diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.md
index 7f97ef5b3..306195cd0 100644
--- a/desktop/design/workspace-status-bar.md
+++ b/desktop/design/workspace-status-bar.md
@@ -104,10 +104,26 @@ shared 10-point upper corners, 8-point outward lower shoulders and 6-point top
inset. Keep space after `+` available for dragging the window. Scroll overflow
and reveal the selected tab on keyboard navigation. Narrow viewports can show
smaller tabs while preserving their controls.
-The right accessory reveals × on hover. While Command is held, the actual
-shortcut replaces the status beside the name without changing the tab width.
-Hover never moves the title. Cmd-W, remapped shortcuts, native menu access,
-and middle-click closing remain available.
+A tab has one revealed state: hovering it reveals that tab, holding Command
+reveals every tab. Revealed, the actual shortcut replaces the status beside the
+name, and Agent Messages' ⇄ and × show at the right, ⇄ just left of ×
+([Agent Messages](../../docs/design/2026-10-10-agent-messages.md)). At rest a tab
+shows only its name and status, plus a bright ⇄ for about a minute after its
+agents last messaged each other while Agent Messages are on. The ⇄ is dim and
+struck through while off, dim while on and quiet; its tooltip says what a click
+does ("Agent messages off · click to turn on", "Agent messages on · click to
+turn off", "Agents messaging · click to turn off"), and a click toggles that
+tab's flag at once, going back — with a notice — if the backend refuses. Only a
+tab the desk holds has a ⇄ (not the Store, Devices, Companions, an orchestrator
+or a draft tab), and only once the daemon and backend have answered for Agent
+Messages; an older CLI or backend shows none. Revealing never changes the tab
+width or moves the title: an idle tab shows its shortcut after the name, and
+only a name that would run into ⇄ gives up its tail. × and ⇄ are 16-point-wide,
+32-point-tall targets with a 3-point dead gap between them, reserved on both
+sides of the centered name, so a 128-point tab still draws its name beside a
+status. The tab's menu and File carry Agent Messages (a checkmark)
+and Show Agent Messages beside Rename Tab and Close Tab. Cmd-W, remapped
+shortcuts, native menu access, and middle-click closing remain available.
Preserve reorder, rename, keyboard focus, and terminal sessions. Cmd-T opens a
tab. Cmd-O opens the shared picker with `#` for projects; Cmd-P opens it directly
on harnesses. Cmd-Shift-P opens commands (`>`). The projects list has
@@ -142,6 +158,12 @@ The mark replaces the native tab's old orange attention indicator; it adds no
new bar, counter, badge, or permanent legend. Hover and accessibility descriptions
explain each symbol.
+Right after the activity mark, a pane header briefly says Agent Messages traffic:
+`→ api` on the sender's pane and `← lead` on each recipient's, in quieter title
+ink, for about five seconds or until that pane is focused (`PaneMessageMarkView`,
+which listens to `AgentMessagesController` itself so the cached header never
+rebuilds). A sender the rate limit stopped shows `→ rate limited` in warning ink.
+
![Activity marks in existing tabs and pane headers, rendered with synthetic state at 640 px](images/workspace-activity.png)
| Mark | Meaning | Terminal color |
diff --git a/desktop/lib/agent_messages/agent_messages.dart b/desktop/lib/agent_messages/agent_messages.dart
new file mode 100644
index 000000000..dfd2d39ce
--- /dev/null
+++ b/desktop/lib/agent_messages/agent_messages.dart
@@ -0,0 +1,693 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+import 'package:flutter/foundation.dart';
+
+/// Agent Messages (docs/design/2026-10-10-agent-messages.md) as this window
+/// sees them: harnesses in a tab with Agent Messages on message each other with
+/// `harness send`, and the daemons deliver. The window only shows it — each
+/// tab's flag (the backend's, off unless a person turned it on), the traffic
+/// the daemons report as `messages_changed`, a tab's log, and the marks a
+/// message leaves on its panes. Nothing here composes or sends.
+
+/// What became of a message for one recipient. A message never expires: it
+/// stays queued until it is delivered, or fails for a reason a person can read.
+enum AgentMessageState {
+ queued,
+ delivered,
+ failed;
+
+ static AgentMessageState? parse(Object? value) => switch (value) {
+ 'queued' => queued,
+ 'delivered' => delivered,
+ 'failed' => failed,
+ _ => null,
+ };
+}
+
+/// One end of a message: a harness on a machine, named as its daemon named it.
+@immutable
+class AgentMessageParty {
+ const AgentMessageParty({
+ required this.machineId,
+ required this.agentId,
+ this.name = '',
+ });
+
+ final String machineId, agentId;
+
+ /// Empty when the frame carried no name (`messages_changed` names nobody).
+ final String name;
+
+ String get key => agentMessageKey(machineId, agentId);
+
+ static AgentMessageParty? fromJson(Object? json) {
+ if (json is! Map) return null;
+ final machineId = json['machineId'], agentId = json['agentId'];
+ if (machineId is! String || machineId.isEmpty) return null;
+ if (agentId is! String || agentId.isEmpty) return null;
+ final name = json['name'];
+ return AgentMessageParty(
+ machineId: machineId,
+ agentId: agentId,
+ name: name is String ? name : '',
+ );
+ }
+}
+
+String agentMessageKey(String machineId, String agentId) =>
+ '$machineId\u0000$agentId';
+
+@immutable
+class AgentMessageStatus {
+ const AgentMessageStatus({
+ required this.machineId,
+ required this.agentId,
+ required this.state,
+ required this.at,
+ this.via,
+ this.reason,
+ });
+
+ final String machineId, agentId;
+ final AgentMessageState state;
+
+ /// `hook` (at the agent's next tool call) or `prompt` (typed into an idle
+ /// agent); null until it is delivered.
+ final String? via;
+ final String? reason;
+ final int at;
+
+ String get key => agentMessageKey(machineId, agentId);
+
+ /// Whether this says more than [other] about the same recipient. Each daemon
+ /// knows its own side: the sender's may still say queued for a recipient
+ /// another machine's daemon has delivered to, so a final state wins over a
+ /// queued one, and between two of the same kind the later one does.
+ bool supersedes(AgentMessageStatus other) {
+ final mine = state == AgentMessageState.queued ? 0 : 1;
+ final theirs = other.state == AgentMessageState.queued ? 0 : 1;
+ return mine != theirs ? mine > theirs : at > other.at;
+ }
+
+ static AgentMessageStatus? fromJson(Object? json) {
+ if (json is! Map) return null;
+ final party = AgentMessageParty.fromJson(json);
+ final state = AgentMessageState.parse(json['state']);
+ if (party == null || state == null) return null;
+ final via = json['via'], reason = json['reason'], at = json['at'];
+ return AgentMessageStatus(
+ machineId: party.machineId,
+ agentId: party.agentId,
+ state: state,
+ via: via is String ? via : null,
+ reason: reason is String && reason.isNotEmpty ? reason : null,
+ at: at is num ? at.toInt() : 0,
+ );
+ }
+}
+
+/// One message in a tab's log, as a daemon's `history` answers it.
+@immutable
+class AgentMessage {
+ const AgentMessage({
+ required this.id,
+ required this.tabId,
+ required this.from,
+ required this.to,
+ required this.text,
+ required this.at,
+ this.statuses = const [],
+ });
+
+ final String id, tabId, text;
+ final AgentMessageParty from;
+ final List<AgentMessageParty> to;
+ final DateTime at;
+ final List<AgentMessageStatus> statuses;
+
+ /// What the log shows of the text: its first non-empty line.
+ String get firstLine =>
+ text
+ .split('\n')
+ .map((line) => line.trim())
+ .where((line) => line.isNotEmpty)
+ .firstOrNull ??
+ '';
+
+ AgentMessageStatus? statusOf(AgentMessageParty recipient) =>
+ statuses.where((s) => s.key == recipient.key).firstOrNull;
+
+ AgentMessageState stateOf(AgentMessageParty recipient) =>
+ statusOf(recipient)?.state ?? AgentMessageState.queued;
+
+ /// The same message as another daemon tells it: the union of what both
+ /// know about each recipient (see [AgentMessageStatus.supersedes]).
+ AgentMessage merge(AgentMessage other) {
+ final best = <String, AgentMessageStatus>{
+ for (final status in statuses) status.key: status,
+ };
+ for (final status in other.statuses) {
+ final known = best[status.key];
+ if (known == null || status.supersedes(known)) best[status.key] = status;
+ }
+ return AgentMessage(
+ id: id,
+ tabId: tabId,
+ from: from.name.isEmpty ? other.from : from,
+ to: to,
+ text: text,
+ at: at,
+ statuses: best.values.toList(growable: false),
+ );
+ }
+
+ static AgentMessage? fromJson(Object? json) {
+ if (json is! Map) return null;
+ final id = json['id'], tabId = json['tabId'], text = json['text'];
+ final at = json['at'];
+ final from = AgentMessageParty.fromJson(json['from']);
+ final to = [
+ for (final row in json['to'] is List ? json['to'] as List : const [])
+ ?AgentMessageParty.fromJson(row),
+ ];
+ if (id is! String || id.isEmpty || tabId is! String || text is! String) {
+ return null;
+ }
+ if (from == null || to.isEmpty || at is! num) return null;
+ return AgentMessage(
+ id: id,
+ tabId: tabId,
+ from: from,
+ to: to,
+ text: text,
+ at: DateTime.fromMillisecondsSinceEpoch(at.toInt()),
+ statuses: [
+ for (final row
+ in json['statuses'] is List ? json['statuses'] as List : const [])
+ ?AgentMessageStatus.fromJson(row),
+ ],
+ );
+ }
+}
+
+/// A tab's log, merged from every daemon that answered. [reached] is false
+/// when none did, which is not the same as an empty log; [complete] is false
+/// when a machine with a harness in the tab did not answer (offline, or gone
+/// from the tab), so its side of the log may be missing.
+typedef AgentMessageLog = ({
+ List<AgentMessage> messages,
+ bool reached,
+ bool complete,
+});
+
+/// A tab with Agent Messages on, and the machines to ask for its traffic.
+typedef AgentMessagesRemoteTab = ({String tabId, List<String> machineIds});
+
+/// The short note a message leaves in a pane's header: `→ api` on the
+/// sender's, `← lead` on each recipient's.
+@immutable
+class PaneMessageMark {
+ const PaneMessageMark({
+ required this.label,
+ this.tooltip,
+ this.warning = false,
+ });
+
+ final String label;
+ final String? tooltip;
+
+ /// The rate limit stopped this pane's harness: the one time Agent Messages
+ /// asks for the person's attention.
+ final bool warning;
+}
+
+/// How a tab's ⇄ reads.
+enum TabMessagesState { off, on, flowing }
+
+typedef AgentMessageTabsRead = Future<Map<String, dynamic>?> Function();
+typedef AgentMessagesWrite = Future<Map<String, dynamic>> Function(
+ String tabId,
+ bool enabled,
+);
+typedef AgentMessagesRequest = Future<Map<String, dynamic>> Function(
+ String machineId,
+ Map<String, dynamic> payload,
+);
+typedef AgentNameOf = String? Function(String machineId, String agentId);
+
+/// Each tab's flag, the traffic the daemons report, and the pane marks it
+/// leaves. Its own notifier, as `AgentAlerts` is: a message arriving must not
+/// rebuild the workspace, only the ⇄ and the marks that listen here.
+class AgentMessagesController extends ChangeNotifier {
+ AgentMessagesController({
+ required this.read,
+ required this.write,
+ required this.request,
+ required this.nameOf,
+ DateTime Function()? now,
+ this.flowingFor = const Duration(seconds: 60),
+ this.markLife = const Duration(seconds: 5),
+ }) : now = now ?? DateTime.now;
+
+ final AgentMessageTabsRead read;
+ final AgentMessagesWrite write;
+ final AgentMessagesRequest request;
+ final AgentNameOf nameOf;
+
+ /// Only to tell a message another machine's log holds from one that just
+ /// moved ([pollRemote]); lifetimes here run on timers.
+ final DateTime Function() now;
+
+ /// How long a tab's ⇄ stays bright after the last message moved in it.
+ final Duration flowingFor;
+
+ /// How long a pane's mark stays, unless the pane is focused first.
+ final Duration markLife;
+
+ final _enabled = <String, bool>{};
+ final _pending = <String, bool>{};
+ final _failed = <String, String>{};
+ final _writes = <String, int>{};
+ final _traffic = <String, int>{};
+ final _seenMessages = <String>{};
+ // What has a lifetime holds the timer that ends it — a tab's ⇄ dims, a
+ // mark goes — so nothing has to compare clocks to know it is over.
+ final _flowing = <String, Timer>{};
+ final _marks = <String, (PaneMessageMark, Timer)>{};
+ final _polling = <String>{};
+ int _reads = 0, _account = 0;
+ bool _disposed = false;
+
+ /// Whether the daemon and backend answered for this account's tabs. Until
+ /// they have — and for good, with an older CLI or backend that does not know
+ /// Agent Messages (404) — there is no ⇄ and no menu row: "off" would be a
+ /// guess, and a click could not take.
+ bool get loaded => _loaded;
+ bool _loaded = false;
+
+ /// On when the person turned it on; off when they did not, and whenever the
+ /// backend or daemon cannot say — an older one has no flag to read.
+ bool isOn(String tabId) => _pending[tabId] ?? _enabled[tabId] ?? false;
+
+ /// A turn on or off is on its way to the backend.
+ bool isPending(String tabId) => _pending.containsKey(tabId);
+
+ /// Messages moved in [tabId] within [flowingFor].
+ bool isFlowing(String tabId) => _flowing.containsKey(tabId);
+
+ TabMessagesState stateOf(String tabId) => !isOn(tabId)
+ ? TabMessagesState.off
+ : isFlowing(tabId)
+ ? TabMessagesState.flowing
+ : TabMessagesState.on;
+
+ /// Why the last turn on or off for [tabId] did not take.
+ String? failureFor(String tabId) => _failed[tabId];
+
+ /// Counts the `messages_changed` frames for [tabId], so an open log knows
+ /// when to read again.
+ int trafficFor(String tabId) => _traffic[tabId] ?? 0;
+
+ PaneMessageMark? markFor(String machineId, String agentId) =>
+ _marks[agentMessageKey(machineId, agentId)]?.$1;
+
+ void _notify() {
+ if (!_disposed) notifyListeners();
+ }
+
+ /// Read every tab's flag again. A failure keeps what was known: one dropped
+ /// request must not turn a tab's ⇄ off under the person. An answer of null
+ /// is a daemon or backend without Agent Messages.
+ Future<void> refresh() async {
+ if (_disposed) return;
+ final read = ++_reads, account = _account;
+ final writes = Map.of(_writes);
+ Map<String, dynamic>? answer;
+ try {
+ answer = await this.read();
+ } catch (_) {
+ return;
+ }
+ if (_disposed || account != _account || read != _reads) return;
+ if (answer == null) {
+ if (!_loaded && _enabled.isEmpty) return;
+ _loaded = false;
+ _enabled.clear();
+ _notify();
+ return;
+ }
+ final tabs = answer['tabs'];
+ final next = <String, bool>{
+ for (final tab in tabs is List ? tabs : const [])
+ if (tab is Map && tab['id'] is String)
+ tab['id'] as String: tab['enabled'] == true,
+ };
+ // A write that landed while this read was out is newer than its answer.
+ for (final MapEntry(:key, :value) in _writes.entries) {
+ if (writes[key] != value && _enabled.containsKey(key)) {
+ next[key] = _enabled[key]!;
+ }
+ }
+ _enabled
+ ..clear()
+ ..addAll(next);
+ _loaded = true;
+ _notify();
+ }
+
+ /// Turn Agent Messages on or off for [tabId]. Shown at once, put back if
+ /// the backend refuses or cannot be reached. Answers whether it took.
+ Future<bool> setEnabled(String tabId, bool enabled) async {
+ if (_disposed || _pending.containsKey(tabId)) return false;
+ final account = _account;
+ _pending[tabId] = enabled;
+ _failed.remove(tabId);
+ _notify();
+ var saved = false;
+ try {
+ final answer = await write(tabId, enabled);
+ if (_disposed || account != _account) return false;
+ final confirmed = answer['enabled'];
+ _enabled[tabId] = confirmed is bool ? confirmed : enabled;
+ saved = _enabled[tabId] == enabled;
+ } catch (_) {
+ if (_disposed || account != _account) return false;
+ }
+ _pending.remove(tabId);
+ _writes[tabId] = (_writes[tabId] ?? 0) + 1;
+ if (!saved) {
+ _failed[tabId] =
+ 'Agent Messages could not be turned ${enabled ? 'on' : 'off'}. '
+ 'Check that Harness is signed in and online, then try again.';
+ }
+ _notify();
+ unawaited(refresh());
+ return saved;
+ }
+
+ Future<bool> toggle(String tabId) => setEnabled(tabId, !isOn(tabId));
+
+ /// A `messages_changed` frame from a daemon: a message moved, or a sender
+ /// hit the rate limit.
+ void handleEvent(Map<String, dynamic> payload) {
+ if (_disposed) return;
+ final limited = AgentMessageParty.fromJson(payload['limited']);
+ if (limited != null) {
+ _mark(
+ limited.key,
+ const PaneMessageMark(
+ label: '→ rate limited',
+ tooltip:
+ 'Agent Messages: this harness sent too many messages. '
+ 'Harness refuses its next ones for a few minutes.',
+ warning: true,
+ ),
+ );
+ _notify();
+ return;
+ }
+ final tabId = payload['tabId'];
+ if (tabId is! String || tabId.isEmpty) return;
+ _flow(tabId);
+ final id = payload['messageId'];
+ // Each status change says the message again; it marks its panes once.
+ if (id is String && _remember(id)) {
+ final from = AgentMessageParty.fromJson(payload['from']);
+ final to = [
+ for (final row
+ in payload['to'] is List ? payload['to'] as List : const [])
+ ?AgentMessageParty.fromJson(row),
+ ];
+ if (from != null) _markPanes(from, to);
+ }
+ _notify();
+ }
+
+ /// [tabId]'s ⇄ is bright for [flowingFor] from now, and an open log reads
+ /// again.
+ void _flow(String tabId) {
+ _flowing.remove(tabId)?.cancel();
+ _flowing[tabId] = Timer(flowingFor, () {
+ _flowing.remove(tabId);
+ _notify();
+ });
+ _traffic[tabId] = trafficFor(tabId) + 1;
+ }
+
+ /// Whether [messageId] is new to this window; remembered either way.
+ bool _remember(String messageId) {
+ if (!_seenMessages.add(messageId)) return false;
+ while (_seenMessages.length > 500) {
+ _seenMessages.remove(_seenMessages.first);
+ }
+ return true;
+ }
+
+ /// Ask [tabs]' machines for what they hold: a daemon tells `messages_changed`
+ /// only to the windows on its own computer (the core's `clients.windows`), so
+ /// traffic between harnesses on other machines would never reach this one.
+ /// A message new to this window that moved within [flowingFor] counts as
+ /// traffic, exactly as if its frame had arrived. One request at a time per
+ /// machine; a machine still answering the last round is skipped.
+ Future<void> pollRemote(Iterable<AgentMessagesRemoteTab> tabs) async {
+ if (_disposed) return;
+ final byMachine = <String, List<String>>{};
+ for (final tab in tabs) {
+ for (final machineId in tab.machineIds) {
+ byMachine.putIfAbsent(machineId, () => []).add(tab.tabId);
+ }
+ }
+ await Future.wait([
+ for (final MapEntry(key: machineId, value: tabIds) in byMachine.entries)
+ if (!_polling.contains(machineId)) _poll(machineId, tabIds),
+ ]);
+ }
+
+ Future<void> _poll(String machineId, List<String> tabIds) async {
+ final account = _account;
+ _polling.add(machineId);
+ try {
+ for (final tabId in tabIds) {
+ // The newest few are enough to see what moved since the last round.
+ final messages = await _historyFrom(machineId, tabId, limit: 20);
+ if (_disposed || account != _account) return;
+ if (messages == null) continue;
+ var moved = false;
+ for (final message in messages) {
+ if (!_remember(message.id)) continue;
+ if (now().difference(message.at) >= flowingFor) continue;
+ moved = true;
+ _markPanes(message.from, message.to);
+ }
+ if (moved) {
+ _flow(tabId);
+ _notify();
+ }
+ }
+ } finally {
+ _polling.remove(machineId);
+ }
+ }
+
+ void _mark(String key, PaneMessageMark mark) {
+ _marks.remove(key)?.$2.cancel();
+ _marks[key] = (
+ mark,
+ Timer(markLife, () {
+ _marks.remove(key);
+ _notify();
+ }),
+ );
+ }
+
+ void _markPanes(AgentMessageParty from, List<AgentMessageParty> to) {
+ if (to.isEmpty) return;
+ final names = [for (final r in to) _name(r)];
+ _mark(
+ from.key,
+ PaneMessageMark(
+ label: '→ ${names.join(', ')}',
+ tooltip: 'Sent an agent message to ${names.join(', ')}',
+ ),
+ );
+ final sender = _name(from);
+ for (final recipient in to) {
+ _mark(
+ recipient.key,
+ PaneMessageMark(
+ label: '← $sender',
+ tooltip: 'Agent message from $sender',
+ ),
+ );
+ }
+ }
+
+ /// The name the window shows for [party]: the app's agent list, then the
+ /// daemon's, then the start of its id.
+ String _name(AgentMessageParty party) {
+ final known = nameOf(party.machineId, party.agentId);
+ if (known != null && known.trim().isNotEmpty) return known.trim();
+ if (party.name.isNotEmpty) return party.name;
+ return party.agentId.substring(0, math.min(8, party.agentId.length));
+ }
+
+ String nameOfParty(AgentMessageParty party) => _name(party);
+
+ /// The person looked at this pane: its mark has done its job.
+ void seen(String machineId, String agentId) {
+ final mark = _marks.remove(agentMessageKey(machineId, agentId));
+ if (mark == null) return;
+ mark.$2.cancel();
+ _notify();
+ }
+
+ void _stopTimers() {
+ for (final timer in _flowing.values) {
+ timer.cancel();
+ }
+ for (final (_, timer) in _marks.values) {
+ timer.cancel();
+ }
+ _flowing.clear();
+ _marks.clear();
+ }
+
+ /// [tabId]'s log from [machineIds]' daemons, merged by message id, oldest
+ /// first. Each daemon holds what it sent and what it delivered, so one
+ /// alone can be missing half of a tab that spans machines; the log is
+ /// complete only when every one of [expected] answered.
+ Future<AgentMessageLog> history(
+ String tabId,
+ Iterable<String> machineIds, {
+ Iterable<String> expected = const [],
+ }) async {
+ final asked = machineIds.toSet().toList();
+ final answers = await Future.wait([
+ for (final machineId in asked) _historyFrom(machineId, tabId),
+ ]);
+ final answered = {
+ for (var i = 0; i < asked.length; i++)
+ if (answers[i] != null) asked[i],
+ };
+ final merged = <String, AgentMessage>{};
+ for (final message in answers.nonNulls.expand((list) => list)) {
+ merged.update(
+ message.id,
+ (known) => known.merge(message),
+ ifAbsent: () => message,
+ );
+ }
+ final messages = merged.values.toList()
+ ..sort((a, b) {
+ final byTime = a.at.compareTo(b.at);
+ return byTime != 0 ? byTime : a.id.compareTo(b.id);
+ });
+ return (
+ messages: messages,
+ reached: answered.isNotEmpty,
+ complete: answered.containsAll(expected),
+ );
+ }
+
+ Future<List<AgentMessage>?> _historyFrom(
+ String machineId,
+ String tabId, {
+ int? limit,
+ }) async {
+ try {
+ final reply = await request(machineId, {
+ 'action': 'history',
+ 'tabId': tabId,
+ 'limit': ?limit,
+ });
+ final rows = reply['messages'];
+ if (reply['error'] != null || rows is! List) return null;
+ return [
+ for (final row in rows)
+ if (AgentMessage.fromJson(row) case final message?
+ when message.tabId == tabId)
+ message,
+ ];
+ } catch (_) {
+ // Offline, or a daemon that predates Agent Messages and goes silent.
+ return null;
+ }
+ }
+
+ /// Sign-out or another account: nothing of this one's stays.
+ void reset() {
+ _account++;
+ _reads++;
+ _enabled.clear();
+ _pending.clear();
+ _failed.clear();
+ _writes.clear();
+ _traffic.clear();
+ _seenMessages.clear();
+ _polling.clear();
+ _stopTimers();
+ _loaded = false;
+ _notify();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _stopTimers();
+ super.dispose();
+ }
+}
+
+/// Asks other machines for their traffic ([AgentMessagesController.pollRemote])
+/// every [every] while the window is in front, and once as soon as it comes
+/// back. A hidden or minimised window asks nothing.
+class AgentMessagesRemoteWatch {
+ AgentMessagesRemoteWatch({
+ required this.controller,
+ required this.foreground,
+ required this.tabs,
+ this.every = const Duration(seconds: 15),
+ });
+
+ final AgentMessagesController controller;
+ final ValueListenable<bool> foreground;
+
+ /// The tabs to ask about now: on, with a harness on another machine.
+ final List<AgentMessagesRemoteTab> Function() tabs;
+ final Duration every;
+ Timer? _timer;
+ bool _started = false, _disposed = false;
+
+ void start() {
+ if (_started || _disposed) return;
+ _started = true;
+ foreground.addListener(_foregroundChanged);
+ _foregroundChanged();
+ }
+
+ void _foregroundChanged() {
+ _timer?.cancel();
+ _timer = null;
+ if (foreground.value) unawaited(poll());
+ }
+
+ @visibleForTesting
+ Future<void> poll() async {
+ _timer?.cancel();
+ _timer = null;
+ if (_disposed || !foreground.value) return;
+ final targets = tabs();
+ if (targets.isNotEmpty) await controller.pollRemote(targets);
+ if (!_disposed && _started && foreground.value && _timer == null) {
+ _timer = Timer(every, () => unawaited(poll()));
+ }
+ }
+
+ void dispose() {
+ _disposed = true;
+ _timer?.cancel();
+ _timer = null;
+ if (_started) foreground.removeListener(_foregroundChanged);
+ }
+}
diff --git a/desktop/lib/agent_messages/agent_messages_view.dart b/desktop/lib/agent_messages/agent_messages_view.dart
new file mode 100644
index 000000000..64f81d952
--- /dev/null
+++ b/desktop/lib/agent_messages/agent_messages_view.dart
@@ -0,0 +1,470 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/skeleton.dart';
+import '../state/app_state.dart';
+import '../widgets/desktop_chrome.dart';
+import '../widgets/terminal_prompt.dart';
+import 'agent_messages.dart';
+
+/// Show Agent Messages: [tabId]'s log, newest last. The person reads it here
+/// and types into panes as always; there is nothing to compose.
+Future<void> showAgentMessages(
+ BuildContext context,
+ AppNotifier app, {
+ required String tabId,
+ required String tabName,
+}) => showTerminalPrompt<void>(
+ context,
+ builder: (context) => AgentMessagesView(
+ controller: app.agentMessages,
+ tabId: tabId,
+ tabName: tabName,
+ load: () => app.readAgentMessages(tabId),
+ onClose: () => Navigator.pop(context),
+ onOpen: (recipient) {
+ Navigator.pop(context);
+ if (!app.revealAgentView(
+ recipient.machineId,
+ recipient.agentId,
+ preferredSwarmId: tabId,
+ )) {
+ unawaited(
+ app.openAgentFromDial(
+ recipient.machineId,
+ recipient.agentId,
+ intent: AttachIntent.person,
+ ),
+ );
+ }
+ },
+ ),
+);
+
+class AgentMessagesView extends StatefulWidget {
+ const AgentMessagesView({
+ super.key,
+ required this.controller,
+ required this.tabId,
+ required this.tabName,
+ required this.load,
+ required this.onClose,
+ required this.onOpen,
+ });
+
+ final AgentMessagesController controller;
+ final String tabId, tabName;
+ final Future<AgentMessageLog> Function() load;
+ final VoidCallback onClose;
+
+ /// Enter on a row: the pane of the message's (first) recipient.
+ final void Function(AgentMessageParty recipient) onOpen;
+
+ @override
+ State<AgentMessagesView> createState() => _AgentMessagesViewState();
+}
+
+class _AgentMessagesViewState extends State<AgentMessagesView> {
+ AgentMessageLog? _log;
+ bool _loading = false, _again = false;
+ late int _traffic = widget.controller.trafficFor(widget.tabId);
+ final _newest = FocusNode(debugLabel: 'Newest agent message');
+
+ @override
+ void initState() {
+ super.initState();
+ widget.controller.addListener(_changed);
+ unawaited(_read(focusNewest: true));
+ }
+
+ @override
+ void dispose() {
+ widget.controller.removeListener(_changed);
+ _newest.dispose();
+ super.dispose();
+ }
+
+ void _changed() {
+ if (!mounted) return;
+ // A message moved in this tab: read the log again, once at a time.
+ final traffic = widget.controller.trafficFor(widget.tabId);
+ if (traffic != _traffic) {
+ _traffic = traffic;
+ unawaited(_read());
+ }
+ setState(() {});
+ }
+
+ Future<void> _read({bool focusNewest = false}) async {
+ if (_loading) {
+ _again = true;
+ return;
+ }
+ setState(() => _loading = true);
+ try {
+ final log = await widget.load();
+ if (!mounted) return;
+ setState(() => _log = log);
+ if (focusNewest && log.messages.isNotEmpty) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ // Only while nothing in the view has the keyboard yet.
+ final focused = FocusManager.instance.primaryFocus;
+ if (mounted && (focused == null || focused.skipTraversal)) {
+ _newest.requestFocus();
+ }
+ });
+ }
+ } finally {
+ if (mounted) setState(() => _loading = false);
+ }
+ if (_again && mounted) {
+ _again = false;
+ await _read();
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final controller = widget.controller;
+ final on = controller.isOn(widget.tabId);
+ final failure = controller.failureFor(widget.tabId);
+ final log = _log;
+ final messages = log?.messages ?? const <AgentMessage>[];
+ final hint =
+ '${terminalPromptHint(context, 'picker.next', '↓')} move · '
+ '${terminalPromptHint(context, 'picker.accept', '⏎')} open pane · '
+ '${terminalPromptHint(context, 'picker.cancel', 'Esc')} close';
+ final Widget body;
+ if (log == null) {
+ body = const SkeletonList(rows: 3, semanticsLabel: 'Loading messages');
+ } else if (messages.isEmpty) {
+ body = Padding(
+ padding: const EdgeInsets.symmetric(vertical: 24),
+ child: Text(
+ log.reached
+ ? 'No messages yet. Turn on Agent Messages, then agents use '
+ '`harness send`.'
+ : 'Could not read this tab’s messages. Check that Harness is '
+ 'running on this computer, then try again.',
+ key: const ValueKey('agent-messages-empty'),
+ textAlign: TextAlign.center,
+ style: DesktopChrome.text(size: 13, color: DesktopChrome.muted),
+ ),
+ );
+ } else {
+ // Reversed, so the newest sits at the bottom and the list opens there.
+ body = ListView.builder(
+ reverse: true,
+ shrinkWrap: true,
+ itemCount: messages.length,
+ itemBuilder: (context, index) {
+ final message = messages[messages.length - 1 - index];
+ return _MessageRow(
+ key: ValueKey('agent-message:${message.id}'),
+ message: message,
+ focusNode: index == 0 ? _newest : null,
+ nameOf: controller.nameOfParty,
+ onOpen: () => widget.onOpen(message.to.first),
+ );
+ },
+ );
+ }
+ return TerminalPromptKeys(
+ cancel: widget.onClose,
+ refresh: () => unawaited(_read()),
+ child: DesktopChrome(
+ child: Dialog(
+ elevation: 0,
+ insetPadding: const EdgeInsets.all(16),
+ backgroundColor: Colors.transparent,
+ child: SizedBox(
+ width: 640,
+ child: DesktopDialogSurface(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxHeight: 620),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ DesktopDialogHeader(
+ title: '${widget.tabName} · Agent Messages',
+ onClose: widget.onClose,
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Agent Messages',
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ Semantics(
+ label: 'Agent Messages',
+ child: Switch(
+ key: const ValueKey('agent-messages-switch'),
+ value: on,
+ onChanged: controller.isPending(widget.tabId)
+ ? null
+ : (value) => unawaited(
+ controller.setEnabled(
+ widget.tabId,
+ value,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (failure != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 4, 24, 0),
+ child: Semantics(
+ liveRegion: true,
+ child: Text(
+ failure,
+ style: DesktopChrome.metadata(
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
+ ),
+ // A machine with a harness here that did not answer
+ // (offline, or gone from the tab) holds its own part of
+ // the log.
+ if (log != null && log.reached && !log.complete)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 8, 24, 0),
+ child: Text(
+ 'Some machines didn’t answer; their messages may be '
+ 'missing.',
+ key: const ValueKey('agent-messages-incomplete'),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ const SizedBox(height: 12),
+ Divider(height: 1, color: DesktopChrome.rim),
+ Flexible(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 8,
+ ),
+ child: body,
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 4, 24, 16),
+ child: Text(
+ hint,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+const _months = [
+ 'Jan',
+ 'Feb',
+ 'Mar',
+ 'Apr',
+ 'May',
+ 'Jun',
+ 'Jul',
+ 'Aug',
+ 'Sep',
+ 'Oct',
+ 'Nov',
+ 'Dec',
+];
+
+/// `14:02` today, `Oct 9 14:02` before.
+String agentMessageTime(DateTime at, {DateTime? now}) {
+ final today = now ?? DateTime.now();
+ String two(int n) => n.toString().padLeft(2, '0');
+ final clock = '${two(at.hour)}:${two(at.minute)}';
+ return at.year == today.year && at.month == today.month && at.day == today.day
+ ? clock
+ : '${_months[at.month - 1]} ${at.day} $clock';
+}
+
+/// The row's state: one word when every recipient is in it, else each
+/// recipient's. Failed ones say why.
+({String text, bool failed, String? reasons}) agentMessageStateLabel(
+ AgentMessage message,
+ String Function(AgentMessageParty) nameOf,
+) {
+ final states = [for (final r in message.to) message.stateOf(r)];
+ final reasons = [
+ for (final r in message.to)
+ if (message.statusOf(r) case AgentMessageStatus(
+ state: AgentMessageState.failed,
+ :final reason?,
+ ))
+ message.to.length == 1 ? reason : '${nameOf(r)}: $reason',
+ ].join(' · ');
+ final failed = states.contains(AgentMessageState.failed);
+ final text = states.toSet().length == 1
+ ? states.first.name
+ : [
+ for (var i = 0; i < message.to.length; i++)
+ '${nameOf(message.to[i])} ${states[i].name}',
+ ].join(' · ');
+ return (
+ text: text,
+ failed: failed,
+ reasons: reasons.isEmpty ? null : reasons,
+ );
+}
+
+class _MessageRow extends StatelessWidget {
+ const _MessageRow({
+ super.key,
+ required this.message,
+ required this.nameOf,
+ required this.onOpen,
+ this.focusNode,
+ });
+
+ final AgentMessage message;
+ final String Function(AgentMessageParty) nameOf;
+ final VoidCallback onOpen;
+ final FocusNode? focusNode;
+
+ @override
+ Widget build(BuildContext context) {
+ final highContrast = MediaQuery.highContrastOf(context);
+ final route =
+ '${nameOf(message.from)} → ${message.to.map(nameOf).join(', ')}';
+ final state = agentMessageStateLabel(message, nameOf);
+ final error = Theme.of(context).colorScheme.error;
+ final time = agentMessageTime(message.at);
+ return Semantics(
+ label:
+ '$time, $route, ${message.firstLine}, ${state.text}'
+ '${state.reasons == null ? '' : ', ${state.reasons}'}',
+ excludeSemantics: true,
+ button: true,
+ onTap: onOpen,
+ child: TextButton(
+ focusNode: focusNode,
+ onPressed: onOpen,
+ style:
+ TextButton.styleFrom(
+ foregroundColor: DesktopChrome.foreground,
+ minimumSize: const Size(0, 40),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ alignment: Alignment.centerLeft,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ ),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ splashFactory: NoSplash.splashFactory,
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? (highContrast
+ ? DesktopChrome.accent
+ : DesktopChrome.focusRing)
+ : Colors.transparent,
+ ),
+ ),
+ overlayColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.pressed)
+ ? DesktopChrome.foreground.withValues(alpha: .12)
+ : states.contains(WidgetState.hovered)
+ ? DesktopChrome.foreground.withValues(alpha: .06)
+ : Colors.transparent,
+ ),
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ width: 88,
+ child: Text(
+ time,
+ maxLines: 1,
+ style: DesktopChrome.metadata().copyWith(
+ fontFeatures: const [FontFeature.tabularFigures()],
+ ),
+ ),
+ ),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ route,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ const SizedBox(width: 12),
+ // Several recipients each with a state can outgrow the
+ // row; the route keeps at least as much room.
+ Flexible(
+ child: Text(
+ state.text,
+ key: const ValueKey('agent-message-state'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ textAlign: TextAlign.end,
+ style: DesktopChrome.metadata(
+ color: state.failed ? error : null,
+ ),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 2),
+ Text(
+ message.firstLine,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ if (state.reasons case final reasons?) ...[
+ const SizedBox(height: 2),
+ Text(
+ reasons,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(color: error),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/agent_messages/pane_message_mark.dart b/desktop/lib/agent_messages/pane_message_mark.dart
new file mode 100644
index 000000000..093f84bd8
--- /dev/null
+++ b/desktop/lib/agent_messages/pane_message_mark.dart
@@ -0,0 +1,59 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/theme/workspace_bar_style.dart';
+import 'agent_messages.dart';
+
+/// A message's mark in a pane header, right after the activity mark: `→ api`
+/// on the sender's pane and `← lead` on each recipient's, for a few seconds
+/// or until the pane is focused. It listens to [controller] itself, as
+/// `HarnessActivityMark` listens to activity, so the cached header never
+/// rebuilds for traffic.
+///
+/// A direct child of the header's row: shown, it is a [Flexible] beside the
+/// title, so a long list of names gives way rather than overflowing; gone, it
+/// takes no share of the row from the title.
+class PaneMessageMarkView extends StatelessWidget {
+ const PaneMessageMarkView({
+ super.key,
+ required this.controller,
+ required this.machineId,
+ required this.agentId,
+ required this.style,
+ });
+
+ final AgentMessagesController controller;
+ final String machineId, agentId;
+
+ /// The header title's style; the mark is a quieter line of the same type.
+ final TextStyle style;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: controller,
+ builder: (context, _) {
+ final mark = controller.markFor(machineId, agentId);
+ if (mark == null) return const SizedBox.shrink();
+ final ink = style.color ?? grid.AppPalette.textPrimary;
+ return Flexible(
+ child: Padding(
+ padding: EdgeInsets.only(left: workspaceBarCellSizeOf(context).width),
+ child: Tooltip(
+ message: mark.tooltip ?? mark.label,
+ child: Text(
+ mark.label,
+ key: const ValueKey('pane-message-mark'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: style.copyWith(
+ color: mark.warning
+ ? grid.AppPalette.warn
+ : ink.withValues(alpha: .7),
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+}
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index a8843c660..594665de3 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -133,6 +133,31 @@ class ApiClient {
return unwrapApiResponse(res) as Map<String, dynamic>?;
}
+ // -- Agent Messages: which desk tabs let their harnesses message each other (proxied like the desk) --
+
+ /// `{revision, machines, tabs: [{id, name, enabled, panes}]}` (backend routes/agentMessages.ts). Null
+ /// when the daemon or backend predates Agent Messages (404): the app then offers none. Signed out
+ /// (401) or a backend out of reach (503) throws [ApiException], a moment the app waits out.
+ Future<Map<String, dynamic>?> readAgentMessageTabs() async {
+ final res = await _dio.get('/api/agent-messages');
+ if (res.statusCode == 404) return null;
+ return unwrapApiResponse(res) as Map<String, dynamic>?;
+ }
+
+ /// Turn Agent Messages on or off for one tab; answers `{tabId, enabled, revision}`. A local write
+ /// to the daemon, like [deskOps].
+ Future<Map<String, dynamic>> setAgentMessages(
+ String tabId,
+ bool enabled,
+ ) async {
+ final res = await _dio.patch(
+ '/api/agent-messages/tabs/${Uri.encodeComponent(tabId)}',
+ data: {'enabled': enabled},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ );
+ return Map<String, dynamic>.from(unwrapApiResponse(res) as Map);
+ }
+
// -- account-wide Experimental preferences --
Future<Map<String, dynamic>> experimentalSettings() async {
final res = await _dio.get('/api/experimental-settings');
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index 9f576e47b..d0d408aca 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -17,8 +17,8 @@ const int e2eVersion = 1;
const Set<String> encryptedDownTypes = {
'harness_devices_list',
'harness_device_settings',
- 'team',
- 'team_delivery',
+ // Agent Messages (CLI messages/wire.ts): a tab's log carries what agents said to each other.
+ 'agent_messages',
'harness_share_list',
'harness_share_invite',
'harness_share_remove',
diff --git a/desktop/lib/screens/swarm_menu_bus.dart b/desktop/lib/screens/swarm_menu_bus.dart
index c138d03a3..61225c4e1 100644
--- a/desktop/lib/screens/swarm_menu_bus.dart
+++ b/desktop/lib/screens/swarm_menu_bus.dart
@@ -83,6 +83,10 @@ class SwarmMenuState extends ChangeNotifier {
bool canClosePane = false;
bool canGoBack = false;
bool canGoForward = false;
+
+ /// Whether Agent Messages is on in the active tab; null where it has none
+ /// (the Store). File's Agent Messages row shows it as a checkmark.
+ bool? agentMessages;
List<SwarmMenuEntry> history = const [];
List<SwarmMenuEntry> closedHistory = const [];
@@ -105,6 +109,7 @@ class SwarmMenuState extends ChangeNotifier {
canClosePane = args['canClosePane'] as bool? ?? false;
canGoBack = args['canGoBack'] as bool? ?? false;
canGoForward = args['canGoForward'] as bool? ?? false;
+ agentMessages = args['activeAgentMessages'] as bool?;
history = _parseEntries(args['history'], closed: false);
closedHistory = _parseEntries(args['closedHistory'], closed: true);
paneActions = {
@@ -129,6 +134,7 @@ class SwarmMenuState extends ChangeNotifier {
canClosePane = false;
canGoBack = false;
canGoForward = false;
+ agentMessages = null;
history = const [];
closedHistory = const [];
paneActions = const {};
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 32f7ddc44..6ab0624f5 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -13,6 +13,8 @@ import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:xterm/xterm.dart' show TerminalTheme;
+import '../agent_messages/agent_messages.dart';
+import '../agent_messages/agent_messages_view.dart';
import '../core/runtime_platform.dart';
import '../api/api_client.dart';
import '../core/desktop_window.dart';
@@ -127,7 +129,6 @@ import '../widgets/task_palette.dart';
import '../state/task_route.dart';
import '../orchestrator/orchestrator_launcher.dart';
import '../orchestrator/orchestrator_workspace.dart';
-import '../teams/team_workspace.dart';
import '../state/workspace_learning.dart';
import '../state/workspace_onboarding.dart';
import '../state/workspace_chrome.dart';
@@ -729,11 +730,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
// Subscription usage is read ahead, so opening a menu shows it without waiting.
_modelsMenu!.start();
_harnessMonitor.start();
+ // Agent Messages between harnesses on other machines, which their
+ // daemons tell only their own computer's windows.
+ app.agentMessagesRemote.start();
});
}
if (_menuHost) {
_menuBus.setHandler(_onNative);
app.addListener(_syncNative);
+ app.agentMessages.addListener(_syncNative);
_syncNative();
}
_tabStripRequest = app.tabStripFocusRequest;
@@ -897,6 +902,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (_menuHost) {
unawaited(_menuBus.send('machinesState', {'machines': []}));
app.removeListener(_syncNative);
+ app.agentMessages.removeListener(_syncNative);
_menuBus.setHandler(null);
unawaited(_menuBus.send('update', {'tabs': [], 'enabled': false}));
}
@@ -2032,8 +2038,20 @@ class _SwarmScreenState extends State<SwarmScreen> {
activity,
color: activityInk(activity),
),
+ // Agent Messages' ⇄; absent where a tab has none
+ // (AppNotifier.agentMessagesOffered). Flowing only while on.
+ if (app.agentMessagesOffered(swarm.id)) ...{
+ 'agentMessages': app.agentMessages.isOn(swarm.id),
+ 'agentMessagesFlowing':
+ app.agentMessages.stateOf(swarm.id) ==
+ TabMessagesState.flowing,
+ },
},
],
+ // The File menu's Agent Messages checkmark, for the active tab.
+ 'activeAgentMessages': app.agentMessagesOffered(app.activeSwarmId)
+ ? app.agentMessages.isOn(app.activeSwarmId)
+ : null,
};
final encoded = jsonEncode(payload);
if (encoded == _nativeState) return;
@@ -2354,6 +2372,20 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (args['id'] is String) unawaited(_rename(args['id']));
case 'renameActive':
unawaited(_rename(app.activeSwarmId));
+ case 'toggleAgentMessages':
+ // From a tab's ⇄ or its menu (with its id), or the File menu (the
+ // active tab).
+ unawaited(
+ _toggleAgentMessages(
+ args['id'] is String ? args['id'] as String : app.activeSwarmId,
+ ),
+ );
+ case 'showAgentMessages':
+ unawaited(
+ _showAgentMessages(
+ args['id'] is String ? args['id'] as String : app.activeSwarmId,
+ ),
+ );
case 'next':
app.stepSwarm(1);
case 'previous':
@@ -2502,6 +2534,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
'new',
'rename',
'renameActive',
+ 'toggleAgentMessages',
+ 'showAgentMessages',
'commands',
'notifications',
'notificationInbox',
@@ -2698,6 +2732,31 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (name != null) app.renameSwarm(id, name);
});
+ /// Turn Agent Messages on or off for [id]. The ⇄ follows at once and goes
+ /// back if the backend does not take it — and then says so where the click
+ /// was, since a ⇄ that quietly flips back reads as a click that missed.
+ Future<void> _toggleAgentMessages(String id) async {
+ if (!app.agentMessagesOffered(id)) return;
+ if (await app.agentMessages.toggle(id) || !mounted) return;
+ final failure = app.agentMessages.failureFor(id);
+ if (failure == null) return;
+ ScaffoldMessenger.maybeOf(context)
+ ?..hideCurrentSnackBar()
+ ..showSnackBar(SnackBar(content: Text(failure)));
+ }
+
+ /// [id]'s Agent Messages log.
+ Future<void> _showAgentMessages(String id) => _dialog(() async {
+ final swarm = app.swarms.where((s) => s.id == id).firstOrNull;
+ if (swarm == null || !app.agentMessagesOffered(id)) return;
+ await showAgentMessages(
+ context,
+ app,
+ tabId: id,
+ tabName: workspaceTabNames(app)[id] ?? swarm.name,
+ );
+ });
+
Agent? get _focusedAgent {
final pane = app.focusedPane;
return pane == null
@@ -6496,8 +6555,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
ShortcutAction.routeTask: _routeTask,
ShortcutAction.orchestrate: () =>
_dialog(() => showOrchestratorLauncher(context, app)),
- ShortcutAction.team: () =>
- _dialog(() => showChannelWorkspace(context, app)),
ShortcutAction.reload: app.retryMachines,
ShortcutAction.showLayout: () =>
_dialog(() => showLayoutPalette(context, app)),
@@ -6532,6 +6589,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
for (var i = 1; i <= 9; i++)
'pane.focus_$i': () => app.focusPaneByIndex(i - 1),
'navigation.commands': _showSearchCommands,
+ 'agent_messages.show': () => _showAgentMessages(app.activeSwarmId),
+ 'agent_messages.toggle': () =>
+ unawaited(_toggleAgentMessages(app.activeSwarmId)),
'app.customize': () => unawaited(_customize()),
'pane.toggle_shading': () => unawaited(
appearancePrefsStore.setShadeInactivePanes(
@@ -6585,6 +6645,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
return false;
}
if (id == 'keyboard.open_config') return _keymap.store != null;
+ if (id.startsWith('agent_messages.')) {
+ return app.agentMessagesOffered(app.activeSwarmId);
+ }
if (id == 'agent.work') {
return WorkspacePaneContext.focused(app)?.agent != null;
}
@@ -6787,6 +6850,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
: command.id == 'agent.restart' &&
isTerminalEngine(_focusedAgent?.engine)
? 'Restart Terminal'
+ : command.id == 'agent_messages.toggle'
+ ? app.agentMessages.isOn(app.activeSwarmId)
+ ? 'Agent Messages: turn off for this tab'
+ : 'Agent Messages: turn on for this tab'
: command.label,
detail: command.group.label,
swarmId: null,
@@ -7773,53 +7840,68 @@ class _SwarmScreenState extends State<SwarmScreen> {
unawaited(app.requestCloseSwarm(swarm.id));
}
},
- child: DesktopWorkspaceTab(
- id: swarm.id,
- onRename: () => _rename(swarm.id),
- label: labels[index],
- selected: selected,
- showShortcuts: _tabShortcutHints,
- shortcutHint: _keymap.hint(
- 'swarm.select_${index + 1}',
+ // Only the tab listens to Agent Messages: its traffic
+ // must not rebuild the workspace.
+ child: ListenableBuilder(
+ listenable: app.agentMessages,
+ builder: (context, _) => DesktopWorkspaceTab(
+ id: swarm.id,
+ onRename: () => _rename(swarm.id),
+ label: labels[index],
+ selected: selected,
+ showShortcuts: _tabShortcutHints,
+ shortcutHint: _keymap.hint(
+ 'swarm.select_${index + 1}',
+ ),
+ tooltip: tabHint.isEmpty ? null : tabHint,
+ activityLabel: activity?.label,
+ onSelect: _shortcutsEnabled
+ ? () => app.selectSwarm(swarm.id)
+ : null,
+ onClose: _shortcutsEnabled
+ ? () => unawaited(
+ app.requestCloseSwarm(swarm.id),
+ )
+ : null,
+ agentMessages: app.agentMessagesOffered(swarm.id)
+ ? app.agentMessages.stateOf(swarm.id)
+ : null,
+ onToggleAgentMessages: _shortcutsEnabled
+ ? () => unawaited(
+ _toggleAgentMessages(swarm.id),
+ )
+ : null,
+ activity:
+ activity == null || activity.mark.isEmpty
+ ? null
+ : ListenableBuilder(
+ listenable: _tabScroll,
+ builder: (context, _) {
+ final left = _tabWidths
+ .take(index)
+ .fold(0.0, (a, b) => a + b);
+ final offset = _tabScroll.hasClients
+ ? _tabScroll.offset
+ : 0.0;
+ return ActivityMark(
+ key: ValueKey(
+ 'tab-activity:${swarm.id}',
+ ),
+ activity: activity,
+ color: activityColor(
+ activity,
+ theme,
+ color: prefs.color,
+ ),
+ emphasized: selected,
+ tooltip: false,
+ visible:
+ left < offset + tabsWidth &&
+ left + _tabWidths[index] > offset,
+ );
+ },
+ ),
),
- tooltip: tabHint.isEmpty ? null : tabHint,
- activityLabel: activity?.label,
- onSelect: _shortcutsEnabled
- ? () => app.selectSwarm(swarm.id)
- : null,
- onClose: _shortcutsEnabled
- ? () =>
- unawaited(app.requestCloseSwarm(swarm.id))
- : null,
- activity: activity == null || activity.mark.isEmpty
- ? null
- : ListenableBuilder(
- listenable: _tabScroll,
- builder: (context, _) {
- final left = _tabWidths
- .take(index)
- .fold(0.0, (a, b) => a + b);
- final offset = _tabScroll.hasClients
- ? _tabScroll.offset
- : 0.0;
- return ActivityMark(
- key: ValueKey(
- 'tab-activity:${swarm.id}',
- ),
- activity: activity,
- color: activityColor(
- activity,
- theme,
- color: prefs.color,
- ),
- emphasized: selected,
- tooltip: false,
- visible:
- left < offset + tabsWidth &&
- left + _tabWidths[index] > offset,
- );
- },
- ),
),
),
);
diff --git a/desktop/lib/settings/sections/experimental_section.dart b/desktop/lib/settings/sections/experimental_section.dart
index 3d2115fea..19a7cdf91 100644
--- a/desktop/lib/settings/sections/experimental_section.dart
+++ b/desktop/lib/settings/sections/experimental_section.dart
@@ -5,7 +5,6 @@ import 'package:flutter/material.dart';
import '../../shared/widgets/section_scaffold.dart';
import '../../shared/widgets/setting_row.dart';
import '../experimental_features.dart';
-import '../../teams/swarm_settings_controller.dart';
import '../../companions/coding_memory_connection.dart';
import '../../companions/coding_memory_settings.dart';
@@ -13,12 +12,10 @@ class ExperimentalSection extends StatefulWidget {
const ExperimentalSection({
super.key,
this.store,
- this.controller,
this.openCodingMemory,
});
final ExperimentalFeaturesStore? store;
- final SwarmSettingsController? controller;
final CodingMemoryConnection? Function()? openCodingMemory;
@override
@@ -30,8 +27,6 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {
void initState() {
super.initState();
unawaited((widget.store ?? _fallbackStore).refresh());
- final controller = widget.controller;
- if (controller != null) unawaited(controller.refresh());
}
final _fallbackStore = ExperimentalFeaturesStore();
@@ -51,7 +46,7 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {
subtitle: 'Try features that are still taking shape. Account experiments sync across your devices; coding memory is local to this computer.',
child: SingleChildScrollView(
child: ListenableBuilder(
- listenable: Listenable.merge([preferences, widget.controller]),
+ listenable: preferences,
builder: (context, _) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: 10,
@@ -118,8 +113,6 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {
)
: null,
),
- if (widget.controller case final controller?)
- _SwarmCollaborationSetting(controller: controller),
if (widget.openCodingMemory case final open?)
_CodingMemorySetting(
open: open,
@@ -214,63 +207,3 @@ class _CodingMemorySettingState extends State<_CodingMemorySetting> {
),
);
}
-
-class _SwarmCollaborationSetting extends StatelessWidget {
- const _SwarmCollaborationSetting({required this.controller});
- final SwarmSettingsController controller;
-
- @override
- Widget build(BuildContext context) {
- final state = controller;
- final status = state.saving
- ? 'Saving…'
- : !state.loaded && state.error == null
- ? 'Loading…'
- : null;
- return SettingRow(
- title: 'Tab collaboration',
- detail:
- 'Let agents automatically consult only peers in the same tab. '
- 'Off by default.',
- control: Semantics(
- label: 'Tab collaboration',
- child: Align(
- alignment: Alignment.centerLeft,
- child: Switch(
- key: const Key('experimental-swarm-collaboration'),
- value: state.enabled,
- onChanged: state.loaded && !state.saving
- ? (on) => unawaited(state.setEnabled(on))
- : null,
- ),
- ),
- ),
- footer: DefaultTextStyle.merge(
- style: Theme.of(context).textTheme.bodySmall,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- const Text(
- 'Use “Tab conversation” in the command palette to inspect '
- 'their questions and replies.',
- ),
- if (status != null) ...[
- const SizedBox(height: 8),
- Semantics(liveRegion: true, child: Text(status)),
- ],
- if (state.error case final error?) ...[
- const SizedBox(height: 8),
- Semantics(liveRegion: true, child: Text(error)),
- TextButton(
- onPressed: state.saving
- ? null
- : () => unawaited(state.refresh()),
- child: const Text('Refresh setting'),
- ),
- ],
- ],
- ),
- ),
- );
- }
-}
diff --git a/desktop/lib/settings/settings_body.dart b/desktop/lib/settings/settings_body.dart
index 8af8e677c..e1634a528 100644
--- a/desktop/lib/settings/settings_body.dart
+++ b/desktop/lib/settings/settings_body.dart
@@ -47,7 +47,6 @@ class SettingsBody extends StatelessWidget {
SettingsSection.notifications => const NotificationsSection(),
SettingsSection.experimental => ExperimentalSection(
store: experimentalFeatures ?? notifier.experimentalFeatures,
- controller: notifier.swarmSettings,
openCodingMemory: notifier.openCodingMemoryConnection,
),
SettingsSection.devices => ListenableBuilder(
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index e7260535d..a7e67d2e1 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -75,7 +75,6 @@ enum ShortcutAction {
shareAgent,
routeTask,
orchestrate,
- team,
reload,
showLayout,
pinPane,
diff --git a/desktop/lib/shortcuts/keymap.dart b/desktop/lib/shortcuts/keymap.dart
index 07f7c4407..bc286f42a 100644
--- a/desktop/lib/shortcuts/keymap.dart
+++ b/desktop/lib/shortcuts/keymap.dart
@@ -212,7 +212,12 @@ class KeymapConfig {
}
final command = row['command'];
// Retired actions must not invalidate the user's other custom shortcuts.
- if (const {'picker.preview', 'navigation.quick_open'}.contains(command) &&
+ // `team.open` was Swarm's Tab conversation, now Show Agent Messages.
+ if (const {
+ 'picker.preview',
+ 'navigation.quick_open',
+ 'team.open',
+ }.contains(command) &&
!commands.contains(command)) {
continue;
}
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 88cb1fc17..d3bd59944 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -60,6 +60,20 @@ class HarnessCommand {
/// they are in no list, no help and no native keymap. The workspace sets it.
final daemonCommandsActive = ValueNotifier<bool>(false);
+/// What a person looking for Agent Messages may type, older names included.
+const _agentMessagesKeywords = [
+ 'agent messages',
+ 'harness send',
+ 'message',
+ 'log',
+ 'tab',
+ 'collaborate',
+ 'communicate',
+ 'swarm',
+ 'team',
+ 'channel',
+];
+
/// Whether [id] is a command this window has now.
bool harnessCommandActive(String id) =>
harnessCommandById[id]?.daemon != true || daemonCommandsActive.value;
@@ -480,22 +494,21 @@ final harnessCommands = <HarnessCommand>[
ShortcutGroup.actions,
action: ShortcutAction.orchestrate,
),
+ // Agent Messages (docs/design/2026-10-10-agent-messages.md): the active
+ // tab's log, and its flag. Their native menu rows are File's.
const HarnessCommand(
- 'team.open',
- 'Tab conversation: view this tab’s collaboration',
+ 'agent_messages.show',
+ 'Show Agent Messages',
ShortcutGroup.actions,
- action: ShortcutAction.team,
- keywords: [
- 'communicate',
- 'collaborate',
- 'message',
- 'question',
- 'reply',
- 'inbox',
- 'tab',
- 'swarm',
- 'channel',
- ],
+ nativeAction: 'showAgentMessages',
+ keywords: _agentMessagesKeywords,
+ ),
+ const HarnessCommand(
+ 'agent_messages.toggle',
+ 'Agent Messages: turn on or off for this tab',
+ ShortcutGroup.actions,
+ nativeAction: 'toggleAgentMessages',
+ keywords: _agentMessagesKeywords,
),
const HarnessCommand(
'app.customize',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 0f2c60587..ad60febd6 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -25,6 +25,7 @@ import 'first_arrival.dart';
import 'harness_monitor_controller.dart';
import 'agent_handoff_file.dart';
import 'agent_switch_handoff.dart';
+import '../agent_messages/agent_messages.dart';
import '../api/api_client.dart';
import '../viewer/sign_in_browser.dart';
import '../viewer/direct_link.dart';
@@ -116,8 +117,6 @@ import '../usage/models_menu_controller.dart';
import '../usage/remote_usage.dart';
import '../usage/usage_accounts.dart';
import '../orchestrator/orchestrator_controller.dart';
-import '../teams/team_controller.dart';
-import '../teams/swarm_settings_controller.dart';
import '../notify/agent_alerts.dart';
import '../notify/alert_sounds.dart';
import '../notify/system_notifications.dart';
@@ -1391,92 +1390,99 @@ class AppNotifier extends ChangeNotifier {
Iterable<TerminalPane> get allPanes => swarms.expand((s) => s.panes).toSet();
String get activeSwarmId => activeSwarm.id;
- final _orchestratorProjects = <String, OrchestratorController>{};
- final _teamControllers = <String, TeamController>{};
- final _channelControllers = <String, TeamController>{};
- SwarmSettingsController? _swarmSettings;
- SwarmSettingsController get swarmSettings =>
- _swarmSettings ??= SwarmSettingsController(
- request: (payload) {
- final gateway = channelGateway(localMachineState?.machine.machineId);
- if (gateway == null) {
- throw const TeamRequestError(
- 'Connect one of your machines to configure tab collaboration.',
- );
- }
- return teamRequest(gateway, payload);
- },
- );
+ /// Agent Messages (docs/design/2026-10-10-agent-messages.md): each tab's
+ /// flag, the traffic the daemons push as `messages_changed`, and the marks it
+ /// leaves on panes. Its own notifier, so traffic never rebuilds the workspace.
+ late final agentMessages = AgentMessagesController(
+ read: () => api.readAgentMessageTabs(),
+ write: (tabId, enabled) => api.setAgentMessages(tabId, enabled),
+ request: (machineId, payload) => _conn(machineId).request(
+ 'agent_messages',
+ payload: payload,
+ timeout: const Duration(seconds: 8),
+ ),
+ nameOf: (machineId, agentId) =>
+ stateOf(machineId)?.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull
+ ?.displayName,
+ );
- /// The first hop may change; the request still names its original tab and
- /// the daemon routes it to that tab's saved host. Observation links cannot
- /// carry owner collaboration commands.
- String? channelGateway(String? preferredMachineId) {
- final candidates = <MachineState>[
- ?machineStates[preferredMachineId],
- ...machineStates.values,
- ].where((state) => !state.machine.isShared);
- return (candidates
- .where(
- (state) =>
- state.connectionStatus == ConnectionStatus.connected,
- )
- .firstOrNull ??
- candidates.firstOrNull)
- ?.machine
- .machineId;
- }
-
- TeamController channelController(String tabId, String gatewayMachineId) =>
- _channelControllers.putIfAbsent(tabId, () {
- late final TeamController controller;
- controller = TeamController(
- channelTabId: tabId,
- request: (payload) {
- final machineId =
- controller.team?['machineId'] as String? ??
- channelGateway(gatewayMachineId);
- if (machineId == null) {
- throw const TeamRequestError(
- 'Connect one of your machines to use tab collaboration.',
- );
- }
- return teamRequest(machineId, payload);
- },
- );
- return controller;
- });
+ /// Whether [tabId] has Agent Messages to offer: a tab the desk holds, since
+ /// the backend keeps the flag per desk tab, once the daemon and backend have
+ /// answered for it. The Store, Devices and Companions, an orchestrator or a
+ /// draft tab, a window before it joins the desk, and an older CLI or backend
+ /// get no ⇄, menu row or command.
+ bool agentMessagesOffered(String tabId) {
+ final swarm = swarms.where((s) => s.id == tabId).firstOrNull;
+ return swarm != null &&
+ _desk.enabled &&
+ _deskTracks(swarm) &&
+ isDeskId(swarm.id) &&
+ agentMessages.loaded;
+ }
- Future<Map<String, dynamic>> teamRequest(
- String machineId,
- Map<String, dynamic> payload,
- ) async {
- try {
- return await _conn(
- machineId,
- ).request('team', payload: payload, timeout: const Duration(seconds: 35));
- } on WsRequestFailure catch (e) {
- throw TeamRequestError(
- e.code == 'UNSUPPORTED'
- ? 'Update Harness on this machine to use agent collaboration.'
- : e.toString(),
- uncertain: const {
- 'UNCONFIRMED',
- 'DISCONNECTED',
- 'TEAM_UNAVAILABLE',
- }.contains(e.code),
- );
- }
+ /// The machines of the owner's with a harness in [tabId], and this
+ /// computer: every daemon that may hold part of the tab's log. A shared
+ /// machine's harnesses never take part.
+ Set<String> _agentMessageMembers(String tabId) {
+ final tab = swarms.where((swarm) => swarm.id == tabId).firstOrNull;
+ return {
+ ?localMachineState?.machine.machineId,
+ for (final pane in tab?.panes ?? const <TerminalPane>[])
+ if (pane.agentId != null &&
+ machineStates[pane.machineId]?.machine.isShared != true)
+ pane.machineId,
+ };
}
- TeamController teamController(String machineId) =>
- _teamControllers.putIfAbsent(
- machineId,
- () => TeamController(
- request: (payload) => teamRequest(machineId, payload),
- ),
+ /// Of [_agentMessageMembers], those that can answer now.
+ List<String> agentMessageMachines(String tabId) => [
+ for (final id in _agentMessageMembers(tabId))
+ if (machineStates[id] case final machine?
+ when !machine.machine.isShared &&
+ !machine.needsLink &&
+ machine.nodeOnline != false &&
+ machine.connectionStatus == ConnectionStatus.connected)
+ id,
+ ];
+
+ /// [tabId]'s Agent Messages log, from every daemon that may hold part of it.
+ Future<AgentMessageLog> readAgentMessages(String tabId) =>
+ agentMessages.history(
+ tabId,
+ agentMessageMachines(tabId),
+ expected: _agentMessageMembers(tabId),
);
+ /// The tabs with Agent Messages on, each with its connected machines other
+ /// than this computer: their daemons' `messages_changed` reaches only their
+ /// own computer's windows, so [agentMessagesRemote] asks them instead. In a
+ /// browser every machine is another computer.
+ List<AgentMessagesRemoteTab> agentMessagesRemoteTabs() {
+ final local = localMachineState?.machine.machineId;
+ return [
+ for (final swarm in swarms)
+ if (agentMessagesOffered(swarm.id) && agentMessages.isOn(swarm.id))
+ if ([
+ for (final id in agentMessageMachines(swarm.id))
+ if (id != local) id,
+ ]
+ case final remote when remote.isNotEmpty)
+ (tabId: swarm.id, machineIds: remote),
+ ];
+ }
+
+ /// Polls [agentMessagesRemoteTabs] while the window is in front; the
+ /// workspace starts it.
+ late final agentMessagesRemote = AgentMessagesRemoteWatch(
+ controller: agentMessages,
+ foreground: foreground,
+ tabs: agentMessagesRemoteTabs,
+ );
+
+ final _orchestratorProjects = <String, OrchestratorController>{};
+
Future<Map<String, dynamic>> orchestratorRequest(
String machineId,
Map<String, dynamic> payload,
@@ -5289,6 +5295,8 @@ class AppNotifier extends ChangeNotifier {
if (refetch && !machinesRefreshing) unawaited(retryMachines());
if (currentUser == null) unawaited(_loadProfile());
_deskEnsure(_authRevision);
+ // A daemon whose backend was away answered the last read with an error.
+ if (_desk.enabled) unawaited(agentMessages.refresh());
}
notifyListeners();
}
@@ -5548,6 +5556,7 @@ class AppNotifier extends ChangeNotifier {
void _clearAccountWorkspace({bool notices = true}) {
if (notices) _clearDeviceNoticeState();
experimentalFeatures.bind(null);
+ agentMessages.reset();
_agentChanges.clear();
++_layoutRevision;
// Sign-out sends the desk nothing: the tabs closing here are this window
@@ -5597,16 +5606,6 @@ class AppNotifier extends ChangeNotifier {
controller.dispose();
}
_orchestratorProjects.clear();
- for (final controller in _teamControllers.values) {
- controller.dispose();
- }
- _teamControllers.clear();
- for (final controller in _channelControllers.values) {
- controller.dispose();
- }
- _channelControllers.clear();
- _swarmSettings?.dispose();
- _swarmSettings = null;
final starter = Swarm(id: 'swarm-${_nextSwarmId++}');
swarms
..clear()
@@ -7067,6 +7066,10 @@ class AppNotifier extends ChangeNotifier {
_desk.pending.isEmpty) {
unawaited(_deskFetch());
}
+ // So are Agent Messages' flags (desk_changed); this catches a missed one.
+ if (!_disposed && status == AppStatus.authenticated && _desk.enabled) {
+ unawaited(agentMessages.refresh());
+ }
unawaited(_rereadMachinesInBackground(pushed: false));
});
if (viewer != null) {
@@ -10763,7 +10766,13 @@ class AppNotifier extends ChangeNotifier {
///
/// Reads the focused pane rather than taking an id, so every route into a
/// harness clears it without each one having to remember to.
- void _seeFocusedAgent() => seeWatchedAgents();
+ void _seeFocusedAgent() {
+ seeWatchedAgents();
+ // Its Agent Messages mark has done its job once the person is looking.
+ if (focusedPane case TerminalPane(:final machineId, :final agentId?)) {
+ agentMessages.seen(machineId, agentId);
+ }
+ }
String? _eventAgentId(
MachineState machine,
@@ -15387,6 +15396,8 @@ class AppNotifier extends ChangeNotifier {
return;
}
_desk.enabled = true;
+ // Each tab's Agent Messages flag lives beside the desk, read once it is.
+ unawaited(agentMessages.refresh());
// Tabs from before the desk carry per-window ids (`swarm-N`) two computers
// would both mint. Give them desk ids once; the layout store keys by the
// same string, so it follows on the next save.
@@ -16665,11 +16676,10 @@ class AppNotifier extends ChangeNotifier {
_orchestratorProjects['$machineId/${payload['id']}']?.changed();
return;
}
- if (type == 'team_changed') {
- _teamControllers[machineId]?.changed();
- for (final controller in _channelControllers.values) {
- controller.changed();
- }
+ if (type == 'messages_changed') {
+ // Before the activity check below: this payload is traffic between
+ // harnesses, never a turn of the pane's own.
+ agentMessages.handleEvent(payload);
return;
}
// Only terminal protocol frames visit the session pool. Heartbeats, dial
@@ -16974,7 +16984,11 @@ class AppNotifier extends ChangeNotifier {
break;
case 'desk_changed':
unawaited(experimentalFeatures.refresh());
- if (_swarmSettings case final settings?) unawaited(settings.refresh());
+ // Turning Agent Messages on or off for a tab says `desk_changed` too,
+ // with the desk itself unchanged (backend routes/agentMessages.ts).
+ if (status == AppStatus.authenticated) {
+ unawaited(agentMessages.refresh());
+ }
// Another window — on another computer, or this one — changed the
// tabs. The payload is only the revision; the document is fetched.
final deskRevision = payload['revision'];
@@ -17480,16 +17494,8 @@ class AppNotifier extends ChangeNotifier {
_modelManager?.dispose();
harnessMonitor.dispose();
_modelsMenu?.dispose();
- for (final controller in _teamControllers.values) {
- controller.dispose();
- }
- _teamControllers.clear();
- for (final controller in _channelControllers.values) {
- controller.dispose();
- }
- _channelControllers.clear();
- _swarmSettings?.dispose();
- _swarmSettings = null;
+ agentMessagesRemote.dispose();
+ agentMessages.dispose();
for (final project in _orchestratorProjects.values) {
project.dispose();
}
diff --git a/desktop/lib/teams/swarm_settings_controller.dart b/desktop/lib/teams/swarm_settings_controller.dart
deleted file mode 100644
index 5b38b60a6..000000000
--- a/desktop/lib/teams/swarm_settings_controller.dart
+++ /dev/null
@@ -1,85 +0,0 @@
-import 'package:flutter/foundation.dart';
-
-import 'team_controller.dart';
-
-/// The account's explicit opt-in. An absent, unreadable, or not-yet-loaded choice
-/// never enables collaboration. The daemon enforces the same gate independently.
-class SwarmSettingsController extends ChangeNotifier {
- SwarmSettingsController({required this.request});
- final TeamRequest request;
- bool enabled = false, loaded = false, saving = false;
- String? error;
- int _epoch = 0, _revision = -1;
- bool _disposed = false;
- Future<void>? _reading;
-
- void _notify() {
- if (!_disposed) notifyListeners();
- }
-
- Future<Map<String, dynamic>> _call(Map<String, dynamic> payload) async {
- final result = await request(payload);
- if (result['error'] != null) {
- throw TeamRequestError(
- result['detail']?.toString() ?? result['error'].toString(),
- );
- }
- if (result['enabled'] is! bool || result['revision'] is! num) {
- throw const TeamRequestError(
- 'Update Harness to configure tab collaboration.',
- );
- }
- return result;
- }
-
- void _apply(Map<String, dynamic> result) {
- final revision = (result['revision'] as num).toInt();
- if (revision < _revision) return;
- _revision = revision;
- enabled = result['enabled'] == true;
- loaded = true;
- error = null;
- }
-
- Future<void> refresh() => _reading ??= _read().whenComplete(() {
- _reading = null;
- });
-
- Future<void> _read() async {
- final epoch = _epoch;
- try {
- final result = await _call({'action': 'channel_settings'});
- if (!_disposed && epoch == _epoch) _apply(result);
- } catch (e) {
- if (!_disposed && epoch == _epoch) error = e.toString();
- }
- _notify();
- }
-
- Future<void> setEnabled(bool value) async {
- if (_disposed || saving || !loaded) return;
- final epoch = ++_epoch;
- saving = true;
- error = null;
- _notify();
- try {
- final result = await _call({
- 'action': 'channel_configure',
- 'enabled': value,
- });
- if (!_disposed && epoch == _epoch) _apply(result);
- } catch (e) {
- if (!_disposed && epoch == _epoch) {
- error = '$e Refresh to check whether the change was saved.';
- }
- }
- if (!_disposed && epoch == _epoch) saving = false;
- _notify();
- }
-
- @override
- void dispose() {
- _disposed = true;
- super.dispose();
- }
-}
diff --git a/desktop/lib/teams/team_controller.dart b/desktop/lib/teams/team_controller.dart
deleted file mode 100644
index 515d27c94..000000000
--- a/desktop/lib/teams/team_controller.dart
+++ /dev/null
@@ -1,404 +0,0 @@
-import 'dart:async';
-import 'dart:math';
-
-import 'package:flutter/foundation.dart';
-
-typedef TeamRequest = Future<Map<String, dynamic>> Function(
- Map<String, dynamic>,
-);
-
-String teamOperationId() {
- final random = Random.secure();
- return List.generate(
- 16,
- (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'),
- ).join();
-}
-
-class TeamRequestError implements Exception {
- const TeamRequestError(this.message, {this.uncertain = false});
- final String message;
- final bool uncertain;
- @override
- String toString() => message;
-}
-
-List<Map<String, dynamic>> teamRows(dynamic value) => [
- for (final row in value is List ? value : const [])
- if (row is Map) Map<String, dynamic>.from(row),
-];
-
-/// A view of daemon-owned work. Closing Team only releases its read subscription.
-/// Uncertain operations and drafts belong here, so reopening cannot duplicate a send.
-class TeamController extends ChangeNotifier {
- TeamController({
- required this.request,
- this.channelTabId,
- this.pollInterval = const Duration(seconds: 3),
- });
- final TeamRequest request;
- final String? channelTabId;
- bool get isChannel => channelTabId != null || team?['channel'] != null;
- final Duration pollInterval;
- List<Map<String, dynamic>> teams = [];
- Map<String, dynamic>? team;
- String? selectedId, error;
- bool loading = true, operating = false;
- String draft = '', newName = 'Build together', newDescription = '';
- String? from, to, selectedExchange;
- final Map<String, Map<String, dynamic>> newMembers = {};
- Map<String, dynamic>? _createAttempt;
- final _askAttempts = <String, Map<String, dynamic>>{};
- final _addAttempts = <String, Map<String, dynamic>>{};
- final _consultAttempts = <String, Map<String, dynamic>>{};
- final _consultFlights = <String, Future<String>>{};
- final _drafts =
- <String, ({String text, String? from, String? to, String? exchange})>{};
- Timer? _timer;
- int _readers = 0, _epoch = 0;
- bool _disposed = false;
- Future<void>? _refresh;
- bool get pendingCreate => _createAttempt != null;
- bool get pendingAsk => _askAttempts.containsKey(selectedId);
- bool get pendingAdd => _addAttempts.containsKey(selectedId);
- List<Map<String, dynamic>> get members => teamRows(team?['members']);
- List<Map<String, dynamic>> get exchanges {
- final rows = [...teamRows(team?['exchanges']).reversed];
- if (isChannel) {
- rows.sort(
- (a, b) => ((b['createdAt'] as num?) ?? 0).compareTo(
- (a['createdAt'] as num?) ?? 0,
- ),
- );
- }
- return rows;
- }
-
- bool get active => team?['state'] == 'active';
-
- void _notify() {
- if (!_disposed) notifyListeners();
- }
-
- void watch() {
- if (_disposed || _readers++ > 0) return;
- unawaited(refresh());
- _timer = Timer.periodic(pollInterval, (_) => unawaited(refresh()));
- }
-
- void unwatch() {
- if (_readers > 0) _readers--;
- if (_readers == 0) {
- _timer?.cancel();
- _timer = null;
- }
- }
-
- void changed() {
- if (_readers > 0) unawaited(refresh());
- }
-
- Future<Map<String, dynamic>> _call(Map<String, dynamic> payload) async {
- final result = await request(payload);
- if (result['error'] != null) {
- throw TeamRequestError(
- result['detail']?.toString() ?? result['error'].toString(),
- uncertain: const {
- 'UNCONFIRMED',
- 'DISCONNECTED',
- 'TEAM_UNAVAILABLE',
- }.contains(result['error']),
- );
- }
- return result;
- }
-
- Future<void> refresh() =>
- _refresh ??= _read().whenComplete(() => _refresh = null);
- Future<void> _read() async {
- final epoch = _epoch, id = selectedId;
- try {
- final result = await _call({
- 'action': channelTabId != null
- ? 'channel_get'
- : id == null
- ? 'list'
- : 'get',
- if (channelTabId != null) 'tabId': channelTabId else 'teamId': ?id,
- });
- if (_disposed || epoch != _epoch) return;
- if (channelTabId != null) {
- selectedId = (result['team'] as Map?)?['id'] as String?;
- _apply(result['team']);
- error = null;
- } else if (id == null) {
- teams = teamRows(result['teams']);
- final faults = teamRows(result['errors']);
- error = faults.isEmpty
- ? null
- : faults.map((f) => f['detail']).join('\n');
- } else {
- _apply(result['team']);
- error = null;
- }
- } catch (e) {
- if (!_disposed && epoch == _epoch) error = e.toString();
- }
- if (!_disposed && epoch == _epoch) {
- loading = false;
- _notify();
- }
- }
-
- void _apply(dynamic value) {
- if (_disposed || value is! Map || value['id'] != selectedId) return;
- if (team?['id'] == value['id'] &&
- (team?['revision'] as num? ?? 0) > (value['revision'] as num? ?? 0)) {
- return;
- }
- team = Map<String, dynamic>.from(value);
- if (isChannel && selectedExchange == null && exchanges.isNotEmpty) {
- selectedExchange = exchanges.first['id'] as String?;
- }
- final enabled = members.where((m) => m['enabled'] != false).toList();
- if (!enabled.any((m) => m['id'] == from)) {
- from = enabled.firstOrNull?['id'] as String?;
- }
- if (!enabled.any((m) => m['id'] == to) || from == to) {
- to = enabled.where((m) => m['id'] != from).firstOrNull?['id'] as String?;
- }
- }
-
- Future<void> select(String? id) async {
- if (selectedId case final current?) {
- _drafts[current] = (
- text: draft,
- from: from,
- to: to,
- exchange: selectedExchange,
- );
- }
- _epoch++;
- selectedId = id;
- team = null;
- final saved = _drafts[id];
- draft = saved?.text ?? '';
- from = saved?.from;
- to = saved?.to;
- selectedExchange = saved?.exchange;
- error = null;
- loading = true;
- _notify();
- // A slow reply for the previous team must not hold up the newly selected one.
- await _read();
- }
-
- void edit() => _notify();
-
- /// The caller captures tab and agent before any await. Retries retain that
- /// instruction's identity, even after focus changes or the view is closed.
- Future<String> consult(String machineId, String agentId) {
- final key = '$machineId/$agentId';
- return _consultFlights[key] ??= _consult(machineId, agentId, key)
- .whenComplete(() {
- _consultFlights.remove(key);
- });
- }
-
- Future<String> _consult(String machineId, String agentId, String key) async {
- if (channelTabId == null) return 'Choose a tab first.';
- final attempt = _consultAttempts.putIfAbsent(
- key,
- () => {
- 'action': 'channel_consult',
- 'tabId': channelTabId,
- 'id': teamOperationId(),
- 'from': {'machineId': machineId, 'agentId': agentId},
- },
- );
- try {
- final result = await _call(attempt);
- if (_disposed) return 'Tab instruction sent.';
- _consultAttempts.remove(key);
- error = null;
- final receipt = (result['consultation'] as Map?)?['receipt'] as Map?;
- _notify();
- return 'Consult tab · ${teamDeliveryLabel(receipt?.cast<String, dynamic>())}';
- } catch (e) {
- if (e is TeamRequestError && !e.uncertain) _consultAttempts.remove(key);
- final message =
- '$e${_consultAttempts.containsKey(key) ? ' Retry consult to check the same instruction.' : ''}';
- if (!_disposed) {
- error = message;
- _notify();
- }
- return message;
- }
- }
-
- Future<void> create() async {
- if (operating) return;
- _createAttempt ??= {
- 'action': 'create',
- 'id': teamOperationId(),
- 'name': newName.trim(),
- 'description': newDescription.trim(),
- 'members': newMembers.values
- .map((m) => Map<String, dynamic>.from(m))
- .toList(),
- };
- operating = true;
- error = null;
- _notify();
- try {
- final result = await _call(_createAttempt!);
- if (_disposed) return;
- final created = result['team'] as Map;
- selectedId = created['id'] as String;
- _epoch++;
- _apply(created);
- _createAttempt = null;
- newMembers.clear();
- loading = false;
- } catch (e) {
- if (e is TeamRequestError && !e.uncertain) _createAttempt = null;
- error =
- '$e${_createAttempt != null ? '\nCheck connection retries this same team.' : ''}';
- } finally {
- operating = false;
- _notify();
- }
- }
-
- Future<void> ask() async {
- if (operating ||
- selectedId == null ||
- (!pendingAsk &&
- (draft.trim().isEmpty ||
- from == null ||
- to == null ||
- from == to))) {
- return;
- }
- final id = selectedId!;
- final attempt = _askAttempts.putIfAbsent(
- id,
- () => {
- 'action': 'ask',
- 'teamId': id,
- 'id': teamOperationId(),
- 'from': from,
- 'to': to,
- 'text': draft.trim(),
- },
- );
- operating = true;
- error = null;
- _notify();
- try {
- final result = await _call(attempt);
- if (_disposed) return;
- if (id == selectedId) {
- selectedExchange = (result['exchange'] as Map)['id'] as String;
- draft = '';
- } else if (_drafts[id] case final saved?) {
- _drafts[id] = (
- text: '',
- from: saved.from,
- to: saved.to,
- exchange: (result['exchange'] as Map)['id'] as String,
- );
- }
- _askAttempts.remove(id);
- await _read();
- } catch (e) {
- if (e is TeamRequestError && !e.uncertain) _askAttempts.remove(id);
- error =
- '$e${_askAttempts.containsKey(id) ? '\nCheck send uses the same question ID.' : ''}';
- } finally {
- operating = false;
- _notify();
- }
- }
-
- Future<void> addMember([Map<String, dynamic>? member]) async {
- if (operating || selectedId == null || (!pendingAdd && member == null)) {
- return;
- }
- final id = selectedId!;
- final attempt = _addAttempts.putIfAbsent(
- id,
- () => {
- 'action': 'add_member',
- 'teamId': id,
- 'member': {...member!, 'id': teamOperationId()},
- },
- );
- operating = true;
- error = null;
- _notify();
- try {
- final result = await _call(attempt);
- if (_disposed) return;
- if (id == selectedId) _apply(result['team']);
- _addAttempts.remove(id);
- } catch (e) {
- if (e is TeamRequestError && !e.uncertain) _addAttempts.remove(id);
- error =
- '$e${_addAttempts.containsKey(id) ? '\nCheck teammate retries this same membership.' : ''}';
- } finally {
- operating = false;
- _notify();
- }
- }
-
- Future<void> act(
- String action, [
- Map<String, dynamic> values = const {},
- ]) async {
- if (operating || selectedId == null) return;
- final id = selectedId;
- operating = true;
- error = null;
- _notify();
- try {
- final result = await _call({'action': action, 'teamId': id, ...values});
- if (!_disposed && id == selectedId) {
- _apply(result['team']);
- await _read();
- }
- } catch (e) {
- error = e.toString();
- } finally {
- operating = false;
- _notify();
- }
- }
-
- @override
- void dispose() {
- _disposed = true;
- _epoch++;
- _timer?.cancel();
- super.dispose();
- }
-}
-
-String teamDeliveryLabel(Map<String, dynamic>? receipt) =>
- switch (receipt?['state']) {
- 'pending' => 'Waiting to deliver',
- 'queued' =>
- receipt?['reason'] == 'team_waiting_draft'
- ? 'Waiting for draft'
- : receipt?['reason'] == 'team_waiting_user'
- ? 'Waiting for user'
- : 'Queued',
- 'submitted' => 'Confirming delivery',
- 'delivered' => 'Delivered',
- 'started' => 'Agent accepted input',
- 'received' => 'Read in inbox',
- 'unknown' => 'Delivery unconfirmed',
- 'rejected' => 'Delivery failed',
- 'cancelled' => 'Notice cancelled',
- _ => 'Not sent',
- };
diff --git a/desktop/lib/teams/team_workspace.dart b/desktop/lib/teams/team_workspace.dart
deleted file mode 100644
index 45b55546c..000000000
--- a/desktop/lib/teams/team_workspace.dart
+++ /dev/null
@@ -1,1522 +0,0 @@
-import 'dart:async';
-import 'dart:math' as math;
-
-import 'package:harness/shared/theme/app_icons.dart';
-import 'package:flutter/material.dart';
-
-import '../shared/theme/app_theme.dart' as grid;
-import '../state/app_state.dart';
-import '../state/harness_sessions.dart';
-import '../widgets/desktop_chrome.dart';
-import '../widgets/terminal_prompt.dart';
-import 'team_controller.dart';
-
-class TeamCandidate {
- const TeamCandidate({
- required this.machineId,
- required this.agentId,
- required this.name,
- required this.machineName,
- required this.engine,
- required this.status,
- required this.available,
- });
- final String machineId, agentId, name, machineName, engine, status;
- final bool available;
- String get key => '$machineId/$agentId';
-}
-
-Future<void> showChannelWorkspace(BuildContext context, AppNotifier app) async {
- final tabId = app.activeSwarmId;
- final gateway = app.channelGateway(app.focusedPane?.machineId);
- if (gateway == null) return;
- final controller = app.channelController(tabId, gateway);
- await showTerminalPrompt<void>(
- context,
- builder: (context) => TeamWorkspace(
- controller: controller,
- candidates: const [],
- machineName: app.activeSwarm.name,
- onClose: () => Navigator.pop(context),
- onOpen: (machine, agent) {
- Navigator.pop(context);
- unawaited(
- app.openAgentFromDial(machine, agent, intent: AttachIntent.person),
- );
- },
- ),
- );
-}
-
-Future<void> showTeamWorkspace(BuildContext context, AppNotifier app) async {
- var machineId =
- app.localMachineState?.machine.machineId ??
- app.focusedPane?.machineId ??
- app.machineStates.keys.firstOrNull;
- if (machineId == null) return;
- await showTerminalPrompt<void>(
- context,
- builder: (context) => StatefulBuilder(
- builder: (context, setHost) => ListenableBuilder(
- listenable: app,
- builder: (context, _) => TeamWorkspace(
- key: ValueKey(machineId),
- controller: app.teamController(machineId!),
- machineName:
- app.stateOf(machineId!)?.machine.displayName ?? 'This machine',
- onChooseHost: () async {
- final host = await showTerminalPrompt<String>(
- context,
- builder: (context) => _TeamChoice(
- title: 'Teams live on this machine',
- choices: [
- for (final state in app.machineStates.values)
- if (!state.machine.isShared)
- (
- id: state.machine.machineId,
- label: state.machine.displayName,
- detail: state.machine.machineId == machineId
- ? 'selected'
- : '',
- ),
- ],
- ),
- );
- if (context.mounted && host != null) {
- setHost(() => machineId = host);
- }
- },
- candidates: [
- for (final row in harnessSessions(app))
- if (!row.machine.machine.isShared &&
- row.agent.engine != 'terminal')
- TeamCandidate(
- machineId: row.machineId,
- agentId: row.agent.id,
- name: row.agent.displayName,
- machineName: row.machine.machine.displayName,
- engine: row.agent.engine ?? 'Agent',
- status: row.status,
- available: row.online,
- ),
- ],
- onClose: () => Navigator.pop(context),
- onOpen: (machine, agent) {
- Navigator.pop(context);
- unawaited(
- app.openAgentFromDial(
- machine,
- agent,
- intent: AttachIntent.person,
- ),
- );
- },
- ),
- ),
- ),
- );
-}
-
-/// Team roster, conversations, and question composer. No terminal is
-/// attached or written by mounting, searching, selecting, or closing this surface.
-class TeamWorkspace extends StatefulWidget {
- const TeamWorkspace({
- super.key,
- required this.controller,
- required this.candidates,
- required this.machineName,
- required this.onClose,
- required this.onOpen,
- this.onChooseHost,
- });
- final TeamController controller;
- final List<TeamCandidate> candidates;
- final String machineName;
- final VoidCallback onClose;
- final void Function(String machineId, String agentId) onOpen;
- final VoidCallback? onChooseHost;
- @override
- State<TeamWorkspace> createState() => _TeamWorkspaceState();
-}
-
-class _TeamWorkspaceState extends State<TeamWorkspace> {
- TeamController get model => widget.controller;
- final _search = TextEditingController();
- late final _name = TextEditingController(text: model.newName);
- late final _description = TextEditingController(text: model.newDescription);
- late final _question = TextEditingController(text: model.draft);
- final _questionFocus = FocusNode(debugLabel: 'Team question');
- final _compactScroll = ScrollController();
- final _exchangeScroll = ScrollController();
- final _conversationScroll = ScrollController();
- final _rosterScroll = ScrollController();
- ScrollController? _activeScroll;
- bool _creating = false;
- String? _selectedMember;
- TextStyle get style => DesktopChrome.text(size: 13);
- TextStyle get faint => DesktopChrome.metadata();
- @override
- void initState() {
- super.initState();
- model.addListener(_changed);
- model.watch();
- _creating = model.pendingCreate;
- }
-
- void _changed() {
- if (!mounted) return;
- if (_question.text != model.draft) {
- _question.value = TextEditingValue(
- text: model.draft,
- selection: TextSelection.collapsed(offset: model.draft.length),
- );
- }
- if (model.selectedId != null) _creating = false;
- setState(() {});
- }
-
- @override
- void dispose() {
- model.removeListener(_changed);
- model.unwatch();
- _search.dispose();
- _name.dispose();
- _description.dispose();
- _question.dispose();
- _questionFocus.dispose();
- _compactScroll.dispose();
- _exchangeScroll.dispose();
- _conversationScroll.dispose();
- _rosterScroll.dispose();
- super.dispose();
- }
-
- void _page(int direction) {
- final focusedContext = FocusManager.instance.primaryFocus?.context;
- final focusedScroll = focusedContext == null
- ? null
- : Scrollable.maybeOf(focusedContext, axis: Axis.vertical)?.position;
- final scroll = _activeScroll?.hasClients == true
- ? _activeScroll
- : _compactScroll.hasClients
- ? _compactScroll
- : _conversationScroll.hasClients
- ? _conversationScroll
- : null;
- final position = focusedScroll ?? scroll?.position;
- if (position == null) return;
- position.jumpTo(
- (position.pixels + direction * position.viewportDimension * .9).clamp(
- 0,
- position.maxScrollExtent,
- ),
- );
- }
-
- Widget _scrollRegion(ScrollController controller, Widget child) => Focus(
- skipTraversal: true,
- onFocusChange: (focused) {
- if (focused) _activeScroll = controller;
- },
- child: child,
- );
-
- Widget _line(
- String label,
- VoidCallback? action, {
- String? trailing,
- String? detail,
- bool? checked,
- bool selected = false,
- Key? key,
- String? semantics,
- }) => _TeamRow(
- key: key,
- label: label,
- detail: detail,
- trailing: trailing,
- selected: selected,
- checked: checked,
- semanticLabel: semantics,
- onPressed: action,
- );
-
- InputDecoration _fieldDecoration(String label) {
- final border = OutlineInputBorder(
- borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
- borderSide: BorderSide(color: DesktopChrome.rim, width: 1.5),
- );
- return InputDecoration(
- labelText: label,
- labelStyle: faint,
- hintStyle: faint,
- filled: true,
- fillColor: DesktopChrome.field,
- isDense: true,
- contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
- border: border,
- enabledBorder: border,
- focusedBorder: border.copyWith(
- borderSide: BorderSide(color: DesktopChrome.focusRing, width: 1.5),
- ),
- );
- }
-
- Widget _field(
- TextEditingController text,
- String label, {
- Key? key,
- int lines = 1,
- bool readOnly = false,
- FocusNode? focus,
- ValueChanged<String>? changed,
- }) => TextField(
- key: key,
- controller: text,
- focusNode: focus,
- readOnly: readOnly,
- minLines: lines,
- maxLines: lines == 1 ? 1 : lines + 3,
- style: style,
- cursorWidth: 2,
- decoration: _fieldDecoration(label),
- onChanged: changed,
- );
- Widget _action(String label, VoidCallback? callback, {Key? key}) =>
- DesktopPill(key: key, label: label, onPressed: callback);
- Widget _gap([double groups = 1]) =>
- SizedBox(height: DesktopChrome.groupGap * groups);
- String _memberName(String? id) {
- final member = model.members.where((m) => m['id'] == id).firstOrNull;
- final runtime = member?['runtime'] as Map?;
- if (model.isChannel && runtime?['name'] is String) {
- return runtime!['name'] as String;
- }
- return member?['name'] as String? ?? 'Choose';
- }
-
- Future<void> _choose(bool source) async {
- final choices = model.members
- .where(
- (m) => m['enabled'] != false && (source || m['id'] != model.from),
- )
- .toList();
- final chosen = await showTerminalPrompt<String>(
- context,
- builder: (context) => _TeamChoice(
- title: source ? 'Ask on behalf of' : 'Ask a teammate',
- choices: [
- for (final m in choices)
- (
- id: m['id'] as String,
- label: '@${m['name']}',
- detail: m['role'] as String? ?? '',
- ),
- ],
- ),
- );
- if (!mounted || chosen == null) return;
- setState(() {
- if (source) {
- model.from = chosen;
- if (model.to == chosen) model.to = null;
- } else {
- model.to = chosen;
- }
- });
- _questionFocus.requestFocus();
- }
-
- void _toggle(TeamCandidate candidate) {
- if (model.pendingCreate || model.operating || !candidate.available) return;
- setState(() {
- if (model.newMembers.remove(candidate.key) != null) return;
- var alias = candidate.name
- .toLowerCase()
- .replaceAll(RegExp('[^a-z0-9_-]+'), '-')
- .replaceAll(RegExp(r'^-+|-+$'), '');
- if (alias.isEmpty) alias = 'teammate';
- if (alias.length > 32) alias = alias.substring(0, 32);
- final base = alias;
- var n = 2;
- while (model.newMembers.values.any((m) => m['name'] == alias)) {
- alias = '$base-${n++}';
- }
- model.newMembers[candidate.key] = {
- 'machineId': candidate.machineId,
- 'agentId': candidate.agentId,
- 'name': alias,
- 'role': candidate.name,
- };
- });
- }
-
- Widget _home() => Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text('Connect the harnesses already doing your work.', style: style),
- _gap(),
- Text(
- 'Give each teammate a role. Questions and answers travel between their existing harnesses, across engines and machines.',
- style: faint,
- ),
- _gap(),
- Align(
- alignment: Alignment.centerLeft,
- child: _action(
- 'New team',
- () => setState(() => _creating = true),
- key: const Key('team-new'),
- ),
- ),
- _gap(2),
- Text('Your teams · ${widget.machineName}', style: faint),
- if (widget.onChooseHost != null)
- Align(
- alignment: Alignment.centerLeft,
- child: _action(
- 'Choose machine',
- model.operating ? null : widget.onChooseHost,
- ),
- ),
- _gap(),
- Expanded(
- child: model.loading
- ? _loadingRows()
- : model.teams.isEmpty
- ? Text('No teams yet. Start with two harnesses.', style: faint)
- : ListView(
- children: [
- for (final team in model.teams)
- _line(
- team['name'] as String,
- () => unawaited(model.select(team['id'] as String)),
- trailing: '${team['members']} peers · ${team['state']}',
- key: ValueKey('team-open-${team['id']}'),
- ),
- ],
- ),
- ),
- ],
- );
- Widget _loadingRows() => SingleChildScrollView(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- for (var i = 0; i < 4; i++)
- Padding(
- padding: const EdgeInsets.only(bottom: 16),
- child: ColoredBox(
- color: DesktopChrome.muted.withValues(alpha: .12),
- child: SizedBox(width: 192 - i * 24, height: 16),
- ),
- ),
- ],
- ),
- );
- Widget _create() {
- final query = _search.text.toLowerCase();
- final candidates = widget.candidates
- .where(
- (c) => '${c.name} ${c.engine} ${c.machineName}'
- .toLowerCase()
- .contains(query),
- )
- .toList();
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _field(
- _name,
- 'Team name',
- key: const Key('team-name'),
- readOnly: model.pendingCreate,
- changed: (v) {
- model.newName = v;
- setState(() {});
- },
- ),
- _gap(),
- _field(
- _description,
- 'What are you building together?',
- readOnly: model.pendingCreate,
- changed: (v) => model.newDescription = v,
- ),
- _gap(.5),
- _field(
- _search,
- 'Find a harness',
- key: const Key('team-search'),
- changed: (_) => setState(() {}),
- ),
- _gap(.5),
- Text(
- '${model.newMembers.length} selected · Connect introduces the team to these harnesses.',
- style: faint,
- ),
- _gap(),
- Expanded(
- child: ListView(
- key: const Key('team-candidates'),
- children: [
- if (candidates.isEmpty)
- Text('No matching harnesses.', style: faint),
- for (final candidate in candidates) ...[
- _line(
- candidate.name,
- model.pendingCreate || !candidate.available
- ? null
- : () => _toggle(candidate),
- trailing:
- '${candidate.engine} · ${candidate.available ? candidate.machineName : candidate.status}',
- key: ValueKey('team-candidate-${candidate.agentId}'),
- checked: model.newMembers.containsKey(candidate.key),
- semantics:
- '${candidate.name}, ${candidate.engine}, ${candidate.status}',
- ),
- if (model.newMembers[candidate.key] case final member?)
- Padding(
- padding: const EdgeInsets.fromLTRB(36, 8, 0, 16),
- child: LayoutBuilder(
- builder: (context, constraints) {
- final name = TextFormField(
- key: ValueKey('team-alias-${candidate.agentId}'),
- initialValue: member['name'] as String,
- readOnly: model.pendingCreate,
- style: style,
- decoration: _fieldDecoration('Team name'),
- onChanged: (v) => member['name'] = v,
- );
- final role = TextFormField(
- key: ValueKey('team-role-${candidate.agentId}'),
- initialValue: member['role'] as String,
- readOnly: model.pendingCreate,
- style: style,
- decoration: _fieldDecoration('Knows about'),
- onChanged: (v) => member['role'] = v,
- );
- return constraints.maxWidth < 440
- ? Column(children: [name, _gap(), role])
- : Row(
- children: [
- SizedBox(width: 176, child: name),
- const SizedBox(width: 16),
- Expanded(child: role),
- ],
- );
- },
- ),
- ),
- ],
- ],
- ),
- ),
- _gap(),
- Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- _action(
- model.pendingCreate ? 'Check connection' : 'Connect teammates',
- model.operating ||
- (!model.pendingCreate &&
- (model.newMembers.length < 2 ||
- model.newName.trim().isEmpty))
- ? null
- : () => unawaited(model.create()),
- key: const Key('team-connect'),
- ),
- _action(
- 'Back',
- model.operating ? null : () => setState(() => _creating = false),
- ),
- ],
- ),
- ],
- );
- }
-
- Widget _roster() {
- final selected = model.members
- .where((m) => m['id'] == _selectedMember)
- .firstOrNull;
- return _scrollRegion(
- _rosterScroll,
- ListView(
- controller: _rosterScroll,
- children: [
- Text(
- model.isChannel ? 'Agents in this tab' : 'Teammates',
- style: DesktopChrome.control(medium: true),
- ),
- _gap(.5),
- for (final member in model.members)
- _line(
- model.isChannel
- ? _memberName(member['id'] as String?)
- : '@${member['name']}',
- () => setState(() => _selectedMember = member['id'] as String),
- selected: _selectedMember == member['id'],
- trailing: member['enabled'] == false
- ? 'Removed'
- : (member['runtime'] as Map?)?['engine'] as String? ??
- 'Offline',
- key: ValueKey('team-member-${member['id']}'),
- ),
- if (selected != null) ...[
- _gap(),
- Text(selected['role'] as String? ?? '', style: faint),
- _gap(),
- Text(
- selected['enabled'] == false
- ? 'Removed from team'
- : (selected['runtime'] as Map?)?['available'] == true
- ? 'Available'
- : 'Offline · questions wait here',
- style: faint,
- ),
- _gap(),
- _action(
- 'Open session',
- () => widget.onOpen(
- selected['machineId'] as String,
- selected['agentId'] as String,
- ),
- ),
- if (!model.isChannel) _gap(.5),
- if (!model.isChannel)
- _action(
- 'Edit teammate',
- model.operating ? null : () => _editMember(selected),
- ),
- ],
- _gap(2),
- if (!model.isChannel)
- Align(
- alignment: Alignment.centerLeft,
- child: _action(
- 'Ask teammate',
- model.active
- ? () {
- setState(() {
- model.selectedExchange = null;
- if (selected?['enabled'] != false &&
- selected?['id'] != model.from &&
- selected != null) {
- model.to = selected['id'] as String;
- }
- });
- _questionFocus.requestFocus();
- }
- : null,
- key: const Key('team-new-question'),
- ),
- ),
- ],
- ),
- );
- }
-
- Future<void> _addMember() async {
- if (model.pendingAdd) {
- await model.addMember();
- return;
- }
- final candidates = widget.candidates
- .where(
- (candidate) =>
- candidate.available &&
- !model.members.any(
- (m) =>
- m['enabled'] != false &&
- m['machineId'] == candidate.machineId &&
- m['agentId'] == candidate.agentId,
- ),
- )
- .toList();
- final chosen = await showTerminalPrompt<String>(
- context,
- builder: (context) => _TeamChoice(
- title: candidates.isEmpty
- ? 'No additional harnesses available'
- : 'Connect an existing harness',
- choices: [
- for (final c in candidates)
- (
- id: c.key,
- label: c.name,
- detail: '${c.engine} · ${c.machineName}',
- ),
- ],
- ),
- );
- if (!mounted || chosen == null) return;
- final candidate = candidates.firstWhere((c) => c.key == chosen);
- var alias = candidate.name
- .replaceAll(RegExp(r'[^a-zA-Z0-9_-]+'), '-')
- .replaceAll(RegExp(r'^-+|-+$'), '');
- if (alias.isEmpty) alias = 'teammate';
- alias = alias.substring(0, math.min(alias.length, 32));
- final base = alias;
- var suffix = 2;
- while (model.members.any(
- (m) =>
- m['enabled'] != false &&
- m['name'].toString().toLowerCase() == alias.toLowerCase(),
- )) {
- alias = '$base-${suffix++}';
- }
- await _editMember({
- 'machineId': candidate.machineId,
- 'agentId': candidate.agentId,
- 'name': alias,
- 'role': candidate.name,
- }, adding: true);
- }
-
- Future<void> _editMember(
- Map<String, dynamic> member, {
- bool adding = false,
- }) async {
- final name = TextEditingController(text: member['name'] as String);
- final role = TextEditingController(text: member['role'] as String? ?? '');
- final result = await showTerminalPrompt<String>(
- context,
- builder: (context) => TerminalPromptKeys(
- cancel: () => Navigator.pop(context),
- child: _TeamSurface(
- width: 620,
- child: SingleChildScrollView(
- padding: const EdgeInsets.all(24),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- adding ? 'Connect teammate' : 'Edit teammate',
- style: DesktopChrome.heading(),
- ),
- _gap(),
- _field(name, 'Team name'),
- _gap(),
- _field(role, 'Knows about'),
- _gap(),
- Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- _action(
- adding ? 'Connect' : 'Save',
- model.team?['state'] == 'archived'
- ? null
- : () => Navigator.pop(context, 'save'),
- ),
- if (!adding)
- _action(
- 'Open harness',
- () => Navigator.pop(context, 'open'),
- ),
- if (!adding &&
- member['enabled'] != false &&
- model.team?['state'] != 'archived')
- _action(
- 'Remove from team',
- () => Navigator.pop(context, 'remove'),
- ),
- _action('Back', () => Navigator.pop(context)),
- ],
- ),
- ],
- ),
- ),
- ),
- ),
- );
- if (mounted && result != null) {
- if (result == 'open') {
- widget.onOpen(
- member['machineId'] as String,
- member['agentId'] as String,
- );
- } else if (adding) {
- await model.addMember({
- ...member,
- 'name': name.text.trim(),
- 'role': role.text.trim(),
- });
- } else {
- await model.act('member', {
- 'member': {
- 'id': member['id'],
- 'name': name.text.trim(),
- 'role': role.text.trim(),
- 'enabled': result != 'remove' && member['enabled'] != false,
- },
- });
- }
- }
- name.dispose();
- role.dispose();
- }
-
- Widget _composer() => SingleChildScrollView(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text('Ask a teammate', style: style),
- _gap(),
- Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- _action(
- 'From @${_memberName(model.from)}',
- model.pendingAsk ? null : () => _choose(true),
- ),
- _action(
- 'To @${_memberName(model.to)}',
- model.pendingAsk ? null : () => _choose(false),
- ),
- ],
- ),
- _gap(),
- _field(
- _question,
- 'What do you need to know?',
- key: const Key('team-question'),
- lines: 3,
- readOnly: model.pendingAsk,
- focus: _questionFocus,
- changed: (v) {
- model.draft = v;
- setState(() {});
- },
- ),
- _gap(),
- Text(
- 'The answer returns to @${_memberName(model.from)} so it can continue. The exchange records that you initiated this question.',
- style: faint,
- ),
- _gap(),
- Align(
- alignment: Alignment.centerLeft,
- child: _action(
- model.pendingAsk ? 'Check send' : 'Ask',
- model.operating ||
- !model.active ||
- (!model.pendingAsk &&
- (model.draft.trim().isEmpty ||
- model.to == null ||
- model.from == model.to))
- ? null
- : () => unawaited(model.ask()),
- key: const Key('team-ask'),
- ),
- ),
- ],
- ),
- );
- Widget _conversation(
- Map<String, dynamic> exchange, {
- bool scrollable = true,
- }) {
- final answer = (exchange['answer'] as Map?)?.cast<String, dynamic>();
- final from =
- model.members.where((m) => m['id'] == exchange['from']).firstOrNull ??
- (exchange['fromPeer'] as Map?)?.cast<String, dynamic>();
- final to =
- model.members.where((m) => m['id'] == exchange['to']).firstOrNull ??
- (exchange['toPeer'] as Map?)?.cast<String, dynamic>();
- final fromName =
- (exchange['fromPeer'] as Map?)?['name'] ??
- _memberName(exchange['from'] as String?);
- final toName =
- (exchange['toPeer'] as Map?)?['name'] ??
- _memberName(exchange['to'] as String?);
- final content = Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- model.isChannel
- ? '$fromName → $toName'
- : '@${from?['name']} → @${to?['name']}',
- style: style,
- ),
- Text(
- '${exchange['origin'] == 'owner' ? 'Requested by you' : 'Agent question'} · ${exchange['state']} · ${teamDeliveryLabel((exchange['delivery'] as Map?)?.cast<String, dynamic>())}',
- style: faint,
- ),
- _gap(),
- SelectableText(exchange['text'] as String? ?? '', style: style),
- if ((exchange['context'] as String? ?? '').isNotEmpty) ...[
- _gap(),
- SelectableText(exchange['context'] as String, style: faint),
- ],
- _gap(),
- if (answer != null) ...[
- Text(
- '${answer['late'] == true ? 'Late answer' : 'Answer'} ${answer['origin'] == 'owner' ? 'supplied by you for' : 'from'} @${to?['name']}',
- style: faint,
- ),
- _gap(.5),
- SelectableText(answer['text'] as String, style: style),
- for (final reference in answer['evidence'] as List? ?? [])
- Padding(
- padding: const EdgeInsets.only(top: 8),
- child: SelectableText(reference.toString(), style: faint),
- ),
- _gap(),
- Text(
- answer['late'] == true
- ? 'Retained for reference. No automatic continuation.'
- : 'Return to @${from?['name']}: ${teamDeliveryLabel((exchange['continuation'] as Map?)?.cast<String, dynamic>())}',
- style: faint,
- ),
- ] else
- Text(
- exchange['state'] == 'pending'
- ? 'Waiting for a correlated answer. Delivery alone does not mean the question is answered.'
- : 'This question is ${exchange['state']}.',
- style: faint,
- ),
- if ((exchange['delivery'] as Map?)?['reason']
- case final String reason) ...[
- _gap(.5),
- Text(reason, style: faint),
- ],
- _gap(),
- Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- if (from != null)
- _action(
- 'Open @${from['name']}',
- () => widget.onOpen(
- from['machineId'] as String,
- from['agentId'] as String,
- ),
- ),
- if (to != null)
- _action(
- 'Open @${to['name']}',
- () => widget.onOpen(
- to['machineId'] as String,
- to['agentId'] as String,
- ),
- ),
- if (exchange['state'] == 'pending')
- _action(
- 'Cancel question',
- model.operating
- ? null
- : () => unawaited(
- model.act('cancel', {
- 'questionId':
- exchange['questionId'] ?? exchange['id'],
- if (exchange['teamId'] != null)
- 'teamId': exchange['teamId'],
- }),
- ),
- ),
- ],
- ),
- ],
- );
- return scrollable
- ? _scrollRegion(
- _conversationScroll,
- SingleChildScrollView(
- controller: _conversationScroll,
- child: content,
- ),
- )
- : content;
- }
-
- Widget _selectedConversation({bool scrollable = true}) {
- final selected = model.exchanges
- .where((e) => e['id'] == model.selectedExchange)
- .firstOrNull;
- if (selected != null) {
- return _conversation(selected, scrollable: scrollable);
- }
- if (!model.isChannel) return _composer();
- final content = Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- 'Agents consult relevant peers in this tab and continue their work.',
- style: style,
- ),
- _gap(),
- Text('Add another agent pane to include it in this tab.', style: faint),
- for (final instruction in teamRows(
- model.team?['consultations'],
- ).reversed.take(5)) ...[
- _gap(),
- Text(
- 'Consult requested for ${_memberName(instruction['memberId'] as String?)} · ${teamDeliveryLabel((instruction['receipt'] as Map?)?.cast<String, dynamic>())}',
- style: faint,
- ),
- ],
- ],
- );
- return scrollable
- ? _scrollRegion(
- _conversationScroll,
- SingleChildScrollView(
- controller: _conversationScroll,
- child: content,
- ),
- )
- : content;
- }
-
- Widget _exchangeList() => _scrollRegion(
- _exchangeScroll,
- ListView(
- key: const ValueKey('team-exchanges'),
- controller: _exchangeScroll,
- shrinkWrap: true,
- children: [
- for (final exchange in model.exchanges)
- _line(
- '${(exchange['fromPeer'] as Map?)?['name'] ?? _memberName(exchange['from'] as String?)} → ${(exchange['toPeer'] as Map?)?['name'] ?? _memberName(exchange['to'] as String?)}',
- () => setState(
- () => model.selectedExchange = exchange['id'] as String,
- ),
- detail: exchange['text'] as String? ?? '',
- selected: model.selectedExchange == exchange['id'],
- trailing: exchange['state'] as String,
- key: ValueKey('team-exchange-${exchange['id']}'),
- ),
- ],
- ),
- );
-
- Widget _exchanges() => LayoutBuilder(
- builder: (context, constraints) => Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text('Exchanges', style: DesktopChrome.control(medium: true)),
- _gap(.5),
- if (model.exchanges.isEmpty)
- Text('Questions and answers will appear here.', style: faint)
- else
- ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight: math.min(224, constraints.maxHeight * .38),
- ),
- child: _exchangeList(),
- ),
- _gap(),
- Expanded(child: _selectedConversation()),
- ],
- ),
- );
-
- Widget _summary() => Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (model.selectedId != null && !_creating) ...[
- Text(
- '${model.isChannel ? 'Tab conversation · ' : ''}${model.members.where((m) => m['enabled'] != false).length} agents · ${model.isChannel ? 'This tab only · ' : ''}${model.team?['state'] ?? 'Connecting'}',
- style: faint,
- ),
- _gap(.5),
- Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- if (!model.isChannel)
- _action(
- 'All teams',
- model.operating ? null : () => unawaited(model.select(null)),
- ),
- if (model.team?['state'] != 'archived')
- _action(
- model.active ? 'Pause collaboration' : 'Resume collaboration',
- model.operating || model.team == null
- ? null
- : () => unawaited(
- model.act(model.active ? 'pause' : 'resume'),
- ),
- ),
- if (!model.isChannel && model.team?['state'] != 'archived')
- _action(
- model.pendingAdd ? 'Check teammate' : 'Add teammate',
- model.operating ? null : _addMember,
- ),
- if (!model.isChannel)
- _action(
- 'New question',
- model.active
- ? () => setState(() {
- model.selectedExchange = null;
- _questionFocus.requestFocus();
- })
- : null,
- key: const Key('team-compose'),
- ),
- if (!model.isChannel && model.team?['state'] == 'paused')
- _action(
- 'Archive paused team',
- model.operating ? null : () => unawaited(model.act('archive')),
- ),
- ],
- ),
- _gap(),
- ],
- if (model.error case final message?) ...[
- Semantics(
- liveRegion: true,
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxHeight: 160),
- child: SingleChildScrollView(
- child: SelectableText(
- message,
- style: DesktopChrome.text(
- size: 13,
- color: Theme.of(context).colorScheme.error,
- ),
- ),
- ),
- ),
- ),
- _gap(),
- ],
- ],
- );
-
- Widget _detail() {
- if (model.team == null) {
- return SingleChildScrollView(
- controller: _compactScroll,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- _summary(),
- if (model.loading)
- _loadingRows()
- else
- _action(
- model.isChannel ? 'Retry reading tab' : 'Retry reading team',
- () => unawaited(model.refresh()),
- ),
- ],
- ),
- );
- }
- return LayoutBuilder(
- builder: (context, constraints) {
- final scale = grid.appTextScaleOf(context);
- if (constraints.maxWidth < 760 * scale ||
- constraints.maxHeight < 420 * scale) {
- return _scrollRegion(
- _compactScroll,
- SingleChildScrollView(
- key: const ValueKey('team-compact-content'),
- controller: _compactScroll,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _summary(),
- Text(
- model.isChannel ? 'Agents in this tab' : 'Teammates',
- style: DesktopChrome.control(medium: true),
- ),
- _gap(.5),
- SizedBox(
- height: math.max(
- 36,
- MediaQuery.textScalerOf(context).scale(19) + 16,
- ),
- child: ListView(
- scrollDirection: Axis.horizontal,
- children: [
- for (final member in model.members)
- Padding(
- padding: const EdgeInsets.only(right: 8),
- child: _action(
- model.isChannel
- ? _memberName(member['id'] as String?)
- : '${member['name']}',
- () => model.isChannel
- ? widget.onOpen(
- member['machineId'] as String,
- member['agentId'] as String,
- )
- : _editMember(member),
- ),
- ),
- ],
- ),
- ),
- _gap(),
- Text('Exchanges', style: DesktopChrome.control(medium: true)),
- _gap(.5),
- if (model.exchanges.isEmpty)
- Text(
- 'Questions and answers will appear here.',
- style: faint,
- )
- else
- ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight: math.min(224, constraints.maxHeight * .45),
- ),
- child: _exchangeList(),
- ),
- _gap(),
- _selectedConversation(scrollable: false),
- ],
- ),
- ),
- );
- }
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _summary(),
- Expanded(
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- SizedBox(width: 240, child: _roster()),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: VerticalDivider(width: 1, color: DesktopChrome.rim),
- ),
- Expanded(child: _exchanges()),
- ],
- ),
- ),
- ],
- );
- },
- );
- }
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final short =
- MediaQuery.sizeOf(context).height < 520 * grid.appTextScaleOf(context);
- final title = _creating
- ? 'Connect a team'
- : model.team?['name'] as String? ??
- (model.isChannel ? 'Tab conversation' : 'Team');
- final hint =
- '${terminalPromptHint(context, 'picker.complete', 'Tab')} move · ${terminalPromptHint(context, 'picker.cancel', 'Esc')} close · conversations stay with the ${model.isChannel ? 'tab' : 'team'}';
- return TerminalPromptKeys(
- cancel: widget.onClose,
- refresh: () => unawaited(model.refresh()),
- submit: model.isChannel ? null : () => unawaited(model.ask()),
- pageDown: () => _page(1),
- pageUp: () => _page(-1),
- child: _TeamSurface(
- width: 1140,
- child: SizedBox(
- height: 680,
- child: Padding(
- padding: EdgeInsets.all(short ? 16 : 24),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Row(
- children: [
- Expanded(
- child: Tooltip(
- message: title,
- child: Text(
- title,
- style: DesktopChrome.heading(),
- maxLines: short ? 1 : 2,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- ),
- const SizedBox(width: 8),
- IconButton(
- key: const ValueKey('team-close'),
- tooltip: 'Close conversation',
- onPressed: widget.onClose,
- icon: const Icon(AppIcons.close, size: 18),
- ),
- ],
- ),
- _gap(short ? .5 : 1),
- Expanded(
- child:
- _creating ||
- (model.selectedId == null && !model.isChannel)
- ? Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _summary(),
- Expanded(child: _creating ? _create() : _home()),
- ],
- )
- : _detail(),
- ),
- if (!short) ...[
- _gap(),
- Tooltip(
- message: hint,
- child: Text(
- hint,
- style: faint,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- ],
- ],
- ),
- ),
- ),
- ),
- );
- }
-}
-
-class _TeamSurface extends StatelessWidget {
- const _TeamSurface({required this.child, required this.width});
- final Widget child;
- final double width;
- @override
- Widget build(BuildContext context) => DesktopChrome(
- child: Dialog(
- elevation: 0,
- insetPadding: const EdgeInsets.all(16),
- backgroundColor: Colors.transparent,
- child: SizedBox(
- width: width,
- child: DesktopDialogSurface(child: child),
- ),
- ),
- );
-}
-
-class _TeamRow extends StatelessWidget {
- const _TeamRow({
- super.key,
- required this.label,
- required this.onPressed,
- this.detail,
- this.trailing,
- this.selected = false,
- this.checked,
- this.semanticLabel,
- });
- final String label;
- final String? detail, trailing, semanticLabel;
- final VoidCallback? onPressed;
- final bool selected;
- final bool? checked;
-
- @override
- Widget build(BuildContext context) {
- final highContrast = MediaQuery.highContrastOf(context);
- return Semantics(
- selected: selected,
- checked: checked,
- label: semanticLabel,
- child: TextButton(
- onPressed: onPressed,
- style:
- TextButton.styleFrom(
- foregroundColor: DesktopChrome.foreground,
- disabledForegroundColor: DesktopChrome.muted,
- backgroundColor: selected
- ? DesktopChrome.selection
- : Colors.transparent,
- minimumSize: const Size(0, 32),
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
- textStyle: DesktopChrome.control(),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(
- DesktopChrome.controlRadius,
- ),
- ),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- splashFactory: NoSplash.splashFactory,
- ).copyWith(
- side: WidgetStateProperty.resolveWith(
- (states) => BorderSide(
- width: 1.5,
- color: states.contains(WidgetState.focused)
- ? (highContrast
- ? DesktopChrome.accent
- : DesktopChrome.focusRing)
- : Colors.transparent,
- ),
- ),
- overlayColor: WidgetStateProperty.resolveWith(
- (states) => states.contains(WidgetState.disabled)
- ? Colors.transparent
- : states.contains(WidgetState.pressed)
- ? DesktopChrome.foreground.withValues(alpha: .12)
- : states.contains(WidgetState.hovered)
- ? DesktopChrome.foreground.withValues(alpha: .06)
- : Colors.transparent,
- ),
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- if (checked != null) ...[
- ExcludeSemantics(
- child: ExcludeFocus(
- child: IgnorePointer(
- child: SizedBox(
- width: 20,
- height: 20,
- child: Checkbox(
- value: checked,
- onChanged: onPressed == null ? null : (_) {},
- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- ),
- ),
- const SizedBox(width: 8),
- ],
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Tooltip(
- message: label,
- child: Text(
- label,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.control(medium: true),
- ),
- ),
- if (detail != null && detail!.isNotEmpty) ...[
- const SizedBox(height: 4),
- Text(
- detail!,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.text(
- size: 13,
- color: DesktopChrome.muted,
- ),
- ),
- ],
- if (trailing != null && trailing!.isNotEmpty) ...[
- const SizedBox(height: 4),
- Text(trailing!, style: DesktopChrome.metadata()),
- ],
- ],
- ),
- ),
- ],
- ),
- ),
- );
- }
-}
-
-class _TeamChoice extends StatefulWidget {
- const _TeamChoice({required this.title, required this.choices});
- final String title;
- final List<({String id, String label, String detail})> choices;
- @override
- State<_TeamChoice> createState() => _TeamChoiceState();
-}
-
-class _TeamChoiceState extends State<_TeamChoice> {
- int _index = 0;
- final _scroll = ScrollController();
- final _rows = <String, GlobalKey>{};
- @override
- void dispose() {
- _scroll.dispose();
- super.dispose();
- }
-
- void _move(int delta) {
- setState(
- () => _index = (_index + delta).clamp(
- 0,
- math.max(0, widget.choices.length - 1),
- ),
- );
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted || widget.choices.isEmpty) return;
- final row = _rows[widget.choices[_index].id]?.currentContext;
- if (row != null) Scrollable.ensureVisible(row);
- });
- }
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- return TerminalPromptKeys(
- cancel: () => Navigator.pop(context),
- previous: () => _move(-1),
- next: () => _move(1),
- accept: () {
- if (widget.choices.isNotEmpty) {
- Navigator.pop(context, widget.choices[_index].id);
- }
- },
- child: _TeamSurface(
- width: 480,
- child: Padding(
- padding: const EdgeInsets.all(24),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Row(
- children: [
- Expanded(
- child: Text(widget.title, style: DesktopChrome.heading()),
- ),
- const SizedBox(width: 8),
- IconButton(
- tooltip: 'Close chooser',
- onPressed: () => Navigator.pop(context),
- icon: const Icon(AppIcons.close, size: 18),
- ),
- ],
- ),
- const SizedBox(height: 16),
- Flexible(
- child: SingleChildScrollView(
- controller: _scroll,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- for (var i = 0; i < widget.choices.length; i++)
- _TeamRow(
- key: _rows.putIfAbsent(
- widget.choices[i].id,
- GlobalKey.new,
- ),
- label: widget.choices[i].label,
- detail: widget.choices[i].detail,
- selected: i == _index,
- onPressed: () =>
- Navigator.pop(context, widget.choices[i].id),
- ),
- ],
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
-}
diff --git a/desktop/lib/widgets/desktop_workspace_tab.dart b/desktop/lib/widgets/desktop_workspace_tab.dart
index 3b4435dcc..d6a157525 100644
--- a/desktop/lib/widgets/desktop_workspace_tab.dart
+++ b/desktop/lib/widgets/desktop_workspace_tab.dart
@@ -4,13 +4,18 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
+import '../agent_messages/agent_messages.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import 'box_chrome.dart';
import 'desktop_chrome.dart';
/// The Flutter counterpart of the AppKit tab: a centered name/status group
-/// and a trailing hover close action. Command replaces status with its hint.
+/// and, at its trailing edge, Agent Messages' ⇄ and the close action.
+///
+/// One revealed state: hovering the tab, or holding Command (every tab).
+/// Revealed, the shortcut replaces the status and ⇄ and × both show; at rest
+/// only a tab whose agents are messaging keeps its ⇄, bright.
class DesktopWorkspaceTab extends StatefulWidget {
const DesktopWorkspaceTab({
super.key,
@@ -26,6 +31,8 @@ class DesktopWorkspaceTab extends StatefulWidget {
this.activityLabel,
this.highlighted = false,
this.onRename,
+ this.agentMessages,
+ this.onToggleAgentMessages,
});
final String id, label;
@@ -33,6 +40,10 @@ class DesktopWorkspaceTab extends StatefulWidget {
final ValueListenable<bool> showShortcuts;
final VoidCallback? onSelect, onClose;
final VoidCallback? onRename;
+
+ /// This tab's Agent Messages, or null where a tab has none (the Store).
+ final TabMessagesState? agentMessages;
+ final VoidCallback? onToggleAgentMessages;
final String? shortcutHint, tooltip, activityLabel;
final Widget? activity;
@@ -48,11 +59,22 @@ class DesktopWorkspaceTab extends StatefulWidget {
return width;
}
- // Reserve the full close target inside the tab's curved body on both sides,
- // keeping the name centered and clear of the hover action.
- static const _contentInset = 32.0 + grid.AppDesktop.tabCloseInset;
+ // × and, left of it, ⇄, inside the tab's curved body, with a dead gap
+ // between them so a click just off × never toggles ⇄. Their width is
+ // reserved on both sides, keeping the name centered and clear of them;
+ // narrow enough that a 128pt tab still shows its name beside a status.
+ static const closeWidth = 16.0, messagesWidth = 16.0, accessoryGap = 3.0;
+ static const _contentInset =
+ closeWidth + accessoryGap + messagesWidth + grid.AppDesktop.tabCloseInset;
static const _indicatorGap = 6.0;
+ /// What the ⇄ says it does, in each state.
+ static String agentMessagesTooltip(TabMessagesState state) => switch (state) {
+ TabMessagesState.off => 'Agent messages off · click to turn on',
+ TabMessagesState.on => 'Agent messages on · click to turn off',
+ TabMessagesState.flowing => 'Agents messaging · click to turn off',
+ };
+
static TextStyle _hintStyle({Color? color}) =>
DesktopChrome.metadata(color: color).copyWith(
fontFamilyFallback: [...grid.AppType.sansFallback, 'Apple Symbols'],
@@ -108,11 +130,57 @@ class DesktopWorkspaceTab extends StatefulWidget {
class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
bool _hovered = false, _focused = false;
+ /// One of the tab's trailing controls: shown, it takes the pointer, focus
+ /// and semantics; hidden, it keeps its place and none of them.
+ Widget _accessory({
+ required bool visible,
+ required double width,
+ required Widget child,
+ }) => SizedBox(
+ width: width,
+ child: Center(
+ child: IgnorePointer(
+ ignoring: !visible,
+ child: ExcludeFocus(
+ excluding: !visible,
+ child: ExcludeSemantics(
+ excluding: !visible,
+ child: Opacity(opacity: visible ? 1 : 0, child: child),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ /// A quiet glyph that takes full ink on hover, focus and press.
+ ButtonStyle _accessoryStyle(Color foreground, double resting) =>
+ IconButton.styleFrom(
+ backgroundColor: Colors.transparent,
+ overlayColor: Colors.transparent,
+ side: BorderSide.none,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ).copyWith(
+ animationDuration: Duration.zero,
+ foregroundColor: WidgetStateProperty.resolveWith(
+ (states) => foreground.withValues(
+ alpha:
+ states.any(
+ (state) =>
+ state == WidgetState.hovered ||
+ state == WidgetState.focused ||
+ state == WidgetState.pressed,
+ )
+ ? 1
+ : resting,
+ ),
+ ),
+ );
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
final enabled = widget.onSelect != null;
- final quietCloseOpacity = MediaQuery.highContrastOf(context) ? .7 : .45;
+ final quietOpacity = MediaQuery.highContrastOf(context) ? .7 : .45;
final focusVisible = _focused || widget.highlighted;
// Workspace palettes can stay dark beside light app surfaces. Match the
// native tab bar's ink to its own surface, independent of terminal colors.
@@ -128,6 +196,9 @@ class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
? foreground
: muted
: foreground.withValues(alpha: .38);
+ final messages = widget.agentMessages;
+ final messagesOn = messages != null && messages != TabMessagesState.off;
+ final flowing = messages == TabMessagesState.flowing;
Widget tab = Padding(
padding: const EdgeInsets.only(top: grid.AppDesktop.tabTopInset),
child: DecoratedBox(
@@ -147,29 +218,47 @@ class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
builder: (context, constraints) => ValueListenableBuilder(
valueListenable: widget.showShortcuts,
builder: (context, showHints, _) {
+ // Hovering this tab, or holding Command, reveals it.
+ final revealed = enabled && (_hovered || showHints);
final showHint =
- enabled &&
- showHints &&
- (widget.shortcutHint?.isNotEmpty ?? false);
+ revealed && (widget.shortcutHint?.isNotEmpty ?? false);
final indicator = DesktopWorkspaceTab.indicatorWidth(
context,
widget.shortcutHint,
hasActivity: widget.activity != null,
);
- final indicatorSpace = widget.activity != null || showHint
+ // The name sits where it rests, so revealing never moves it.
+ // A tab with a status shows the shortcut in that slot; an idle
+ // one shows it after the name, shortening only a name that
+ // would otherwise run into ⇄.
+ final restingSpace = widget.activity != null
? indicator + DesktopWorkspaceTab._indicatorGap
: 0.0;
- final labelWidth = math.min(
+ final contentRight =
+ constraints.maxWidth - DesktopWorkspaceTab._contentInset;
+ final restingWidth = math.min(
DesktopWorkspaceTab.labelWidth(context, widget.label),
math.max(
0.0,
- constraints.maxWidth -
- DesktopWorkspaceTab._contentInset * 2 -
- indicatorSpace,
+ contentRight -
+ DesktopWorkspaceTab._contentInset -
+ restingSpace,
),
);
final groupLeft =
- (constraints.maxWidth - labelWidth - indicatorSpace) / 2;
+ (constraints.maxWidth - restingWidth - restingSpace) / 2;
+ var labelWidth = restingWidth;
+ if (showHint && widget.activity == null) {
+ final overflow =
+ groupLeft +
+ restingWidth +
+ DesktopWorkspaceTab._indicatorGap +
+ indicator -
+ contentRight;
+ if (overflow > 0) {
+ labelWidth = math.max(0.0, restingWidth - overflow);
+ }
+ }
return Stack(
children: [
Positioned.fill(
@@ -182,6 +271,13 @@ class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
if (widget.onClose != null)
const CustomSemanticsAction(label: 'Close tab'):
widget.onClose!,
+ if (messages != null &&
+ widget.onToggleAgentMessages != null)
+ CustomSemanticsAction(
+ label: messagesOn
+ ? 'Turn Agent Messages off'
+ : 'Turn Agent Messages on',
+ ): widget.onToggleAgentMessages!,
},
child: FocusableActionDetector(
enabled: enabled,
@@ -220,7 +316,7 @@ class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
),
),
),
- if (indicatorSpace > 0)
+ if (widget.activity != null || showHint)
Positioned(
left:
groupLeft +
@@ -255,67 +351,53 @@ class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
),
Positioned(
right: grid.AppDesktop.tabCloseInset,
- width: 32,
top: 0,
bottom: 0,
- child: Center(
- child: IgnorePointer(
- ignoring: !_hovered || !enabled,
- child: ExcludeFocus(
- excluding: !_hovered || !enabled,
- child: ExcludeSemantics(
- excluding: !_hovered || !enabled,
- child: Opacity(
- opacity: _hovered && enabled ? 1 : 0,
- child: IconButton(
- key: ValueKey('tab-close:${widget.id}'),
- tooltip: 'Close tab',
- onPressed: widget.onClose,
- padding: EdgeInsets.zero,
- constraints: const BoxConstraints.tightFor(
- width: 32,
- height: 32,
- ),
- style:
- IconButton.styleFrom(
- foregroundColor: ink,
- backgroundColor: Colors.transparent,
- overlayColor: Colors.transparent,
- side: BorderSide.none,
- tapTargetSize:
- MaterialTapTargetSize.shrinkWrap,
- ).copyWith(
- animationDuration: Duration.zero,
- foregroundColor:
- WidgetStateProperty.resolveWith(
- (states) => foreground.withValues(
- alpha:
- states.any(
- (state) =>
- state ==
- WidgetState
- .hovered ||
- state ==
- WidgetState
- .focused ||
- state ==
- WidgetState
- .pressed,
- )
- ? 1
- : quietCloseOpacity,
- ),
- ),
- ),
- icon: const Icon(
- AppIcons.close,
- size: AppIcons.closeSize,
+ child: Row(
+ children: [
+ _accessory(
+ visible:
+ messages != null &&
+ enabled &&
+ (revealed || flowing),
+ width: DesktopWorkspaceTab.messagesWidth,
+ child: messages == null
+ ? const SizedBox.shrink()
+ : _AgentMessagesButton(
+ key: ValueKey(
+ 'tab-agent-messages:${widget.id}',
+ ),
+ state: messages,
+ onPressed: widget.onToggleAgentMessages,
+ style: _accessoryStyle(
+ foreground,
+ flowing ? 1 : quietOpacity,
+ ),
),
- ),
+ ),
+ const SizedBox(
+ width: DesktopWorkspaceTab.accessoryGap,
+ ),
+ _accessory(
+ visible: revealed,
+ width: DesktopWorkspaceTab.closeWidth,
+ child: IconButton(
+ key: ValueKey('tab-close:${widget.id}'),
+ tooltip: 'Close tab',
+ onPressed: widget.onClose,
+ padding: EdgeInsets.zero,
+ constraints: const BoxConstraints.tightFor(
+ width: DesktopWorkspaceTab.closeWidth,
+ height: 32,
+ ),
+ style: _accessoryStyle(foreground, quietOpacity),
+ icon: const Icon(
+ AppIcons.close,
+ size: AppIcons.closeSize,
),
),
),
- ),
+ ],
),
),
],
@@ -342,3 +424,85 @@ class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
);
}
}
+
+/// Agent Messages' ⇄: dim when off (struck through) or on and quiet, bright
+/// while agents are messaging. Its tooltip says what a click does.
+class _AgentMessagesButton extends StatelessWidget {
+ const _AgentMessagesButton({
+ super.key,
+ required this.state,
+ required this.onPressed,
+ required this.style,
+ });
+
+ final TabMessagesState state;
+ final VoidCallback? onPressed;
+ final ButtonStyle style;
+
+ @override
+ Widget build(BuildContext context) {
+ final tooltip = DesktopWorkspaceTab.agentMessagesTooltip(state);
+ // One node that says what it is and whether it is on; the tooltip's
+ // sentence is its hint, not a second label.
+ return Semantics(
+ container: true,
+ button: true,
+ toggled: state != TabMessagesState.off,
+ label: 'Agent Messages',
+ hint: tooltip,
+ onTap: onPressed,
+ excludeSemantics: true,
+ child: Tooltip(
+ message: tooltip,
+ excludeFromSemantics: true,
+ child: IconButton(
+ onPressed: onPressed,
+ padding: EdgeInsets.zero,
+ constraints: const BoxConstraints.tightFor(
+ width: DesktopWorkspaceTab.messagesWidth,
+ height: 32,
+ ),
+ style: style,
+ icon: _MessagesGlyph(struck: state == TabMessagesState.off),
+ ),
+ ),
+ );
+ }
+}
+
+/// ⇄, struck through while Agent Messages are off.
+class _MessagesGlyph extends StatelessWidget {
+ const _MessagesGlyph({required this.struck});
+ final bool struck;
+
+ @override
+ Widget build(BuildContext context) {
+ const icon = Icon(AppIcons.arrowRightLeft, size: 13);
+ if (!struck) return icon;
+ return CustomPaint(
+ key: const ValueKey('agent-messages-struck'),
+ foregroundPainter: _SlashPainter(
+ IconTheme.of(context).color ?? DesktopChrome.foreground,
+ ),
+ child: icon,
+ );
+ }
+}
+
+class _SlashPainter extends CustomPainter {
+ const _SlashPainter(this.color);
+ final Color color;
+
+ @override
+ void paint(Canvas canvas, Size size) => canvas.drawLine(
+ Offset(size.width * .15, size.height * .9),
+ Offset(size.width * .85, size.height * .1),
+ Paint()
+ ..color = color
+ ..strokeWidth = 1.2
+ ..strokeCap = StrokeCap.round,
+ );
+
+ @override
+ bool shouldRepaint(_SlashPainter oldDelegate) => oldDelegate.color != color;
+}
diff --git a/desktop/lib/widgets/linux_menu_bar.dart b/desktop/lib/widgets/linux_menu_bar.dart
index 5b7cc4c08..f2d3f290b 100644
--- a/desktop/lib/widgets/linux_menu_bar.dart
+++ b/desktop/lib/widgets/linux_menu_bar.dart
@@ -348,6 +348,22 @@ class _LinuxMenuBarState extends State<LinuxMenuBar> {
label: 'Close Tab',
action: 'closeActive',
),
+ // The active tab's Agent Messages: the tab's ⇄, and its log.
+ _swarmRow(
+ key: 'menu-bar-agent-messages',
+ icon: AppIcons.arrowRightLeft,
+ label: 'Agent Messages',
+ action: 'toggleAgentMessages',
+ selected: state.agentMessages == true,
+ enabled: state.enabled && state.agentMessages != null,
+ ),
+ _swarmRow(
+ key: 'menu-bar-show-agent-messages',
+ icon: AppIcons.messagesSquare,
+ label: 'Show Agent Messages',
+ action: 'showAgentMessages',
+ enabled: state.enabled && state.agentMessages != null,
+ ),
const AppMenuDivider(),
_swarmRow(
key: 'menu-bar-split-right',
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index c093aa5e3..9c5c24f7a 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -45,6 +45,7 @@ import '../shared/theme/workspace_bar_style.dart';
import '../theme/app_theme.dart';
import 'engine_identity.dart';
import 'harness_agent_control.dart';
+import '../agent_messages/pane_message_mark.dart';
import 'harness_activity_mark.dart';
import 'grid_model_picker.dart';
import 'pane_header_actions.dart';
@@ -2877,7 +2878,10 @@ class _TerminalHeader extends StatelessWidget {
Expanded(
child: Row(
children: [
+ // Four parts to an Agent Messages mark's one while it
+ // shows; alone, the title has all the room.
Flexible(
+ flex: 4,
child: Tooltip(
message: identityDetail,
waitDuration: const Duration(milliseconds: 500),
@@ -2907,6 +2911,12 @@ class _TerminalHeader extends StatelessWidget {
machineId: session.machineId,
agentId: session.agentId,
),
+ PaneMessageMarkView(
+ controller: notifier.agentMessages,
+ machineId: session.machineId,
+ agentId: session.agentId,
+ style: titleStyle,
+ ),
if ((status != null && !leadingStatus) ||
starting != null ||
!compact)
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 726915728..d576406b1 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -29,6 +29,8 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private var canFind = false
private var canClosePane = false
private var paneActions: [String: Bool] = [:]
+ /// Whether Agent Messages is on in the active tab; nil where it has none.
+ private var activeAgentMessages: Bool?
private let historyMenu = NSMenu(title: "History")
private var historyMenuNeedsRebuild = false
private var historyMenuIsOpen = false
@@ -71,6 +73,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
self.canFind = state["canFind"] as? Bool == true
self.canClosePane = state["canClosePane"] as? Bool == true
self.paneActions = state["paneActions"] as? [String: Bool] ?? [:]
+ self.activeAgentMessages = state["activeAgentMessages"] as? Bool
self.canGoBack = state["canGoBack"] as? Bool == true
self.canGoForward = state["canGoForward"] as? Bool == true
self.updateHistory(state["history"] as? [[String: Any]] ?? [], closed: state["closedHistory"] as? [[String: Any]] ?? [])
@@ -128,7 +131,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
private func sendTabAction(_ method: String, arguments: Any?) {
- guard ["daemon", "subscriptions", "focusedContext", "harnessControls", "resourceMonitor", "machineControls", "modelControls", "select", "close", "new", "rename", "commands", "notifications", "notificationInbox", "openStatusHarness", "store", "devices", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
+ guard ["daemon", "subscriptions", "focusedContext", "harnessControls", "resourceMonitor", "machineControls", "modelControls", "select", "close", "toggleAgentMessages", "new", "rename", "commands", "notifications", "notificationInbox", "openStatusHarness", "store", "devices", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
channel.invokeMethod(method, arguments: arguments)
return
}
@@ -303,6 +306,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
"cloneAgent": "plus.square.on.square", "restartAgent": "arrow.clockwise",
"shareAgent": "square.and.arrow.up",
"renameActive": "pencil", "closeActive": "xmark",
+ "toggleAgentMessages": "arrow.left.arrow.right", "showAgentMessages": "bubble.left.and.bubble.right",
"splitRight": "rectangle.split.2x1", "splitDown": "rectangle.split.1x2",
"zoomPane": "viewfinder", "movePaneToTab": "arrow.right.square", "closePane": "xmark",
"commands": "command", "notifications": "bell",
@@ -334,6 +338,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
add(file, "New Tab", "t", "new")
add(file, "Rename Tab", "r", "renameActive", [.command, .shift])
add(file, "Close Tab", "w", "closeActive")
+ // The active tab's Agent Messages: its ⇄ (a checkmark here) and its log.
+ add(file, "Agent Messages", "", "toggleAgentMessages")
+ add(file, "Show Agent Messages", "", "showAgentMessages")
file.addItem(.separator())
add(file, "Split Right", "r", "splitRight")
add(file, "Split Down", "d", "splitDown")
@@ -506,6 +513,10 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
if ["restartAgent", "shareAgent", "toggleViewer", "toggleComposer"].contains(action) {
return actionsEnabled && paneActions[action] == true
}
+ if action == "toggleAgentMessages" || action == "showAgentMessages" {
+ if action == "toggleAgentMessages" { menuItem.state = activeAgentMessages == true ? .on : .off }
+ return actionsEnabled && activeAgentMessages != nil
+ }
if menuItem.action == #selector(machineAction(_:)) {
return actionsEnabled && machines.contains(where: { $0.id == action })
}
@@ -2266,6 +2277,9 @@ private final class SwarmTabStrip: NSView {
tab.actionsEnabled = actionsEnabled
tab.attention = (row["attention"] as? Int ?? 0) > 0
tab.activity = HarnessNativeActivity(row["activity"] as? [String: Any])
+ tab.agentMessages = (row["agentMessages"] as? Bool).map {
+ SwarmTabMessages(on: $0, flowing: row["agentMessagesFlowing"] as? Bool == true)
+ }
tab.emit = { [weak self, weak tab] method, args in
guard let self, let tab, self.actionsEnabled,
self.tabs.contains(where: { $0 === tab }) else { return }
@@ -2618,11 +2632,17 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
private static let upperRadius: CGFloat = 10
private static let shoulder: CGFloat = 8
private static let topInset: CGFloat = 6
- // Mirror AppDesktop.tabCloseInset: keep the 32pt hover target inside the
- // curved tab body, with equal space reserved around the centered title.
+ // Mirror AppDesktop.tabCloseInset and DesktopWorkspaceTab: × and, left of
+ // it, Agent Messages' ⇄, as 32pt-tall targets inside the curved tab body,
+ // with a dead gap between them so a click just off × never toggles ⇄. Their
+ // width is reserved on both sides of the centered title, and kept narrow
+ // enough that a 128pt tab still draws its name beside a status.
private static let trailingInset: CGFloat = 8
- private static let accessorySide: CGFloat = 32
- private static let contentInset: CGFloat = trailingInset + accessorySide
+ private static let accessoryHeight: CGFloat = 32
+ private static let closeWidth: CGFloat = 16
+ private static let accessoryGap: CGFloat = 3
+ private static let messagesWidth: CGFloat = 16
+ private static let contentInset: CGFloat = trailingInset + closeWidth + accessoryGap + messagesWidth
private static let gap: CGFloat = 6
private static let activityWidth: CGFloat = 16
@@ -2633,21 +2653,32 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
var name = "New Tab" { didSet { if name != oldValue { invalidateLabel(); updateAccessibility() } } }
var displayLabel = "New Tab" { didSet { if displayLabel != oldValue { invalidateLabel() } } }
var shortcutHint: String? { didSet { if shortcutHint != oldValue { invalidateLabel(); updateAccessibility() } } }
+ /// Command is held: every tab is revealed, as a hovered one is.
var showsShortcutHint = false {
- didSet { if showsShortcutHint != oldValue { needsLayout = true; needsDisplay = true } }
+ didSet {
+ if showsShortcutHint != oldValue { updateAccessoryVisibility(); needsLayout = true; needsDisplay = true }
+ }
+ }
+ /// Agent Messages' ⇄ (docs/design/2026-10-10-agent-messages.md); nil where
+ /// the row carries none (the Store tab).
+ var agentMessages: SwarmTabMessages? {
+ didSet { if agentMessages != oldValue { updateMessagesControls() } }
}
var foreground = NSColor(white: 0.85, alpha: 1) {
didSet {
if foreground != oldValue { invalidateLabel() }
closeButton.foreground = foreground
+ messagesButton.foreground = foreground
}
}
private var indicatorWidth: CGFloat {
min(72, max(activityLabel == nil ? 0 : Self.activityWidth, shortcutLayout?.size.width ?? 0))
}
private var reservedIndicatorSpace: CGFloat { indicatorWidth == 0 ? 0 : indicatorWidth + Self.gap }
+ /// The status slot as the tab rests. The title is placed from it alone, so
+ /// revealing the shortcut never moves the title.
private var activitySpace: CGFloat {
- (activityMark?.isEmpty ?? true) && !displaysShortcut ? 0 : reservedIndicatorSpace
+ (activityMark?.isEmpty ?? true) ? 0 : reservedIndicatorSpace
}
private var naturalTitleWidth: CGFloat { max(labelLayout.size.width, emphasizedLabelLayout.size.width) }
var minimumWidth: CGFloat { Self.contentInset * 2 + reservedIndicatorSpace + 16 }
@@ -2666,11 +2697,21 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
if let activity { return activity.symbol(frame: activityFrame) }
return attention ? "?" : nil
}
- private var titleRect: NSRect {
+ private var restingTitleRect: NSRect {
let width = min(naturalTitleWidth, max(0, bounds.width - Self.contentInset * 2 - activitySpace))
return NSRect(x: (bounds.width - width - activitySpace) / 2, y: 0,
width: width, height: bounds.height)
}
+ /// An idle tab shows its shortcut after the title when revealed; only a
+ /// title that would run into ⇄ gives up its tail for it.
+ private var titleRect: NSRect {
+ var rect = restingTitleRect
+ if displaysShortcut && activitySpace == 0 {
+ let overflow = rect.maxX + reservedIndicatorSpace - (bounds.width - Self.contentInset)
+ if overflow > 0 { rect.size.width = max(0, rect.width - overflow) }
+ }
+ return rect
+ }
private var indicatorRect: NSRect {
if bounds.width < minimumWidth {
let width = min(indicatorWidth, max(0, bounds.width - 16))
@@ -2694,6 +2735,8 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
var isHovered: Bool { hovered && actionsEnabled }
private let selectButton = SwarmSelectButton()
private let closeButton = SwarmPlainIconButton()
+ private let messagesButton = SwarmMessagesButton()
+ private var messagesItems: [NSMenuItem] = []
/// Whether the middle button went down on THIS tab — see otherMouseUp.
private var middleDown = false
/// Tab navigation stays in system UI type, independent of terminal/status preferences.
@@ -2719,6 +2762,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
didSet {
selectButton.isEnabled = actionsEnabled
closeButton.isEnabled = actionsEnabled
+ messagesButton.isEnabled = actionsEnabled
updateAccessoryVisibility()
needsDisplay = true
}
@@ -2754,24 +2798,48 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
closeButton.action = #selector(closeSwarm)
closeButton.isHidden = true
addSubview(closeButton)
+ messagesButton.title = ""
+ messagesButton.isBordered = false
+ messagesButton.image = HarnessControlSymbols.image("arrow.left.arrow.right")
+ messagesButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 10, weight: .regular)
+ messagesButton.imagePosition = .imageOnly
+ messagesButton.foreground = foreground
+ messagesButton.target = self
+ messagesButton.action = #selector(toggleMessages)
+ messagesButton.isHidden = true
+ addSubview(messagesButton)
let menu = NSMenu()
- for (title, action) in [("Rename Tab…", #selector(renameSwarm)), ("Close Tab", #selector(closeSwarm))] {
+ func item(_ title: String, _ action: Selector) -> NSMenuItem {
let item = NSMenuItem(title: title, action: action, keyEquivalent: "")
item.target = self
menu.addItem(item)
- }
+ return item
+ }
+ _ = item("Rename Tab…", #selector(renameSwarm))
+ let separator = NSMenuItem.separator()
+ menu.addItem(separator)
+ // Agent Messages carries a checkmark while on (validateMenuItem).
+ messagesItems = [separator, item("Agent Messages", #selector(toggleMessages)),
+ item("Show Agent Messages", #selector(showMessages))]
+ menu.addItem(.separator())
+ _ = item("Close Tab", #selector(closeSwarm))
self.menu = menu
+ updateMessagesControls()
updateAccessibility()
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func layout() {
super.layout()
selectButton.frame = bounds
- closeButton.frame = NSRect(x: max(0, bounds.width - Self.trailingInset - Self.accessorySide),
- y: contentCenterY - Self.accessorySide / 2, width: min(Self.accessorySide, bounds.width), height: Self.accessorySide)
+ let closeX = max(0, bounds.width - Self.trailingInset - Self.closeWidth)
+ closeButton.frame = NSRect(x: closeX, y: contentCenterY - Self.accessoryHeight / 2,
+ width: min(Self.closeWidth, bounds.width), height: Self.accessoryHeight)
+ messagesButton.frame = NSRect(x: max(0, closeX - Self.accessoryGap - Self.messagesWidth),
+ y: contentCenterY - Self.accessoryHeight / 2,
+ width: min(Self.messagesWidth, bounds.width), height: Self.accessoryHeight)
let fullName = name.trimmingCharacters(in: .whitespacesAndNewlines)
var hints: [String] = []
- if naturalTitleWidth > titleRect.width { hints.append(displayLabel) }
+ if naturalTitleWidth > restingTitleRect.width { hints.append(displayLabel) }
if !fullName.isEmpty && fullName != displayLabel { hints.append(name) }
if let activityLabel { hints.append(activityLabel) }
toolTip = hints.isEmpty ? nil : hints.joined(separator: "\n")
@@ -2790,12 +2858,36 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
guard hovered != value else { return }
hovered = value
updateAccessoryVisibility()
+ needsLayout = true
needsDisplay = true
hoverChanged?()
}
- private var displaysShortcut: Bool { actionsEnabled && showsShortcutHint && shortcutHint?.isEmpty == false }
+ /// One revealed state: hovering this tab, or holding Command (every tab).
+ /// Revealed, the shortcut replaces the status and ⇄ and × both show.
+ var isRevealed: Bool { actionsEnabled && (hovered || showsShortcutHint) }
+ private var displaysShortcut: Bool { isRevealed && shortcutHint?.isEmpty == false }
private func updateAccessoryVisibility() {
- closeButton.isHidden = !isHovered
+ closeButton.isHidden = !isRevealed
+ // At rest only a tab whose agents are messaging keeps its ⇄ — on, since
+ // traffic seen as it was turned off says nothing about this tab now.
+ let flowing = agentMessages?.on == true && agentMessages?.flowing == true
+ messagesButton.isHidden = agentMessages == nil || !(isRevealed || (actionsEnabled && flowing))
+ }
+ /// The ⇄'s look, tooltip and accessibility, and the menu rows, for its state.
+ private func updateMessagesControls() {
+ for item in messagesItems { item.isHidden = agentMessages == nil }
+ if let state = agentMessages {
+ messagesButton.struck = !state.on
+ let bright = state.on && state.flowing
+ messagesButton.restingOpacity = bright ? 1 : 0.45
+ messagesButton.highContrastRestingOpacity = bright ? 1 : 0.7
+ messagesButton.toolTip = state.tooltip
+ messagesButton.setAccessibilityLabel("Agent Messages")
+ messagesButton.setAccessibilityValue(state.on ? "On" : "Off")
+ messagesButton.setAccessibilityHelp(state.tooltip)
+ }
+ updateAccessoryVisibility()
+ needsDisplay = true
}
private func invalidateLabel() {
cachedLabel = nil
@@ -2916,7 +3008,12 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
keyboardFocus ? "Keyboard is on the tabs. Press Return to type in this tab." : nil].compactMap { $0 }
selectButton.setAccessibilityHelp(help.isEmpty ? nil : help.joined(separator: ". "))
}
- func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { actionsEnabled }
+ func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
+ if menuItem.action == #selector(toggleMessages) {
+ menuItem.state = agentMessages?.on == true ? .on : .off
+ }
+ return actionsEnabled
+ }
override func mouseDown(with event: NSEvent) {
guard actionsEnabled else { return }
downPoint = event.locationInWindow
@@ -2967,11 +3064,50 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
}
func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { .move }
override func accessibilityChildren() -> [Any]? {
- closeButton.isHidden ? [selectButton] : [selectButton, closeButton]
+ [selectButton, messagesButton, closeButton].filter { !$0.isHidden }
}
@objc private func selectSwarm() { if actionsEnabled { emit?("select", ["id": swarmId]) } }
@objc private func closeSwarm() { if actionsEnabled { emit?("close", ["id": swarmId]) } }
@objc private func renameSwarm() { if actionsEnabled { emit?("rename", ["id": swarmId]) } }
+ @objc private func toggleMessages() {
+ if actionsEnabled && agentMessages != nil { emit?("toggleAgentMessages", ["id": swarmId]) }
+ }
+ @objc private func showMessages() {
+ if actionsEnabled && agentMessages != nil { emit?("showAgentMessages", ["id": swarmId]) }
+ }
+}
+
+/// A tab's Agent Messages, as the `update` payload's row says it.
+struct SwarmTabMessages: Equatable {
+ var on: Bool
+ var flowing: Bool
+ /// What the ⇄ says a click does; the Flutter tab says the same.
+ var tooltip: String {
+ !on ? "Agent messages off · click to turn on"
+ : flowing ? "Agents messaging · click to turn off" : "Agent messages on · click to turn off"
+ }
+}
+
+/// ⇄, struck through while Agent Messages are off.
+private final class SwarmMessagesButton: SwarmPlainIconButton {
+ var struck = false { didSet { if struck != oldValue { needsDisplay = true } } }
+ override func draw(_ dirtyRect: NSRect) {
+ super.draw(dirtyRect)
+ guard struck, let symbol = image?.withSymbolConfiguration(symbolConfiguration ?? HarnessControlSymbols.configuration)
+ else { return }
+ let glyph = NSRect(x: (bounds.width - symbol.size.width) / 2, y: (bounds.height - symbol.size.height) / 2,
+ width: symbol.size.width, height: symbol.size.height)
+ let emphasized = isEnabled && (hovered || hasKeyboardFocus || isHighlighted)
+ let quiet = NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast
+ ? highContrastRestingOpacity ?? restingOpacity : restingOpacity
+ foreground.withAlphaComponent(isEnabled ? (emphasized ? 1 : quiet) : 0.28).setStroke()
+ let slash = NSBezierPath()
+ slash.move(to: NSPoint(x: glyph.minX + glyph.width * 0.1, y: glyph.minY - 1))
+ slash.line(to: NSPoint(x: glyph.maxX - glyph.width * 0.1, y: glyph.maxY + 1))
+ slash.lineWidth = 1.2
+ slash.lineCapStyle = .round
+ slash.stroke()
+ }
}
/// The full tab remains a selection/drag target; the hover close button sits
diff --git a/desktop/test/agent_messages_commands_test.dart b/desktop/test/agent_messages_commands_test.dart
new file mode 100644
index 000000000..725e86561
--- /dev/null
+++ b/desktop/test/agent_messages_commands_test.dart
@@ -0,0 +1,89 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shortcuts/keymap_commands.dart';
+import 'package:harness/state/app_state.dart';
+
+import 'support/agent_messages_api.dart';
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount;
+import 'swarm_state_test.dart' show createApp;
+
+/// ⇧⌘P: "Show Agent Messages" (this tab's log) and "Agent Messages: turn on/off
+/// for this tab" replace Swarm's "Tab conversation".
+void main() {
+ test('the commands are named for Agent Messages, and Swarm\'s is gone', () {
+ expect(
+ harnessCommandById['agent_messages.show']?.label,
+ 'Show Agent Messages',
+ );
+ expect(harnessCommandById['agent_messages.toggle'], isNotNull);
+ expect(harnessCommandById['team.open'], isNull);
+ });
+
+ Future<void> search(WidgetTester tester, String query) async {
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ query,
+ );
+ await tester.pump();
+ }
+
+ testWidgets('the palette turns Agent Messages on for this tab', (
+ tester,
+ ) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final api = await joinAgentMessagesDesk(app);
+ await mount(tester, app);
+ final tab = app.activeSwarmId;
+ await search(tester, '> agent messages');
+ // The row, and the preview of the chosen one.
+ expect(find.text('Show Agent Messages'), findsWidgets);
+ expect(find.text('Agent Messages: turn on for this tab'), findsWidgets);
+ expect(find.textContaining('Tab conversation'), findsNothing);
+ await tester.tap(
+ find.text('Agent Messages: turn on for this tab').hitTestable().first,
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(api.writes, [(tab, true)]);
+ expect(app.agentMessages.isOn(tab), isTrue);
+ await search(tester, '> agent messages');
+ expect(find.text('Agent Messages: turn off for this tab'), findsWidgets);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('a tab without Agent Messages lists neither command', (
+ tester,
+ ) async {
+ // Before the desk is joined there is no flag to show or set.
+ final app = createApp()..status = AppStatus.authenticated;
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ await search(tester, '> agent messages');
+ expect(find.text('Show Agent Messages'), findsNothing);
+ expect(find.textContaining('for this tab'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('Show Agent Messages opens this tab\'s log', (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await joinAgentMessagesDesk(app);
+ await mount(tester, app);
+ app.renameSwarm(app.activeSwarmId, 'app');
+ await tester.pump();
+ await search(tester, '> show agent messages');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('app · Agent Messages'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('app · Agent Messages'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/agent_messages_tab_test.dart b/desktop/test/agent_messages_tab_test.dart
new file mode 100644
index 000000000..f06b6a331
--- /dev/null
+++ b/desktop/test/agent_messages_tab_test.dart
@@ -0,0 +1,299 @@
+import 'dart:ui' show Tristate;
+
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/semantics.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/agent_messages/agent_messages.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/desktop_workspace_tab.dart';
+
+import 'support/agent_messages_api.dart';
+import 'swarm_screen_test.dart' show mount;
+import 'swarm_state_test.dart' show createApp;
+
+/// The tab's ⇄ and the one revealed state (docs/design/2026-10-10-agent-messages.md,
+/// "The tab"): hovering a tab or holding Command reveals the shortcut, ⇄ and ×;
+/// at rest only a tab whose agents are messaging keeps a bright ⇄.
+typedef _Spec = ({String id, TabMessagesState? messages, bool working});
+
+Widget _host(
+ ValueNotifier<bool> command,
+ List<_Spec> tabs, {
+ Brightness brightness = Brightness.dark,
+ void Function(String id)? onToggle,
+ void Function(String id)? onSelect,
+}) => MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ themeAnimationDuration: Duration.zero,
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topLeft,
+ child: SizedBox(
+ height: 40,
+ child: Row(
+ children: [
+ for (final (index, tab) in tabs.indexed)
+ SizedBox(
+ width: 240,
+ child: DesktopWorkspaceTab(
+ id: tab.id,
+ label: tab.id,
+ selected: index == 0,
+ shortcutHint: '⌘${index + 1}',
+ showShortcuts: command,
+ onSelect: () => onSelect?.call(tab.id),
+ onClose: () {},
+ agentMessages: tab.messages,
+ onToggleAgentMessages: () => onToggle?.call(tab.id),
+ activityLabel: tab.working ? 'Working' : null,
+ activity: tab.working
+ ? SizedBox(
+ key: ValueKey('status:${tab.id}'),
+ width: 16,
+ child: const Text('⠋'),
+ )
+ : null,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+);
+
+Finder _messages(String id) => find.byKey(ValueKey('tab-agent-messages:$id'));
+Finder _close(String id) => find.byKey(ValueKey('tab-close:$id'));
+Finder _label(String id) => find.byKey(ValueKey('tab-label:$id'));
+Finder _hint(String id) => find.byKey(ValueKey('tab-shortcut:$id'));
+Finder _struck(String id) => find.descendant(
+ of: _messages(id),
+ matching: find.byKey(const ValueKey('agent-messages-struck')),
+);
+
+/// The ink the ⇄ glyph is drawn in, while the pointer is not on it.
+double _glyphAlpha(WidgetTester tester, String id) => IconTheme.of(
+ tester.element(
+ find.descendant(
+ of: _messages(id),
+ matching: find.byIcon(AppIcons.arrowRightLeft),
+ ),
+ ),
+).color!.a;
+
+String _tooltip(WidgetTester tester, String id) => tester
+ .widget<Tooltip>(
+ find.descendant(of: _messages(id), matching: find.byType(Tooltip)).first,
+ )
+ .message!;
+
+void main() {
+ late ValueNotifier<bool> command;
+ setUp(() => command = ValueNotifier(false));
+ tearDown(() => command.dispose());
+
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'off: nothing at rest; revealed, ⌘1 and a struck dim ⇄ beside × '
+ '(${brightness.name})',
+ (tester) async {
+ final toggled = <String>[];
+ await tester.pumpWidget(
+ _host(
+ command,
+ [(id: 'app', messages: TabMessagesState.off, working: false)],
+ brightness: brightness,
+ onToggle: toggled.add,
+ ),
+ );
+ expect(_messages('app').hitTestable(), findsNothing);
+ expect(_close('app').hitTestable(), findsNothing);
+ expect(_hint('app'), findsNothing);
+ final title = tester.getRect(_label('app'));
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: title.center);
+ addTearDown(mouse.removePointer);
+ await tester.pump();
+ expect(_hint('app'), findsOneWidget);
+ expect(_messages('app').hitTestable(), findsOneWidget);
+ expect(_close('app').hitTestable(), findsOneWidget);
+ expect(_struck('app'), findsOneWidget);
+ expect(_glyphAlpha(tester, 'app'), closeTo(.45, .01));
+ expect(
+ _tooltip(tester, 'app'),
+ 'Agent messages off · click to turn on',
+ );
+ final messages = tester.getRect(_messages('app'));
+ final close = tester.getRect(_close('app'));
+ expect(
+ close.left - messages.right,
+ DesktopWorkspaceTab.accessoryGap,
+ reason: '⇄ sits left of ×, past a gap that neither takes',
+ );
+ await tester.tapAt(Offset(close.left - 1.5, close.center.dy));
+ await tester.pump();
+ expect(toggled, isEmpty, reason: 'a click just off × toggles nothing');
+ expect(
+ messages.size,
+ const Size(DesktopWorkspaceTab.messagesWidth, 32),
+ );
+ expect(tester.getRect(_label('app')), title, reason: 'never moves');
+ expect(
+ tester.getRect(_hint('app')).right,
+ lessThanOrEqualTo(messages.left),
+ );
+ },
+ );
+ }
+
+ testWidgets('on and quiet: a dim ⇄ only when revealed', (tester) async {
+ await tester.pumpWidget(
+ _host(command, [
+ (id: 'app', messages: TabMessagesState.on, working: true),
+ ]),
+ );
+ expect(_messages('app').hitTestable(), findsNothing);
+ expect(find.byKey(const ValueKey('status:app')), findsOneWidget);
+ command.value = true;
+ await tester.pump();
+ expect(_messages('app').hitTestable(), findsOneWidget);
+ expect(_struck('app'), findsNothing);
+ expect(_glyphAlpha(tester, 'app'), closeTo(.45, .01));
+ expect(_tooltip(tester, 'app'), 'Agent messages on · click to turn off');
+ expect(_hint('app'), findsOneWidget);
+ expect(find.byKey(const ValueKey('status:app')), findsNothing);
+ });
+
+ testWidgets('flowing: a bright ⇄ at rest, without ×', (tester) async {
+ await tester.pumpWidget(
+ _host(command, [
+ (id: 'app', messages: TabMessagesState.flowing, working: false),
+ ]),
+ );
+ expect(_messages('app').hitTestable(), findsOneWidget);
+ expect(_close('app').hitTestable(), findsNothing);
+ expect(_hint('app'), findsNothing);
+ expect(_glyphAlpha(tester, 'app'), 1);
+ expect(_tooltip(tester, 'app'), 'Agents messaging · click to turn off');
+ command.value = true;
+ await tester.pump();
+ expect(_close('app').hitTestable(), findsOneWidget);
+ expect(_glyphAlpha(tester, 'app'), 1);
+ });
+
+ testWidgets('Command reveals every tab; hover reveals only its own', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ _host(command, [
+ (id: 'one', messages: TabMessagesState.off, working: false),
+ (id: 'two', messages: TabMessagesState.on, working: true),
+ (id: 'store', messages: null, working: false),
+ ]),
+ );
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: tester.getCenter(_label('one')));
+ addTearDown(mouse.removePointer);
+ await tester.pump();
+ expect(_close('one').hitTestable(), findsOneWidget);
+ expect(_close('two').hitTestable(), findsNothing);
+ expect(_hint('two'), findsNothing);
+ await mouse.moveTo(const Offset(900, 300));
+ await tester.pump();
+ command.value = true;
+ await tester.pump();
+ for (final id in ['one', 'two', 'store']) {
+ expect(_close(id).hitTestable(), findsOneWidget, reason: id);
+ expect(_hint(id), findsOneWidget, reason: id);
+ }
+ expect(_messages('one').hitTestable(), findsOneWidget);
+ expect(_messages('two').hitTestable(), findsOneWidget);
+ expect(
+ _messages('store'),
+ findsNothing,
+ reason: 'the Store tab has no Agent Messages',
+ );
+ command.value = false;
+ await tester.pump();
+ for (final id in ['one', 'two', 'store']) {
+ expect(_close(id).hitTestable(), findsNothing, reason: id);
+ }
+ });
+
+ testWidgets('clicking ⇄ toggles that tab without selecting it', (
+ tester,
+ ) async {
+ final toggled = <String>[], selected = <String>[];
+ await tester.pumpWidget(
+ _host(
+ command,
+ [
+ (id: 'one', messages: TabMessagesState.off, working: false),
+ (id: 'two', messages: TabMessagesState.flowing, working: false),
+ ],
+ onToggle: toggled.add,
+ onSelect: selected.add,
+ ),
+ );
+ await tester.tap(_messages('two'));
+ await tester.pump();
+ expect(toggled, ['two']);
+ expect(selected, isEmpty);
+ });
+
+ testWidgets('the ⇄ has a label and a state', (tester) async {
+ final semantics = tester.ensureSemantics();
+ final toggled = <String>[];
+ await tester.pumpWidget(
+ _host(command, [
+ (id: 'app', messages: TabMessagesState.flowing, working: false),
+ (id: 'off', messages: TabMessagesState.off, working: false),
+ ], onToggle: toggled.add),
+ );
+ final on = tester.getSemantics(_messages('app'));
+ expect(on.label, 'Agent Messages');
+ expect(on.hint, 'Agents messaging · click to turn off');
+ expect(on.getSemanticsData().flagsCollection.isToggled, Tristate.isTrue);
+ // Hidden at rest: off the semantics tree until revealed, but the tab
+ // itself still offers the action.
+ expect(find.semantics.byLabel('Agent Messages').evaluate(), hasLength(1));
+ command.value = true;
+ await tester.pump();
+ final off = tester.getSemantics(_messages('off'));
+ expect(off.getSemanticsData().flagsCollection.isToggled, Tristate.isFalse);
+ final tab = tester.getSemantics(find.bySemanticsLabel(RegExp(r'^off$')));
+ final actions = [
+ for (final id in tab.getSemanticsData().customSemanticsActionIds!)
+ CustomSemanticsAction.getAction(id)!.label,
+ ];
+ expect(actions, containsAll(['Close tab', 'Turn Agent Messages on']));
+ semantics.dispose();
+ });
+
+ testWidgets('the workspace strip offers ⇄ only on desk tabs, once answered', (
+ tester,
+ ) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ final before = app.activeSwarmId;
+ expect(_messages(before), findsNothing, reason: 'before the desk');
+ await tester.pumpWidget(const SizedBox());
+ final api = await joinAgentMessagesDesk(app);
+ await mount(tester, app);
+ final tab = app.activeSwarmId;
+ expect(_messages(tab), findsOneWidget);
+ app.openStore();
+ await tester.pump();
+ expect(app.activeSwarm.isStore, isTrue);
+ expect(_messages(app.activeSwarmId), findsNothing, reason: 'the Store');
+ api.unsupported = true;
+ await app.agentMessages.refresh();
+ await tester.pump();
+ expect(_messages(tab), findsNothing, reason: 'an older CLI or backend');
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/agent_messages_test.dart b/desktop/test/agent_messages_test.dart
new file mode 100644
index 000000000..b5f194a59
--- /dev/null
+++ b/desktop/test/agent_messages_test.dart
@@ -0,0 +1,790 @@
+import 'dart:async';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/agent_messages/agent_messages.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/terminal/terminal_session.dart';
+
+import 'support/agent_messages_api.dart';
+
+/// Agent Messages as the window keeps it (docs/design/2026-10-10-agent-messages.md):
+/// each tab's flag, the traffic `messages_changed` reports, the pane marks it
+/// leaves, and a tab's log merged from every daemon that holds part of it.
+class _Backend {
+ Map<String, bool> tabs = {};
+ int reads = 0;
+ Object? readError;
+ bool readNull = false;
+ Completer<Map<String, dynamic>>? pendingWrite;
+ Object? writeError;
+ final writes = <(String, bool)>[];
+
+ Future<Map<String, dynamic>?> read() async {
+ reads++;
+ if (readError case final error?) throw error;
+ if (readNull) return null;
+ return {
+ 'revision': 3,
+ 'machines': const [],
+ 'tabs': [
+ for (final MapEntry(:key, :value) in tabs.entries)
+ {'id': key, 'name': key, 'enabled': value, 'panes': const []},
+ ],
+ };
+ }
+
+ Future<Map<String, dynamic>> write(String tabId, bool enabled) async {
+ writes.add((tabId, enabled));
+ if (pendingWrite case final pending?) return pending.future;
+ if (writeError case final error?) throw error;
+ tabs[tabId] = enabled;
+ return {'tabId': tabId, 'enabled': enabled, 'revision': writes.length};
+ }
+}
+
+Map<String, dynamic> _sent({
+ String tabId = 'tab',
+ String id = 'm0000001',
+ String to = 'api',
+ String state = 'queued',
+}) => {
+ 'tabId': tabId,
+ 'messageId': id,
+ 'at': 1,
+ 'from': {'machineId': 'studio', 'agentId': 'lead'},
+ 'to': [
+ {'machineId': 'laptop', 'agentId': to, 'state': state},
+ ],
+};
+
+Map<String, dynamic> _row(
+ String id, {
+ required int at,
+ List<Map<String, Object?>> statuses = const [],
+ String text = 'Review of 3f2a9c1\nthe cleanup leaves workers running',
+}) => {
+ 'id': id,
+ 'tabId': 'tab',
+ 'from': {
+ 'machineId': 'studio',
+ 'agentId': 'lead',
+ 'name': 'lead',
+ 'engine': 'codex',
+ 'machine': 'studio',
+ },
+ 'to': [
+ {'machineId': 'laptop', 'agentId': 'api', 'name': 'api'},
+ ],
+ 'text': text,
+ 'at': at,
+ 'statuses': statuses,
+};
+
+void main() {
+ late _Backend backend;
+ final names = {'lead': 'Lead', 'api': 'API worker'};
+
+ AgentMessagesController controller({
+ AgentMessagesRequest? request,
+ AgentNameOf? nameOf,
+ }) => AgentMessagesController(
+ read: backend.read,
+ write: backend.write,
+ request: request ?? (_, _) async => throw StateError('offline'),
+ nameOf: nameOf ?? (_, agentId) => names[agentId],
+ );
+
+ setUp(() {
+ backend = _Backend();
+ });
+
+ group('the flag', () {
+ test('reads each tab, and off is the default', () async {
+ backend.tabs = {'on': true, 'off': false};
+ final messages = controller();
+ addTearDown(messages.dispose);
+ expect(messages.isOn('on'), isFalse, reason: 'unknown until read');
+ await messages.refresh();
+ expect(messages.loaded, isTrue);
+ expect(messages.isOn('on'), isTrue);
+ expect(messages.isOn('off'), isFalse);
+ expect(messages.isOn('never-seen'), isFalse);
+ expect(messages.stateOf('on'), TabMessagesState.on);
+ expect(messages.stateOf('off'), TabMessagesState.off);
+ });
+
+ test('an older daemon or backend (404) offers nothing, for good', () async {
+ backend.tabs = {'tab': true};
+ final messages = controller();
+ addTearDown(messages.dispose);
+ backend.readNull = true;
+ await messages.refresh();
+ expect(messages.loaded, isFalse);
+ expect(messages.isOn('tab'), isFalse);
+ backend.readNull = false;
+ await messages.refresh();
+ expect(messages.loaded, isTrue);
+ // The daemon was replaced by one without Agent Messages.
+ backend.readNull = true;
+ var notified = 0;
+ messages.addListener(() => notified++);
+ await messages.refresh();
+ expect(messages.loaded, isFalse);
+ expect(messages.isOn('tab'), isFalse);
+ expect(notified, 1);
+ });
+
+ test('a failure before any answer stays unanswered', () async {
+ final messages = controller();
+ addTearDown(messages.dispose);
+ backend.readError = StateError('daemon down');
+ await messages.refresh();
+ expect(messages.loaded, isFalse);
+ expect(messages.isOn('tab'), isFalse);
+ });
+
+ test('a failed read keeps what was known', () async {
+ backend.tabs = {'tab': true};
+ final messages = controller();
+ addTearDown(messages.dispose);
+ await messages.refresh();
+ backend.readError = StateError('one dropped request');
+ await messages.refresh();
+ expect(messages.isOn('tab'), isTrue);
+ });
+
+ test('a toggle shows at once, then reads again', () async {
+ final messages = controller();
+ addTearDown(messages.dispose);
+ await messages.refresh();
+ backend.pendingWrite = Completer();
+ final saved = messages.toggle('tab');
+ expect(messages.isOn('tab'), isTrue, reason: 'optimistic');
+ expect(messages.isPending('tab'), isTrue);
+ expect(
+ await messages.toggle('tab'),
+ isFalse,
+ reason: 'one write at a time',
+ );
+ backend.pendingWrite!.complete({'tabId': 'tab', 'enabled': true});
+ backend.tabs['tab'] = true;
+ final readsBefore = backend.reads;
+ expect(await saved, isTrue);
+ expect(messages.isPending('tab'), isFalse);
+ expect(messages.isOn('tab'), isTrue);
+ expect(messages.failureFor('tab'), isNull);
+ await pumpEventQueue();
+ expect(backend.reads, readsBefore + 1, reason: 're-read after a toggle');
+ expect(backend.writes, [('tab', true)]);
+ });
+
+ test('a refused toggle goes back and says why', () async {
+ final messages = controller();
+ addTearDown(messages.dispose);
+ var notified = 0;
+ messages.addListener(() => notified++);
+ backend.writeError = StateError('backend unreachable');
+ final saved = messages.setEnabled('tab', true);
+ expect(messages.isOn('tab'), isTrue);
+ expect(await saved, isFalse);
+ expect(messages.isOn('tab'), isFalse);
+ expect(messages.failureFor('tab'), contains('could not be turned on'));
+ expect(notified, greaterThanOrEqualTo(2));
+ backend.writeError = null;
+ expect(await messages.setEnabled('tab', true), isTrue);
+ expect(messages.failureFor('tab'), isNull);
+ });
+
+ test('a read that started before a toggle landed cannot undo it', () async {
+ final messages = controller();
+ addTearDown(messages.dispose);
+ final stale = Completer<Map<String, dynamic>?>();
+ final reading = AgentMessagesController(
+ read: () => stale.future,
+ write: backend.write,
+ request: (_, _) async => {},
+ nameOf: (_, _) => null,
+ );
+ addTearDown(reading.dispose);
+ final read = reading.refresh();
+ await reading.setEnabled('tab', true);
+ stale.complete({
+ 'tabs': [
+ {'id': 'tab', 'enabled': false},
+ ],
+ });
+ await read;
+ expect(reading.isOn('tab'), isTrue);
+ });
+
+ test('signing out forgets the account', () async {
+ backend.tabs = {'tab': true};
+ final messages = controller();
+ addTearDown(messages.dispose);
+ await messages.refresh();
+ messages.handleEvent(_sent());
+ messages.reset();
+ expect(messages.isOn('tab'), isFalse);
+ expect(messages.isFlowing('tab'), isFalse);
+ expect(messages.markFor('studio', 'lead'), isNull);
+ expect(messages.loaded, isFalse);
+ });
+ });
+
+ group('traffic', () {
+ test('a tab flows for a minute after its last message', () {
+ fakeAsync((async) {
+ backend.tabs = {'tab': true};
+ final messages = controller();
+ unawaited(messages.refresh());
+ async.flushMicrotasks();
+ var notified = 0;
+ messages.addListener(() => notified++);
+ messages.handleEvent(_sent());
+ expect(messages.isFlowing('tab'), isTrue);
+ expect(messages.stateOf('tab'), TabMessagesState.flowing);
+ expect(messages.trafficFor('tab'), 1);
+ async.elapse(const Duration(seconds: 40));
+ messages.handleEvent(_sent(state: 'delivered'));
+ expect(messages.trafficFor('tab'), 2);
+ async.elapse(const Duration(seconds: 59));
+ expect(messages.isFlowing('tab'), isTrue);
+ final before = notified;
+ async.elapse(const Duration(seconds: 1));
+ expect(messages.isFlowing('tab'), isFalse);
+ expect(messages.stateOf('tab'), TabMessagesState.on);
+ expect(notified, greaterThan(before), reason: 'the ⇄ dims by itself');
+ expect(async.pendingTimers, isEmpty);
+ messages.dispose();
+ });
+ });
+
+ test('marks the sender and each recipient once per message', () {
+ fakeAsync((async) {
+ final messages = controller();
+ messages.handleEvent(_sent());
+ expect(messages.markFor('studio', 'lead')?.label, '→ API worker');
+ expect(messages.markFor('laptop', 'api')?.label, '← Lead');
+ expect(messages.markFor('studio', 'lead')?.warning, isFalse);
+ // The next status of the same message is not a new message.
+ messages.seen('laptop', 'api');
+ messages.handleEvent(_sent(state: 'delivered'));
+ expect(messages.markFor('laptop', 'api'), isNull);
+ async.elapse(const Duration(seconds: 5));
+ expect(messages.markFor('studio', 'lead'), isNull);
+ messages.handleEvent(_sent(id: 'm0000002', to: 'web'));
+ expect(
+ messages.markFor('studio', 'lead')?.label,
+ '→ web',
+ reason: 'an unknown name falls back to the start of its id',
+ );
+ messages.dispose();
+ expect(async.pendingTimers, isEmpty);
+ });
+ });
+
+ test('focusing a pane clears its mark', () {
+ fakeAsync((async) {
+ final messages = controller();
+ messages.handleEvent(_sent());
+ var notified = 0;
+ messages.addListener(() => notified++);
+ messages.seen('studio', 'lead');
+ expect(messages.markFor('studio', 'lead'), isNull);
+ expect(messages.markFor('laptop', 'api'), isNotNull);
+ expect(notified, 1);
+ messages.seen('studio', 'lead');
+ expect(notified, 1);
+ messages.dispose();
+ });
+ });
+
+ test('a sender stopped by the rate limit is the one alert', () {
+ fakeAsync((async) {
+ final messages = controller();
+ messages.handleEvent({
+ 'limited': {'machineId': 'studio', 'agentId': 'lead'},
+ });
+ final mark = messages.markFor('studio', 'lead')!;
+ expect(mark.warning, isTrue);
+ expect(mark.label, '→ rate limited');
+ expect(messages.isFlowing('tab'), isFalse);
+ messages.dispose();
+ });
+ });
+
+ test('frames without a tab or parties change nothing', () {
+ final messages = controller();
+ addTearDown(messages.dispose);
+ messages.handleEvent({'messageId': 'm0000001'});
+ messages.handleEvent({'tabId': '', 'messageId': 'm0000001'});
+ messages.handleEvent({'limited': 'nobody'});
+ expect(messages.isFlowing(''), isFalse);
+ messages.handleEvent({'tabId': 'tab', 'messageId': 'm0000003'});
+ expect(messages.isFlowing('tab'), isTrue);
+ expect(messages.markFor('studio', 'lead'), isNull);
+ });
+ });
+
+ group('the log', () {
+ test('merges every daemon by message id, oldest first', () async {
+ final asked = <(String, Map<String, dynamic>)>[];
+ final messages = controller(
+ request: (machineId, payload) async {
+ asked.add((machineId, payload));
+ return switch (machineId) {
+ // The sender's daemon still says queued for the remote recipient.
+ 'studio' => {
+ 'messages': [
+ _row(
+ 'm0000002',
+ at: 2000,
+ statuses: [
+ {
+ 'machineId': 'laptop',
+ 'agentId': 'api',
+ 'state': 'queued',
+ 'at': 2000,
+ },
+ ],
+ ),
+ _row('m0000001', at: 1000),
+ ],
+ },
+ // The recipient's daemon delivered it.
+ 'laptop' => {
+ 'messages': [
+ _row(
+ 'm0000002',
+ at: 2000,
+ statuses: [
+ {
+ 'machineId': 'laptop',
+ 'agentId': 'api',
+ 'state': 'delivered',
+ 'via': 'hook',
+ 'at': 2500,
+ },
+ ],
+ ),
+ {..._row('m0000009', at: 9), 'tabId': 'another'},
+ 'not a message',
+ ],
+ },
+ _ => throw StateError('offline'),
+ };
+ },
+ );
+ addTearDown(messages.dispose);
+ final log = await messages.history('tab', [
+ 'studio',
+ 'laptop',
+ 'laptop',
+ 'gone',
+ ]);
+ expect(log.reached, isTrue);
+ expect(asked, hasLength(3));
+ expect(asked.first.$2, {'action': 'history', 'tabId': 'tab'});
+ expect(log.messages.map((m) => m.id), ['m0000001', 'm0000002']);
+ final merged = log.messages.last;
+ expect(merged.stateOf(merged.to.single), AgentMessageState.delivered);
+ expect(merged.statusOf(merged.to.single)?.via, 'hook');
+ expect(merged.firstLine, 'Review of 3f2a9c1');
+ expect(
+ log.messages.first.stateOf(log.messages.first.to.single),
+ AgentMessageState.queued,
+ );
+ });
+
+ test('no daemon answering is not an empty log', () async {
+ final messages = controller(
+ request: (_, _) async => {'error': 'UNKNOWN_ACTION'},
+ );
+ addTearDown(messages.dispose);
+ final unreachable = await messages.history('tab', ['studio']);
+ expect(unreachable.reached, isFalse);
+ expect(unreachable.messages, isEmpty);
+ final empty = await controller(request: (_, _) async => {'messages': []})
+ .history('tab', ['studio']);
+ expect(empty.reached, isTrue);
+ expect(empty.complete, isTrue);
+ });
+
+ test(
+ 'a member machine that did not answer leaves the log incomplete',
+ () async {
+ final messages = controller(
+ request: (machineId, _) async => machineId == 'studio'
+ ? {
+ 'messages': [_row('m0000001', at: 1)],
+ }
+ : throw StateError('offline'),
+ );
+ addTearDown(messages.dispose);
+ final partial = await messages.history(
+ 'tab',
+ ['studio', 'laptop'],
+ expected: {'studio', 'laptop'},
+ );
+ expect(partial.reached, isTrue);
+ expect(partial.complete, isFalse);
+ final unasked = await messages.history(
+ 'tab',
+ ['studio'],
+ expected: {'studio', 'gone-offline'},
+ );
+ expect(unasked.complete, isFalse, reason: 'offline, so never asked');
+ final whole = await messages.history(
+ 'tab',
+ ['studio'],
+ expected: {'studio'},
+ );
+ expect(whole.complete, isTrue);
+ },
+ );
+
+ test('a later final state wins, and failed says why', () {
+ AgentMessage message(String state, int at, {String? reason}) =>
+ AgentMessage.fromJson(
+ _row(
+ 'm0000001',
+ at: 1,
+ statuses: [
+ {
+ 'machineId': 'laptop',
+ 'agentId': 'api',
+ 'state': state,
+ 'at': at,
+ 'reason': ?reason,
+ },
+ ],
+ ),
+ )!;
+ final failed = message('failed', 5, reason: 'left the tab');
+ final queued = message('queued', 9);
+ final merged = queued.merge(failed);
+ expect(merged.stateOf(merged.to.single), AgentMessageState.failed);
+ expect(merged.statusOf(merged.to.single)?.reason, 'left the tab');
+ expect(
+ failed.merge(message('delivered', 7)).stateOf(failed.to.single),
+ AgentMessageState.delivered,
+ );
+ });
+ });
+
+ group('other machines', () {
+ // A daemon tells `messages_changed` only to its own computer's windows:
+ // traffic between harnesses elsewhere is read from their logs.
+ final now = DateTime(2026, 10, 10, 12);
+ Map<String, dynamic> recent(String id, {required Duration ago}) =>
+ _row(id, at: now.subtract(ago).millisecondsSinceEpoch);
+
+ test('a new message that just moved flows and marks its panes', () async {
+ final asked = <(String, Map<String, dynamic>)>[];
+ final messages = AgentMessagesController(
+ read: backend.read,
+ write: backend.write,
+ request: (machineId, payload) async {
+ asked.add((machineId, payload));
+ return {
+ 'messages': [
+ recent('m0000001', ago: const Duration(minutes: 5)),
+ recent('m0000002', ago: const Duration(seconds: 10)),
+ ],
+ };
+ },
+ nameOf: (_, agentId) => names[agentId],
+ now: () => now,
+ );
+ addTearDown(messages.dispose);
+ await messages.pollRemote([
+ (tabId: 'tab', machineIds: ['laptop']),
+ ]);
+ expect(asked.single.$1, 'laptop');
+ expect(asked.single.$2, {
+ 'action': 'history',
+ 'tabId': 'tab',
+ 'limit': 20,
+ });
+ expect(messages.isFlowing('tab'), isTrue);
+ expect(messages.trafficFor('tab'), 1);
+ expect(messages.markFor('studio', 'lead')?.label, '→ API worker');
+ expect(messages.markFor('laptop', 'api')?.label, '← Lead');
+ // Already seen: the next round changes nothing, and neither does the
+ // same message's own frame.
+ messages.seen('studio', 'lead');
+ await messages.pollRemote([
+ (tabId: 'tab', machineIds: ['laptop']),
+ ]);
+ expect(messages.trafficFor('tab'), 1);
+ expect(messages.markFor('studio', 'lead'), isNull);
+ messages.handleEvent(_sent(id: 'm0000002', state: 'delivered'));
+ expect(messages.markFor('studio', 'lead'), isNull);
+ });
+
+ test('older messages are remembered, not announced', () async {
+ final messages = AgentMessagesController(
+ read: backend.read,
+ write: backend.write,
+ request: (_, _) async => {
+ 'messages': [recent('m0000003', ago: const Duration(minutes: 2))],
+ },
+ nameOf: (_, _) => null,
+ now: () => now,
+ );
+ addTearDown(messages.dispose);
+ await messages.pollRemote([
+ (tabId: 'tab', machineIds: ['laptop']),
+ ]);
+ expect(messages.isFlowing('tab'), isFalse);
+ expect(messages.markFor('studio', 'lead'), isNull);
+ messages.handleEvent(_sent(id: 'm0000003', state: 'delivered'));
+ expect(
+ messages.markFor('studio', 'lead'),
+ isNull,
+ reason: 'its marks were due when it moved, not now',
+ );
+ });
+
+ test('one request at a time per machine', () async {
+ final answer = Completer<Map<String, dynamic>>();
+ final asked = <String>[];
+ final messages = AgentMessagesController(
+ read: backend.read,
+ write: backend.write,
+ request: (machineId, payload) {
+ asked.add('$machineId/${payload['tabId']}');
+ return machineId == 'laptop'
+ ? answer.future
+ : Future.value({'messages': const []});
+ },
+ nameOf: (_, _) => null,
+ now: () => now,
+ );
+ addTearDown(messages.dispose);
+ final tabs = <AgentMessagesRemoteTab>[
+ (tabId: 'one', machineIds: ['laptop', 'mini']),
+ (tabId: 'two', machineIds: ['laptop']),
+ ];
+ final first = messages.pollRemote(tabs);
+ await pumpEventQueue();
+ final second = messages.pollRemote(tabs);
+ await pumpEventQueue();
+ expect(asked, ['laptop/one', 'mini/one', 'mini/one']);
+ answer.complete({'messages': const []});
+ await Future.wait([first, second]);
+ expect(asked, ['laptop/one', 'mini/one', 'mini/one', 'laptop/two']);
+ });
+
+ test('a watch asks while the window is in front, every 15 seconds', () {
+ fakeAsync((async) {
+ final foreground = ValueNotifier(false);
+ var rounds = 0;
+ final messages = AgentMessagesController(
+ read: backend.read,
+ write: backend.write,
+ request: (_, _) async {
+ rounds++;
+ return {'messages': const []};
+ },
+ nameOf: (_, _) => null,
+ now: () => now,
+ );
+ var tabs = <AgentMessagesRemoteTab>[
+ (tabId: 'tab', machineIds: ['laptop']),
+ ];
+ final watch = AgentMessagesRemoteWatch(
+ controller: messages,
+ foreground: foreground,
+ tabs: () => tabs,
+ )..start();
+ async.flushMicrotasks();
+ expect(rounds, 0, reason: 'a background window asks nothing');
+ foreground.value = true;
+ async.flushMicrotasks();
+ expect(rounds, 1, reason: 'once on coming to the front');
+ async.elapse(const Duration(seconds: 15));
+ expect(rounds, 2);
+ async.elapse(const Duration(seconds: 15));
+ expect(rounds, 3);
+ tabs = [];
+ async.elapse(const Duration(seconds: 15));
+ expect(rounds, 3, reason: 'no tab is on with remote harnesses');
+ tabs = [
+ (tabId: 'tab', machineIds: ['laptop']),
+ ];
+ foreground.value = false;
+ async.elapse(const Duration(minutes: 1));
+ expect(rounds, 3);
+ expect(async.pendingTimers, isEmpty);
+ watch.dispose();
+ messages.dispose();
+ foreground.dispose();
+ });
+ });
+ });
+
+ group('the app', () {
+ late AppNotifier app;
+
+ setUp(() {
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ const machine = Machine(
+ machineId: 'studio',
+ authMode: MachineAuthMode.remote,
+ name: 'Studio',
+ );
+ app.machines = [machine];
+ app.machineStates['studio'] = MachineState(machine)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = [
+ const Agent(id: 'lead', name: 'Lead', terminalAvailable: true),
+ const Agent(id: 'api', name: 'API worker', terminalAvailable: true),
+ ];
+ });
+ tearDown(() => app.dispose());
+
+ test(
+ 'messages_changed reaches Agent Messages, never turn activity',
+ () async {
+ await app.handleEventForTest('studio', {
+ 'type': 'messages_changed',
+ 'payload': {
+ 'tabId': app.activeSwarmId,
+ 'messageId': 'm0000001',
+ 'at': 1,
+ 'from': {'machineId': 'studio', 'agentId': 'lead'},
+ 'to': [
+ {'machineId': 'studio', 'agentId': 'api', 'state': 'queued'},
+ ],
+ },
+ });
+ expect(app.agentMessages.isFlowing(app.activeSwarmId), isTrue);
+ expect(
+ app.agentMessages.markFor('studio', 'lead')?.label,
+ '→ API worker',
+ );
+ expect(app.agentMessages.markFor('studio', 'api')?.label, '← Lead');
+ final state = app.machineStates['studio']!;
+ expect(state.unknownActivityAgentIds, isEmpty);
+ expect(state.processingAgentIds, isEmpty);
+ app.agentMessages.reset();
+ },
+ );
+
+ test('flags are read when the desk is joined, on desk_changed, and '
+ 'forgotten on sign-out', () async {
+ final api = await joinAgentMessagesDesk(app);
+ expect(api.reads, 1);
+ expect(app.agentMessages.loaded, isTrue);
+ await app.handleEventForTest('studio', {
+ 'type': 'desk_changed',
+ 'payload': {'revision': 0},
+ });
+ await pumpEventQueue();
+ expect(api.reads, 2);
+ app.expireSessionForTest('Signed out');
+ expect(app.agentMessages.loaded, isFalse);
+ });
+
+ test('only desk tabs, once answered, have Agent Messages', () async {
+ final desk = app.activeSwarmId;
+ expect(
+ app.agentMessagesOffered(desk),
+ isFalse,
+ reason: 'before the desk',
+ );
+ final api = await joinAgentMessagesDesk(app);
+ final joined = app.activeSwarmId;
+ expect(app.agentMessagesOffered(joined), isTrue);
+ app.openStore();
+ expect(app.activeSwarm.isStore, isTrue);
+ expect(app.agentMessagesOffered(app.activeSwarmId), isFalse);
+ app.newSwarm(draft: true, newTabPage: true);
+ expect(app.isDraftSwarm(app.activeSwarmId), isTrue);
+ expect(app.agentMessagesOffered(app.activeSwarmId), isFalse);
+ api.unsupported = true;
+ await app.agentMessages.refresh();
+ expect(
+ app.agentMessagesOffered(joined),
+ isFalse,
+ reason: 'an older CLI or backend',
+ );
+ });
+
+ test('a tab that is on polls its harnesses on other machines', () async {
+ const laptop = Machine(
+ machineId: 'laptop',
+ authMode: MachineAuthMode.remote,
+ name: 'Laptop',
+ );
+ app.machineStates['laptop'] = MachineState(laptop)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = [
+ const Agent(id: 'web', name: 'Web', terminalAvailable: true),
+ ];
+ final api = await joinAgentMessagesDesk(app);
+ for (final (machineId, agentId) in [
+ ('studio', 'lead'),
+ ('laptop', 'web'),
+ ]) {
+ app.adoptSessionForTest(
+ TerminalSession(
+ machineId: machineId,
+ agentId: agentId,
+ agentName: agentId,
+ engineId: 'codex',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ ),
+ );
+ }
+ final tab = app.activeSwarmId;
+ expect(app.agentMessagesRemoteTabs(), isEmpty, reason: 'off');
+ api.flags[tab] = true;
+ await app.agentMessages.refresh();
+ final remote = app.agentMessagesRemoteTabs().single;
+ expect(remote.tabId, tab);
+ // No daemon of this computer in this fixture: every machine is remote.
+ expect(remote.machineIds, ['studio', 'laptop']);
+ app.machineStates['laptop']!.connectionStatus =
+ ConnectionStatus.disconnected;
+ expect(app.agentMessagesRemoteTabs().single.machineIds, ['studio']);
+ });
+
+ test('a tab asks this computer and its connected machines', () {
+ expect(
+ app.agentMessageMachines(app.activeSwarmId),
+ isEmpty,
+ reason: 'no local daemon and no panes',
+ );
+ app.adoptSessionForTest(
+ TerminalSession(
+ machineId: 'studio',
+ agentId: 'lead',
+ agentName: 'Lead',
+ engineId: 'codex',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ ),
+ );
+ expect(app.agentMessageMachines(app.activeSwarmId), ['studio']);
+ app.machineStates['studio']!.connectionStatus =
+ ConnectionStatus.disconnected;
+ expect(app.agentMessageMachines(app.activeSwarmId), isEmpty);
+ });
+ });
+}
diff --git a/desktop/test/agent_messages_view_test.dart b/desktop/test/agent_messages_view_test.dart
new file mode 100644
index 000000000..5d89eb94f
--- /dev/null
+++ b/desktop/test/agent_messages_view_test.dart
@@ -0,0 +1,338 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/agent_messages/agent_messages.dart';
+import 'package:harness/agent_messages/agent_messages_view.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/terminal_prompt.dart';
+
+/// Show Agent Messages: a tab's log, newest last, with its On/Off switch. Enter
+/// opens the recipient's pane; Esc closes; nothing is composed here.
+AgentMessage _message(
+ String id,
+ DateTime at, {
+ String from = 'lead',
+ List<String> to = const ['api'],
+ String text = 'Review of 3f2a9c1\nmore detail',
+ Map<String, (String, String?)> states = const {},
+}) => AgentMessage(
+ id: id,
+ tabId: 'tab',
+ from: AgentMessageParty(machineId: 'studio', agentId: from, name: from),
+ to: [
+ for (final r in to)
+ AgentMessageParty(machineId: 'laptop', agentId: r, name: r),
+ ],
+ text: text,
+ at: at,
+ statuses: [
+ for (final MapEntry(:key, :value) in states.entries)
+ AgentMessageStatus(
+ machineId: 'laptop',
+ agentId: key,
+ state: AgentMessageState.parse(value.$1)!,
+ reason: value.$2,
+ at: at.millisecondsSinceEpoch,
+ ),
+ ],
+);
+
+void main() {
+ late AgentMessagesController controller;
+ late Map<String, bool> saved;
+ late Object? writeError;
+
+ setUp(() {
+ saved = {};
+ writeError = null;
+ controller = AgentMessagesController(
+ read: () async => {
+ 'tabs': [
+ for (final MapEntry(:key, :value) in saved.entries)
+ {'id': key, 'enabled': value},
+ ],
+ },
+ write: (tabId, enabled) async {
+ if (writeError case final error?) throw error;
+ saved[tabId] = enabled;
+ return {'tabId': tabId, 'enabled': enabled};
+ },
+ request: (_, _) async => {},
+ nameOf: (_, agentId) => agentId,
+ );
+ });
+ tearDown(() => controller.dispose());
+
+ Future<List<AgentMessageParty>> open(
+ WidgetTester tester,
+ Future<AgentMessageLog> Function() load, {
+ Brightness brightness = Brightness.dark,
+ }) async {
+ final opened = <AgentMessageParty>[];
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Builder(
+ builder: (context) => TextButton(
+ key: const ValueKey('open'),
+ onPressed: () => showTerminalPrompt<void>(
+ context,
+ builder: (context) => AgentMessagesView(
+ controller: controller,
+ tabId: 'tab',
+ tabName: 'app',
+ load: load,
+ onClose: () => Navigator.pop(context),
+ onOpen: (recipient) {
+ opened.add(recipient);
+ Navigator.pop(context);
+ },
+ ),
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.byKey(const ValueKey('open')));
+ await tester.pumpAndSettle();
+ return opened;
+ }
+
+ final now = DateTime.now();
+ final today = DateTime(now.year, now.month, now.day, 14, 2);
+
+ for (final brightness in Brightness.values) {
+ testWidgets('rows read time, sender → recipients, first line and state, '
+ 'newest last (${brightness.name})', (tester) async {
+ await open(
+ tester,
+ () async => (
+ reached: true,
+ complete: true,
+ messages: [
+ _message(
+ 'm0000001',
+ DateTime(2026, 10, 9, 9, 5),
+ states: {'api': ('delivered', null)},
+ ),
+ _message(
+ 'm0000002',
+ today,
+ from: 'api',
+ to: ['lead', 'web'],
+ text: '\nShipped the fix\nsecond line',
+ states: {
+ 'lead': ('delivered', null),
+ 'web': ('failed', 'web left the tab'),
+ },
+ ),
+ ],
+ ),
+ brightness: brightness,
+ );
+ expect(find.text('app · Agent Messages'), findsOneWidget);
+ expect(find.text('lead → api'), findsOneWidget);
+ expect(find.text('Oct 9 09:05'), findsOneWidget);
+ expect(find.text('Review of 3f2a9c1'), findsOneWidget);
+ expect(find.text('more detail'), findsNothing);
+ expect(find.text('delivered'), findsOneWidget);
+ expect(find.text('api → lead, web'), findsOneWidget);
+ expect(find.text('14:02'), findsOneWidget);
+ expect(find.text('Shipped the fix'), findsOneWidget);
+ expect(find.text('lead delivered · web failed'), findsOneWidget);
+ expect(find.text('web: web left the tab'), findsOneWidget);
+ expect(
+ tester.getTopLeft(find.text('lead → api')).dy,
+ lessThan(tester.getTopLeft(find.text('api → lead, web')).dy),
+ reason: 'newest last',
+ );
+ expect(tester.takeException(), isNull);
+ });
+ }
+
+ testWidgets('Enter opens the recipient of the focused row; arrows move', (
+ tester,
+ ) async {
+ final opened = await open(
+ tester,
+ () async => (
+ reached: true,
+ complete: true,
+ messages: [
+ _message('m0000001', today, to: ['api']),
+ _message('m0000002', today, from: 'api', to: ['lead']),
+ ],
+ ),
+ );
+ // The newest row has the keyboard when the log opens.
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(opened.map((r) => r.agentId), ['lead']);
+ expect(find.text('app · Agent Messages'), findsNothing);
+
+ await tester.tap(find.byKey(const ValueKey('open')));
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(opened.map((r) => r.agentId), ['lead', 'api']);
+ });
+
+ testWidgets('Esc closes', (tester) async {
+ final opened = await open(
+ tester,
+ () async => (reached: true, complete: true, messages: <AgentMessage>[]),
+ );
+ expect(find.text('app · Agent Messages'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.text('app · Agent Messages'), findsNothing);
+ expect(opened, isEmpty);
+ });
+
+ testWidgets('an empty log says how to start; an unreachable one says so', (
+ tester,
+ ) async {
+ await open(
+ tester,
+ () async => (reached: true, complete: true, messages: <AgentMessage>[]),
+ );
+ expect(
+ find.text(
+ 'No messages yet. Turn on Agent Messages, then agents use '
+ '`harness send`.',
+ ),
+ findsOneWidget,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await open(
+ tester,
+ () async => (reached: false, complete: false, messages: <AgentMessage>[]),
+ );
+ expect(
+ find.textContaining('Could not read this tab’s messages'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a machine that did not answer is said, once', (tester) async {
+ await open(
+ tester,
+ () async => (
+ reached: true,
+ complete: false,
+ messages: [_message('m0000001', today)],
+ ),
+ );
+ expect(
+ find.text('Some machines didn’t answer; their messages may be missing.'),
+ findsOneWidget,
+ );
+ expect(find.text('lead → api'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await open(
+ tester,
+ () async => (
+ reached: true,
+ complete: true,
+ messages: [_message('m0000001', today)],
+ ),
+ );
+ expect(
+ find.byKey(const ValueKey('agent-messages-incomplete')),
+ findsNothing,
+ );
+ });
+
+ testWidgets('many recipients each with a state never overflow a row', (
+ tester,
+ ) async {
+ final recipients = [for (var i = 0; i < 8; i++) 'worker-$i'];
+ await open(
+ tester,
+ () async => (
+ reached: true,
+ complete: true,
+ messages: [
+ _message(
+ 'm0000001',
+ today,
+ to: recipients,
+ states: {
+ for (final (i, r) in recipients.indexed)
+ r: (i.isEven ? 'delivered' : 'queued', null),
+ },
+ ),
+ ],
+ ),
+ );
+ expect(tester.takeException(), isNull);
+ final state = tester.widget<Text>(
+ find.byKey(const ValueKey('agent-message-state')),
+ );
+ expect(state.overflow, TextOverflow.ellipsis);
+ expect(state.data, contains('worker-0 delivered · worker-1 queued'));
+ });
+
+ testWidgets('the switch turns Agent Messages on, and back when refused', (
+ tester,
+ ) async {
+ await open(
+ tester,
+ () async => (reached: true, complete: true, messages: <AgentMessage>[]),
+ );
+ final toggle = find.byKey(const ValueKey('agent-messages-switch'));
+ expect(tester.widget<Switch>(toggle).value, isFalse);
+ await tester.tap(toggle);
+ await tester.pumpAndSettle();
+ expect(tester.widget<Switch>(toggle).value, isTrue);
+ expect(saved, {'tab': true});
+ writeError = StateError('offline');
+ await tester.tap(toggle);
+ await tester.pumpAndSettle();
+ expect(tester.widget<Switch>(toggle).value, isTrue, reason: 'reverted');
+ expect(find.textContaining('could not be turned off'), findsOneWidget);
+ });
+
+ testWidgets('traffic in this tab reads the log again', (tester) async {
+ var reads = 0;
+ await open(tester, () async {
+ reads++;
+ return (
+ reached: true,
+ complete: true,
+ messages: [
+ for (var i = 0; i < reads; i++)
+ _message('m000000$i', today.add(Duration(minutes: i))),
+ ],
+ );
+ });
+ expect(reads, 1);
+ controller.handleEvent({'tabId': 'another', 'messageId': 'm1000000'});
+ await tester.pumpAndSettle();
+ expect(reads, 1);
+ controller.handleEvent({'tabId': 'tab', 'messageId': 'm1000001'});
+ await tester.pumpAndSettle();
+ expect(reads, 2);
+ expect(find.text('lead → api'), findsNWidgets(2));
+ // Let the ⇄'s minute run out before the test ends.
+ await tester.pump(const Duration(seconds: 61));
+ expect(controller.isFlowing('tab'), isFalse);
+ });
+
+ test('times read as a clock today and with the day before', () {
+ final now = DateTime(2026, 10, 10, 18);
+ expect(agentMessageTime(DateTime(2026, 10, 10, 9, 7), now: now), '09:07');
+ expect(
+ agentMessageTime(DateTime(2026, 9, 30, 23, 59), now: now),
+ 'Sep 30 23:59',
+ );
+ });
+}
diff --git a/desktop/test/api_client_test.dart b/desktop/test/api_client_test.dart
index 5d2c50ac8..4b0438ec3 100644
--- a/desktop/test/api_client_test.dart
+++ b/desktop/test/api_client_test.dart
@@ -107,6 +107,85 @@ void main() {
},
);
+ test(
+ 'Agent Messages: 404 is a daemon without them, 401 and 503 are a moment',
+ () async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ var status = 200;
+ final seen = <(String, String, String?, String)>[];
+ final subscription = server.listen((request) async {
+ seen.add((
+ request.method,
+ request.uri.path,
+ request.headers.value('x-adapter-local'),
+ await utf8.decoder.bind(request).join(),
+ ));
+ request.response
+ ..statusCode = status
+ ..headers.contentType = ContentType.json
+ ..write(
+ jsonEncode(
+ status == 200
+ ? {
+ 'success': true,
+ 'data': request.method == 'GET'
+ ? {'revision': 1, 'machines': [], 'tabs': []}
+ : {'tabId': 'tab-1', 'enabled': true, 'revision': 2},
+ }
+ : {
+ 'success': false,
+ 'error': {'message': 'Not now'},
+ },
+ ),
+ );
+ await request.response.close();
+ });
+ try {
+ final api = ApiClient(
+ config: AppConfig(
+ apiBaseUrl: 'http://unused.invalid',
+ localCliBaseUrl: 'http://127.0.0.1:${server.port}',
+ ),
+ session: AuthSession(),
+ );
+ expect(await api.readAgentMessageTabs(), {
+ 'revision': 1,
+ 'machines': [],
+ 'tabs': [],
+ });
+ expect(await api.setAgentMessages('tab-1', true), {
+ 'tabId': 'tab-1',
+ 'enabled': true,
+ 'revision': 2,
+ });
+ expect(seen.last, (
+ 'PATCH',
+ '/api/agent-messages/tabs/tab-1',
+ '1',
+ jsonEncode({'enabled': true}),
+ ));
+ status = 404;
+ expect(await api.readAgentMessageTabs(), isNull);
+ for (final transient in [401, 503]) {
+ status = transient;
+ await expectLater(
+ api.readAgentMessageTabs(),
+ throwsA(
+ isA<ApiException>().having((e) => e.status, 'status', transient),
+ ),
+ );
+ }
+ await expectLater(
+ api.setAgentMessages('tab-1', false),
+ throwsA(isA<ApiException>()),
+ );
+ } finally {
+ await subscription.cancel();
+ await server.close(force: true);
+ }
+ },
+ );
+
test('machine request hits the local CLI proxy, not the backend, with no credential', () async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final paths = <String>[];
diff --git a/desktop/test/channel_controller_test.dart b/desktop/test/channel_controller_test.dart
deleted file mode 100644
index ae36397f4..000000000
--- a/desktop/test/channel_controller_test.dart
+++ /dev/null
@@ -1,93 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/teams/team_controller.dart';
-
-import 'support/team_fixture.dart';
-
-void main() {
- test(
- 'channel history opens directly and only reads its pinned tab',
- () async {
- final calls = <Map<String, dynamic>>[];
- final controller = TeamController(
- channelTabId: 'device',
- request: (p) async {
- calls.add(p);
- return {
- 'team': {
- ...teamFixture(),
- 'channel': {'tabId': 'device'},
- },
- };
- },
- );
- addTearDown(controller.dispose);
- controller.watch();
- await controller.refresh();
- controller.unwatch();
- expect(calls, [
- {'action': 'channel_get', 'tabId': 'device'},
- ]);
- expect(controller.isChannel, isTrue);
- expect(controller.selectedExchange, questionId);
- },
- );
-
- test(
- 'uncertain consult retries the same source and joins repeated keypresses',
- () async {
- final calls = <Map<String, dynamic>>[];
- final pending = Completer<Map<String, dynamic>>();
- final controller = TeamController(
- channelTabId: 'device',
- request: (p) {
- calls.add(p);
- if (calls.length == 1) return pending.future;
- return Future.value({
- 'consultation': {
- 'receipt': {'state': 'queued'},
- },
- });
- },
- );
- addTearDown(controller.dispose);
- final first = controller.consult('host', 'mobile');
- final repeated = controller.consult('host', 'mobile');
- expect(identical(first, repeated), isTrue);
- pending.completeError(TimeoutException('Lost reply'));
- expect(await first, contains('same instruction'));
- await controller.consult('host', 'mobile');
- expect(calls[1], calls[0]);
- expect(calls[0]['tabId'], 'device');
- expect(calls[0]['from'], {'machineId': 'host', 'agentId': 'mobile'});
- await controller.consult('host', 'firmware');
- expect(calls[2]['id'], isNot(calls[0]['id']));
- expect(calls.map((p) => p['action']), everyElement('channel_consult'));
- },
- );
-
- test(
- 'a definitive channel refusal does not leave an uncertain instruction',
- () async {
- final ids = <String>[];
- final controller = TeamController(
- channelTabId: 'single',
- request: (p) async {
- ids.add(p['id'] as String);
- return {
- 'error': 'NO_PEERS',
- 'detail': 'Add another agent to this tab.',
- };
- },
- );
- addTearDown(controller.dispose);
- expect(
- await controller.consult('host', 'mobile'),
- contains('Add another agent'),
- );
- await controller.consult('host', 'mobile');
- expect(ids.toSet(), hasLength(2));
- },
- );
-}
diff --git a/desktop/test/channel_shortcut_test.dart b/desktop/test/channel_shortcut_test.dart
deleted file mode 100644
index 4a71f239f..000000000
--- a/desktop/test/channel_shortcut_test.dart
+++ /dev/null
@@ -1,106 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/core/models.dart';
-import 'package:harness/state/app_state.dart';
-import 'package:harness/teams/team_workspace.dart';
-import 'package:harness/terminal/terminal_binary.dart';
-import 'package:harness/ws/ws_conn.dart';
-
-import 'keymap_host_test.dart' show MemoryKeymap, key;
-import 'keymap_runtime_test.dart' show mount;
-import 'swarm_screen_test.dart' show terminal;
-import 'swarm_state_test.dart' show createApp;
-import 'support/team_fixture.dart';
-
-class ChannelConnection extends WsConn {
- ChannelConnection()
- : super(
- wsBaseUrl: 'ws://fixture.invalid',
- autonomousEnv: 'test',
- machineId: 'm',
- accessTokenProvider: (_, _) async => '',
- onAuthFailure: (_) {},
- onEvent: (_) {},
- onStatus: (_) {},
- );
- final calls = <Map<String, dynamic>>[];
- final pending = Completer<Map<String, dynamic>>();
- @override
- Future<Map<String, dynamic>> request(
- String type, {
- Map<String, dynamic> payload = const {},
- Duration timeout = const Duration(seconds: 20),
- }) async {
- if (type == 'team') {
- calls.add(payload);
- return pending.future;
- }
- return {};
- }
-}
-
-void main() {
- for (final shared in [true, false]) {
- test(
- 'tab reads use an owned available gateway when preferred is ${shared ? 'shared' : 'offline'}',
- () async {
- final connection = ChannelConnection();
- final gateways = <String>[];
- final app = createApp(
- connected: true,
- connectionForTest: (machineId) {
- gateways.add(machineId);
- return connection;
- },
- );
- final preferred = Machine(
- machineId: 'preferred',
- authMode: MachineAuthMode.remote,
- isShared: shared,
- );
- app.machineStates['preferred'] = MachineState(preferred)
- ..connectionStatus = shared
- ? ConnectionStatus.connected
- : ConnectionStatus.disconnected;
- final tabId = app.activeSwarmId;
- final controller = app.channelController(tabId, 'preferred');
- connection.pending.complete({
- 'team': {
- ...teamFixture(),
- 'machineId': 'm',
- 'channel': {'tabId': tabId},
- },
- });
- await controller.refresh();
- expect(gateways, ['m']);
- expect(connection.calls, [
- {'action': 'channel_get', 'tabId': tabId},
- ]);
- expect(controller.error, isNull);
- app.dispose();
- await connection.close();
- },
- );
- }
-
- testWidgets('Cmd+Shift+A does not start cross-tab work', (tester) async {
- final connection = ChannelConnection();
- final app = createApp(connectionForTest: (_) => connection, connected: true)
- ..status = AppStatus.authenticated;
- final map = MemoryKeymap();
- final frames = <TerminalBinaryFrame>[];
- app.adoptSessionForTest(terminal('a0', frames));
- await mount(tester, app, map);
- await key(tester, LogicalKeyboardKey.keyA, cmd: true, shift: true);
- await tester.pump();
- expect(connection.calls, isEmpty);
- expect(find.byType(TeamWorkspace), findsNothing);
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- map.dispose();
- await connection.close();
- });
-}
diff --git a/desktop/test/channel_workspace_test.dart b/desktop/test/channel_workspace_test.dart
deleted file mode 100644
index 09abb5e53..000000000
--- a/desktop/test/channel_workspace_test.dart
+++ /dev/null
@@ -1,290 +0,0 @@
-import 'dart:io';
-import 'dart:ui' as ui;
-
-import 'package:flutter/material.dart';
-import 'package:flutter/rendering.dart';
-import 'package:flutter/services.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/teams/team_controller.dart';
-import 'package:harness/teams/team_workspace.dart';
-import 'package:harness/terminal/terminal_font_store.dart';
-import 'package:harness/widgets/desktop_chrome.dart';
-
-import 'support/team_fixture.dart';
-import 'support/real_fonts.dart';
-
-void main() {
- setUpAll(() async {
- await loadRealFonts();
- if (Platform.isMacOS &&
- Platform.environment['CHANNEL_RENDER_DIR'] != null) {
- final font = ByteData.sublistView(
- await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
- );
- for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {
- await (FontLoader(family)..addFont(Future.value(font))).load();
- }
- }
- await (FontLoader(
- 'MaterialIcons',
- )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
- });
-
- Future<void> capture(WidgetTester tester, String name) async {
- final directory = Platform.environment['CHANNEL_RENDER_DIR'];
- if (directory == null) return;
- final oldShadows = debugDisableShadows;
- try {
- debugDisableShadows = false;
- for (final object in tester.allRenderObjects) {
- object.markNeedsPaint();
- }
- await tester.pump();
- final boundary = tester.renderObject<RenderRepaintBoundary>(
- find.byKey(const ValueKey('channel-preview')),
- );
- await tester.runAsync(() async {
- final image = await boundary.toImage(pixelRatio: 2);
- final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
- await Directory(directory).create(recursive: true);
- await File('$directory/$name.png')
- .writeAsBytes(bytes!.buffer.asUint8List());
- image.dispose();
- });
- } finally {
- debugDisableShadows = oldShadows;
- for (final object in tester.allRenderObjects) {
- object.markNeedsPaint();
- }
- await tester.pump();
- }
- }
-
- Future<TeamController> show(
- WidgetTester tester, {
- required List<Map<String, dynamic>> calls,
- Map<String, dynamic>? fixture,
- Brightness brightness = Brightness.dark,
- Size size = const Size(390, 620),
- double scale = 1,
- VoidCallback? onClose,
- String? error,
- }) async {
- tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = size;
- addTearDown(tester.view.reset);
- final oldBrightness = grid.AppTheme.brightness.value;
- grid.AppTheme.brightness.value = brightness;
- addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
- final model = TeamController(
- channelTabId: 'device',
- request: (payload) async {
- calls.add(payload);
- if (error != null) throw TeamRequestError(error);
- return {
- 'team': {
- ...fixture ?? teamFixture(),
- 'name': 'Device',
- 'channel': {'tabId': 'device'},
- },
- };
- },
- );
- await tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- builder: (context, child) => MediaQuery(
- data: MediaQuery.of(context)
- .copyWith(textScaler: TextScaler.linear(scale)),
- child: child!,
- ),
- home: RepaintBoundary(
- key: const ValueKey('channel-preview'),
- child: Scaffold(
- body: TeamWorkspace(
- controller: model,
- candidates: const [],
- machineName: 'Mac',
- onClose: onClose ?? () {},
- onOpen: (_, _) {},
- ),
- ),
- ),
- ),
- );
- addTearDown(() async {
- await tester.pumpWidget(const SizedBox());
- model.dispose();
- });
- await tester.pumpAndSettle();
- return model;
- }
-
- for (final width in [390.0, 1280.0]) {
- for (final brightness in Brightness.values) {
- for (final scale in [1.0, 2.0]) {
- testWidgets(
- 'tab channel $width ${brightness.name} $scale keeps the same read-only history',
- (tester) async {
- final calls = <Map<String, dynamic>>[];
- await show(
- tester,
- calls: calls,
- brightness: brightness,
- size: Size(width, width == 390 && scale == 2 ? 360 : 820),
- scale: scale,
- );
- expect(find.text('Device'), findsOneWidget);
- expect(find.textContaining('This tab only'), findsOneWidget);
- expect(find.byKey(const Key('team-question')), findsNothing);
- expect(find.byKey(const Key('team-new')), findsNothing);
- expect(find.text('New question'), findsNothing);
- expect(
- find.textContaining('Use GET /api/daemons.'),
- findsOneWidget,
- );
- expect(calls.map((p) => p['action']), everyElement('channel_get'));
- expect(tester.takeException(), isNull);
- if (width == 390 && scale == 2) {
- expect(
- tester
- .getSize(find.byKey(const ValueKey('team-compact-content')))
- .height,
- greaterThan(220),
- );
- expect(
- find.byKey(const ValueKey('team-close')).hitTestable(),
- findsOneWidget,
- );
- }
- await capture(
- tester,
- 'channel-${brightness.name}-${width.toInt()}-$scale',
- );
- if (width == 390 || scale == 2) {
- await tester.ensureVisible(
- find.textContaining('Use GET /api/daemons.'),
- );
- await tester.pumpAndSettle();
- expect(tester.takeException(), isNull);
- await capture(
- tester,
- 'answer-${brightness.name}-${width.toInt()}-$scale',
- );
- }
- },
- );
- }
- }
- }
-
- testWidgets(
- 'page keys scroll the active list and keyboard focus keeps row geometry',
- (tester) async {
- final calls = <Map<String, dynamic>>[];
- final fixture = teamFixture();
- final exchange = (fixture['exchanges'] as List).first as Map;
- fixture['exchanges'] = [
- for (var i = 0; i < 24; i++)
- {
- ...exchange,
- 'id': 'exchange-$i',
- 'createdAt': i,
- 'text':
- 'Review $i: Which endpoint should the frontend use while the owner machine reconnects?',
- },
- ];
- var closed = false;
- final model = await show(
- tester,
- calls: calls,
- fixture: fixture,
- size: const Size(390, 540),
- scale: 1.6,
- onClose: () => closed = true,
- );
- final compact = tester
- .widget<SingleChildScrollView>(
- find.byKey(const ValueKey('team-compact-content')),
- )
- .controller!;
- await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
- await tester.pump();
- expect(compact.offset, greaterThan(0));
- await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
- await tester.pump();
- expect(compact.offset, 0);
-
- final row = find.byKey(const ValueKey('team-exchange-exchange-23'));
- await tester.ensureVisible(row);
- await tester.pumpAndSettle();
- final before = tester.getRect(row);
- await tester.tap(row);
- await tester.pumpAndSettle();
- expect(model.selectedExchange, 'exchange-23');
- expect(tester.getRect(row), before);
- final button = find.descendant(
- of: row,
- matching: find.byType(TextButton),
- );
- Focus.of(
- tester.element(
- find.descendant(of: button, matching: find.byType(Text)).first,
- ),
- ).requestFocus();
- await tester.pump();
- final style = tester.widget<TextButton>(button).style!;
- expect(
- style.side!.resolve({WidgetState.focused})!.color,
- DesktopChrome.focusRing,
- );
- expect(
- style.backgroundColor!.resolve({WidgetState.focused}),
- DesktopChrome.selection,
- );
- final list = tester
- .widget<ListView>(find.byKey(const ValueKey('team-exchanges')))
- .controller!;
- await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
- await tester.pump();
- expect(list.offset, greaterThan(0));
- await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
- await tester.pump();
- expect(list.offset, 0);
-
- final originalFont = terminalFontStore.value;
- addTearDown(() => terminalFontStore.value = originalFont);
- terminalFontStore.value = originalFont.copyWith(fontSize: 26);
- await tester.pumpAndSettle();
- expect(tester.getRect(row), before);
- expect(calls.map((p) => p['action']), everyElement('channel_get'));
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- expect(closed, isTrue);
- expect(tester.takeException(), isNull);
- },
- );
-
- testWidgets(
- 'a long failed read remains readable without enabling team actions',
- (tester) async {
- final calls = <Map<String, dynamic>>[];
- await show(
- tester,
- calls: calls,
- size: const Size(390, 360),
- scale: 2,
- error: 'The owner is unavailable. ' * 20,
- );
- expect(find.text('No teams yet. Start with two sessions.'), findsNothing);
- final retry = find.widgetWithText(TextButton, 'Retry reading tab');
- await tester.ensureVisible(retry);
- await tester.pumpAndSettle();
- expect(retry.hitTestable(), findsOneWidget);
- expect(calls.map((p) => p['action']), everyElement('channel_get'));
- expect(tester.takeException(), isNull);
- await capture(tester, 'unavailable-dark-2.0');
- },
- );
-}
diff --git a/desktop/test/desk_sync_test.dart b/desktop/test/desk_sync_test.dart
index 6b631a9bd..0021cf4ff 100644
--- a/desktop/test/desk_sync_test.dart
+++ b/desktop/test/desk_sync_test.dart
@@ -72,6 +72,10 @@ class _DeskApi extends ApiClient {
doc = DeskDoc(revision: doc!.revision + 1, tabs: next);
return _json(doc!);
}
+
+ /// Agent Messages' flags are read once the desk is; this proxy has none.
+ @override
+ Future<Map<String, dynamic>?> readAgentMessageTabs() async => null;
}
void main() {
diff --git a/desktop/test/desktop_workspace_tab_test.dart b/desktop/test/desktop_workspace_tab_test.dart
index abb6083e7..160bed341 100644
--- a/desktop/test/desktop_workspace_tab_test.dart
+++ b/desktop/test/desktop_workspace_tab_test.dart
@@ -225,7 +225,10 @@ void main() {
);
expect(icon.icon, AppIcons.close);
expect(icon.size, 12);
- expect(tester.getSize(_close('Desktop')), const Size(32, 32));
+ expect(
+ tester.getSize(_close('Desktop')),
+ const Size(DesktopWorkspaceTab.closeWidth, 32),
+ );
await _capture(
tester,
boundary,
diff --git a/desktop/test/e2ee/encrypted_down_types_test.dart b/desktop/test/e2ee/encrypted_down_types_test.dart
index 5d156891e..255086f5f 100644
--- a/desktop/test/e2ee/encrypted_down_types_test.dart
+++ b/desktop/test/e2ee/encrypted_down_types_test.dart
@@ -69,7 +69,10 @@ void main() {
...namesIn(relay, 'PAIR_REQUESTS'),
plateRequest(relay),
...namesIn(cli('sharing/protocol.ts'), 'SHARE_REQUEST_TYPES'),
- ...namesIn(cli('teams/wire.ts'), 'TEAM_REQUEST_TYPES'),
+ ...namesIn(
+ cli('messages/wire.ts'),
+ 'AGENT_MESSAGES_REQUEST_TYPES',
+ ),
...namesIn(cli('lib/viewerFrames.ts'), 'VIEWER_DOWN_TYPES'),
};
});
@@ -99,7 +102,7 @@ void main() {
'VIEWER_DOWN_TYPES',
'PAIR_REQUESTS',
'PLATE_REQUEST',
- 'TEAM_REQUEST_TYPES',
+ 'AGENT_MESSAGES_REQUEST_TYPES',
});
expect(body, contains('isEncryptedDownType(type)'));
});
diff --git a/desktop/test/e2ee/strict_down_test.dart b/desktop/test/e2ee/strict_down_test.dart
index f5d3b08f5..683f82519 100644
--- a/desktop/test/e2ee/strict_down_test.dart
+++ b/desktop/test/e2ee/strict_down_test.dart
@@ -46,25 +46,23 @@ Future<RelaySessionCrypto> _session(Map<String, Object> features) async {
}
void main() {
- test('team capabilities and peer content are always sealed', () async {
+ test('agent messages are always sealed', () async {
+ // A tab's log carries what agents said to each other (CLI messages/wire.ts).
for (final features in [
<String, Object>{},
<String, Object>{'strictDown': 1},
]) {
final session = await _session(features);
- for (final type in ['team', 'team_delivery']) {
- final out = session.wrapOutgoing({
- 'type': type,
- 'payload': {
- 'requestId': 'team-1',
- 'memberKey': 'private-capability',
- 'text': 'private-question',
- },
- });
- expect(isWrapped(out['payload']), isTrue, reason: type);
- expect(jsonEncode(out), isNot(contains('private-capability')));
- expect(jsonEncode(out), isNot(contains('private-question')));
- }
+ final out = session.wrapOutgoing({
+ 'type': 'agent_messages',
+ 'payload': {
+ 'requestId': 'messages-1',
+ 'action': 'history',
+ 'tabId': 'private-tab',
+ },
+ });
+ expect(isWrapped(out['payload']), isTrue);
+ expect(jsonEncode(out), isNot(contains('private-tab')));
}
});
diff --git a/desktop/test/keymap_test.dart b/desktop/test/keymap_test.dart
index a219b0b90..1e5a76de1 100644
--- a/desktop/test/keymap_test.dart
+++ b/desktop/test/keymap_test.dart
@@ -96,6 +96,7 @@ void main() {
final config = KeymapConfig.parse('''{"bindings":[
{"keys":"cmd+i","command":"picker.preview","when":"picker"},
{"keys":"cmd+o","command":"navigation.quick_open"},
+ {"keys":"cmd+shift+y","command":"team.open"},
{"keys":"cmd+ctrl+h","command":"pane.focus_left"}
]}''', commands: commands);
expect(config.bindings.single.command, 'pane.focus_left');
diff --git a/desktop/test/linux_menu_bar_test.dart b/desktop/test/linux_menu_bar_test.dart
index 2367d6e9d..725dfa938 100644
--- a/desktop/test/linux_menu_bar_test.dart
+++ b/desktop/test/linux_menu_bar_test.dart
@@ -4,6 +4,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/screens/swarm_menu_bus.dart';
import 'package:harness/shared/theme/app_theme.dart';
+import 'package:harness/shared/widgets/app_menu.dart';
import 'package:harness/widgets/linux_menu_bar.dart';
/// The Linux menu bar's wiring.
@@ -157,6 +158,35 @@ void main() {
expect(swarmCalls.last.method, 'closeActive');
});
+ testWidgets('Agent Messages rows act on the active tab', (tester) async {
+ swarmMenuBus.send('update', {'enabled': true, 'activeAgentMessages': true});
+ await pumpBar(tester);
+
+ await tap(tester, 'menu-bar-file');
+ expect(
+ tester
+ .widget<AppMenuItem>(find.byKey(const Key('menu-bar-agent-messages')))
+ .selected,
+ isTrue,
+ reason: 'a checkmark while on',
+ );
+ await tap(tester, 'menu-bar-agent-messages');
+ expect(swarmCalls.last.method, 'toggleAgentMessages');
+ expect(swarmCalls.last.arguments, isNull, reason: 'the active tab');
+
+ await tap(tester, 'menu-bar-file');
+ await tap(tester, 'menu-bar-show-agent-messages');
+ expect(swarmCalls.last.method, 'showAgentMessages');
+
+ // The Store tab has no Agent Messages: both rows go quiet.
+ swarmMenuBus.send('update', {'enabled': true});
+ await tester.pump();
+ await tap(tester, 'menu-bar-file');
+ expect(find.byKey(const Key('menu-bar-agent-messages')), findsNothing);
+ expect(find.byKey(const Key('menu-bar-show-agent-messages')), findsNothing);
+ expect(find.text('Show Agent Messages'), findsOneWidget);
+ });
+
testWidgets('View reaches both channels', (tester) async {
await pumpBar(tester);
diff --git a/desktop/test/native_toolbar_sync_test.dart b/desktop/test/native_toolbar_sync_test.dart
index 9e7d10524..3819e827c 100644
--- a/desktop/test/native_toolbar_sync_test.dart
+++ b/desktop/test/native_toolbar_sync_test.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -10,6 +12,7 @@ import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm.dart';
import 'package:harness/state/swarm_catalog.dart';
+import 'support/agent_messages_api.dart';
import 'swarm_screen_test.dart' show mount;
class _App extends AppNotifier {
@@ -215,4 +218,92 @@ void main() {
await tester.pumpWidget(const SizedBox());
},
);
+
+ testWidgets('tabs carry Agent Messages, and its actions reach the tab', (
+ tester,
+ ) async {
+ final app = _App();
+ addTearDown(app.dispose);
+ final api = await joinAgentMessagesDesk(app);
+ await mount(tester, app, nativeTabs: true);
+ await tester.pumpAndSettle();
+ final tab = app.activeSwarmId;
+ Map row() => (updates().last['tabs'] as List).single as Map;
+
+ // Traffic alone rebuilds no workspace; it reaches the ⇄ only while on,
+ // since a struck ⇄ at rest would say nothing true.
+ app.agentMessages.handleEvent({'tabId': tab, 'messageId': 'm0000001'});
+ await tester.idle();
+ expect(row()['agentMessages'], isFalse);
+ expect(row()['agentMessagesFlowing'], isFalse);
+ expect(updates().last['activeAgentMessages'], isFalse);
+
+ Future<void> native(String method) =>
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ 'harness/swarm_tabs',
+ const StandardMethodCodec().encodeMethodCall(
+ MethodCall(method, {'id': tab}),
+ ),
+ (_) {},
+ );
+ // ⇄ or the tab's menu turns it on for that tab.
+ unawaited(native('toggleAgentMessages'));
+ await tester.pumpAndSettle();
+ expect(api.writes, [(tab, true)]);
+ expect(row()['agentMessages'], isTrue);
+ expect(row()['agentMessagesFlowing'], isTrue);
+ expect(updates().last['activeAgentMessages'], isTrue);
+
+ // A refused turn off goes back, and says so where the click was.
+ api.writeError = StateError('offline');
+ unawaited(native('toggleAgentMessages'));
+ await tester.pumpAndSettle();
+ expect(app.agentMessages.isOn(tab), isTrue);
+ expect(row()['agentMessages'], isTrue);
+ expect(find.textContaining('could not be turned off'), findsOneWidget);
+ api.writeError = null;
+
+ // Show Agent Messages opens the tab's log.
+ unawaited(native('showAgentMessages'));
+ await tester.pumpAndSettle();
+ expect(find.text('Before · Agent Messages'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.text('Before · Agent Messages'), findsNothing);
+
+ await tester.pump(const Duration(seconds: 61));
+ await tester.idle();
+ expect(row()['agentMessagesFlowing'], isFalse);
+
+ // An older CLI or backend: no ⇄, no menu row.
+ api.unsupported = true;
+ await app.agentMessages.refresh();
+ await tester.idle();
+ expect(row().containsKey('agentMessages'), isFalse);
+ expect(updates().last['activeAgentMessages'], isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('a tab off the desk has no Agent Messages', (tester) async {
+ final app = _App();
+ addTearDown(app.dispose);
+ await mount(tester, app, nativeTabs: true);
+ await tester.pumpAndSettle();
+ expect(app.agentMessagesOffered(app.activeSwarmId), isFalse);
+ final row = (updates().last['tabs'] as List).single as Map;
+ expect(row.containsKey('agentMessages'), isFalse);
+ expect(updates().last['activeAgentMessages'], isNull);
+ unawaited(
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ 'harness/swarm_tabs',
+ const StandardMethodCodec().encodeMethodCall(
+ MethodCall('showAgentMessages'),
+ ),
+ (_) {},
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Agent Messages'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
}
diff --git a/desktop/test/pane_message_mark_test.dart b/desktop/test/pane_message_mark_test.dart
new file mode 100644
index 000000000..bf76ef424
--- /dev/null
+++ b/desktop/test/pane_message_mark_test.dart
@@ -0,0 +1,130 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/agent_messages/pane_message_mark.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/terminal_panel.dart';
+
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+/// The pane header's Agent Messages mark (docs/design/2026-10-10-agent-messages.md,
+/// "Panes"): `→ <recipient>` on the sender, `← <sender>` on the recipient, for a
+/// few seconds or until that pane is focused, beside the activity mark.
+Map<String, dynamic> _changed(String id, String from, String to) => {
+ 'type': 'messages_changed',
+ 'payload': {
+ 'tabId': 'tab',
+ 'messageId': id,
+ 'at': 1,
+ 'from': {'machineId': 'm', 'agentId': from},
+ 'to': [
+ {'machineId': 'm', 'agentId': to, 'state': 'queued'},
+ ],
+ },
+};
+
+void main() {
+ for (final brightness in Brightness.values) {
+ testWidgets('a message marks its panes for five seconds '
+ '(${brightness.name})', (tester) async {
+ final app = createApp(connected: true);
+ final sender = terminal('a0', []), recipient = terminal('a1', []);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: Column(
+ children: [
+ for (final session in [sender, recipient])
+ Expanded(
+ child: TerminalPanel(
+ key: ValueKey(session.agentId),
+ notifier: app,
+ session: session,
+ focused: false,
+ compactHeader: true,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ final panel = tester.state(find.byKey(const ValueKey('a0')));
+ final mark = find.byKey(const ValueKey('pane-message-mark'));
+ expect(mark, findsNothing);
+ expect(find.byType(PaneMessageMarkView), findsNWidgets(2));
+ final title = tester.getRect(
+ find.byKey(const ValueKey('terminal-pane-title')).first,
+ );
+
+ await app.handleEventForTest('m', _changed('m0000001', 'a0', 'a1'));
+ await tester.pump();
+ expect(find.text('→ Agent 1'), findsOneWidget);
+ expect(find.text('← Agent 0'), findsOneWidget);
+ expect(
+ tester.getRect(find.text('→ Agent 1')).left,
+ greaterThan(title.right),
+ reason: 'after the title and its activity mark',
+ );
+ expect(
+ tester.getRect(find.byKey(const ValueKey('terminal-pane-title')).first),
+ title,
+ );
+ expect(
+ tester.state(find.byKey(const ValueKey('a0'))),
+ same(panel),
+ reason: 'the cached header is not rebuilt',
+ );
+ await tester.pump(const Duration(seconds: 4));
+ expect(mark, findsNWidgets(2));
+ await tester.pump(const Duration(seconds: 1, milliseconds: 100));
+ expect(mark, findsNothing);
+ expect(tester.takeException(), isNull);
+
+ await app.handleEventForTest('m', {
+ 'type': 'messages_changed',
+ 'payload': {
+ 'limited': {'machineId': 'm', 'agentId': 'a0'},
+ },
+ });
+ await tester.pump();
+ expect(find.text('→ rate limited'), findsOneWidget);
+ await tester.pump(const Duration(seconds: 61));
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ sender.dispose();
+ recipient.dispose();
+ });
+ }
+
+ testWidgets('focusing the pane clears its mark', (tester) async {
+ final app = createApp(connected: true);
+ final session = terminal('a1', []);
+ final pane = app.adoptSessionForTest(session);
+ app.focusedPaneId = null;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: TerminalPanel(
+ notifier: app,
+ session: session,
+ focused: false,
+ compactHeader: true,
+ ),
+ ),
+ ),
+ );
+ await app.handleEventForTest('m', _changed('m0000002', 'a0', 'a1'));
+ await tester.pump();
+ expect(find.text('← Agent 0'), findsOneWidget);
+ app.focusPane(pane.id);
+ await tester.pump();
+ expect(find.text('← Agent 0'), findsNothing);
+ await tester.pump(const Duration(seconds: 61));
+ await tester.pumpWidget(const SizedBox());
+ // The app disposes the session it adopted.
+ app.dispose();
+ });
+}
diff --git a/desktop/test/support/agent_messages_api.dart b/desktop/test/support/agent_messages_api.dart
new file mode 100644
index 000000000..3c9d3f430
--- /dev/null
+++ b/desktop/test/support/agent_messages_api.dart
@@ -0,0 +1,91 @@
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/desk_sync.dart';
+
+/// The daemon's desk and Agent Messages proxies, scripted: a window's tabs
+/// live on a desk, and each desk tab has an Agent Messages flag beside it
+/// (backend routes/agentMessages.ts).
+class AgentMessagesApi extends ApiClient {
+ AgentMessagesApi() : super(config: AppConfig.dev, session: AuthSession());
+
+ DeskDoc doc = const DeskDoc(revision: 0, tabs: []);
+ final flags = <String, bool>{};
+ int reads = 0;
+
+ /// A daemon or backend that predates Agent Messages (404).
+ bool unsupported = false;
+
+ /// A daemon whose backend is away: the read throws.
+ Object? readError;
+ Object? writeError;
+ final writes = <(String, bool)>[];
+
+ Map<String, dynamic> _json(DeskDoc d) => {
+ 'revision': d.revision,
+ 'tabs': [for (final t in d.tabs) t.toJson()],
+ };
+
+ @override
+ Future<Map<String, dynamic>?> desk() async => _json(doc);
+
+ @override
+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async {
+ doc = DeskDoc(
+ revision: doc.revision + 1,
+ tabs: applyDeskOps(doc.tabs, ops),
+ );
+ return _json(doc);
+ }
+
+ @override
+ Future<Map<String, dynamic>?> readAgentMessageTabs() async {
+ reads++;
+ if (readError case final error?) throw error;
+ if (unsupported) return null;
+ return {
+ 'revision': doc.revision,
+ 'machines': const [],
+ 'tabs': [
+ for (final tab in doc.tabs)
+ {
+ 'id': tab.id,
+ 'name': tab.name,
+ 'enabled': flags[tab.id] ?? false,
+ 'panes': const [],
+ },
+ ],
+ };
+ }
+
+ @override
+ Future<Map<String, dynamic>> setAgentMessages(
+ String tabId,
+ bool enabled,
+ ) async {
+ writes.add((tabId, enabled));
+ if (writeError case final error?) throw error;
+ flags[tabId] = enabled;
+ return {'tabId': tabId, 'enabled': enabled, 'revision': writes.length};
+ }
+}
+
+/// Signs [app] in on [api] and joins its desk, so its tabs can have Agent
+/// Messages; [AppNotifier.agentMessagesOffered] holds for its desk tabs after.
+Future<AgentMessagesApi> joinAgentMessagesDesk(
+ AppNotifier app, [
+ AgentMessagesApi? api,
+]) async {
+ final fake = api ?? AgentMessagesApi();
+ app
+ ..api = fake
+ ..status = AppStatus.authenticated;
+ await app.deskStartForTest();
+ // The flags are read beside the desk, after it is joined: let that read
+ // land without a timer, so widget and plain tests alike can call this.
+ for (var i = 0; i < 10 && !app.agentMessages.loaded; i++) {
+ await Future<void>.value();
+ }
+ return fake;
+}
diff --git a/desktop/test/support/team_fixture.dart b/desktop/test/support/team_fixture.dart
deleted file mode 100644
index aa5a11f6a..000000000
--- a/desktop/test/support/team_fixture.dart
+++ /dev/null
@@ -1,59 +0,0 @@
-const teamId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
-const otherTeamId = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb';
-const questionId = 'cccccccccccccccccccccccccccccccc';
-const mobileId = 'dddddddddddddddddddddddddddddddd';
-const daemonId = 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
-
-Map<String, dynamic> teamFixture({
- String id = teamId,
- int revision = 1,
- bool answered = true,
-}) => {
- 'id': id,
- 'name': 'Harness team',
- 'description': 'Build across the stack',
- 'machineId': 'host',
- 'state': 'active',
- 'revision': revision,
- 'members': [
- {
- 'id': mobileId,
- 'name': 'mobile',
- 'role': 'Phone UI and device pairing',
- 'machineId': 'host',
- 'agentId': 'mobile-session',
- 'enabled': true,
- 'runtime': {'engine': 'claude', 'available': true},
- },
- {
- 'id': daemonId,
- 'name': 'daemons',
- 'role': 'Daemon lifecycle and API contracts',
- 'machineId': 'host',
- 'agentId': 'daemon-session',
- 'enabled': true,
- 'runtime': {'engine': 'codex', 'available': true},
- },
- ],
- 'exchanges': [
- if (answered)
- {
- 'id': questionId,
- 'from': mobileId,
- 'to': daemonId,
- 'origin': 'agent',
- 'state': 'answered',
- 'text': 'Which endpoint should mobile use to read daemon status?',
- 'delivery': {'state': 'started'},
- 'continuation': {'state': 'queued', 'reason': 'team_waiting_draft'},
- 'answer': {
- 'text': 'Use GET /api/daemons. Read the state field and keep the last known status while the machine reconnects.',
- 'origin': 'agent',
- 'author': daemonId,
- 'at': 1790500000000,
- 'late': false,
- 'evidence': ['routes/daemons.ts:24'],
- },
- },
- ],
-};
diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dart
index 7de4a187f..e48bb822d 100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@ -20,6 +20,7 @@ import 'package:harness/store/store_mark.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/pane_grid.dart';
+import 'package:harness/widgets/desktop_workspace_tab.dart';
import 'package:harness/widgets/terminal_panel.dart';
import 'package:harness/ws/local_cli_discovery.dart';
import 'package:xterm/xterm.dart';
@@ -109,20 +110,35 @@ void main() {
await mouse.moveTo(tester.getCenter(label));
await tester.pumpAndSettle();
expect(close.hitTestable(), findsOneWidget);
- expect(tester.getRect(label), nameBounds);
+ // Hover reveals the tab: its shortcut follows the name, which keeps its
+ // place (only a name that would run into ⇄ gives up its tail).
+ expect(find.text('⌘1'), findsNothing);
+ expect(find.text('⌘2'), findsOneWidget);
+ final revealedName = tester.getRect(label);
+ expect(revealedName.left, nameBounds.left);
await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
await tester.pump();
+ // Command reveals every tab, × included.
expect(find.text('⌘1'), findsOneWidget);
expect(find.text('⌘2'), findsOneWidget);
expect(close.hitTestable(), findsOneWidget);
+ expect(
+ find.byKey(ValueKey('tab-close:${first.id}')).hitTestable(),
+ findsOneWidget,
+ );
final commandName = tester.getRect(label);
final commandHint = tester.getRect(find.text('⌘2'));
expect(commandHint.left - commandName.right, closeTo(6, .1));
+ // Clear of ⇄'s slot, held left of × whether or not ⇄ is offered.
expect(
- (commandName.left + commandHint.right) / 2,
- closeTo(tester.getCenter(tab).dx, .1),
+ commandHint.right,
+ lessThanOrEqualTo(
+ tester.getRect(close).left -
+ DesktopWorkspaceTab.accessoryGap -
+ DesktopWorkspaceTab.messagesWidth,
+ ),
);
- expect(commandName.size, nameBounds.size);
+ expect(commandName, revealedName);
expect(app.activeSwarm, same(second));
await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
await tester.pump();
diff --git a/desktop/test/swarm_settings_test.dart b/desktop/test/swarm_settings_test.dart
deleted file mode 100644
index dfd79c5c0..000000000
--- a/desktop/test/swarm_settings_test.dart
+++ /dev/null
@@ -1,179 +0,0 @@
-import 'dart:async';
-import 'dart:io';
-import 'dart:ui' as ui;
-
-import 'package:flutter/material.dart';
-import 'package:flutter/rendering.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/settings/sections/experimental_section.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/teams/swarm_settings_controller.dart';
-
-import 'support/real_fonts.dart';
-import 'support/experimental_settings.dart';
-import 'swarm_state_test.dart' show MemoryStore;
-
-void main() {
- setUpAll(loadRealFonts);
- test('opening settings is read-only and the explicit saved choice survives reopening', () async {
- var enabled = false, revision = 0;
- final calls = <Map<String, dynamic>>[];
- SwarmSettingsController open() => SwarmSettingsController(
- request: (p) async {
- calls.add(p);
- if (p['action'] == 'channel_configure') {
- enabled = p['enabled'] as bool;
- revision++;
- }
- return {'enabled': enabled, 'revision': revision};
- },
- );
- final first = open();
- expect(first.enabled, isFalse);
- await first.refresh();
- expect(calls, [
- {'action': 'channel_settings'},
- ]);
- await first.setEnabled(true);
- expect(first.enabled, isTrue);
- first.dispose();
- final reopened = open();
- await reopened.refresh();
- expect(reopened.enabled, isTrue);
- await reopened.setEnabled(false);
- reopened.dispose();
- final last = open();
- await last.refresh();
- expect(last.enabled, isFalse);
- last.dispose();
- });
-
- test('late reads cannot reverse a saved choice and a failed save does not pretend success', () async {
- final lateRead = Completer<Map<String, dynamic>>();
- var reads = 0, failWrite = false;
- final controller = SwarmSettingsController(
- request: (p) async {
- if (p['action'] == 'channel_settings') {
- if (++reads > 1) return lateRead.future;
- return {'enabled': false, 'revision': 0};
- }
- if (failWrite) throw StateError('unavailable');
- return {'enabled': p['enabled'], 'revision': 1};
- },
- );
- await controller.refresh();
- final reading = controller.refresh();
- await controller.setEnabled(true);
- lateRead.complete({'enabled': false, 'revision': 0});
- await reading;
- expect(controller.enabled, isTrue);
- failWrite = true;
- await controller.setEnabled(false);
- expect(controller.enabled, isTrue);
- expect(controller.error, contains('Refresh'));
- expect(controller.saving, isFalse);
- controller.dispose();
- });
-
- test(
- 'unreadable settings never opt in and disposal ignores an in-flight write',
- () async {
- final writing = Completer<Map<String, dynamic>>();
- var failed = true;
- final controller = SwarmSettingsController(
- request: (p) async {
- if (failed) throw StateError('unsupported');
- if (p['action'] == 'channel_configure') return writing.future;
- return {'enabled': false, 'revision': 0};
- },
- );
- await controller.refresh();
- expect(controller.enabled, isFalse);
- expect(controller.loaded, isFalse);
- failed = false;
- await controller.refresh();
- final saving = controller.setEnabled(true);
- controller.dispose();
- writing.complete({'enabled': true, 'revision': 1});
- await saving;
- expect(controller.enabled, isFalse);
- },
- );
-
- for (final width in [390.0, 1100.0]) {
- testWidgets(
- 'Experimental switch defaults off and changes only on a user action at $width',
- (tester) async {
- tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = Size(width, 820);
- addTearDown(tester.view.reset);
- final calls = <Map<String, dynamic>>[];
- final controller = SwarmSettingsController(
- request: (p) async {
- calls.add(p);
- return {
- 'enabled': p['enabled'] == true,
- 'revision': p['action'] == 'channel_configure' ? 1 : 0,
- };
- },
- );
- final capture = GlobalKey();
- final preferences = MemoryExperimentalFeaturesStore(
- storage: MemoryStore(),
- );
- addTearDown(preferences.dispose);
- await preferences.refresh();
- await tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: Scaffold(
- body: RepaintBoundary(
- key: capture,
- child: ExperimentalSection(
- store: preferences,
- controller: controller,
- ),
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- final toggle = find.byKey(
- const Key('experimental-swarm-collaboration'),
- );
- await tester.ensureVisible(toggle);
- await tester.pumpAndSettle();
- expect(tester.widget<Switch>(toggle).value, isFalse);
- expect(calls, [
- {'action': 'channel_settings'},
- ]);
- expect(find.textContaining('automatically consult'), findsOneWidget);
- expect(tester.takeException(), isNull);
- final output = Platform.environment['CHANNEL_RENDER_DIR'];
- if (output != null) {
- await tester.runAsync(() async {
- final boundary =
- capture.currentContext!.findRenderObject()!
- as RenderRepaintBoundary;
- final image = await boundary.toImage();
- final bytes = await image.toByteData(
- format: ui.ImageByteFormat.png,
- );
- await Directory(output).create(recursive: true);
- await File('$output/experimental-swarm-${width.toInt()}.png')
- .writeAsBytes(bytes!.buffer.asUint8List());
- image.dispose();
- });
- }
- await tester.tap(toggle);
- await tester.pumpAndSettle();
- expect(calls.last, {'action': 'channel_configure', 'enabled': true});
- expect(tester.widget<Switch>(toggle).value, isTrue);
- expect(tester.takeException(), isNull);
- await tester.pumpWidget(const SizedBox());
- controller.dispose();
- },
- );
- }
-}
diff --git a/desktop/test/team_controller_test.dart b/desktop/test/team_controller_test.dart
deleted file mode 100644
index db925e3fe..000000000
--- a/desktop/test/team_controller_test.dart
+++ /dev/null
@@ -1,176 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/teams/team_controller.dart';
-
-import 'support/team_fixture.dart';
-
-void main() {
- test('watch and reopen only read; stopping a view stops polling', () async {
- final calls = <Map<String, dynamic>>[];
- final controller = TeamController(
- request: (p) async {
- calls.add(p);
- return {'teams': []};
- },
- );
- addTearDown(controller.dispose);
- controller.watch();
- await controller.refresh();
- controller.unwatch();
- controller.watch();
- await controller.refresh();
- controller.unwatch();
- expect(calls.map((p) => p['action']), everyElement('list'));
- expect(calls.length, 2);
- });
- test(
- 'uncertain creation retries its original ID and original roster',
- () async {
- final calls = <Map<String, dynamic>>[];
- final controller = TeamController(
- request: (p) async {
- calls.add(p);
- if (calls.length == 1) throw TimeoutException('Connection lost');
- return {
- 'team': {...teamFixture(), 'id': p['id']},
- };
- },
- );
- addTearDown(controller.dispose);
- controller.newMembers['one'] = {
- 'machineId': 'host',
- 'agentId': 'one',
- 'name': 'one',
- };
- await controller.create();
- expect(controller.pendingCreate, isTrue);
- controller.newName = 'Edited after timeout';
- controller.newMembers.clear();
- await controller.create();
- expect(calls[1], calls[0]);
- expect(controller.pendingCreate, isFalse);
- },
- );
- test(
- 'uncertain ask retries one question; a definitive refusal permits editing',
- () async {
- final sends = <Map<String, dynamic>>[];
- final controller = TeamController(
- request: (p) async {
- if (p['action'] == 'get') return {'team': teamFixture()};
- sends.add(p);
- if (sends.length == 1) throw TimeoutException('Lost acknowledgement');
- if (sends.length == 3) throw const TeamRequestError('Team paused');
- return {
- 'exchange': {'id': p['id']},
- };
- },
- );
- addTearDown(controller.dispose);
- await controller.select(teamId);
- controller.draft = 'Which endpoint?';
- await controller.ask();
- expect(controller.pendingAsk, isTrue);
- controller.draft = 'Different draft';
- await controller.ask();
- expect(sends[1], sends[0]);
- expect(controller.draft, isEmpty);
- controller.draft = 'New question';
- await controller.ask();
- expect(controller.pendingAsk, isFalse);
- expect(controller.draft, 'New question');
- expect(sends[2]['id'], isNot(sends[0]['id']));
- },
- );
- test(
- 'late refresh cannot replace a newer revision or another team',
- () async {
- final stale = Completer<Map<String, dynamic>>();
- var reads = 0;
- final controller = TeamController(
- request: (p) async {
- reads++;
- if (reads == 2) return stale.future;
- return {'team': teamFixture(id: p['teamId'] as String, revision: 4)};
- },
- );
- addTearDown(controller.dispose);
- await controller.select(teamId);
- controller.draft = 'Keep this draft';
- final slow = controller.refresh();
- await controller.select(otherTeamId);
- stale.complete({'team': teamFixture(revision: 99)});
- await slow;
- expect(controller.team?['id'], otherTeamId);
- await controller.select(teamId);
- expect(controller.draft, 'Keep this draft');
- controller.team!['revision'] = 9;
- await controller.refresh();
- expect(controller.team?['revision'], 9);
- },
- );
- test(
- 'a send completed after changing teams clears only its own saved draft',
- () async {
- final sent = Completer<Map<String, dynamic>>();
- final controller = TeamController(
- request: (p) async => p['action'] == 'ask'
- ? sent.future
- : {'team': teamFixture(id: p['teamId'] as String)},
- );
- addTearDown(controller.dispose);
- await controller.select(teamId);
- controller.draft = 'Sent draft';
- final sending = controller.ask();
- await controller.select(otherTeamId);
- controller.draft = 'Unrelated draft';
- sent.complete({
- 'exchange': {'id': questionId},
- });
- await sending;
- expect(controller.draft, 'Unrelated draft');
- await controller.select(teamId);
- expect(controller.draft, isEmpty);
- expect(controller.selectedExchange, questionId);
- },
- );
- test(
- 'adding a teammate reconciles an uncertain membership with the same ID',
- () async {
- final additions = <Map<String, dynamic>>[];
- final controller = TeamController(
- request: (p) async {
- if (p['action'] == 'add_member') {
- additions.add(p);
- if (additions.length == 1) throw TimeoutException('Lost reply');
- }
- return {'team': teamFixture()};
- },
- );
- addTearDown(controller.dispose);
- await controller.select(teamId);
- await controller.addMember({
- 'machineId': 'host',
- 'agentId': 'firmware',
- 'name': 'firmware',
- });
- expect(controller.pendingAdd, isTrue);
- await controller.addMember();
- expect(additions[1], additions[0]);
- expect(controller.pendingAdd, isFalse);
- },
- );
- test(
- 'disposal ignores a delayed response and never cancels daemon work',
- () async {
- final pending = Completer<Map<String, dynamic>>();
- final controller = TeamController(request: (p) => pending.future);
- final loading = controller.select(teamId);
- controller.dispose();
- pending.complete({'team': teamFixture()});
- await loading;
- expect(controller.team, isNull);
- },
- );
-}
diff --git a/desktop/test/team_workspace_test.dart b/desktop/test/team_workspace_test.dart
deleted file mode 100644
index 33cf0fae9..000000000
--- a/desktop/test/team_workspace_test.dart
+++ /dev/null
@@ -1,197 +0,0 @@
-import 'dart:io';
-import 'dart:ui' as ui;
-
-import 'package:flutter/material.dart';
-import 'package:flutter/rendering.dart';
-import 'package:flutter/services.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/teams/team_controller.dart';
-import 'package:harness/teams/team_workspace.dart';
-import 'package:harness/terminal/terminal_font_store.dart';
-import 'package:xterm/xterm.dart' show TerminalStyle;
-
-import 'support/real_fonts.dart';
-import 'support/team_fixture.dart';
-
-const candidates = [
- TeamCandidate(
- machineId: 'host',
- agentId: 'mobile-session',
- name: 'Mobile',
- machineName: 'Mac',
- engine: 'claude',
- status: 'Available',
- available: true,
- ),
- TeamCandidate(
- machineId: 'host',
- agentId: 'daemon-session',
- name: 'Daemons',
- machineName: 'Mac',
- engine: 'codex',
- status: 'Available',
- available: true,
- ),
-];
-
-void main() {
- setUpAll(loadRealFonts);
- testWidgets('large terminal font keeps creation and asking usable', (
- tester,
- ) async {
- tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = const Size(600, 760);
- final originalFont = terminalFontStore.value;
- terminalFontStore.value = const TerminalStyle(
- fontSize: 22,
- fontFamily: 'SF Mono',
- );
- addTearDown(() {
- terminalFontStore.value = originalFont;
- tester.view.reset();
- });
- final calls = <Map<String, dynamic>>[];
- String? createdId;
- final model = TeamController(
- request: (p) async {
- calls.add(p);
- if (p['action'] == 'list') return {'teams': []};
- if (p['action'] == 'create') createdId = p['id'] as String;
- return {
- 'team': {...teamFixture(answered: false), 'id': createdId},
- };
- },
- );
- await tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: Scaffold(
- body: TeamWorkspace(
- controller: model,
- candidates: candidates,
- machineName: 'Mac',
- onClose: () {},
- onOpen: (_, _) {},
- ),
- ),
- ),
- );
- addTearDown(() async {
- await tester.pumpWidget(const SizedBox());
- model.dispose();
- });
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const Key('team-new')));
- await tester.pumpAndSettle();
- for (final candidate in candidates) {
- final row = find.byKey(ValueKey('team-candidate-${candidate.agentId}'));
- await tester.scrollUntilVisible(
- row,
- 100,
- scrollable: find
- .descendant(
- of: find.byKey(const Key('team-candidates')),
- matching: find.byType(Scrollable),
- )
- .first,
- );
- await tester.tap(row);
- await tester.pumpAndSettle();
- }
- expect(calls.map((p) => p['action']), everyElement('list'));
- final connect = find.byKey(const Key('team-connect'));
- await tester.ensureVisible(connect);
- await tester.tap(connect);
- await tester.pumpAndSettle();
- expect(calls.where((p) => p['action'] == 'create'), hasLength(1));
- final question = find.byKey(const Key('team-question'));
- await tester.ensureVisible(question);
- await tester.enterText(question, 'Keep this draft through refresh.');
- await model.refresh();
- await tester.pumpAndSettle();
- expect(find.text('Keep this draft through refresh.'), findsOneWidget);
- expect(tester.takeException(), isNull);
- });
- for (final size in [
- const Size(1280, 850),
- const Size(600, 760),
- const Size(390, 740),
- ]) {
- for (final brightness in Brightness.values) {
- testWidgets('team exchange fits $size in $brightness', (tester) async {
- tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = size;
- addTearDown(tester.view.reset);
- final calls = <Map<String, dynamic>>[];
- final model = TeamController(
- request: (p) async {
- calls.add(p);
- return {'team': teamFixture()};
- },
- );
- await model.select(teamId);
- model.selectedExchange = questionId;
- final key = GlobalKey();
- var closed = false;
- grid.AppTheme.brightness.value = brightness;
- await tester.pumpWidget(
- RepaintBoundary(
- key: key,
- child: MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- home: Scaffold(
- body: TeamWorkspace(
- controller: model,
- candidates: candidates,
- machineName: 'Mac',
- onClose: () {
- closed = true;
- },
- onOpen: (_, _) {},
- ),
- ),
- ),
- ),
- );
- addTearDown(() async {
- await tester.pumpWidget(const SizedBox());
- model.dispose();
- });
- await tester.pumpAndSettle();
- expect(find.textContaining('Use GET /api/daemons.'), findsOneWidget);
- expect(find.textContaining('Waiting for draft'), findsOneWidget);
- expect(tester.takeException(), isNull);
- final output = Platform.environment['HARNESS_TEAM_CAPTURE_DIR'];
- if (output != null) {
- final boundary =
- key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
- await tester.runAsync(() async {
- final image = await boundary.toImage(pixelRatio: 1);
- final bytes = await image.toByteData(
- format: ui.ImageByteFormat.png,
- );
- await Directory(output).create(recursive: true);
- await File(
- '$output/team-${brightness.name}-${size.width.toInt()}.png',
- ).writeAsBytes(bytes!.buffer.asUint8List());
- image.dispose();
- });
- }
- await tester.tap(find.byKey(const Key('team-compose')));
- await tester.pumpAndSettle();
- await tester.enterText(
- find.byKey(const Key('team-question')),
- 'How should reconnect work?',
- );
- await model.refresh();
- await tester.pumpAndSettle();
- expect(find.text('How should reconnect work?'), findsOneWidget);
- expect(calls.every((p) => p['action'] == 'get'), isTrue);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- expect(closed, isTrue);
- });
- }
- }
-}
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 9dd2b048b..0e151091d 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -432,13 +432,13 @@ private extension SwarmTabButton {
let hovered = renderedBitmap()
try checkTitlebar(hovered.colorAt(x: 20, y: 12)!.alphaComponent > 0 && renderedPixels() != resting,
"Hover quietly marks the tab surface")
- try checkTitlebar(preferredWidth == width && !closeButton.isHidden && drawnFont == labelFont,
- "Hover reveals the right close button without changing tab width or type")
+ try checkTitlebar(preferredWidth == width && !closeButton.isHidden && drawnFont == labelFont && displaysShortcut,
+ "Hover reveals the shortcut in place of the status and the right close button, without changing tab width or type")
let titleBeforeHint = titleRect, closeBeforeHint = closeButton.frame
showsShortcutHint = true
layoutSubtreeIfNeeded()
- try checkTitlebar(displaysShortcut && !closeButton.isHidden && renderedPixels() != Data(bytes: hovered.bitmapData!, count: hovered.bytesPerRow * hovered.pixelsHigh),
- "Holding Command replaces status with its shortcut while keeping the hover close action")
+ try checkTitlebar(displaysShortcut && !closeButton.isHidden && renderedPixels() == Data(bytes: hovered.bitmapData!, count: hovered.bytesPerRow * hovered.pixelsHigh),
+ "Holding Command over a hovered tab changes nothing: both are the one revealed state")
try checkTitlebar(titleRect == titleBeforeHint && closeButton.frame == closeBeforeHint && preferredWidth == width,
"Command hints never move the title, close target or tab boundaries")
showsShortcutHint = false
@@ -488,8 +488,8 @@ private extension SwarmTabButton {
timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!
mouseEntered(with: hover)
try checkTitlebar(!closeButton.isHidden && closeButton.frame.minX > title.maxX &&
- closeButton.frame.size == NSSize(width: 32, height: 32),
- "A hovered tab exposes a separate 32pt close target on the right")
+ closeButton.frame.size == NSSize(width: 16, height: 32) && closeButton.frame.maxX == bounds.maxX - 8,
+ "A hovered tab exposes a separate 16x32pt close target at its right inset")
try checkTitlebar(accessibilityChildren()?.count == 2 && closeButton.accessibilityLabel() == "Close 1: Release planning",
"The hover close button has the exact custom title as its accessible purpose")
let closeBitmap = closeButton.renderedBitmap()
@@ -502,15 +502,15 @@ private extension SwarmTabButton {
let inkWidth = (closeInk.map(\.x).max() ?? 0) - (closeInk.map(\.x).min() ?? 0) + 1
let inkHeight = (closeInk.map(\.y).max() ?? 0) - (closeInk.map(\.y).min() ?? 0) + 1
try checkTitlebar(!closeInk.isEmpty && inkWidth <= 7 && inkHeight <= 7,
- "The tab close paints a tiny regular cross inside its unchanged 32pt target")
+ "The tab close paints a tiny regular cross inside its unchanged target")
closeButton.performClick(nil)
try checkTitlebar(events == ["close"], "Clicking the close control closes once without selecting the tab")
showsShortcutHint = true
try checkTitlebar(displaysShortcut && !closeButton.isHidden && shortcutLabel?.string == "⌘2",
"Command reveals the supplied shortcut beside the name without hiding hover close")
try checkTitlebar(indicatorRect.minX == titleRect.maxX + 6 &&
- indicatorRect.maxX <= closeButton.frame.minX,
- "The inline Command hint stays outside the close action's entire hit target")
+ indicatorRect.maxX <= messagesButton.frame.minX,
+ "The inline Command hint stays clear of the ⇄ and close targets")
let commandBitmap = renderedBitmap()
let hasActivityInk = (0..<commandBitmap.pixelsWide).contains { x in
(0..<commandBitmap.pixelsHigh).contains { y in
@@ -525,8 +525,8 @@ private extension SwarmTabButton {
try checkTitlebar(titleRect == title && closeButton.frame == close && preferredWidth == width,
"Modifier changes preserve every tab and title boundary")
mouseExited(with: hover)
- try checkTitlebar(displaysShortcut && closeButton.isHidden,
- "Command hints remain visible without pointer hover")
+ try checkTitlebar(displaysShortcut && !closeButton.isHidden,
+ "Holding Command reveals the tab without pointer hover: its shortcut and close action")
showsShortcutHint = false
try checkTitlebar(closeButton.isHidden && accessibilityChildren()?.count == 1,
"Releasing Command returns an unhovered tab to its quiet state")
@@ -654,12 +654,124 @@ private extension SwarmTabButton {
func checkCenteredLabel() throws {
let paragraph = label.attribute(.paragraphStyle, at: 0, effectiveRange: nil) as? NSParagraphStyle
- let group = activitySpace == 0 ? titleRect : titleRect.union(indicatorRect)
+ let resting = restingTitleRect
+ let group = activitySpace == 0 ? resting
+ : NSRect(x: resting.minX, y: 0, width: resting.width + activitySpace, height: bounds.height)
try checkTitlebar(paragraph?.alignment == .center && abs(group.midX - bounds.midX) < 0.01,
- "The visible title and adjacent indicator form a centered group")
+ "The resting title and adjacent indicator form a centered group")
+ try checkTitlebar(titleRect.minX == resting.minX, "Revealing a tab never moves its title")
try checkTitlebar(selectButton.frame == bounds, "Selection and drag retain the whole tab target beneath its accessory")
- try checkTitlebar(subviews.count == 2 && closeButton.frame.maxX == bounds.maxX - 8,
- "The close action stays inset inside the tab's curved body")
+ try checkTitlebar(subviews.count == 3 && closeButton.frame.maxX == bounds.maxX - 8 &&
+ closeButton.frame.minX - messagesButton.frame.maxX == 3,
+ "The close action, and ⇄ left of it past a dead gap, stay inset inside the tab's curved body")
+ }
+
+ /// Agent Messages' ⇄ (docs/design/2026-10-10-agent-messages.md): one revealed
+ /// state, three looks, a click and the tab's menu.
+ func checkAgentMessages() throws {
+ frame = NSRect(x: 0, y: 0, width: 240, height: 40)
+ contentCenterY = 20
+ name = "app"
+ displayLabel = "app"
+ shortcutHint = "⌘1"
+ activity = nil
+ layoutSubtreeIfNeeded()
+ var events: [(String, String?)] = []
+ emit = { method, args in events.append((method, (args as? [String: Any])?["id"] as? String)) }
+ defer { emit = nil }
+ let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],
+ timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!
+ let rows = menu?.items ?? []
+ try checkTitlebar(rows.map(\.title) == ["Rename Tab…", "", "Agent Messages", "Show Agent Messages", "", "Close Tab"],
+ "The tab menu: Rename Tab…, Agent Messages, Show Agent Messages, Close Tab")
+ try checkTitlebar(rows[1...3].allSatisfy(\.isHidden), "A tab without Agent Messages (the Store) lists neither row")
+ mouseEntered(with: hover)
+ try checkTitlebar(messagesButton.isHidden && !closeButton.isHidden, "A tab without Agent Messages shows no ⇄")
+ mouseExited(with: hover)
+
+ agentMessages = SwarmTabMessages(on: false, flowing: false)
+ try checkTitlebar(rows[1...3].allSatisfy { !$0.isHidden }, "A tab with Agent Messages lists both rows")
+ try checkTitlebar(messagesButton.isHidden && closeButton.isHidden && !displaysShortcut,
+ "Off, at rest, a tab shows nothing extra")
+ let title = titleRect
+ mouseEntered(with: hover)
+ try checkTitlebar(displaysShortcut && !messagesButton.isHidden && !closeButton.isHidden &&
+ closeButton.frame.minX - messagesButton.frame.maxX == 3 && messagesButton.struck &&
+ messagesButton.restingOpacity == 0.45,
+ "Hovered and off: the shortcut, a dim struck ⇄ just left of ×")
+ let gap = NSPoint(x: closeButton.frame.minX - 1.5, y: closeButton.frame.midY)
+ try checkTitlebar(!messagesButton.frame.contains(gap) && !closeButton.frame.contains(gap),
+ "A click between ⇄ and × lands on neither")
+ try checkTitlebar(titleRect.minX == title.minX && indicatorRect.minX == titleRect.maxX + 6 &&
+ indicatorRect.maxX <= messagesButton.frame.minX,
+ "Revealing an idle tab shows its shortcut after the title without moving it")
+ try checkTitlebar(messagesButton.toolTip == "Agent messages off · click to turn on" &&
+ messagesButton.accessibilityLabel() == "Agent Messages" &&
+ messagesButton.accessibilityValue() as? String == "Off" &&
+ accessibilityChildren()?.count == 3,
+ "The ⇄ says what it is, its state and what a click does")
+ messagesButton.performClick(nil)
+ try checkTitlebar(events.count == 1 && events[0] == ("toggleAgentMessages", swarmId),
+ "Clicking ⇄ asks to toggle this tab's Agent Messages, without selecting it")
+ mouseExited(with: hover)
+ showsShortcutHint = true
+ try checkTitlebar(!messagesButton.isHidden && !closeButton.isHidden && displaysShortcut,
+ "Holding Command reveals ⇄ and × as hover does")
+ showsShortcutHint = false
+ try checkTitlebar(messagesButton.isHidden && closeButton.isHidden, "Releasing Command hides them again")
+
+ agentMessages = SwarmTabMessages(on: false, flowing: true)
+ try checkTitlebar(messagesButton.isHidden && closeButton.isHidden,
+ "Off, a tab at rest shows nothing even if its last traffic was recent")
+ agentMessages = SwarmTabMessages(on: true, flowing: false)
+ try checkTitlebar(messagesButton.isHidden, "On and quiet, a tab at rest shows nothing extra")
+ mouseEntered(with: hover)
+ try checkTitlebar(!messagesButton.isHidden && !messagesButton.struck && messagesButton.restingOpacity == 0.45 &&
+ messagesButton.toolTip == "Agent messages on · click to turn off" &&
+ messagesButton.accessibilityValue() as? String == "On",
+ "Revealed, on and quiet: a dim ⇄ that turns it off")
+ mouseExited(with: hover)
+
+ agentMessages = SwarmTabMessages(on: true, flowing: true)
+ try checkTitlebar(!messagesButton.isHidden && closeButton.isHidden && !displaysShortcut &&
+ messagesButton.restingOpacity == 1 && messagesButton.toolTip == "Agents messaging · click to turn off",
+ "While agents message, a bright ⇄ stays at rest without ×")
+ try checkTitlebar(accessibilityChildren()?.count == 2, "The resting ⇄ stays reachable by accessibility")
+ let toggle = rows[2]
+ _ = validateMenuItem(toggle)
+ try checkTitlebar(toggle.state == .on, "The menu's Agent Messages row is checked while on")
+ _ = (toggle.target as AnyObject).perform(toggle.action, with: toggle)
+ let show = rows[3]
+ _ = (show.target as AnyObject).perform(show.action, with: show)
+ try checkTitlebar(events.suffix(2).map(\.0) == ["toggleAgentMessages", "showAgentMessages"] &&
+ events.suffix(2).allSatisfy { $0.1 == swarmId },
+ "The tab menu's rows act on this tab")
+ agentMessages = SwarmTabMessages(on: false, flowing: false)
+ _ = validateMenuItem(toggle)
+ try checkTitlebar(toggle.state == .off, "The row's checkmark follows the flag")
+ actionsEnabled = false
+ agentMessages = SwarmTabMessages(on: true, flowing: true)
+ let before = events.count
+ messagesButton.performClick(nil)
+ try checkTitlebar(messagesButton.isHidden && events.count == before, "A modal hides and disables the ⇄")
+ actionsEnabled = true
+ agentMessages = nil
+ }
+
+ /// At the 128pt minimum, a tab still draws its centered name beside a status.
+ func checkMinimumWidth() throws {
+ frame = NSRect(x: 0, y: 0, width: SwarmTabButton.minimumLayoutWidth, height: 40)
+ contentCenterY = 20
+ name = "app"
+ displayLabel = "app"
+ activity = HarnessNativeActivity(["mark": "⠋", "label": "Working", "working": true, "color": Int64(0xff64d2ff)])
+ for digit in 1...9 {
+ shortcutHint = "⌘\(digit)"
+ layoutSubtreeIfNeeded()
+ try checkTitlebar(bounds.width >= minimumWidth && titleRect.width >= 16,
+ "A 128pt tab keeps 16pt for its name beside ⌘\(digit) and the ⇄ and × reservations")
+ try checkCenteredLabel()
+ }
}
func checkNameFitsOrHasTooltip() throws {
@@ -1381,6 +1493,14 @@ private extension SwarmTabStrip {
["id": "custom", "name": "1: Release planning", "label": "1: Release planning", "shortcutHint": "⌃⌥⌘R"],
["id": "unbound", "name": "Notes", "label": "Notes", "shortcutHint": NSNull()],
]
+ var messageRows = rows
+ messageRows[0]["agentMessages"] = true
+ messageRows[0]["agentMessagesFlowing"] = true
+ messageRows[1]["agentMessages"] = false
+ update(["enabled": true, "activeId": "work", "tabs": messageRows])
+ try checkTitlebar(tabs.map(\.agentMessages) == [SwarmTabMessages(on: true, flowing: true),
+ SwarmTabMessages(on: false, flowing: false), nil, nil],
+ "Each row's Agent Messages reaches its tab; a row without one has no ⇄")
update(["enabled": true, "activeId": "work", "tabs": rows])
try checkTitlebar(tabs.map(\.displayLabel) == ["New Tab", "Desktop", "1: Release planning", "Notes"],
"Clean labels preserve numeric-looking custom names and omit generated prefixes")
@@ -2258,7 +2378,7 @@ private extension SwarmTitlebar {
"New Terminal stays off the File menu; its chord lives in the keymap")
let historyMenu = main.item(withTitle: "History")!.submenu!
try checkTitlebar(agent.items.contains { $0.title == "Clone Harness" && $0.representedObject as? String == "cloneAgent" }, "Clone Harness preserves its action")
- try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["newAgent", "sessions", "addAgent", "cloneAgent", "restartAgent", "shareAgent", "separator", "new", "renameActive", "closeActive", "separator", "splitRight", "splitDown", "zoomPane", "movePaneToTab", "closePane"], "File groups harness, tab and pane actions, harnesses first")
+ try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["newAgent", "sessions", "addAgent", "cloneAgent", "restartAgent", "shareAgent", "separator", "new", "renameActive", "closeActive", "toggleAgentMessages", "showAgentMessages", "separator", "splitRight", "splitDown", "zoomPane", "movePaneToTab", "closePane"], "File groups harness, tab and pane actions, harnesses first")
for (action, title, menu) in [
("restartAgent", "Restart Harness", agent),
("shareAgent", "Share Harness", agent),
@@ -2303,6 +2423,28 @@ private extension SwarmTitlebar {
canFind = true
try checkTitlebar(validateMenuItem(movePane), "Move Pane to Tab is available with a focused pane")
try checkTitlebar(agent.items.contains { $0.title == "Close Tab" && $0.representedObject as? String == "closeActive" }, "Close Tab preserves its command")
+ // Agent Messages for the active tab: a checkmark row and its log.
+ let messagesRow = agent.items.first { $0.representedObject as? String == "toggleAgentMessages" }!
+ let showMessagesRow = agent.items.first { $0.representedObject as? String == "showAgentMessages" }!
+ try checkTitlebar(messagesRow.title == "Agent Messages" && showMessagesRow.title == "Show Agent Messages",
+ "File names Agent Messages and Show Agent Messages")
+ actionsEnabled = true
+ activeAgentMessages = nil
+ try checkTitlebar(!validateMenuItem(messagesRow) && !validateMenuItem(showMessagesRow),
+ "A tab without Agent Messages (the Store) leaves both rows unavailable")
+ activeAgentMessages = true
+ try checkTitlebar(validateMenuItem(messagesRow) && messagesRow.state == .on && validateMenuItem(showMessagesRow),
+ "Agent Messages carries a checkmark while on in the active tab")
+ activeAgentMessages = false
+ try checkTitlebar(validateMenuItem(messagesRow) && messagesRow.state == .off, "The checkmark follows the active tab")
+ for row in [messagesRow, showMessagesRow] {
+ menuAction(row)
+ try checkTitlebar(messenger.calls.last?.method == row.representedObject as? String,
+ "\(row.title) dispatches to Flutter for the active tab")
+ }
+ actionsEnabled = false
+ try checkTitlebar(!validateMenuItem(messagesRow), "Agent Messages respects modal state")
+ actionsEnabled = true
let closeTabShortcut = agent.items.first { $0.representedObject as? String == "closeActive" }!
let closePaneShortcut = agent.items.first { $0.representedObject as? String == "closePane" }!
try checkTitlebar(closeTabShortcut.keyEquivalent == "w" && closeTabShortcut.keyEquivalentModifierMask == [.command], "Close Tab defaults to Command-W")
@@ -2639,6 +2781,8 @@ do {
try strip.checkActivityMarks()
try SwarmTabButton(id: "label-measurements").checkLabelMeasurementChanges()
try SwarmTabButton(id: "close-shortcuts").checkHoverCloseAndShortcutHints()
+ try SwarmTabButton(id: "agent-messages").checkAgentMessages()
+ try SwarmTabButton(id: "minimum-width").checkMinimumWidth()
try SwarmTabButton(id: "selection-surface").checkSelectionSurface()
try strip.checkTabPresentationAndCapture()
try SwarmTabButton(id: "hover-fixture").checkHoverStyleAndTooltips()
diff --git a/docs/naming-system.md b/docs/naming-system.md
index 90fdc7d1e..ef57ff37d 100644
--- a/docs/naming-system.md
+++ b/docs/naming-system.md
@@ -73,8 +73,9 @@ existing action name.
A pane is a view, so closing a pane or tab closes views. **Stop Harness** ends the
running harness. Adding harnesses to a tab groups them without a separate team
-setup. **Settings → Experimental → Tab collaboration** lets their agents consult
-peers; it is off by default. The word *tab* can also name the keyboard key or a
+setup. Turning on **Agent Messages** for a tab lets its harnesses message each
+other (`harness send`); it is off by default, per tab, and **Show Agent Messages**
+opens the tab's log. The word *tab* can also name the keyboard key or a
browser tab; context distinguishes them.
A project belongs to a computer; identical paths on different computers do not