The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Desktop: a Swarm dropdown with your Personal Swarm, tabs unchanged (#2278)
0xken15835183d7c81d
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 879796937..7310a6d1d 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -8345,6 +8345,8 @@ class _SwarmScreenState extends State<SwarmScreen> {onNewProject: () => unawaited(_newAgent(newSwarmProject: true),),+ onNewSwarm: () =>+ _newTab(superTab: true),onAddAgent: (group) => unawaited(_addAgent(conversationId: group.id),),diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 850a11f36..44418954a 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -2359,6 +2359,30 @@ class AppNotifier extends ChangeNotifier {bindSuperTab(activeSwarmId, tabId, name);}+ /// Shows Swarm [tabId] in the Swarm tab [swarmId] in place of the Swarm it+ /// shows, from the Swarm dropdown: the tab keeps its place and its name+ /// follows. A Swarm already open in another tab is selected there instead,+ /// so no tab is added or closed. The Swarm the tab showed is hidden here as+ /// a closed one is, and let go, which keeps its draft for its return.+ void showSuperTabIn(String swarmId, String tabId, String name) {+ final tab = swarms.where((s) => s.id == swarmId).firstOrNull;+ final previous = tab?.superTabId;+ if (tab == null || previous == null || previous == tabId) return;+ final open = swarms.where((s) => s.superTabId == tabId).firstOrNull;+ if (open != null) {+ selectSwarm(open.id);+ return;+ }+ // As openSuperTab: Reopen later must not add a second view of it.+ _closedHistory.removeWhere(+ (entry) => entry is ClosedSwarm && entry.superTabId == tabId,+ );+ _rememberSuperTabVisibility(previous, false);+ superTabs.release(previous);+ bindSuperTab(swarmId, tabId, name);+ selectSwarm(swarmId);+ }+/// Opens a tab from [closedSuperTabs]. False when it is no longer listed/// (open already, or the account has left it).bool openClosedSuperTab(String tabId, {String? intoSwarmId}) {diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex 4d39326e2..acf872d0f 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -352,6 +352,11 @@ class SuperTabClient {/// account still belongs to.Set<String> get hiddenIds => Set.unmodifiable(_hidden);+ /// Who owns Swarm [id], as the open Swarm says or the last full list read+ /// said; null for one this account is not listed in.+ String? ownerOf(String id) => _loaded[id]?.snapshot?.ownerId ?? _owners[id];+ Map<String, String> _owners = const {};+void bind(String? account) {if (_account == account) return;for (final timer in _viewSaves.values) {@@ -377,6 +382,7 @@ class SuperTabClient {_visibility.clear();_tagCounts.clear();_tagDigests.clear();+ _owners = const {};_tagsSeen.clear();_listMentions = true;discoveryError = null;@@ -464,6 +470,7 @@ class SuperTabClient {await _readHidden(account, generation);if (generation != _generation) return;final tabs = <String, SuperTabListing>{};+ final owners = <String, String>{};final tags = <String, ({int count, String digest})>{};final cursors = <String>{};String? after;@@ -480,6 +487,7 @@ class SuperTabClient {}final id = row['id'] as String;tabs[id] = (id: id, name: row['name'] as String);+ if (row['ownerId'] case final String owner) owners[id] = owner;// Told only by a backend that counts them (and only when asked).if (row['mentionsWaiting'] case final int countwhen row['mentionsDigest'] is String) {@@ -495,6 +503,7 @@ class SuperTabClient {}} while (after != null);discoveryError = null;+ _owners = owners;final hidden = Set<String>.unmodifiable({..._hidden, ..._creating});onTabs!(tabs.values.toList(), hidden);// Every page read: a Swarm not listed is no longer this account's.diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex ce91dfcbd..2ab421733 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -351,6 +351,7 @@ Future<bool> _sendContribution(required int maxAgents,required bool Function() alive,bool teamAccountOnly = false,+ bool offerTeamAccount = true,}) async {// An earlier lost reply leaves an uncertain attempt holding its own// receipt, and only one action may be in flight: check that one first, then@@ -387,7 +388,7 @@ Future<bool> _sendContribution(await app.wakeSuperTabHost(machineId);// This Mac, added while its person is here: macOS asks once for the Harness// Team account (cli/src/team/autoSetup.ts).- if (app.stateOf(machineId)?.isLocalMachine == true) {+ if (offerTeamAccount && app.stateOf(machineId)?.isLocalMachine == true) {unawaited(app.offerTeamAccount('contribute', tabId: c.tabId));}return true;@@ -400,7 +401,9 @@ Future<bool> _sendContribution(/// [setupId] is the caller's to keep between tries: a setup still running/// answers the next try with the same one. With [teamAccountOnly], teammates'/// work reaches it only through its Harness Team account once that passes its-/// privacy check (backend superTabs/machines.ts `teamWorkRefusal`).+/// privacy check (backend superTabs/machines.ts `teamWorkRefusal`). Without+/// [offerTeamAccount], this Mac is not offered a Harness Team account: a+/// Personal Swarm has no teammates to run work for./// [readResources] stands in for [AppNotifier.readMachineResources].Future<String?> contributeComputer(SuperTabController c,@@ -409,6 +412,7 @@ Future<String?> contributeComputer(required String setupId,required bool Function() alive,bool teamAccountOnly = false,+ bool offerTeamAccount = true,Future<MachineResources?> Function(String machineId)? readResources,}) async {final prepared = await _prepareContribution(@@ -440,6 +444,7 @@ Future<String?> contributeComputer(maxAgents: slots,alive: alive,teamAccountOnly: teamAccountOnly,+ offerTeamAccount: offerTeamAccount,);return added ? machineId : null;}diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex 91bb59a42..4d50a579a 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -24,6 +24,7 @@ import 'machines.dart';import 'model.dart';import 'buddy_rows.dart';import 'section_heading.dart';+import 'swarm_switcher.dart';import 'task_status.dart';import 'workgroup_name.dart';import 'project_github.dart';@@ -40,6 +41,7 @@ class ProjectSidebar extends StatelessWidget {required this.onAddAgent,this.app,this.onNewProject,+ this.onNewSwarm,this.onYourDevices,this.devicesSelected = false,this.onNotifications,@@ -56,6 +58,10 @@ class ProjectSidebar extends StatelessWidget {final ValueChanged<SuperTabConversation> onAddAgent;final AppNotifier? app;final VoidCallback? onNewProject;++ /// The existing New Swarm. Given, the bar starts with the Swarm dropdown+ /// ([SwarmSwitcher]), which offers it last.+ final VoidCallback? onNewSwarm;final VoidCallback? onYourDevices;final bool devicesSelected;@@ -92,6 +98,7 @@ class ProjectSidebar extends StatelessWidget {required VoidCallback? onTap,bool selected = false,int badge = 0,+ Widget? trailing,}) => Padding(padding: const EdgeInsets.only(bottom: 2),child: Material(@@ -139,11 +146,9 @@ class ProjectSidebar extends StatelessWidget {),),),- if (badge > 0)- Padding(- padding: const EdgeInsets.only(right: 10),- child: SuperTabCountBadge(badge),- ),+ if (trailing ?? (badge > 0 ? SuperTabCountBadge(badge) : null)+ case final mark?)+ Padding(padding: const EdgeInsets.only(right: 10), child: mark),],),),@@ -787,6 +792,25 @@ class ProjectSidebar extends StatelessWidget {child: ListView(padding: const EdgeInsets.all(8),children: [+ if ((app, onNewSwarm) case (final app?, final onNewSwarm?))+ SwarmSwitcher(+ app: app,+ controller: controller,+ onNewSwarm: onNewSwarm,+ row:+ ({+ required label,+ required icon,+ required onTap,+ required trailing,+ }) => _navigationRow(+ key: 'super-swarm-switcher',+ label: label,+ icon: icon,+ onTap: onTap,+ trailing: trailing,+ ),+ ),if (onNewProject != null)_navigationRow(key: 'super-new-project',diff --git a/desktop/lib/super_tabs/swarm_switcher.dart b/desktop/lib/super_tabs/swarm_switcher.dartnew file mode 100644index 000000000..3bd36b5c8--- /dev/null+++ b/desktop/lib/super_tabs/swarm_switcher.dart@@ -0,0 +1,507 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../core/models.dart' show sameMachineId;+import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_menu.dart';+import '../state/app_state.dart';+import '../widgets/desktop_chrome.dart';+import 'buddy_rows.dart' show SuperTabCountBadge;+import 'controller.dart';+import 'machines.dart' show contributeComputer;+import 'section_heading.dart' show SuperTabSectionHeading;++/// The Swarm dropdown at the top of a Swarm tab's left bar (Dee, 10-30): the+/// Swarm the tab shows, and in its menu Personal, every other Swarm the+/// person belongs to and New Swarm. Picking one shows it in the same tab+/// ([AppNotifier.showSuperTabIn]); nothing else about tabs changes.++const kPersonalSwarmName = 'Personal';++/// The request id Personal is created with. The server derives a new Swarm's+/// id from the signed-in account and this id (backend superTabs/store.ts+/// `create`), so each person has one Personal Swarm, made once whichever+/// window or computer asks first, and two people's never meet.+const kPersonalSwarmOperation = 'personal-swarm';++/// One Swarm the dropdown lists, with what waits for the person in it.+typedef SwarmChoice = ({String id, String name, int waiting});++/// The person's Personal Swarm, per app: which Swarm it is, and creating it+/// once. Created only when the person picks it, with this computer added and+/// no Product Manager started.+class PersonalSwarm extends ChangeNotifier {+ PersonalSwarm._(this.app);+ static final _of = Expando<PersonalSwarm>();+ static PersonalSwarm of(AppNotifier app) => _of[app] ??= PersonalSwarm._(app);++ final AppNotifier app;++ /// Each account's Personal Swarm as the personal-swarm request answered+ /// on this computer.+ final _pickedIds = <String, String>{};+ final _reads = <String, Future<void>>{};+ final _creating = <String, Future<String>>{};+ final _adding = <String>{};++ /// Swarms taken away from each account while shown here: listed no more,+ /// even once their tab has let them go.+ final _lost = <String, Set<String>>{};+ String? _error, _errorAccount;++ String? get _account => app.currentUser?.id;+ static String _key(String account) => 'super_tab.personal.$account';++ /// The signed-in person's Personal Swarm as the menu shows it: picked here+ /// before, else a Swarm they own named Personal that no one else is in, as+ /// far as its read says. Never one whose read was taken away. Picking it+ /// asks the server first ([ensure]).+ String? get id {+ final account = _account;+ if (account == null) return null;+ unawaited(_read(account));+ return _picked(account) ?? _owned(account);+ }++ /// The Swarm the personal-swarm request answered for [account], while it+ /// is still theirs to read.+ String? _picked(String account) => switch (_pickedIds[account]) {+ final id? when _usable(id) => id,+ _ => null,+ };++ bool _usable(String id) =>+ !lost(id) && app.superTabs.peek(id)?.accessRevoked != true;++ /// Personal is being created or set up for the signed-in person.+ bool get busy =>+ _creating.containsKey(_account) || _adding.contains(_account);++ /// Why creating Personal or adding this computer to it failed last.+ String? get error => _errorAccount == _account ? _error : null;++ void clearError() {+ if (_error == null) return;+ _error = null;+ notifyListeners();+ }++ /// Whether Swarm [id] was taken away from the signed-in person while shown.+ bool lost(String id) => _lost[_account]?.contains(id) ?? false;++ /// A Swarm the person owns named Personal, of those they belong to, with+ /// no one else in it when it has been read.+ String? _owned(String account) {+ final ids = <String>[+ for (final tab in app.swarms) ?tab.superTabId,+ for (final closed in app.closedSuperTabs) closed.id,+ ]..sort();+ return ids.where((id) {+ final people = app.superTabs.peek(id)?.snapshot?.people;+ return _usable(id) &&+ app.superTabs.ownerOf(id) == account &&+ app.superTabName(id)?.trim() == kPersonalSwarmName &&+ (people == null || people.every((p) => p.id == account));+ }).firstOrNull;+ }++ /// What this computer remembers of [account]'s Personal, read once.+ Future<void> _read(String account) => _reads[account] ??= () async {+ try {+ final saved = await app.superTabs.storage.read(_key(account));+ if (saved != null && saved.isNotEmpty && _account == account) {+ _pickedIds.putIfAbsent(account, () => saved);+ notifyListeners();+ }+ } catch (_) {+ // Not remembered: the server's answer is asked for when it is picked.+ }+ }();++ /// The person's Personal Swarm, created on the server if it is not known+ /// here. Every caller while one is being created joins that one.+ Future<String> ensure() {+ final account = _account;+ if (account == null) {+ return Future.error(+ const SuperTabFailure('SIGNED_OUT', 'Sign in to use Swarm.'),+ );+ }+ if (_picked(account) case final known?) return Future.value(known);+ if (_creating[account] case final pending?) return pending;+ final creating = _create(account);+ _creating[account] = creating;+ notifyListeners();+ unawaited(+ creating.catchError((Object _) => '').whenComplete(() {+ _creating.remove(account);+ notifyListeners();+ }),+ );+ return creating;+ }++ /// The Swarm the personal-swarm request names: remembered here, else+ /// asked of the server, which creates it the first time. A Swarm merely+ /// named Personal is never taken for it.+ Future<String> _create(String account) async {+ _error = null;+ try {+ await _read(account);+ if (_picked(account) case final known?) return known;+ final created = await app.superTabs.map(+ 'POST',+ '/api/super-tabs',+ body: {+ 'operationId': kPersonalSwarmOperation,+ 'name': kPersonalSwarmName,+ },+ );+ if (_account != account) {+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');+ }+ final id = created['id'];+ if (id is! String || id.isEmpty) {+ throw const SuperTabFailure(+ 'INVALID_RESPONSE',+ 'Could not create your Personal Swarm. Try again.',+ );+ }+ // Discovery may list it before this tab shows it: no second tab.+ app.superTabs.deferTabDiscovery(id);+ _remember(account, id);+ return id;+ } catch (failure) {+ _fail(account, failure, 'Could not create your Personal Swarm.');+ rethrow;+ }+ }++ void _remember(String account, String id) {+ if (_pickedIds[account] == id) return;+ _pickedIds[account] = id;+ unawaited(+ app.superTabs.storage.write(_key(account), id).catchError((Object _) {}),+ );+ }++ void _fail(String account, Object failure, String fallback) {+ if (_account != account) return;+ final message = failure is SuperTabFailure ? failure.message : fallback;+ if (failure is SuperTabFailure && failure.code == 'ACCOUNT_CHANGED') return;+ _error = message;+ _errorAccount = account;+ notifyListeners();+ }++ /// Shows Personal in Swarm tab [swarmId], creating it first if needed, then+ /// adds this computer to it. A tab that moved to another Swarm meanwhile,+ /// or a person who signed out, is left as it is.+ Future<void> show(String swarmId) async {+ final account = _account;+ final shown = _tabShowing(swarmId);+ if (account == null || shown == null) return;+ final String personal;+ try {+ personal = await ensure();+ } catch (_) {+ return;+ }+ if (_account != account || _tabShowing(swarmId) != shown) return;+ app.showSuperTabIn(swarmId, personal, kPersonalSwarmName);+ await _addThisComputer(account, personal);+ }++ String? _tabShowing(String swarmId) =>+ app.swarms.where((s) => s.id == swarmId).firstOrNull?.superTabId;++ /// This computer, added as Add machine adds it: only the person's own,+ /// linked and online, and never a Harness Team account's machine.+ Future<void> _addThisComputer(String account, String personal) async {+ final here = app.machineStates.values+ .where(+ (m) =>+ m.isLocalMachine &&+ !m.machine.isTeamAccount &&+ !m.belongsToOtherAccount &&+ !m.needsLink &&+ !m.isOffline,+ )+ .firstOrNull;+ if (here == null || !_adding.add(account)) return;+ notifyListeners();+ SuperTabController? opened;+ // Let go since (the tab moved on): its answers are no one's now.+ bool alive() =>+ _account == account &&+ opened != null &&+ !opened.accessRevoked &&+ identical(app.superTabs.peek(personal), opened);+ try {+ final c = opened = await app.superTabs.open(personal);+ if (c.snapshot == null) await c.refresh();+ final machineId = here.machine.machineId;+ final snapshot = c.snapshot;+ if (!alive() || snapshot == null) return;+ if (snapshot.machines.any(+ (m) =>+ m['machineId'] is String &&+ sameMachineId(m['machineId'], machineId),+ )) {+ return;+ }+ await contributeComputer(+ c,+ app,+ machineId,+ setupId: 'personal-swarm-setup',+ alive: alive,+ // As Add machine: where the Swarm runs teammates' work through Team+ // accounts, this Mac is never lent under its owner's own login.+ teamAccountOnly: snapshot.teamAccounts,+ offerTeamAccount: false,+ );+ } catch (failure) {+ // A request still out when Personal was let go answers no one.+ if (opened == null || alive()) {+ _fail(account, failure, 'Could not add this computer to Personal.');+ }+ } finally {+ _adding.remove(account);+ notifyListeners();+ }+ }+}++/// The Swarms the dropdown lists under Personal, by name: every Swarm the+/// person belongs to, open in a tab here or closed, but not Personal and not+/// one whose read was taken away. Only Swarms the signed-in account's own+/// list or read named: a tab left from another account lists nothing.+List<SwarmChoice> swarmChoices(AppNotifier app) {+ final personal = PersonalSwarm.of(app).id;+ final names = <String, String>{};+ for (final tab in app.swarms) {+ final id = tab.superTabId;+ if (id != null) names[id] = app.superTabName(id) ?? tab.name;+ }+ for (final closed in app.closedSuperTabs) {+ names.putIfAbsent(closed.id, () => closed.name);+ }+ return [+ for (final MapEntry(key: id, value: name) in names.entries)+ if (id != personal &&+ app.superTabs.ownerOf(id) != null &&+ !PersonalSwarm.of(app).lost(id) &&+ app.superTabs.peek(id)?.accessRevoked != true)+ (+ id: id,+ name: name.trim().isEmpty ? 'Swarm' : name,+ waiting: swarmWaiting(app, id),+ ),+ ]..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));+}++/// What a Swarm's tab badge counts: its tags and unread Buddy chat lines.+int swarmWaiting(AppNotifier app, String id) =>+ app.superTabs.waitingTags(id) + app.superTabs.waitingBuddy(id);++/// The Swarm tab showing [c]'s Swarm moves to Personal when that Swarm is+/// taken away, once the person has picked Personal here (read from this+/// computer first); it never creates Personal. Nothing of the lost Swarm+/// stays in the tab. Handled once per loss: with Personal open in another+/// tab, that tab is selected and this one is left as it is after.+Future<void> fallBackToPersonal(AppNotifier app, SuperTabController c) async {+ final personal = PersonalSwarm.of(app);+ final account = c.accountId;+ if (!c.accessRevoked || account != app.currentUser?.id) return;+ if (personal._lost[account]?.contains(c.tabId) ?? false) return;+ await personal._read(account);+ final id = personal._picked(account);+ if (!c.accessRevoked ||+ account != app.currentUser?.id ||+ id == null ||+ id == c.tabId ||+ !(personal._lost[account] ??= {}).add(c.tabId)) {+ return;+ }+ final tab = app.swarms.where((s) => s.superTabId == c.tabId).firstOrNull;+ if (tab != null) app.showSuperTabIn(tab.id, id, kPersonalSwarmName);+}++/// The top row of a Swarm tab's left bar and its menu. [row] draws the row+/// as the sidebar draws its others: a label, an icon, a tap, and a trailing+/// mark.+class SwarmSwitcher extends StatefulWidget {+ const SwarmSwitcher({+ super.key,+ required this.app,+ required this.controller,+ required this.onNewSwarm,+ required this.row,+ });++ final AppNotifier app;+ final SuperTabController controller;+ final VoidCallback onNewSwarm;+ final Widget Function({+ required String label,+ required IconData icon,+ required VoidCallback? onTap,+ required Widget trailing,+ })+ row;++ @override+ State<SwarmSwitcher> createState() => _SwarmSwitcherState();+}++class _SwarmSwitcherState extends State<SwarmSwitcher> {+ final _menu = MenuController();++ AppNotifier get app => widget.app;+ PersonalSwarm get personal => PersonalSwarm.of(app);++ /// The Swarm tab this left bar is in.+ String? get _tab => app.swarms+ .where((s) => s.superTabId == widget.controller.tabId)+ .firstOrNull+ ?.id;++ void _pick(String id) {+ _menu.close();+ final tab = _tab;+ // Taken away since the menu was drawn: nothing to show.+ final choice = swarmChoices(app).where((c) => c.id == id).firstOrNull;+ if (tab == null || choice == null) return;+ app.showSuperTabIn(tab, choice.id, choice.name);+ }++ void _pickPersonal() {+ _menu.close();+ final tab = _tab;+ if (tab != null) unawaited(personal.show(tab));+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: Listenable.merge([app, personal, widget.controller]),+ builder: (context, _) {+ grid.AppTheme.watch(context);+ final c = widget.controller;+ final personalId = personal.id;+ final current = c.accessRevoked ? null : c.tabId;+ final isPersonal = current != null && current == personalId;+ final label = isPersonal+ ? kPersonalSwarmName+ : current == null+ ? 'Swarm'+ : app.superTabName(current) ?? c.snapshot?.name ?? 'Swarm';+ final choices = swarmChoices(app);+ final personalWaiting = personalId == null || isPersonal+ ? 0+ : swarmWaiting(app, personalId);+ Widget? badge(int count) => count > 0 ? SuperTabCountBadge(count) : null;+ return LayoutBuilder(+ builder: (context, box) {+ final width = box.maxWidth.isFinite ? box.maxWidth : 260.0;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ MenuAnchor(+ controller: _menu,+ consumeOutsideTap: true,+ alignmentOffset: const Offset(0, grid.AppControl.menuGap),+ style: grid.AppMenu.style(minWidth: width, maxWidth: width),+ onOpen: personal.clearError,+ // As wide as the row it opens from.+ menuChildren: [+ for (final item in <Widget>[+ AppMenuItem(+ key: const ValueKey('swarm-switch-personal'),+ label: kPersonalSwarmName,+ icon: AppIcons.user,+ selected: isPersonal,+ expandLabel: true,+ trailing: personal.busy+ ? const SizedBox.square(+ dimension: 12,+ child: CircularProgressIndicator(+ strokeWidth: 1.5,+ ),+ )+ : badge(personalWaiting),+ onPressed: _pickPersonal,+ ),+ for (final choice in choices)+ AppMenuItem(+ key: ValueKey('swarm-switch-${choice.id}'),+ label: choice.name,+ icon: AppIcons.users,+ selected: choice.id == current,+ expandLabel: true,+ trailing: choice.id == current+ ? null+ : badge(choice.waiting),+ onPressed: () => _pick(choice.id),+ ),+ AppMenuItem(+ key: const ValueKey('swarm-switch-new'),+ label: 'New Swarm',+ icon: AppIcons.plus,+ expandLabel: true,+ onPressed: () {+ _menu.close();+ widget.onNewSwarm();+ },+ ),+ ])+ SizedBox(width: width, child: item),+ ],+ builder: (context, menu, _) => Semantics(+ label: 'Swarm: $label',+ hint: 'Shows another Swarm in this tab',+ child: widget.row(+ label: label,+ icon: isPersonal ? AppIcons.user : AppIcons.users,+ onTap: () => menu.isOpen ? menu.close() : menu.open(),+ trailing: Icon(+ AppIcons.chevronDown,+ size: 14,+ color: DesktopChrome.muted,+ ),+ ),+ ),+ ),+ if (personal.error case final error?) ...[+ // Under the row's label, as the row's own text column.+ Row(+ key: const ValueKey('super-swarm-switcher-error'),+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(+ width:+ SuperTabSectionHeading.indentFor(0) ++ SuperTabSectionHeading.actionWidth,+ ),+ Expanded(+ child: Text(+ error,+ style: DesktopChrome.metadata(+ color: grid.AppPalette.warn,+ ),+ ),+ ),+ ],+ ),+ const SizedBox(height: grid.AppDesktop.controlGap),+ ],+ ],+ );+ },+ );+ },+ );+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex a8a5ba177..24729e02a 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -53,6 +53,7 @@ import 'terminal_row.dart';import 'thread_panel.dart';import 'work_details.dart';import 'project_sidebar.dart';+import 'swarm_switcher.dart' show fallBackToPersonal;import 'project_options.dart';import 'pane_layout.dart';import '../widgets/dial_list_scroll.dart';@@ -84,6 +85,7 @@ class SuperTabView extends StatefulWidget {this.terminalsVisible = false,this.app,this.onNewProject,+ this.onNewSwarm,this.onChooseAgentTerminal,this.linkSwarms,});@@ -101,6 +103,10 @@ class SuperTabView extends StatefulWidget {final bool terminalsVisible;final AppNotifier? app;final VoidCallback? onNewProject;++ /// The existing New Swarm, for the Swarm dropdown atop the left bar; none+ /// without it.+ final VoidCallback? onNewSwarm;final ValueChanged<SuperTabAgent>? onChooseAgentTerminal;/// How a message link reaches the account's other Swarms. Without it, and@@ -297,6 +303,16 @@ class _SuperTabViewState extends State<SuperTabView>_newAfter.clear();_awayFromEnd.clear();_unread.reset();+ // With the Swarm dropdown, a tab whose Swarm is taken away moves to+ // Personal once the person has picked it here.+ if ((widget.app, widget.onNewSwarm) case (final app?, _?)) {+ final lost = c;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && widget.controller == lost) {+ unawaited(fallBackToPersonal(app, lost));+ }+ });+ }}final visible =c.snapshot?.conversations.map((g) => g.id).toSet() ?? <String>{};@@ -1324,6 +1340,7 @@ class _SuperTabViewState extends State<SuperTabView>board: _board,onAddAgent: widget.onAddAgent,onNewProject: widget.onNewProject,+ onNewSwarm: widget.onNewSwarm,devicesSelected: _devicesVisible,notificationsSelected: _notificationsVisible,// On a Mac what needs the person is in the menu bar's Harness menu and ondiff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dartindex 84dfd259d..8c14679c6 100644--- a/desktop/lib/super_tabs/workspace.dart+++ b/desktop/lib/super_tabs/workspace.dart@@ -24,11 +24,13 @@ class SuperTabWorkspace extends StatefulWidget {required this.canvas,required this.onAddAgent,this.onNewProject,+ this.onNewSwarm,});final AppNotifier app;final Widget canvas;final ValueChanged<SuperTabConversation> onAddAgent;final VoidCallback? onNewProject;+ final VoidCallback? onNewSwarm;@overrideState<SuperTabWorkspace> createState() => _SuperTabWorkspaceState();@@ -534,6 +536,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {unawaited(showSuperTabPeople(context, controller)),onAddAgent: widget.onAddAgent,onNewProject: widget.onNewProject,+ onNewSwarm: widget.onNewSwarm,onOpenTerminal: (agent) => _focusAgent(controller,tab.id,diff --git a/desktop/test/super_tab_swarm_switcher_test.dart b/desktop/test/super_tab_swarm_switcher_test.dartnew file mode 100644index 000000000..9218639fc--- /dev/null+++ b/desktop/test/super_tab_swarm_switcher_test.dart@@ -0,0 +1,845 @@+import 'dart:async';++import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/project_sidebar.dart';+import 'package:harness/super_tabs/swarm_switcher.dart';+import 'package:harness/super_tabs/view.dart';+import 'package:harness/ws/ws_conn.dart';++import 'support/capture.dart';+import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show MemoryStore, createApp;++/// The backend as the Swarm dropdown meets it: the account's Swarm list, a+/// Swarm's own reads and commands, and Swarm creation, one Swarm per account+/// and request id (backend superTabs/store.ts `create`).+class _Backend {+ final tabs = <Map<String, dynamic>>[];+ final servers = <String, ConversationServer>{};++ /// Every creation request, with the account that sent it.+ final creates = <(String, Map<String, dynamic>)>[];++ /// What each machine was asked outside the backend, in order.+ final machineCalls = <(String, String)>[];+ Completer<void>? holdCreate;+ bool failCreate = false;++ /// While set, preparing a machine for a Swarm waits for it.+ Completer<void>? holdPrepare;++ /// The Swarm an account's personal-swarm request already made, by account.+ final personalOf = <String, String>{};++ /// The account the next request is from.+ String account = 'owner';++ ConversationServer add(+ String id,+ String name, {+ String owner = 'owner',+ List<String> members = const ['owner'],+ }) {+ final server = ConversationServer();+ server.state+ ..['id'] = id+ ..['name'] = name+ ..['ownerId'] = owner+ ..['people'] = [+ for (final person in members)+ {+ 'id': person,+ 'email': '[email protected]',+ 'role': person == owner ? 'owner' : 'collaborator',+ },+ ];+ servers[id] = server;+ tabs.add({'id': id, 'name': name, 'ownerId': owner, 'members': members});+ return server;+ }++ /// The machine.contribute commands Swarm [id] received.+ List<Map<String, dynamic>> contributions(String id) => [+ for (final post in servers[id]!.posts)+ if ((post['command'] as Map?)?['type'] == 'machine.contribute')+ Map<String, dynamic>.from(post['command'] as Map),+ ];++ Future<Object?> request(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ final uri = Uri.parse(path);+ if (uri.path == '/api/super-tabs/list') {+ return {+ 'tabs': [+ for (final tab in tabs)+ if ((tab['members'] as List).contains(account))+ {'id': tab['id'], 'name': tab['name'], 'ownerId': tab['ownerId']},+ ],+ 'next': null,+ };+ }+ if (method == 'POST' && uri.path == '/api/super-tabs') {+ final asker = account;+ creates.add((asker, Map<String, dynamic>.from(body!)));+ if (holdCreate case final hold?) await hold.future;+ if (failCreate) {+ throw const SuperTabFailure(+ 'SERVICE_UNAVAILABLE',+ 'Swarm is busy. Try again.',+ statusCode: 503,+ );+ }+ final id =+ (body['operationId'] == kPersonalSwarmOperation+ ? personalOf[asker]+ : null) ??+ 'swarm-$asker-${body['operationId']}';+ if (!servers.containsKey(id)) {+ add(id, body['name'] as String, owner: asker, members: [asker]);+ }+ return {'id': id, 'revision': 0};+ }+ final swarm = RegExp(r'^/api/super-tabs/([^/]+)/').firstMatch(uri.path);+ final server = servers[swarm?.group(1)];+ if (server == null) {+ throw const SuperTabFailure('NOT_FOUND', 'Swarm not found.');+ }+ return server.request(method, path, body: body);+ }+}++class _Connection extends WsConn {+ _Connection(this.backend, String machineId)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final _Backend backend;++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type != 'super_tabs') return {};+ final action = payload['action'] as String?;+ if (action == 'backend') {+ return {+ 'value': await backend.request(+ payload['method'] as String,+ payload['path'] as String,+ body: payload['body'] as Map<String, dynamic>?,+ ),+ };+ }+ backend.machineCalls.add((machineId, action ?? ''));+ if (action == 'prepareContribution') {+ if (backend.holdPrepare case final hold?) await hold.future;+ return {+ 'state': 'ready',+ 'scope': 'swarm',+ 'cwd': '/Users/person/harnesses/swarm',+ 'engines': ['claude', 'codex'],+ 'maxAgents': 4,+ };+ }+ return {};+ }+}++AppNotifier _computer(+ _Backend backend,+ MemoryStore store, {+ String account = 'owner',+ bool teamMachineToo = false,+}) {+ final app = createApp(+ store: store,+ connected: true,+ connectionForTest: (machineId) => _Connection(backend, machineId),+ );+ app.machineStates['m']!.localOnly = true;+ if (teamMachineToo) {+ // This Mac's Harness Team account, served by the same daemon.+ const team = Machine(+ machineId: 'team-m',+ authMode: MachineAuthMode.remote,+ name: 'Test host (Team)',+ sessionKind: 'team',+ );+ app.machines = [...app.machines, team];+ app.machineStates['team-m'] = MachineState(team)+ ..localOnly = true+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected;+ }+ app.status = AppStatus.authenticated;+ app.currentUser = CurrentUserProfile(+ id: account,+ email: '[email protected]',+ );+ app.enterSuperTabs();+ addTearDown(app.dispose);+ return app;+}++/// Lets requests through the fake transport and saved-state writes finish.+Future<void> _settle([WidgetTester? tester]) async {+ for (var i = 0; i < 30; i++) {+ if (tester != null) {+ await tester.pump();+ } else {+ await Future<void>.delayed(Duration.zero);+ }+ }+}++String _shown(AppNotifier app, String deskId) =>+ app.swarms.firstWhere((s) => s.id == deskId).superTabId!;++/// Alpha and Beta, both open in tabs, Alpha shown; Gamma closed here.+Future<(AppNotifier, _Backend)> _twoTabs({+ MemoryStore? store,+ bool teamMachineToo = false,+}) async {+ final backend = _Backend()+ ..add('alpha', 'Alpha')+ ..add('beta', 'Beta')+ ..add('gamma', 'Gamma');+ final app = _computer(+ backend,+ store ?? MemoryStore(),+ teamMachineToo: teamMachineToo,+ );+ await app.superTabs.setTabVisible('gamma', false);+ await app.superTabs.refreshTabs();+ final alpha = app.swarms.firstWhere((s) => s.superTabId == 'alpha');+ app.selectSwarm(alpha.id);+ return (app, backend);+}++Future<SuperTabController> _pumpBar(+ WidgetTester tester,+ AppNotifier app, {+ Brightness brightness = Brightness.dark,+ VoidCallback? onNewSwarm,+}) async {+ await tester.binding.setSurfaceSize(const Size(300, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ late SuperTabController shown;+ await tester.runAsync(() async {+ shown = await app.superTabs.open(app.activeSwarm.superTabId!);+ await shown.refresh();+ });+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: ListenableBuilder(+ listenable: app,+ // The Swarm the tab shows, once opened, as the workspace gives it.+ builder: (context, _) =>+ switch (app.superTabs.peek(app.activeSwarm.superTabId!)) {+ null => const SizedBox(),+ final c => ListenableBuilder(+ listenable: c,+ builder: (context, _) => ProjectSidebar(+ key: ValueKey(c.tabId),+ controller: c,+ app: app,+ onAddAgent: (_) {},+ needsHuman: (_) => 0,+ onSelect: c.select,+ onNewProject: () {},+ onNewSwarm: onNewSwarm ?? () {},+ ),+ ),+ },+ ),+ ),+ ),+ );+ await tester.pump();+ await tester.pump();+ return shown;+}++/// Lets go of every Swarm opened, as closing their tabs does: no poll is+/// left running after a widget test.+Future<void> _releaseAll(WidgetTester tester, AppNotifier app) async {+ await tester.pumpWidget(const SizedBox());+ for (final c in app.superTabs.loadedControllers.toList()) {+ app.superTabs.release(c.tabId);+ }+ await tester.runAsync(() => _settle());+}++Finder _rowText(String text) => find.descendant(+ of: find.byKey(const ValueKey('super-swarm-switcher')),+ matching: find.text(text),+);++Future<void> _openMenu(WidgetTester tester) async {+ await tester.tap(find.byKey(const ValueKey('super-swarm-switcher')));+ await tester.pump();+ await tester.pump();+}++/// Set to a folder to write the PR's pictures of the dropdown there.+final _shots = Platform.environment['SWARM_SWITCHER_SHOTS'];++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ setUpAll(() => loadCaptureFonts(_shots));++ for (final brightness in Brightness.values) {+ testWidgets('pictures of the Swarm dropdown, closed and open, in '+ '${brightness.name}', (tester) async {+ if (_shots == null) return;+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ tester.view.devicePixelRatio = 2;+ tester.view.physicalSize = const Size(2400, 1300);+ addTearDown(tester.view.reset);+ late AppNotifier app;+ late SuperTabController shown;+ await tester.runAsync(() async {+ final backend = _Backend()+ ..add('openharness', 'openharness')+ ..add('robots', 'Autonomous Robots')+ ..add('crit', 'Design crit');+ backend.servers['robots']!.state['mentionsWaiting'] = 3;+ app = _computer(backend, MemoryStore());+ await app.superTabs.setTabVisible('crit', false);+ await app.superTabs.refreshTabs();+ app.selectSwarm(+ app.swarms.firstWhere((s) => s.superTabId == 'openharness').id,+ );+ await (await app.superTabs.open('robots')).refresh();+ shown = await app.superTabs.open('openharness');+ await shown.refresh();+ });+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabView(+ controller: shown,+ app: app,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ onNewProject: () {},+ onNewSwarm: () {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pump();+ await tester.pump();+ await captureWindow(+ tester,+ _shots,+ 'swarm-dropdown-closed-${brightness.name}',+ );+ await _openMenu(tester);+ await captureWindow(+ tester,+ _shots,+ 'swarm-dropdown-open-${brightness.name}',+ );+ await _releaseAll(tester, app);+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ }++ testWidgets('the bar starts with the shown Swarm; its menu lists Personal, '+ 'every Swarm with what waits, the shown one ticked, then New Swarm', (+ tester,+ ) async {+ late AppNotifier app;+ late _Backend backend;+ await tester.runAsync(() async {+ (app, backend) = await _twoTabs();+ backend.servers['beta']!.state['mentionsWaiting'] = 2;+ final beta = await app.superTabs.open('beta');+ await beta.refresh();+ });+ var newSwarm = 0;+ await _pumpBar(tester, app, onNewSwarm: () => newSwarm++);+ expect(_rowText('Alpha'), findsOneWidget);+ final bar = tester.getTopLeft(+ find.byKey(const ValueKey('super-swarm-switcher')),+ );+ expect(+ bar.dy,+ lessThan(+ tester.getTopLeft(find.byKey(const ValueKey('super-new-project'))).dy,+ ),+ );++ await _openMenu(tester);+ final order = [+ 'swarm-switch-personal',+ 'swarm-switch-alpha',+ 'swarm-switch-beta',+ 'swarm-switch-gamma',+ 'swarm-switch-new',+ ];+ final tops = [+ for (final key in order) tester.getTopLeft(find.byKey(ValueKey(key))).dy,+ ];+ expect(tops, [...tops]..sort());+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('swarm-switch-beta')),+ matching: find.text('2'),+ ),+ findsOneWidget,+ );+ await tester.tap(find.byKey(const ValueKey('swarm-switch-new')));+ await tester.pump();+ expect(newSwarm, 1);+ await _releaseAll(tester, app);+ });++ test('picking a Swarm open in another tab selects that tab; no tab is '+ 'added, closed or moved', () async {+ final (app, _) = await _twoTabs();+ final before = [for (final s in app.swarms) (s.id, s.superTabId, s.name)];+ final alphaTab = app.activeSwarmId;+ app.showSuperTabIn(alphaTab, 'beta', 'Beta');+ expect([for (final s in app.swarms) (s.id, s.superTabId, s.name)], before);+ expect(app.activeSwarm.superTabId, 'beta');+ });++ test('picking a closed Swarm shows it in this same tab with its name; '+ 'the Swarm it showed is closed here and not rediscovered', () async {+ final (app, _) = await _twoTabs();+ final count = app.swarms.length;+ final tab = app.activeSwarmId;+ final index = app.swarms.indexWhere((s) => s.id == tab);+ app.showSuperTabIn(tab, 'gamma', 'Gamma');+ await _settle();+ await app.superTabs.refreshTabs();+ expect(app.swarms, hasLength(count));+ expect(app.swarms.indexWhere((s) => s.id == tab), index);+ expect(_shown(app, tab), 'gamma');+ expect(app.activeSwarm.name, 'Gamma');+ expect(app.swarms.where((s) => s.superTabId == 'alpha'), isEmpty);+ expect(app.closedSuperTabs.map((c) => c.id), contains('alpha'));+ expect(swarmChoices(app).map((c) => c.id), containsAll(['alpha', 'gamma']));+ });++ test('a half-written message stays with its Swarm across a switch', () async {+ final (app, _) = await _twoTabs();+ final tab = app.activeSwarmId;+ final alpha = await app.superTabs.open('alpha');+ await alpha.refresh();+ alpha.setDraft('lead', 'Half a thought for Alpha');+ app.showSuperTabIn(tab, 'gamma', 'Gamma');+ await _settle();+ final gamma = await app.superTabs.open('gamma');+ await gamma.refresh();+ expect(gamma.draft('lead'), '');+ app.showSuperTabIn(tab, 'alpha', 'Alpha');+ await _settle();+ final back = await app.superTabs.open('alpha');+ expect(back, isNot(same(alpha)));+ expect(back.draft('lead'), 'Half a thought for Alpha');+ });++ test('Personal is created once under a double pick, shown in this tab, '+ 'with this computer added and no Product Manager started', () async {+ final (app, backend) = await _twoTabs(teamMachineToo: true);+ final tab = app.activeSwarmId;+ final count = app.swarms.length;+ backend.holdCreate = Completer<void>();+ final personal = PersonalSwarm.of(app);+ final first = personal.show(tab);+ final second = personal.show(tab);+ await _settle();+ expect(personal.busy, isTrue);+ backend.holdCreate!.complete();+ await Future.wait([first, second]);+ await _settle();+ expect(backend.creates, hasLength(1));+ expect(backend.creates.single.$2, {+ 'operationId': kPersonalSwarmOperation,+ 'name': 'Personal',+ });+ final id = backend.creates.single.$1 == 'owner'+ ? 'swarm-owner-$kPersonalSwarmOperation'+ : null;+ expect(_shown(app, tab), id);+ expect(app.activeSwarm.name, 'Personal');+ expect(app.swarms, hasLength(count));+ // This Mac only: never its Harness Team account.+ expect(backend.contributions(id!).map((c) => c['machineId']), ['m']);+ expect(backend.machineCalls.where((c) => c.$1 == 'team-m'), isEmpty);+ expect(+ backend.servers[id]!.posts.where(+ (p) => (p['command'] as Map?)?['type'] == 'lead.start',+ ),+ isEmpty,+ );+ // Picked again: the same Swarm, nothing created or added again.+ app.showSuperTabIn(tab, 'alpha', 'Alpha');+ await personal.show(tab);+ await _settle();+ expect(backend.creates, hasLength(1));+ expect(backend.contributions(id), hasLength(1));+ expect(_shown(app, tab), id);+ });++ test('two windows picking Personal get the same Swarm', () async {+ final backend = _Backend()..add('alpha', 'Alpha');+ final one = _computer(backend, MemoryStore());+ final two = _computer(backend, MemoryStore());+ for (final app in [one, two]) {+ await app.superTabs.refreshTabs();+ app.selectSwarm(app.swarms.firstWhere((s) => s.superTabId == 'alpha').id);+ }+ await Future.wait([+ PersonalSwarm.of(one).show(one.activeSwarmId),+ PersonalSwarm.of(two).show(two.activeSwarmId),+ ]);+ await _settle();+ expect(backend.servers.keys.where((id) => id != 'alpha'), hasLength(1));+ expect(_shown(one, one.activeSwarmId), _shown(two, two.activeSwarmId));+ });++ test('a computer signed in as a Harness Team account sends no Personal '+ 'request and adds no machine', () async {+ final backend = _Backend()..add('alpha', 'Alpha');+ final app = _computer(backend, MemoryStore());+ await app.superTabs.refreshTabs();+ app.selectSwarm(app.swarms.firstWhere((s) => s.superTabId == 'alpha').id);+ // This computer's daemon switched to the Team account (`harness team on`).+ const team = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'Test host',+ sessionKind: 'team',+ );+ app.machines = [team];+ app.machineStates['m'] = MachineState(team)+ ..localOnly = true+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected;+ final personal = PersonalSwarm.of(app);+ await personal.show(app.activeSwarmId);+ await _settle();+ expect(backend.creates, isEmpty);+ expect(backend.machineCalls, isEmpty);+ expect(personal.error, AppNotifier.teamComputerSwarmMessage);+ expect(app.activeSwarm.superTabId, 'alpha');+ });++ test('two accounts never share a Personal Swarm', () async {+ final backend = _Backend()+ ..add('alpha', 'Alpha', members: ['owner', 'mate']);+ final app = _computer(backend, MemoryStore());+ await app.superTabs.refreshTabs();+ app.selectSwarm(app.swarms.firstWhere((s) => s.superTabId == 'alpha').id);+ await PersonalSwarm.of(app).show(app.activeSwarmId);+ await _settle();+ final mine = PersonalSwarm.of(app).id;+ expect(mine, isNotNull);++ app.currentUser = const CurrentUserProfile(+ id: 'mate',+ email: '[email protected]',+ );+ backend.account = 'mate';+ await app.superTabs.refreshTabs();+ expect(PersonalSwarm.of(app).id, isNull);+ expect(swarmChoices(app).map((c) => c.id), isNot(contains(mine)));+ final theirs = await PersonalSwarm.of(app).ensure();+ expect(theirs, isNot(mine));+ expect(backend.creates.map((c) => c.$1), ['owner', 'mate']);+ });++ test('a Swarm the person owns named Personal is their Personal, listed '+ 'once; one someone else owns is an ordinary Swarm', () async {+ final backend = _Backend()+ ..add('alpha', 'Alpha')+ ..add('own-personal', 'Personal')+ ..add(+ 'their-personal',+ 'Personal',+ owner: 'mate',+ members: ['mate', 'owner'],+ );+ final app = _computer(backend, MemoryStore());+ await app.superTabs.refreshTabs();+ expect(PersonalSwarm.of(app).id, 'own-personal');+ expect(swarmChoices(app).map((c) => c.id), ['alpha', 'their-personal']);+ // The server confirms it is the one the personal-swarm request made.+ backend.personalOf['owner'] = 'own-personal';+ final tab = app.swarms.firstWhere((s) => s.superTabId == 'alpha').id;+ await PersonalSwarm.of(app).show(tab);+ await _settle();+ expect(backend.creates, hasLength(1));+ expect(backend.servers.keys, hasLength(3));+ // Open in its own tab already: that tab is shown.+ expect(app.activeSwarm.superTabId, 'own-personal');+ });++ test(+ 'a Swarm the person owns named Personal is only taken for it when the '+ 'server says so: one with teammates is never used, nor added to',+ () async {+ final backend = _Backend()+ ..add('alpha', 'Alpha')+ ..add('team-personal', 'Personal', members: ['owner', 'mate']);+ final app = _computer(backend, MemoryStore());+ await app.superTabs.refreshTabs();+ await (await app.superTabs.open('team-personal')).refresh();+ expect(PersonalSwarm.of(app).id, isNull);+ expect(swarmChoices(app).map((c) => c.id), contains('team-personal'));+ final tab = app.swarms.firstWhere((s) => s.superTabId == 'alpha').id;+ app.selectSwarm(tab);+ await PersonalSwarm.of(app).show(tab);+ await _settle();+ const mine = 'swarm-owner-$kPersonalSwarmOperation';+ expect(_shown(app, tab), mine);+ expect(backend.contributions('team-personal'), isEmpty);+ expect(backend.contributions(mine).map((c) => c['machineId']), ['m']);+ },+ );++ test('a Swarm owned and named Personal but not the server\'s is not used, '+ 'even unread', () async {+ final backend = _Backend()+ ..add('alpha', 'Alpha')+ ..add('renamed', 'Personal');+ final app = _computer(backend, MemoryStore());+ await app.superTabs.refreshTabs();+ final tab = app.swarms.firstWhere((s) => s.superTabId == 'alpha').id;+ app.selectSwarm(tab);+ await PersonalSwarm.of(app).show(tab);+ await _settle();+ expect(backend.contributions('renamed'), isEmpty);+ expect(_shown(app, tab), 'swarm-owner-$kPersonalSwarmOperation');+ });++ test('this computer joins Personal as Add machine adds it: through Team '+ 'accounts where the Swarm uses them', () async {+ final (app, backend) = await _twoTabs();+ await PersonalSwarm.of(app).show(app.activeSwarmId);+ await _settle();+ final id = PersonalSwarm.of(app).id!;+ expect(backend.contributions(id).single['teamAccountOnly'], isTrue);+ });++ test('an add that answers after Personal was let go adds nothing and '+ 'says nothing', () async {+ final (app, backend) = await _twoTabs();+ final tab = app.activeSwarmId;+ backend.holdPrepare = Completer<void>();+ final picking = PersonalSwarm.of(app).show(tab);+ await _settle();+ final id = PersonalSwarm.of(app).id!;+ expect(_shown(app, tab), id);+ // The add goes out, and its answer is slow.+ final answer = backend.servers[id]!.holdCommands = Completer<void>();+ backend.holdPrepare!.complete();+ await _settle();+ expect(backend.contributions(id), hasLength(1));+ // The person moves the tab on before it answers.+ app.showSuperTabIn(tab, 'gamma', 'Gamma');+ answer.complete();+ await picking;+ await _settle();+ expect(PersonalSwarm.of(app).error, isNull);+ expect(_shown(app, tab), 'gamma');+ });++ test('a loss handled once: with Personal open in another tab, that tab is '+ 'selected, and the tab that lost access is not bounced again', () async {+ final (app, _) = await _twoTabs();+ final betaTab = app.swarms.firstWhere((s) => s.superTabId == 'beta').id;+ await PersonalSwarm.of(app).show(betaTab);+ await _settle();+ final personal = PersonalSwarm.of(app).id!;+ expect(_shown(app, betaTab), personal);+ final alphaTab = app.swarms.firstWhere((s) => s.superTabId == 'alpha').id;+ app.selectSwarm(alphaTab);+ final alpha = await app.superTabs.open('alpha');+ await alpha.refresh();+ alpha.revokeAccess('You no longer have access to this Swarm.');+ await fallBackToPersonal(app, alpha);+ expect(app.activeSwarmId, betaTab);+ app.selectSwarm(alphaTab);+ await fallBackToPersonal(app, alpha);+ expect(app.activeSwarmId, alphaTab);+ });++ test('a loss right after launch waits for what this computer remembers of '+ 'Personal before deciding', () async {+ final backend = _Backend()+ ..add('alpha', 'Alpha')+ ..add('mine', 'Personal');+ final store = MemoryStore()..values['super_tab.personal.owner'] = 'mine';+ final app = _computer(backend, store);+ await app.superTabs.setTabVisible('mine', false);+ await app.superTabs.refreshTabs();+ final tab = app.swarms.firstWhere((s) => s.superTabId == 'alpha').id;+ app.selectSwarm(tab);+ final alpha = await app.superTabs.open('alpha');+ await alpha.refresh();+ alpha.revokeAccess('You no longer have access to this Swarm.');+ await fallBackToPersonal(app, alpha);+ expect(_shown(app, tab), 'mine');+ });++ test('a Swarm taken away while shown moves its tab to Personal and leaves '+ 'the menu; without Personal picked here the tab stays', () async {+ final (app, _) = await _twoTabs();+ final tab = app.activeSwarmId;+ final alpha = await app.superTabs.open('alpha');+ await alpha.refresh();+ alpha.revokeAccess('You no longer have access to this Swarm.');+ await fallBackToPersonal(app, alpha);+ expect(_shown(app, tab), 'alpha');+ expect(swarmChoices(app).map((c) => c.id), isNot(contains('alpha')));++ final (app2, _) = await _twoTabs();+ final tab2 = app2.activeSwarmId;+ await PersonalSwarm.of(app2).show(tab2);+ await _settle();+ final personal = PersonalSwarm.of(app2).id!;+ app2.showSuperTabIn(tab2, 'alpha', 'Alpha');+ await _settle();+ final shown = await app2.superTabs.open('alpha');+ await shown.refresh();+ shown.revokeAccess('You no longer have access to this Swarm.');+ await fallBackToPersonal(app2, shown);+ expect(_shown(app2, tab2), personal);+ expect(app2.activeSwarm.name, 'Personal');+ expect(swarmChoices(app2).map((c) => c.id), isNot(contains('alpha')));+ });++ test('a Personal creation that answers after the tab moved on, or after '+ 'sign-out, changes nothing', () async {+ final (app, backend) = await _twoTabs();+ final tab = app.activeSwarmId;+ backend.holdCreate = Completer<void>();+ final picking = PersonalSwarm.of(app).show(tab);+ await _settle();+ app.showSuperTabIn(tab, 'gamma', 'Gamma');+ backend.holdCreate!.complete();+ await picking;+ await _settle();+ expect(_shown(app, tab), 'gamma');+ expect(backend.servers.values.expand((s) => s.posts), isEmpty);++ final (other, backend2) = await _twoTabs();+ final tab2 = other.activeSwarmId;+ backend2.holdCreate = Completer<void>();+ final late = PersonalSwarm.of(other).show(tab2);+ await _settle();+ other.currentUser = const CurrentUserProfile(+ id: 'mate',+ email: '[email protected]',+ );+ backend2.holdCreate!.complete();+ await late;+ await _settle();+ expect(_shown(other, tab2), 'alpha');+ expect(PersonalSwarm.of(other).error, isNull);+ });++ for (final dropdown in [true, false]) {+ testWidgets('the Swarm view moves a tab whose Swarm is taken away to '+ 'Personal${dropdown ? '' : ', but not without the dropdown'}', (+ tester,+ ) async {+ late AppNotifier app;+ late String tab, personal;+ late SuperTabController alpha;+ await tester.runAsync(() async {+ (app, _) = await _twoTabs();+ tab = app.activeSwarmId;+ await PersonalSwarm.of(app).show(tab);+ await _settle();+ personal = PersonalSwarm.of(app).id!;+ app.showSuperTabIn(tab, 'alpha', 'Alpha');+ await _settle();+ alpha = await app.superTabs.open('alpha');+ await alpha.refresh();+ });+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: alpha,+ app: app,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ onNewSwarm: dropdown ? () {} : null,+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pump();+ alpha.revokeAccess('You no longer have access to this Swarm.');+ await tester.pump();+ // What this computer remembers of Personal was read in the real zone.+ await tester.runAsync(() => _settle());+ await tester.pump();+ expect(_shown(app, tab), dropdown ? personal : 'alpha');+ await _releaseAll(tester, app);+ });+ }++ testWidgets('a failed creation says so under the bar, and picking Personal '+ 'again creates it', (tester) async {+ late AppNotifier app;+ late _Backend backend;+ await tester.runAsync(() async {+ (app, backend) = await _twoTabs();+ });+ backend.failCreate = true;+ await _pumpBar(tester, app);+ await _openMenu(tester);+ await tester.tap(find.byKey(const ValueKey('swarm-switch-personal')));+ await tester.runAsync(() => _settle(tester));+ await tester.pump();+ expect(find.text('Swarm is busy. Try again.'), findsOneWidget);+ expect(_rowText('Alpha'), findsOneWidget);++ backend.failCreate = false;+ await _openMenu(tester);+ expect(find.text('Swarm is busy. Try again.'), findsNothing);+ await tester.tap(find.byKey(const ValueKey('swarm-switch-personal')));+ await tester.runAsync(() => _settle(tester));+ await tester.pump();+ await tester.pump();+ expect(backend.creates, hasLength(2));+ expect(_rowText('Personal'), findsOneWidget);+ await _releaseAll(tester, app);+ });+}