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
Merge batch 11-03 b1922: #2779 #2776 (#2816)
0xken1567fadefbe0ad
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dartindex 271d2aab2..fd7c50f54 100644--- a/desktop/lib/app_shell.dart+++ b/desktop/lib/app_shell.dart@@ -25,6 +25,7 @@ import 'screens/login_screen.dart';import 'screens/swarm_menu_bus.dart';import 'state/app_state.dart';import 'stats/stats_lifecycle.dart';+import 'super_tabs/team_account_setup.dart';import 'viewer/viewer_services.dart';import 'ws/terminal_transport_plugin.dart';import 'shared/theme/app_theme.dart' as grid;@@ -164,7 +165,7 @@ class HarnessApp extends StatelessWidget {// surfaces own their no-scaling boundary alongside terminal zoom.builder: (context, child) {final app = child ?? const SizedBox.shrink();- final framed = frame?.call(app) ?? app;+ final framed = _TeamSetupHold(child: frame?.call(app) ?? app);return _GridTokenScope(child: keymap == null? framed@@ -178,6 +179,19 @@ class HarnessApp extends StatelessWidget {}}+/// The whole window, every route and dialog included, waits while this+/// computer's Harness Team account must be set up after it joined a Swarm+/// (super_tabs/team_account_setup.dart).+class _TeamSetupHold extends ConsumerWidget {+ const _TeamSetupHold({required this.child});++ final Widget child;++ @override+ Widget build(BuildContext context, WidgetRef ref) =>+ TeamAccountSetupLock(app: ref.watch(appStateProvider), child: child);+}+/// Carries Grid's design tokens past this app's `const` chrome.////// A `const` widget is reference-identical across its parent's rebuild, so a@@ -317,7 +331,11 @@ class _RootShellState extends ConsumerState<RootShell>/// ([InWindowMenuBar]) fires the same strings directly, so one switch serves/// every platform.Future<void> runAppMenuAction(String action) async {- if (!mounted) return;+ // The Harness Team account's setup holds the whole window+ // (super_tabs/team_account_setup.dart). AppKit's own Quit and About panel+ // never come here; every action that does waits, the Linux and Windows+ // strip's About included.+ if (!mounted || ref.read(appStateProvider).teamSetupLocked) return;switch (action) {case 'settings':final app = ref.read(appStateProvider);diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 472688708..65db5f825 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -487,6 +487,9 @@ class _SwarmScreenState extends State<SwarmScreen> {/// clears first ([_onNative]). A titlebar dropdown is an overlay, not a/// cover: the titlebar stays as it is, and a click there closes it._TitlebarCover get _titlebarCover {+ // The Harness Team account's setup holds the whole window+ // (TeamAccountSetupLock): menus, shortcuts and the row wait with it.+ if (app.teamSetupLocked) return _TitlebarCover.modal;if (_spokenPaletteOpen) return _TitlebarCover.modal;if (settingsPageOnTop.value != null) return _TitlebarCover.settingsPage;if (!_routeIsCurrent || _dialogOpen) return _TitlebarCover.modal;@@ -2464,6 +2467,9 @@ class _SwarmScreenState extends State<SwarmScreen> {/// closes every open dropdown first ([dismissTransientMenus]); a row click/// pops the Settings page first; a modal still drops it ([_actOnNative]).Future<void> _onNative(MethodCall call) async {+ // Held with the window ([_titlebarCover]): a row or key equivalent that+ // AppKit sent before it greyed out does nothing either.+ if (app.teamSetupLocked) return;var action = call;final args = call.arguments is Map ? call.arguments as Map : const {};// AppKit wraps the row's clicks while its menus are off, which, with the@@ -4992,7 +4998,11 @@ class _SwarmScreenState extends State<SwarmScreen> {// Paint hints only; the keymap still owns every shortcut and input event._tabShortcutHints.value = showsTabShortcutHints(HardwareKeyboard.instance);// Off, this is not here at all: every key goes where it went before.- if (event is! KeyDownEvent || _zoo.daemons == DaemonsSwitch.off) {+ // Nor while the Harness Team account's setup holds the window+ // (TeamAccountSetupLock): this handler hears keys whatever has focus.+ if (event is! KeyDownEvent ||+ _zoo.daemons == DaemonsSwitch.off ||+ app.teamSetupLocked) {return false;}_noteWindowInput();diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 4bf317fdc..b092ea5fe 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -2255,18 +2255,23 @@ class AppNotifier extends ChangeNotifier {}/// The Harness Team account on this computer (cli/src/team/autoSetup.ts),- /// offered while the person is here: as they join a Swarm ([reason]- /// `join`), add this computer to one (`contribute`), or open the app- /// (`startup`). This computer's own daemon decides whether it is wanted: no- /// account yet, not declined before, and at start only while this computer- /// is in a Swarm with other people in it. It is then explained before the- /// system asks ([teamSetupAsks]): macOS's prompt is titled "osascript",- /// which nobody recognised as Harness (2026-10-27). On a Mac, Linux and- /// Windows ([teamAccountOn]), and never for another machine, where nobody- /// may be at it.+ /// asked of this computer's own daemon while the person is here: as they+ /// join a Swarm ([reason] `join`), add this computer to one (`contribute`),+ /// or open the app (`startup`). On a Mac, Linux and Windows+ /// ([teamAccountOn]), and never for another machine, where nobody may be at+ /// it.+ ///+ /// A join or a contribution with the account missing locks the app until it+ /// exists ([teamSetupLocked]; Scholes, 2026-11-03: Macs that joined stayed+ /// "not set up" until someone found their row in Machines). A cancel or a+ /// failure the daemon remembers from before locks too: this is a new join.+ /// At start the daemon decides (no account, not declined, in a Swarm with+ /// other people), and it is explained once a launch ([teamSetupAsks]),+ /// never behind the lock.////// [tabId]: the Swarm joined or added to, so a Swarm its server does not- /// try team accounts in yet asks nothing (the daemon reads it).+ /// try team accounts in yet asks nothing (the daemon reads it), and the lock+ /// knows where Remove this Mac from the Swarm removes it from.////// True when the daemon answered, whatever it decided; false when it was not/// asked or could not say.@@ -2279,18 +2284,18 @@ class AppNotifier extends ChangeNotifier {'reason': reason,'tabId': ?tabId,});- appLog.info(- 'super-tabs',- 'team account offer ($reason): ${answer['state']}',- );- if (answer['state'] == 'wanted') {+ final state = answer['state'];+ appLog.info('super-tabs', 'team account offer ($reason): $state');+ if (reason == 'startup') {// The start check runs once for each daemon process, so a restart// with the explanation still open must not show it again: once a- // launch at start. A join, a contribution or the machine row's Set up- // is the person asking, and always explains.- if (reason != 'startup' || !_teamStartExplained)+ // launch.+ if (state == 'wanted' && !_teamStartExplained && !teamSetupLocked) {_teamSetupAsks.add(reason);- if (reason == 'startup') _teamStartExplained = true;+ }+ if (state == 'wanted') _teamStartExplained = true;+ } else if (tabId != null && _teamLockStates.contains(state)) {+ await _lockForTeamSetup(tabId);}return true;} catch (error) {@@ -2300,6 +2305,208 @@ class AppNotifier extends ChangeNotifier {}}+ /// The daemon's answers that leave the account to be made here: wanted, or+ /// held back only by an earlier cancel or failure, already running, or with+ /// no prompt to ask in (the window then says how).+ static const _teamLockStates = {+ 'wanted',+ 'declined',+ 'waiting',+ 'running',+ 'no-prompt',+ };++ /// The Swarms this computer joined, or was added to, while its Harness Team+ /// account was missing, for [_teamLockAccount]. Kept on this computer so a+ /// restart locks again.+ final _teamLockTabs = <String>{};+ String? _teamLockAccount;+ String? _teamLockRestored;++ static String _teamLockKey(String account) => 'team_setup_lock.$account';++ /// Whether the app is held until this computer's Harness Team account exists+ /// (super_tabs/team_account_setup.dart `TeamAccountSetupLock`).+ bool get teamSetupLocked =>+ _teamLockTabs.isNotEmpty &&+ _teamLockAccount != null &&+ _teamLockAccount == currentUser?.id &&+ _teamAccountHere() != null;++ Future<void> _lockForTeamSetup(String tabId) async {+ final account = currentUser?.id;+ if (account == null) return;+ if (_teamLockAccount != account) {+ _teamLockAccount = account;+ _teamLockTabs.clear();+ }+ if (!_teamLockTabs.add(tabId)) return;+ notifyListeners();+ await _saveTeamLock(account);+ }++ Future<void> _saveTeamLock(String account) async {+ final store = localStore;+ if (store == null) return;+ try {+ if (_teamLockTabs.isEmpty) {+ await store.delete(_teamLockKey(account));+ } else {+ await store.write(+ _teamLockKey(account),+ jsonEncode(_teamLockTabs.toList()),+ );+ }+ } catch (error) {+ appLog.info('super-tabs', 'team account lock not saved: $error');+ }+ }++ /// At each connection of this computer's daemon: a lock left by a join+ /// before the app closed holds again, unless the account exists by now.+ /// Read once for each account.+ Future<void> _restoreTeamSetupLock() async {+ final account = currentUser?.id;+ final store = localStore;+ if (account == null || store == null || _teamLockRestored == account) {+ return;+ }+ if (_teamAccountHere() == null) return;+ _teamLockRestored = account;+ List<String> tabs;+ try {+ final raw = await store.read(_teamLockKey(account));+ tabs = raw == null+ ? const []+ : [+ for (final id in jsonDecode(raw) as List)+ if (id is String) id,+ ];+ } catch (error) {+ appLog.info('super-tabs', 'team account lock not read: $error');+ return;+ }+ if (tabs.isEmpty || _disposed || currentUser?.id != account) return;+ final setup = await teamSetupStatus();+ if (_disposed || currentUser?.id != account) return;+ if (_teamLockAccount != account) {+ _teamLockAccount = account;+ _teamLockTabs.clear();+ }+ _teamLockTabs.addAll(tabs);+ if (setup?.state == 'exists') {+ await teamAccountMade();+ return;+ }+ // A Swarm that let this computer go meanwhile (removed from Machines on+ // another device, or the person's access gone) holds nothing.+ final here = _teamAccountHere();+ if (here != null) {+ for (final tabId in tabs) {+ if (await _swarmHolds(tabId, here) == false) {+ _teamLockTabs.remove(tabId);+ }+ }+ }+ if (_disposed || currentUser?.id != account) return;+ notifyListeners();+ if (_teamLockTabs.length != tabs.length) await _saveTeamLock(account);+ }++ /// Whether Swarm [tabId] still has computer [here] in its Machines list, not+ /// being removed: false when it does not, or when this person can no longer+ /// open it; null when it cannot be read now (offline), which keeps the lock.+ Future<bool?> _swarmHolds(String tabId, String here) async {+ try {+ final c = await superTabs.open(tabId);+ await c.refresh();+ if (c.accessRevoked) return false;+ final snapshot = c.snapshot;+ if (snapshot == null || c.error != null) return null;+ return snapshot.machines.any(+ (m) => m['machineId'] == here && m['removal'] == null,+ );+ } on SuperTabFailure catch (failure) {+ return const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)+ ? false+ : null;+ } catch (_) {+ return null;+ }+ }++ /// The Swarms the lock holds for, by the names they go by, read now so+ /// Remove can say which it leaves; "a Swarm" for one that cannot be read.+ Future<List<String>> readTeamSetupLockSwarmNames() async => [+ for (final id in [..._teamLockTabs])+ switch (await _swarmName(id)) {+ final String name when name.isNotEmpty => name,+ _ => 'a Swarm',+ },+ ];++ /// A Swarm's name, given up after [_teamLockNameWait] (offline): Remove+ /// still asks, naming it "a Swarm".+ Future<String?> _swarmName(String tabId) async {+ try {+ return await () async {+ final c = await superTabs.open(tabId);+ if (c.snapshot == null) await c.refresh();+ return c.snapshot?.name.trim();+ }().timeout(_teamLockNameWait);+ } catch (_) {+ return null;+ }+ }++ static const _teamLockNameWait = Duration(seconds: 5);++ /// This computer's Harness Team account exists: the lock ends.+ Future<void> teamAccountMade() async {+ final account = _teamLockAccount;+ if (account == null || _teamLockTabs.isEmpty) return;+ _teamLockTabs.clear();+ notifyListeners();+ await _saveTeamLock(account);+ }++ /// The lock's one way out, where setup can never finish here: removes this+ /// computer from each Swarm it is held for. Null when that is done;+ /// otherwise why not, and the lock stays for the Swarms not done.+ Future<String?> removeLockedMachine() async {+ final here = _teamAccountHere();+ final account = currentUser?.id;+ if (here == null || account == null || _teamLockAccount != account) {+ return null;+ }+ for (final tabId in [..._teamLockTabs]) {+ // Already gone from it, being removed, or no longer this person's to+ // open: nothing to remove, and the lock lets it go.+ final holds = await _swarmHolds(tabId, here);+ if (holds != false) {+ try {+ final c = await superTabs.open(tabId);+ final result = await c.command({+ 'type': 'machine.remove',+ 'machineId': here,+ });+ if (result == null) {+ return c.operationError ?? 'Could not do that. Try again.';+ }+ } on SuperTabFailure catch (failure) {+ return failure.message;+ } catch (error) {+ appLog.info('super-tabs', 'machine not removed for the lock: $error');+ return 'Could not reach the Swarm. Try again.';+ }+ }+ _teamLockTabs.remove(tabId);+ notifyListeners();+ await _saveTeamLock(account);+ }+ return null;+ }+/// The start offer, once for each process of this Mac's daemon: Macs/// already in a Swarm meet no join or contribute moment, and one ask a/// launch went to whichever daemon answered first, one still starting or the@@ -5910,6 +6117,7 @@ class AppNotifier extends ChangeNotifier {// joined a Swarm before teammates' work went only to Team machines never// met the join or contribute moment.if (!machine.machine.isSharedMachine) {+ unawaited(_restoreTeamSetupLock());unawaited(_offerTeamAccountAtStart());}} else {diff --git a/desktop/lib/super_tabs/backlog.dart b/desktop/lib/super_tabs/backlog.dartnew file mode 100644index 000000000..1103d5a4e--- /dev/null+++ b/desktop/lib/super_tabs/backlog.dart@@ -0,0 +1,69 @@+import 'package:collection/collection.dart';++import 'controller.dart';+import 'linked_tasks.dart';+import 'model.dart';++/// The groups Manage ▸ Backlog lists a Swarm's tasks in, in this order (Scholes,+/// task #2355): where each task is on its way from asked to shipped.+enum SuperTabBacklogGroup {+ waitingForMachine('Waiting for a machine'),+ working('Working'),+ waitingOnSomeone('Waiting on someone'),+ inReview('In review'),+ readyToMerge('Ready to merge'),+ shipped('Shipped');++ const SuperTabBacklogGroup(this.label);+ final String label;+}++/// Which group [task] is listed in; null for a cancelled task, which is not+/// listed. A wait on a person is "Waiting on someone", as the sidebar's groups+/// read it (task_groups.dart, Huy); the task's own line says on whom.+SuperTabBacklogGroup? superTabBacklogGroupOf(SuperTabConversation task) {+ if (task.shippedAt != null) return SuperTabBacklogGroup.shipped;+ final assignment = task.assignment;+ final status = assignment?['status'];+ final liveness = task.liveness;+ final wait = liveness?['state'] == 'waiting' ? liveness!['why'] : null;+ if (status == 'cancelled') return null;+ if (status == 'done') return SuperTabBacklogGroup.readyToMerge;+ if (wait == 'person' || status == 'needs_human' || status == 'blocked') {+ return SuperTabBacklogGroup.waitingOnSomeone;+ }+ if (status == 'review' || wait == 'review' || wait == 'revision') {+ return SuperTabBacklogGroup.inReview;+ }+ // Orphaned (its agent removed or lost, never started, its start failed),+ // though the assignment may still read working: it needs a new agent.+ if (assignment == null ||+ assignment['agentId'] is! String ||+ status == 'stopped' ||+ status == 'lost' ||+ wait == 'queued' ||+ liveness?['state'] == 'orphaned') {+ return SuperTabBacklogGroup.waitingForMachine;+ }+ return SuperTabBacklogGroup.working;+}++/// Every task of the Swarm the controller holds, open and closed, across+/// projects, newest first: the groups the server lets this reader read, less+/// project chats, Buddy chats, steps and private chats, as the sidebar lists+/// a project's work (project_sidebar.dart superTabOpenWorkgroups).+List<SuperTabConversation> superTabBacklogTasks(SuperTabController c) {+ final snapshot = c.snapshot;+ if (snapshot == null) return const [];+ final tasks = [+ for (final project in snapshot.projects)+ for (final g in superTabListedWork(c.projectConversations(project.id)))+ if (g.id != project.leadConversationId &&+ !g.isBuddyChat &&+ !c.hiddenByBuddies(g))+ g,+ ];+ // A stable sort keeps the snapshot's order among unnumbered ones.+ mergeSort(tasks, compare: (a, b) => (b.number ?? 0).compareTo(a.number ?? 0));+ return tasks;+}diff --git a/desktop/lib/super_tabs/backlog_view.dart b/desktop/lib/super_tabs/backlog_view.dartnew file mode 100644index 000000000..aae20a882--- /dev/null+++ b/desktop/lib/super_tabs/backlog_view.dart@@ -0,0 +1,346 @@+import 'package:collection/collection.dart';+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_select_field.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/laid_out_list.dart';+import 'backlog.dart';+import 'controller.dart';+import 'machine_status.dart';+import 'model.dart';+import 'pull_request_facts.dart';+import 'task_status.dart';++/// Manage ▸ Backlog (Scholes, task #2355): every task of the Swarm the reader+/// can read, across projects, in the groups of its state, two lines a row. It+/// reads only what the controller already holds; the checks of open tasks'+/// pull requests come from [facts], watched only while it shows.+class SuperTabBacklogView extends StatefulWidget {+ const SuperTabBacklogView({+ super.key,+ required this.controller,+ required this.onOpenConversation,+ this.facts,+ this.now = DateTime.now,+ });++ final SuperTabController controller;+ final ValueChanged<String> onOpenConversation;+ final SuperTabPullRequestFacts? facts;+ final DateTime Function() now;++ @override+ State<SuperTabBacklogView> createState() => _SuperTabBacklogViewState();+}++class _SuperTabBacklogViewState extends State<SuperTabBacklogView> {+ String? _project;+ bool _mine = false;+ SuperTabBacklogGroup? _group;++ /// The pull requests watched for their checks: open tasks' alone.+ Set<String> _watched = const {};++ @override+ void dispose() {+ widget.facts?.unwatch(_watched);+ super.dispose();+ }++ void _watch(Iterable<SuperTabConversation> open) {+ final facts = widget.facts;+ if (facts == null) return;+ final next = {for (final task in open) ?_pullRequest(task)};+ if (const SetEquality<String>().equals(next, _watched)) return;+ facts+ ..watch(next.difference(_watched))+ ..unwatch(_watched.difference(next));+ _watched = next;+ }++ // Rebuilt when GitHub's answer lands, as the live cards are: Manage rebuilds+ // only on the controller (review of #2776).+ @override+ Widget build(BuildContext context) => switch (widget.facts) {+ final facts? => ListenableBuilder(+ listenable: facts,+ builder: (context, _) => _build(context),+ ),+ null => _build(context),+ };++ Widget _build(BuildContext context) {+ grid.AppTheme.watch(context);+ final c = widget.controller, snapshot = c.snapshot;+ final all = superTabBacklogTasks(c);+ final placed = [+ for (final task in all)+ if (superTabBacklogGroupOf(task) case final group?) (task, group),+ ];+ // Watched after the frame: a build changes nothing outside itself.+ final open = [+ for (final (task, group) in placed)+ if (group != SuperTabBacklogGroup.shipped) task,+ ];+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _watch(open);+ });+ final shown = [+ for (final (task, group) in placed)+ if ((_project == null || task.projectId == _project) &&+ (!_mine || task.requesterId == c.accountId) &&+ (_group == null || group == _group))+ (task, group),+ ];+ final entries = <Object>[+ for (final group in SuperTabBacklogGroup.values)+ if (shown.where((e) => e.$2 == group).toList() case final tasks+ when tasks.isNotEmpty) ...[+ (group, tasks.length),+ for (final (task, _) in tasks) task,+ ],+ ];+ final projects = snapshot?.projects ?? const <SuperTabProject>[];+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ ),+ child: Row(+ children: [+ AppSelectField<String?>(+ key: const ValueKey('super-backlog-project'),+ semanticLabel: 'Project',+ width: AppSelectField.fitWidth(+ context,+ labels: ['All projects', for (final p in projects) p.name],+ ),+ value: _project,+ options: [+ const SelectOption(value: null, label: 'All projects'),+ for (final project in projects)+ SelectOption(value: project.id, label: project.name),+ ],+ onChanged: (value) => setState(() => _project = value),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ DesktopPill(+ key: const ValueKey('super-backlog-mine'),+ label: 'Mine',+ selected: _mine,+ tooltip: 'Only the tasks you asked for',+ onPressed: () => setState(() => _mine = !_mine),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ AppSelectField<SuperTabBacklogGroup?>(+ key: const ValueKey('super-backlog-state'),+ semanticLabel: 'State',+ width: AppSelectField.fitWidth(+ context,+ labels: [+ 'All states',+ for (final group in SuperTabBacklogGroup.values)+ group.label,+ ],+ ),+ value: _group,+ options: [+ const SelectOption(value: null, label: 'All states'),+ for (final group in SuperTabBacklogGroup.values)+ SelectOption(value: group, label: group.label),+ ],+ onChanged: (value) => setState(() => _group = value),+ ),+ const Spacer(),+ Text(+ shown.length == 1 ? '1 task' : '${shown.length} tasks',+ style: DesktopChrome.metadata(color: DesktopChrome.muted),+ ),+ ],+ ),+ ),+ Expanded(+ child: entries.isEmpty+ ? Center(+ child: Text(+ _mine && all.isNotEmpty+ ? 'No tasks you asked for'+ : 'No tasks',+ style: DesktopChrome.control(color: DesktopChrome.muted),+ ),+ )+ : LaidOutListView.builder(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ ),+ itemCount: entries.length,+ itemBuilder: (context, i) => switch (entries[i]) {+ (final SuperTabBacklogGroup group, final int count) =>+ _Heading(group: group, count: count),+ final SuperTabConversation task => _Row(+ task: task,+ controller: c,+ facts: widget.facts,+ now: widget.now(),+ onOpen: () => widget.onOpenConversation(task.id),+ ),+ _ => const SizedBox.shrink(),+ },+ ),+ ),+ ],+ );+ }+}++/// The task's pull request the row shows: the newest one it names.+String? _pullRequest(SuperTabConversation task) =>+ task.cards.pullRequests.lastOrNull?.url ?? task.pullRequestUrls.lastOrNull;++class _Heading extends StatelessWidget {+ const _Heading({required this.group, required this.count});+ final SuperTabBacklogGroup group;+ final int count;++ @override+ Widget build(BuildContext context) => Padding(+ key: ValueKey('super-backlog-group-${group.name}'),+ padding: const EdgeInsets.only(+ top: grid.AppDesktop.groupGap,+ bottom: grid.AppDesktop.menuInset,+ ),+ child: Text(+ '${group.label} · $count',+ style: DesktopChrome.control(medium: true),+ ),+ );+}++/// One task: its number and title, project and who asked; then its agent and+/// machine, its pull request and checks, and what it waits on; how long since+/// it last changed at the right.+class _Row extends StatelessWidget {+ const _Row({+ required this.task,+ required this.controller,+ required this.facts,+ required this.now,+ required this.onOpen,+ });++ final SuperTabConversation task;+ final SuperTabController controller;+ final SuperTabPullRequestFacts? facts;+ final DateTime now;+ final VoidCallback onOpen;++ String? _personName(String id) => controller.snapshot?.people+ .where((p) => p.id == id)+ .firstOrNull+ ?.username;++ String get _pullRequestText {+ final url = _pullRequest(task);+ if (url == null) return '';+ final number = Uri.parse(url).pathSegments.elementAtOrNull(3) ?? '';+ final merged =+ task.cards.pullRequests.firstWhereOrNull((p) => p.url == url)?.merged ==+ true;+ final entry = facts?.of(url);+ final checks = merged+ ? 'merged'+ : entry == null+ ? ''+ : entry.finalState+ ? entry.state.toLowerCase()+ : entry.total > 0+ ? entry.checksLabel+ : '';+ return ['PR #$number', if (checks.isNotEmpty) checks].join(' ');+ }++ @override+ Widget build(BuildContext context) {+ final snapshot = controller.snapshot!;+ final assignment = task.assignment;+ final agentId = assignment?['agentId'];+ final agent = agentId is String ? snapshot.agent(agentId) : null;+ final execution = assignment?['execution'];+ final machineId = execution is Map && execution['machineId'] is String+ ? execution['machineId'] as String+ : agent?.machineId;+ final status = superTabTaskStatus(task, now, personName: _personName);+ final second = [+ if (agentId is! String)+ 'No agent yet'+ else ...[+ snapshot.agentName(agentId, fallback: 'Agent unavailable'),+ if (machineId != null) ?controller.sessionMachineName(machineId),+ ],+ if (_pullRequestText case final pr when pr.isNotEmpty) pr,+ if (status != null) status.reason,+ ].join(' · ');+ final first = [+ snapshot.projectById(task.projectId)?.name,+ if (task.requesterId case final id?) _personName(id),+ ].nonNulls.join(' · ');+ final changed = controller.groupChangedAt(task.id);+ final muted = DesktopChrome.metadata(color: DesktopChrome.muted);+ return InkWell(+ key: ValueKey('super-backlog-row-${task.id}'),+ onTap: onOpen,+ hoverColor: grid.AppSurface.hoverFill,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ vertical: grid.AppDesktop.menuInset,+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Flexible(+ child: Text(+ task.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(),+ ),+ ),+ if (first.isNotEmpty) ...[+ const SizedBox(width: grid.AppDesktop.controlGap),+ Text(first, maxLines: 1, style: muted),+ ],+ ],+ ),+ Text(+ second,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: muted,+ ),+ ],+ ),+ ),+ if (changed != null) ...[+ const SizedBox(width: grid.AppDesktop.controlGap),+ Text(superTabAgoShort(now.difference(changed)), style: muted),+ ],+ ],+ ),+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex f5b750296..c1760d779 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -2960,6 +2960,14 @@ class SuperTabController extends ChangeNotifier {return !_disposed && snapshot?.conversation(id) != null;}+ /// When group [groupId] last changed, a message included (parts.dart+ /// `groupChangedAt`); null for one this reader does not hold.+ DateTime? groupChangedAt(String groupId) =>+ switch (_parts?.groupChangedAt(groupId)) {+ final int at => DateTime.fromMillisecondsSinceEpoch(at),+ null => null,+ };+/// [projectId]'s conversations, open and closed, in the snapshot's order.List<SuperTabConversation> projectConversations(String projectId) =>_indexed()?.byProject[projectId] ?? const [];diff --git a/desktop/lib/super_tabs/manage_page.dart b/desktop/lib/super_tabs/manage_page.dartindex eba4e4235..59a1fef79 100644--- a/desktop/lib/super_tabs/manage_page.dart+++ b/desktop/lib/super_tabs/manage_page.dart@@ -17,7 +17,9 @@ import 'leaderboard/reader.dart';import 'message_row.dart' show SuperTabMessageRow;import 'local_models.dart';import 'machines.dart';+import 'backlog_view.dart';import 'model.dart';+import 'pull_request_facts.dart';import 'sharing.dart';import 'swarm_delete.dart';import 'swarm_switcher.dart' show PersonalSwarm;@@ -25,9 +27,9 @@ import 'swarm_switcher.dart' show PersonalSwarm;/// What Manage shows (docs/plans/2026-11-02-quiet-swarm-design.md, screens 10,/// 10b, 10c): what used to stand in the sidebar and the Swarm dropdown, one/// click away. Devices is the devices pane the view already holds.-enum SuperTabManageTab { machines, models, devices, swarm }+enum SuperTabManageTab { machines, models, devices, swarm, backlog }-/// Machines, Models, Devices, Swarm, under Manage's heading.+/// Machines, Models, Devices, Swarm, Backlog, under Manage's heading.class SuperTabManageTabs extends StatelessWidget {const SuperTabManageTabs({super.key,@@ -89,14 +91,16 @@ class SuperTabManageTabs extends StatelessWidget {tab(SuperTabManageTab.models, 'Models'),if (devices) tab(SuperTabManageTab.devices, 'Devices'),tab(SuperTabManageTab.swarm, 'Swarm'),+ tab(SuperTabManageTab.backlog, 'Backlog'),],),);}}-/// Manage's Machines, Models or Swarm. Each is built only while it shows, so-/// what it runs (the machines' clock) stops when it does not.+/// Manage's Machines, Models, Swarm or Backlog. Each is built only while it+/// shows, so what it runs (the machines' clock, the Backlog's pull request+/// watch) stops when it does not.class SuperTabManagePage extends StatelessWidget {const SuperTabManagePage({super.key,@@ -106,6 +110,8 @@ class SuperTabManagePage extends StatelessWidget {this.app,this.board,this.onOpenAgent,+ this.onOpenConversation,+ this.facts,this.readLocal,this.now = DateTime.now,});@@ -117,6 +123,10 @@ class SuperTabManagePage extends StatelessWidget {final ValueChanged<SuperTabConversation> onAddAgent;final ValueChanged<SuperTabAgent>? onOpenAgent;+ /// Opens a task's chat from the Backlog; [facts] gives its rows' checks.+ final bool Function(String id)? onOpenConversation;+ final SuperTabPullRequestFacts? facts;+/// Forwarded to [SuperTabMachines], for a test without a real machine.final Future<MachineResources?> Function(String machineId)? readLocal;final DateTime Function() now;@@ -154,6 +164,12 @@ class SuperTabManagePage extends StatelessWidget {controller: controller,app: app,),+ SuperTabManageTab.backlog => SuperTabBacklogView(+ controller: controller,+ facts: facts,+ now: now,+ onOpenConversation: (id) => onOpenConversation?.call(id),+ ),},),);diff --git a/desktop/lib/super_tabs/team_account_setup.dart b/desktop/lib/super_tabs/team_account_setup.dartindex c5fdbe555..f29714ffb 100644--- a/desktop/lib/super_tabs/team_account_setup.dart+++ b/desktop/lib/super_tabs/team_account_setup.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter/material.dart';import '../core/runtime_platform.dart';@@ -41,6 +43,14 @@ class _Words {required this.update,required this.cannot,required this.unreachable,+ required this.lead,+ required this.waiting,+ required this.rejected,+ required this.cancelled,+ required this.removeWhy,+ required this.removeOnly,+ required this.remove,+ required this.here,this.noPrompt,});@@ -57,6 +67,18 @@ class _Words {cannot: _computerCannot,unreachable: _computerUnreachable,noPrompt: 'Run harness team setup in a terminal on this computer.',+ lead: _computerLead,+ waiting:+ 'Your system is asking for your password. '+ 'Setup then takes a minute or two, and Harness opens when it is done.',+ rejected: 'Your system did not accept that password. Try again.',+ cancelled: 'The password window was closed before setup finished.',+ removeWhy:+ 'No administrator password for this computer? Remove it from the Swarm. '+ 'You can add it again from Machines.',+ removeOnly: _computerRemoveOnly,+ remove: _computerRemove,+ here: 'this computer',),'windows' => const _Words(title: 'Set up Harness Team on this computer',@@ -69,6 +91,18 @@ class _Words {update: _computerUpdate,cannot: _computerCannot,unreachable: _computerUnreachable,+ lead: _computerLead,+ waiting:+ 'Windows is asking for permission. '+ 'Setup then takes a minute or two, and Harness opens when it is done.',+ rejected: 'Windows did not give permission. Try again.',+ cancelled: 'The permission window was closed before setup finished.',+ removeWhy:+ 'No administrator permission on this computer? Remove it from the Swarm. '+ 'You can add it again from Machines.',+ removeOnly: _computerRemoveOnly,+ remove: _computerRemove,+ here: 'this computer',),_ => const _Words(title: 'Set up Harness Team on this Mac',@@ -88,21 +122,76 @@ class _Words {'or run harness team setup in Terminal.',cannot: 'Harness Team cannot be set up on this Mac right now.',unreachable: 'Could not reach Harness on this Mac. Try again.',+ lead:+ 'This Mac joined a Swarm, so it needs Harness Team before you go on.',+ waiting:+ 'macOS is asking for your password in a window titled “osascript”. '+ 'Setup then takes a minute or two, and Harness opens when it is done.',+ rejected: 'macOS did not accept that password. Try again.',+ cancelled: 'The password window was closed before setup finished.',+ removeWhy:+ 'No administrator password for this Mac? Remove it from the Swarm. '+ 'You can add it again from Machines.',+ removeOnly: 'To go on, remove this Mac from the Swarm. You can add it again from Machines.',+ remove: 'Remove this Mac from the Swarm',+ here: 'this Mac',),};+ static const _computerLead =+ 'This computer joined a Swarm, so it needs Harness Team before you go on.';+ static const _computerRemoveOnly =+ 'To go on, remove this computer from the Swarm. You can add it again from Machines.';+ static const _computerRemove = 'Remove this computer from the Swarm';+static const _computerAccount ='Teammates\' agents in your Swarms run on this computer in a separate ''account, Harness Team. They cannot read your files or use your GitHub login. ''They use this computer\'s Claude Code and Codex subscriptions, so nobody signs in again.';- static const _computerExists = 'Harness Team is already set up on this computer.';+ static const _computerExists =+ 'Harness Team is already set up on this computer.';static const _computerUpdate ='This computer\'s Harness is too old to set it up from here. Update Harness, ''or run harness team setup in a terminal.';- static const _computerCannot = 'Harness Team cannot be set up on this computer right now.';- static const _computerUnreachable = 'Could not reach Harness on this computer. Try again.';+ static const _computerCannot =+ 'Harness Team cannot be set up on this computer right now.';+ static const _computerUnreachable =+ 'Could not reach Harness on this computer. Try again.';++ final String title,+ account,+ prompt,+ started,+ exists,+ update,+ cannot,+ unreachable;- final String title, account, prompt, started, exists, update, cannot, unreachable;+ /// The lock's ([TeamAccountSetupLock]): why the app waits, setup under way,+ /// the password refused, the system's window closed, and the one way out.+ final String lead,+ waiting,+ rejected,+ cancelled,+ removeWhy,+ removeOnly,+ remove;++ /// "this Mac", or "this computer": what Remove takes out of the Swarms.+ final String here;++ /// What Remove asks before it removes anything (security review of #2779):+ /// it deletes this computer from each Swarm in [swarms], which it names.+ String confirmRemove(List<String> swarms) {+ final names = switch (swarms.length) {+ 0 => 'the Swarm',+ 1 => swarms.single,+ _ =>+ '${swarms.sublist(0, swarms.length - 1).join(', ')} and ${swarms.last}',+ };+ return 'Remove $here from $names? Its agents there stop, and teammates\' '+ 'work no longer runs on it. You can add it again from Machines.';+ }/// For the daemon's `no-prompt` (cli/src/team/autoSetup.ts): no desktop session to ask in, so the terminal is the/// way. Null where that never happens.@@ -220,3 +309,362 @@ class _TeamAccountSetupState extends State<_TeamAccountSetup> {);}}++/// Holds the whole app while this computer's Harness Team account must be set+/// up ([AppNotifier.teamSetupLocked]): from the moment it joins a Swarm, or is+/// added to one, until setup succeeds (Scholes, 2026-11-03). It sits above the+/// Navigator (app_shell.dart), so every route, dialog and menu is under it,+/// and nothing there takes a click, a key, focus or a screen reader. There is+/// no close. Where setup can never finish here (no administrator password, a+/// Harness too old, a system that cannot ask), the one way out is removing+/// this computer from the Swarm.+///+/// The password is asked only by the system's own prompt, through the same+/// daemon actions as Set up on the machine row.+///+/// Nothing in it may need an Overlay (no tooltips): there is none above the+/// Navigator.+class TeamAccountSetupLock extends StatefulWidget {+ const TeamAccountSetupLock({+ super.key,+ required this.app,+ required this.child,+ this.operatingSystem,+ });++ final AppNotifier app;+ final Widget child;++ /// Whose words, by [RuntimePlatform.operatingSystem] (this computer's when+ /// null).+ final String? operatingSystem;++ @override+ State<TeamAccountSetupLock> createState() => _TeamAccountSetupLockState();+}++enum _LockStep { intro, waiting, retry, cancelled, cannot }++/// How long the system's prompt may stay open (cli/src/team/admin.ts, 15+/// minutes), with a minute for the setup after it.+const _setupLimit = Duration(minutes: 16);+const _setupRead = Duration(seconds: 2);++/// macOS's "The administrator user name or password was incorrect. (-60005)",+/// as the daemon hands it back inside its detail.+final _refusedPassword = RegExp(+ r'-60005|incorrect|not accepted|wrong password',+ caseSensitive: false,+);++class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {+ late final _Words _words = _Words.of(+ widget.operatingSystem ?? RuntimePlatform.operatingSystem,+ );+ _LockStep _step = _LockStep.intro;+ String? _outcome, _removeError;+ bool _busy = false;++ /// Remove was pressed: the panel asks before anything is removed, naming+ /// these Swarms.+ bool _confirming = false;+ List<String> _confirmSwarms = const [];+ Timer? _read;+ DateTime? _since;++ @override+ void initState() {+ super.initState();+ widget.app.addListener(_changed);+ }++ @override+ void didUpdateWidget(TeamAccountSetupLock old) {+ super.didUpdateWidget(old);+ if (!identical(old.app, widget.app)) {+ old.app.removeListener(_changed);+ widget.app.addListener(_changed);+ }+ }++ @override+ void dispose() {+ widget.app.removeListener(_changed);+ _read?.cancel();+ super.dispose();+ }++ void _changed() {+ if (!mounted) return;+ setState(() {+ if (!widget.app.teamSetupLocked) _reset();+ });+ }++ void _reset() {+ _read?.cancel();+ _read = null;+ _step = _LockStep.intro;+ _outcome = _removeError = null;+ _busy = false;+ _confirming = false;+ }++ void _show(_LockStep step, String outcome) {+ if (!mounted) return;+ setState(() {+ _busy = false;+ _step = step;+ _outcome = outcome;+ });+ }++ Future<void> _start() async {+ setState(() {+ _busy = true;+ _removeError = null;+ });+ final words = _words;+ try {+ switch (await widget.app.setUpTeamAccount()) {+ case 'started' || 'running':+ _since = DateTime.now();+ _show(_LockStep.waiting, words.waiting);+ _scheduleRead();+ case 'exists':+ await widget.app.teamAccountMade();+ case 'update':+ _show(_LockStep.cannot, words.update);+ case 'no-prompt' when words.noPrompt != null:+ _show(_LockStep.cannot, words.noPrompt!);+ case _:+ _show(_LockStep.cannot, words.cannot);+ }+ } on SuperTabFailure catch (failure) {+ if (failure.code == 'NO_PROMPT') {+ _show(_LockStep.cannot, words.noPrompt ?? failure.message);+ } else {+ _show(_LockStep.retry, failure.message);+ }+ } catch (_) {+ _show(_LockStep.retry, words.unreachable);+ }+ }++ /// The setup runs in this computer's daemon after the system's prompt;+ /// nothing tells the app when it ends, so its status is read while the+ /// prompt can still be open, and never after.+ void _scheduleRead() {+ _read?.cancel();+ _read = Timer(_setupRead, () => unawaited(_readSetup()));+ }++ Future<void> _readSetup() async {+ _read = null;+ final setup = await widget.app.teamSetupStatus();+ if (!mounted || _step != _LockStep.waiting) return;+ switch (setup?.state) {+ case 'exists':+ await widget.app.teamAccountMade();+ return;+ case 'failed':+ final detail = setup?.detail?.trim();+ if (detail != null && _refusedPassword.hasMatch(detail)) {+ _show(_LockStep.retry, _words.rejected);+ } else {+ _show(+ _LockStep.retry,+ detail == null || detail.isEmpty+ ? 'Setup did not finish. Try again.'+ : 'Setup did not finish: ${_sentence(detail)}',+ );+ }+ return;+ case 'declined':+ _show(_LockStep.cancelled, _words.cancelled);+ return;+ }+ final since = _since;+ if (since != null && DateTime.now().difference(since) > _setupLimit) {+ _show(_LockStep.retry, 'Setup did not finish. Try again.');+ return;+ }+ _scheduleRead();+ }++ static String _sentence(String text) =>+ RegExp(r'[.!?]$').hasMatch(text) ? text : '$text.';++ Future<void> _askRemove() async {+ setState(() {+ _busy = true;+ _removeError = null;+ });+ final swarms = await widget.app.readTeamSetupLockSwarmNames();+ if (!mounted) return;+ setState(() {+ _busy = false;+ _confirming = true;+ _confirmSwarms = swarms;+ });+ }++ Future<void> _remove() async {+ setState(() {+ _busy = true;+ _removeError = null;+ });+ final why = await widget.app.removeLockedMachine();+ if (!mounted) return;+ setState(() {+ _busy = false;+ _confirming = false;+ _removeError = why;+ });+ }++ @override+ Widget build(BuildContext context) {+ final locked = widget.app.teamSetupLocked;+ // One tree shape locked or not, so the app below is never remounted.+ return Stack(+ fit: StackFit.expand,+ children: [+ // The barrier takes every click and hides the app from a screen+ // reader; keys follow focus, which nothing under it may hold.+ ExcludeFocus(excluding: locked, child: widget.child),+ if (locked) ...[+ ModalBarrier(dismissible: false, color: dialogVeilTintOf(context)),+ _panel(context),+ ],+ ],+ );+ }++ Widget _panel(BuildContext context) {+ final words = _words;+ final body = grid.AppType.body(height: 1.45);+ final muted = body.copyWith(color: Theme.of(context).hintColor);+ final outcome = _outcome;+ final retry = FilledButton(+ key: const Key('team-account-lock-retry'),+ autofocus: true,+ onPressed: _busy ? null : _start,+ child: const Text('Try again'),+ );+ // It deletes this computer from the Swarms: never focused, so no Enter+ // presses it, and it asks first (security review of #2779).+ final remove = TextButton(+ key: const Key('team-account-lock-remove'),+ onPressed: _busy ? null : () => unawaited(_askRemove()),+ child: Text(words.remove),+ );+ final confirming = [+ TextButton(+ key: const Key('team-account-lock-remove-back'),+ autofocus: true,+ onPressed: _busy ? null : () => setState(() => _confirming = false),+ child: const Text('Back'),+ ),+ FilledButton(+ key: const Key('team-account-lock-remove-confirm'),+ style: FilledButton.styleFrom(+ backgroundColor: Theme.of(context).colorScheme.error,+ foregroundColor: Theme.of(context).colorScheme.onError,+ ),+ onPressed: _busy ? null : _remove,+ child: const Text('Remove'),+ ),+ ];+ final removeError = _removeError;+ return Center(+ key: const Key('team-account-lock'),+ child: FocusScope(+ autofocus: true,+ child: AlertDialog(+ title: Text(words.title),+ content: SizedBox(+ width: 420,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (_step == _LockStep.intro) ...[+ Text(words.lead, style: body),+ const SizedBox(height: 12),+ Text(words.account, style: body),+ const SizedBox(height: 12),+ Text(words.prompt, style: body),+ const SizedBox(height: 12),+ Text(+ 'Your home folder becomes private to you. Your own agents work as before. '+ 'To remove the account later, run harness team remove.',+ style: muted,+ ),+ ] else ...[+ Row(+ children: [+ if (_step == _LockStep.waiting) ...[+ const SizedBox.square(+ dimension: 14,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ const SizedBox(width: 10),+ ],+ Expanded(+ child: Text(+ outcome ?? '',+ key: const Key('team-account-lock-outcome'),+ style: body,+ ),+ ),+ ],+ ),+ if (_confirming) ...[+ const SizedBox(height: 12),+ Text(+ words.confirmRemove(_confirmSwarms),+ key: const Key('team-account-lock-confirm'),+ style: body,+ ),+ ] else if (_step == _LockStep.cancelled) ...[+ const SizedBox(height: 12),+ Text(words.removeWhy, style: muted),+ ] else if (_step == _LockStep.cannot) ...[+ const SizedBox(height: 12),+ Text(words.removeOnly, style: muted),+ ],+ ],+ if (removeError != null) ...[+ const SizedBox(height: 12),+ Text(+ removeError,+ style: body.copyWith(+ color: Theme.of(context).colorScheme.error,+ ),+ ),+ ],+ ],+ ),+ ),+ actions: _confirming+ ? confirming+ : switch (_step) {+ _LockStep.intro => [+ FilledButton(+ key: const Key('team-account-lock-continue'),+ autofocus: true,+ onPressed: _busy ? null : _start,+ child: const Text('Continue'),+ ),+ ],+ _LockStep.waiting => const [],+ _LockStep.retry => [retry],+ _LockStep.cancelled => [remove, retry],+ _LockStep.cannot => [remove],+ },+ ),+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 6b9ea12b4..9c4fc6487 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -4477,6 +4477,8 @@ class _SuperTabViewState extends State<SuperTabView>widget.onOpenTerminal).call(agent);},+ onOpenConversation: _openConversation,+ facts: _facts,): const SizedBox.shrink(),],diff --git a/desktop/test/native_toolbar_sync_test.dart b/desktop/test/native_toolbar_sync_test.dartindex 29577dff5..fb3d0cc90 100644--- a/desktop/test/native_toolbar_sync_test.dart+++ b/desktop/test/native_toolbar_sync_test.dart@@ -104,6 +104,21 @@ class _SharesDaemon extends WsConn {}}+/// This computer's daemon wanting its Harness Team account set up.+class _TeamDaemon extends _SharesDaemon {+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type == 'super_tabs' && payload['action'] == 'teamSetupCheck') {+ return {'ok': true, 'state': 'wanted'};+ }+ return super.request(type, payload: payload, timeout: timeout);+ }+}+/// A roster as `shares` lists it: [owner]'s tab with [harnesses] harnesses,/// shared from [ownerMachine]. The owner's own roster names its desk tab/// ([tabId]); a member's desk tab is derived from [sharedTabId] ([_memberTab]).@@ -840,4 +855,64 @@ void main() {await tester.pumpWidget(const SizedBox());});});++ // Review of #2779: the menu bar, its key equivalents and the tab row reach+ // the workspace over the channel, not through Flutter's focus, so the lock's+ // barrier alone did not hold them.+ testWidgets(+ 'the Team account setup lock greys the menus and the tab row, and drops their actions',+ (tester) async {+ final app = _App(daemon: _TeamDaemon())+ ..teamAccountHereForTest = true+ ..currentUser = const CurrentUserProfile(+ id: 'owner',+ email: '[email protected]',+ );+ addTearDown(app.dispose);+ final first = app.activeSwarmId;+ app.newSwarm(name: 'Other');+ final other = app.activeSwarmId;+ expect(other, isNot(first));+ await mount(tester, app, nativeTabs: true);+ await tester.pumpAndSettle();+ expect(updates().last['enabled'], isTrue);++ await app.offerTeamAccount('join', tabId: 'tab-1');+ await tester.pumpAndSettle();+ expect(app.teamSetupLocked, isTrue);+ expect(updates().last['enabled'], isFalse);+ expect(updates().last['stripEnabled'], isFalse);++ Future<void> native(String method, Map args) =>+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(+ 'harness/swarm_tabs',+ const StandardMethodCodec().encodeMethodCall(+ MethodCall(method, args),+ ),+ (_) {},+ );+ // A row click or key equivalent that arrives anyway does nothing.+ unawaited(native('select', {'id': first}));+ await tester.pumpAndSettle();+ unawaited(+ native('rowAction', {+ 'method': 'select',+ 'arguments': {'id': first},+ }),+ );+ await tester.pumpAndSettle();+ unawaited(native('keymapCommand', {'command': 'tab.previous'}));+ await tester.pumpAndSettle();+ expect(app.activeSwarmId, other);++ await app.teamAccountMade();+ await tester.pumpAndSettle();+ expect(updates().last['enabled'], isTrue);+ expect(updates().last['stripEnabled'], isTrue);+ unawaited(native('select', {'id': first}));+ await tester.pumpAndSettle();+ expect(app.activeSwarmId, first);+ await tester.pumpWidget(const SizedBox());+ },+ );}diff --git a/desktop/test/super_tab_backlog_shots_test.dart b/desktop/test/super_tab_backlog_shots_test.dartnew file mode 100644index 000000000..afc3d02b4--- /dev/null+++ b/desktop/test/super_tab_backlog_shots_test.dart@@ -0,0 +1,222 @@+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/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/backlog_view.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_BACKLOG_SHOTS'];++/// Set to measure how long the Backlog takes to build with 300 tasks.+final bench = Platform.environment['SUPER_TAB_BACKLOG_BENCH'] != null;++/// Manage ▸ Backlog as the PR shows it (Scholes, task #2355): a Swarm with a+/// task in every group, in both appearances, all of it, Mine, and one project.+void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ /// [projects] projects, [perProject] tasks in each, cycling through the+ /// states; Scholes asked for every third.+ ConversationServer swarm({int projects = 2, int perProject = 4}) {+ final server = ConversationServer();+ const names = ['openharness', 'lampos', 'website', 'firmware'];+ server.state['projects'] = [+ for (var p = 0; p < projects; p++)+ projectFixture(+ 'p$p',+ p < names.length ? names[p] : 'project-$p',+ 'chat-$p',+ ),+ ];+ (server.state['people'] as List).addAll([+ {+ 'id': 'scholes',+ 'email': '[email protected]',+ 'username': 'scholes',+ 'role': 'collaborator',+ },+ {+ 'id': 'huy',+ 'email': '[email protected]',+ 'username': 'huy',+ 'role': 'collaborator',+ },+ ]);+ server.state['agents'] = [+ for (final (id, name, machine) in const [+ ('thorne', 'Thorne', 'pro9'),+ ('lyra', 'Lyra', 'pro9'),+ ('quill', 'Quill', 'studio'),+ ])+ {+ 'id': id,+ 'name': name,+ 'displayName': name,+ 'machineId': machine,+ 'harnessId': 'h-$id',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'claude'},+ },+ ];+ server.state['machines'] = [+ {'machineId': 'pro9', 'name': 'MacBook Pro-9'},+ {'machineId': 'studio', 'name': 'Mac Studio'},+ ];+ const titles = [+ 'New session starts on the last project',+ 'Sidebar task groups',+ 'Machine names in every row',+ 'Thread reply bar',+ 'Status menu fixture',+ 'GitHub setup line clears in seconds',+ ];+ final now = DateTime(2026, 11, 3, 17).millisecondsSinceEpoch;+ final conversations = server.state['conversations'] as List;+ conversations.removeWhere((g) => (g as Map)['id'] == 'offline');+ var number = 2300;+ for (var p = 0; p < projects; p++) {+ conversations.add({+ ...conversationFixture('chat-$p', 'chat'),+ 'projectId': 'p$p',+ });+ for (var i = 0; i < perProject; i++) {+ final state = (number - 2300) % 6;+ final agent = const ['thorne', 'lyra', 'quill'][number % 3];+ conversations.add(<String, dynamic>{+ ...conversationFixture('t$number', titles[state]),+ 'projectId': 'p$p',+ 'number': number,+ 'requesterId': const ['scholes', 'huy', 'owner'][number % 3],+ 'agentIds': [if (state > 0) agent],+ if (state > 0)+ 'assignment': {+ 'id': 'a$number',+ 'agentId': agent,+ 'status': const [+ '',+ 'working',+ 'working',+ 'review',+ 'done',+ 'done',+ ][state],+ 'progressAt': now,+ },+ if (state == 2)+ 'liveness': {+ 'state': 'waiting',+ 'why': 'person',+ 'personId': 'scholes',+ 'since': now,+ },+ if (state == 5) 'shippedAt': now,+ if (state > 0)+ 'pullRequestUrls': [+ 'https://github.com/autonomous-ai/openharness/pull/${number + 400}',+ ],+ });+ number++;+ }+ }+ return server;+ }++ Future<void> show(+ WidgetTester tester,+ ConversationServer server, {+ Brightness brightness = Brightness.light,+ GlobalKey? picture,+ }) async {+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(900, 640));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => picture == null+ ? child!+ : RepaintBoundary(key: picture, child: child),+ home: Scaffold(+ body: ListenableBuilder(+ listenable: c,+ builder: (context, _) => SuperTabBacklogView(+ controller: c,+ onOpenConversation: (_) {},+ now: () => (c.groupChangedAt('t2301') ?? DateTime(2026)).add(+ const Duration(minutes: 7),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ for (final brightness in Brightness.values) {+ for (final scene in ['all', 'mine', 'project']) {+ testWidgets('screenshots for review ($scene, ${brightness.name})', (+ tester,+ ) async {+ final picture = GlobalKey();+ await show(+ tester,+ swarm(perProject: 3),+ brightness: brightness,+ picture: picture,+ );+ if (scene == 'mine') {+ await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));+ await tester.pumpAndSettle();+ } else if (scene == 'project') {+ await tester.tap(find.byKey(const ValueKey('super-backlog-project')));+ await tester.pumpAndSettle();+ await tester.tap(find.text('lampos').last);+ await tester.pumpAndSettle();+ }+ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 2);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/backlog-$scene-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }, skip: shots == null);+ }+ }++ testWidgets('300 tasks across 30 projects: build and rebuild times', (+ tester,+ ) async {+ final server = swarm(projects: 30, perProject: 10);+ final first = Stopwatch()..start();+ await show(tester, server);+ first.stop();+ final rebuild = Stopwatch()..start();+ await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));+ await tester.pump();+ rebuild.stop();+ // ignore: avoid_print+ print(+ 'Backlog, 300 tasks: first frame ${first.elapsedMilliseconds} ms '+ '(controller read included), filter rebuild '+ '${rebuild.elapsedMilliseconds} ms (headless debug VM)',+ );+ }, skip: !bench);+}diff --git a/desktop/test/super_tab_backlog_test.dart b/desktop/test/super_tab_backlog_test.dartnew file mode 100644index 000000000..ad83822b2--- /dev/null+++ b/desktop/test/super_tab_backlog_test.dart@@ -0,0 +1,568 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/backlog.dart';+import 'package:harness/super_tabs/backlog_view.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/pull_request_facts.dart';++import 'support/super_tab_fixture.dart';++/// Manage ▸ Backlog (Scholes, task #2355): every task of the Swarm the reader+/// can read, across projects, in the groups of its state.+void main() {+ const now = 1793700000000;++ SuperTabConversation task({+ Map<String, dynamic>? assignment,+ Map<String, dynamic>? liveness,+ int? shippedAt,+ }) => SuperTabConversation.fromJson({+ ...conversationFixture('work', 'A task'),+ 'number': 7,+ 'assignment': ?assignment,+ 'liveness': ?liveness,+ 'shippedAt': ?shippedAt,+ });++ Map<String, dynamic> working(String status) => {+ 'id': 'a1',+ 'agentId': 'kestrel',+ 'status': status,+ };++ group('each state lands in its group', () {+ for (final (name, built, expected) in [+ ('no assignment', task(), SuperTabBacklogGroup.waitingForMachine),+ (+ 'queued for a machine',+ task(+ assignment: working('planned'),+ liveness: {'state': 'waiting', 'why': 'queued', 'since': now},+ ),+ SuperTabBacklogGroup.waitingForMachine,+ ),+ (+ 'its agent lost',+ task(assignment: working('lost')),+ SuperTabBacklogGroup.waitingForMachine,+ ),+ (+ 'stopped',+ task(assignment: working('stopped')),+ SuperTabBacklogGroup.waitingForMachine,+ ),+ // Review of #2776: the server marks these orphaned while the assignment+ // still reads working with an agent; each needs a new agent.+ for (final why in ['removed', 'unstarted', 'start-failed', 'lost'])+ (+ 'orphaned: $why',+ task(+ assignment: working('working'),+ liveness: {'state': 'orphaned', 'why': why, 'since': now},+ ),+ SuperTabBacklogGroup.waitingForMachine,+ ),+ (+ 'planned with an agent',+ task(assignment: working('planned')),+ SuperTabBacklogGroup.working,+ ),+ (+ 'working',+ task(assignment: working('working')),+ SuperTabBacklogGroup.working,+ ),+ (+ 'starting',+ task(+ assignment: working('working'),+ liveness: {'state': 'waiting', 'why': 'starting', 'since': now},+ ),+ SuperTabBacklogGroup.working,+ ),+ (+ 'quiet',+ task(+ assignment: working('working'),+ liveness: {'state': 'quiet', 'since': now},+ ),+ SuperTabBacklogGroup.working,+ ),+ (+ 'waiting on a person',+ task(+ assignment: working('working'),+ liveness: {+ 'state': 'waiting',+ 'why': 'person',+ 'personId': 'scholes',+ 'since': now,+ },+ ),+ SuperTabBacklogGroup.waitingOnSomeone,+ ),+ (+ 'needs a person',+ task(assignment: working('needs_human')),+ SuperTabBacklogGroup.waitingOnSomeone,+ ),+ (+ 'stuck',+ task(assignment: working('blocked')),+ SuperTabBacklogGroup.waitingOnSomeone,+ ),+ (+ 'in review',+ task(assignment: working('review')),+ SuperTabBacklogGroup.inReview,+ ),+ (+ 'fixing review findings',+ task(+ assignment: working('working'),+ liveness: {'state': 'waiting', 'why': 'revision', 'since': now},+ ),+ SuperTabBacklogGroup.inReview,+ ),+ (+ 'done, not merged',+ task(assignment: working('done')),+ SuperTabBacklogGroup.readyToMerge,+ ),+ (+ 'shipped',+ task(assignment: working('done'), shippedAt: now),+ SuperTabBacklogGroup.shipped,+ ),+ ('cancelled', task(assignment: working('cancelled')), null),+ ]) {+ test(name, () => expect(superTabBacklogGroupOf(built), expected));+ }+ });++ test('the groups read in order, as the mockup Scholes accepted', () {+ expect(SuperTabBacklogGroup.values.map((g) => g.label), [+ 'Waiting for a machine',+ 'Working',+ 'Waiting on someone',+ 'In review',+ 'Ready to merge',+ 'Shipped',+ ]);+ });++ test('lists every task across projects, newest first, and no project chat, '+ 'Buddy chat, step or private chat', () async {+ final server = ConversationServer();+ server.state['projects'] = [+ projectFixture('lead', 'web-project', 'lead'),+ projectFixture('api', 'api', 'api-chat'),+ ];+ final conversations = server.state['conversations'] as List;+ (conversations[1] as Map)+ ..['projectId'] = 'lead'+ ..['number'] = 3;+ conversations.addAll(<Map<String, dynamic>>[+ {...conversationFixture('api-chat', 'api'), 'projectId': 'api'},+ {+ ...conversationFixture('api-task', 'Rate limits'),+ 'projectId': 'api',+ 'number': 9,+ },+ {+ ...conversationFixture('closed-task', 'Old fix'),+ 'projectId': 'lead',+ 'number': 1,+ 'shippedAt': now,+ },+ {+ ...conversationFixture('review-step', 'Review: Rate limits'),+ 'projectId': 'api',+ 'number': 10,+ 'reviewOf': 'api-task',+ },+ {+ ...conversationFixture('buddy', 'Wren'),+ 'projectId': 'lead',+ 'kind': 'buddy',+ 'buddyOwnerId': 'owner',+ },+ {+ ...conversationFixture('private', 'Just us'),+ 'projectId': 'lead',+ 'audience': {+ 'people': [+ {'id': 'owner'},+ ],+ },+ },+ ]);+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ expect(superTabBacklogTasks(c).map((t) => t.id), [+ 'api-task',+ 'offline',+ 'closed-task',+ ]);+ });++ group('the Backlog view', () {+ final at = DateTime.fromMillisecondsSinceEpoch(now);++ /// A Swarm with two projects and a task in each group, Kestrel working on+ /// Mac Studio; Pilot asked for #12, the reader (owner) for the rest.+ ConversationServer swarm() {+ final server = ConversationServer();+ server.state['projects'] = [+ projectFixture('lead', 'web-project', 'lead'),+ projectFixture('api', 'api', 'api-chat'),+ ];+ (server.state['people'] as List).add({+ 'id': 'pilot',+ 'email': '[email protected]',+ 'username': 'pilot',+ 'role': 'collaborator',+ });+ server.state['agents'] = [+ {+ 'id': 'kestrel',+ 'name': 'Builder',+ 'displayName': 'Kestrel',+ 'machineId': 'studio',+ 'harnessId': 'h1',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'claude'},+ },+ ];+ server.state['machines'] = [+ {'machineId': 'studio', 'name': 'Mac Studio'},+ ];+ final conversations = server.state['conversations'] as List;+ conversations.removeWhere((g) => (g as Map)['id'] == 'offline');+ Map<String, dynamic> work(+ String id,+ int number,+ String title, {+ String project = 'lead',+ String requester = 'owner',+ String? status,+ Map<String, dynamic>? liveness,+ int? shippedAt,+ String? pr,+ }) => {+ ...conversationFixture(id, title),+ 'projectId': project,+ 'number': number,+ 'requesterId': requester,+ 'agentIds': [if (status != null) 'kestrel'],+ if (status != null)+ 'assignment': {+ 'id': 'a-$id',+ 'agentId': 'kestrel',+ 'status': status,+ 'progressAt': now,+ 'execution': {'machineId': 'studio', 'harnessId': 'h1'},+ },+ 'liveness': ?liveness,+ 'shippedAt': ?shippedAt,+ if (pr != null) 'pullRequestUrls': [pr],+ };+ conversations.addAll(<Map<String, dynamic>>[+ {...conversationFixture('api-chat', 'api'), 'projectId': 'api'},+ work('queued', 10, 'New session starts on last project'),+ work(+ 'working',+ 11,+ 'Sidebar task groups',+ status: 'working',+ pr: 'https://github.com/acme/app/pull/2733',+ ),+ work(+ 'asking',+ 12,+ 'Machine names',+ project: 'api',+ requester: 'pilot',+ status: 'working',+ liveness: {+ 'state': 'waiting',+ 'why': 'person',+ 'personId': 'pilot',+ 'since': now,+ },+ ),+ work('review', 13, 'Thread reply bar', status: 'review'),+ work('done', 14, 'Status menu fixture', status: 'done'),+ work(+ 'shipped',+ 15,+ 'GitHub line',+ status: 'done',+ shippedAt: now,+ pr: 'https://github.com/acme/app/pull/2713',+ ),+ {+ ...work('private', 16, 'Just us'),+ 'audience': {+ 'people': [+ {'id': 'owner'},+ ],+ },+ },+ ]);+ return server;+ }++ final opened = <String>[];+ late SuperTabController shown;++ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server, {+ SuperTabPullRequestFacts? facts,+ }) async {+ opened.clear();+ final c = shown = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ await tester.binding.setSurfaceSize(const Size(1100, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: ListenableBuilder(+ listenable: c,+ builder: (context, _) => SuperTabBacklogView(+ controller: c,+ facts: facts,+ onOpenConversation: opened.add,+ // Five minutes after #11 last changed (the fixture's own+ // clock), for its row's age.+ now: () => (c.groupChangedAt('working') ?? at).add(+ const Duration(minutes: 5),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return c;+ }++ Finder row(String id) => find.byKey(ValueKey('super-backlog-row-$id'));+ Finder header(SuperTabBacklogGroup g) =>+ find.byKey(ValueKey('super-backlog-group-${g.name}'));+ List<String> listed(WidgetTester tester) => [+ for (final e+ in find+ .byWidgetPredicate(+ (w) =>+ w.key is ValueKey<String> &&+ (w.key! as ValueKey<String>).value.startsWith(+ 'super-backlog-row-',+ ),+ )+ .evaluate())+ (e.widget.key! as ValueKey<String>).value.substring(+ 'super-backlog-row-'.length,+ ),+ ];+ String rowText(WidgetTester tester, String id) => [+ for (final t in tester.widgetList<Text>(+ find.descendant(of: row(id), matching: find.byType(Text)),+ ))+ t.data ?? t.textSpan?.toPlainText() ?? '',+ ].join(' | ');++ testWidgets('groups in order with their counts, each row its two lines', (+ tester,+ ) async {+ await show(tester, swarm());+ for (final (group, count) in [+ (SuperTabBacklogGroup.waitingForMachine, 1),+ (SuperTabBacklogGroup.working, 1),+ (SuperTabBacklogGroup.waitingOnSomeone, 1),+ (SuperTabBacklogGroup.inReview, 1),+ (SuperTabBacklogGroup.readyToMerge, 1),+ (SuperTabBacklogGroup.shipped, 1),+ ]) {+ expect(+ find.descendant(+ of: header(group),+ matching: find.text('${group.label} · $count'),+ ),+ findsOneWidget,+ reason: group.label,+ );+ }+ // The groups' order, top to bottom.+ final tops = [+ for (final g in SuperTabBacklogGroup.values)+ tester.getTopLeft(header(g)).dy,+ ];+ expect(tops, [...tops]..sort());+ expect(listed(tester), [+ 'queued',+ 'working',+ 'asking',+ 'review',+ 'done',+ 'shipped',+ ]);+ expect(find.text('6 tasks'), findsOneWidget);+ // Line one: number and title, project and who asked; line two: agent,+ // machine, pull request, what it waits on; then how long ago.+ final working = rowText(tester, 'working');+ expect(working, contains('#11 Sidebar task groups'));+ expect(working, contains('web-project · owner'));+ expect(working, contains('Kestrel · Mac Studio · PR #2733'));+ expect(working, contains('5m'));+ expect(rowText(tester, 'asking'), contains('api · pilot'));+ expect(rowText(tester, 'asking'), contains('Waiting on pilot'));+ expect(rowText(tester, 'queued'), contains('No agent yet'));+ expect(rowText(tester, 'shipped'), contains('PR #2713'));+ });++ testWidgets('a task the reader cannot read is absent, even when a server '+ 'sends it', (tester) async {+ final server = swarm()..parts.leaksHiddenGroups = true;+ (server.state['conversations'] as List).add({+ ...conversationFixture('secret', 'Pilot only'),+ 'projectId': 'lead',+ 'number': 17,+ 'audience': {+ 'people': [+ {'id': 'pilot'},+ ],+ },+ });+ await show(tester, server);+ expect(shown.snapshot!.conversation('secret'), isNotNull);+ expect(row('secret'), findsNothing);+ expect(row('private'), findsNothing);+ expect(listed(tester), hasLength(6));+ });++ testWidgets('Mine shows only the tasks the reader asked for', (+ tester,+ ) async {+ await show(tester, swarm());+ await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));+ await tester.pumpAndSettle();+ expect(listed(tester), isNot(contains('asking')));+ expect(listed(tester), hasLength(5));+ expect(find.text('5 tasks'), findsOneWidget);+ });++ testWidgets('the project and state filters narrow the list and the count', (+ tester,+ ) async {+ await show(tester, swarm());+ await tester.tap(find.byKey(const ValueKey('super-backlog-project')));+ await tester.pumpAndSettle();+ await tester.tap(find.text('api').last);+ await tester.pumpAndSettle();+ expect(listed(tester), ['asking']);+ expect(find.text('1 task'), findsOneWidget);++ await tester.tap(find.byKey(const ValueKey('super-backlog-project')));+ await tester.pumpAndSettle();+ await tester.tap(find.text('All projects').last);+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-backlog-state')));+ await tester.pumpAndSettle();+ await tester.tap(find.text('In review').last);+ await tester.pumpAndSettle();+ expect(listed(tester), ['review']);+ expect(header(SuperTabBacklogGroup.working), findsNothing);+ });++ // Review of #2776: GitHub's answer lands after the first frame, in a quiet+ // Swarm where nothing else rebuilds the tab.+ testWidgets('a row shows its pull request\'s checks once GitHub answers', (+ tester,+ ) async {+ final answer = Completer<Map<String, dynamic>>();+ final facts = SuperTabPullRequestFacts((_) => answer.future);+ addTearDown(facts.dispose);+ await show(tester, swarm(), facts: facts);+ expect(rowText(tester, 'working'), isNot(contains('checks passed')));+ answer.complete({+ 'account': 'ada',+ 'rows': [+ {+ 'url': 'https://github.com/acme/app/pull/2733',+ 'status': 'found',+ 'title': 'Sidebar task groups',+ 'state': 'Open',+ 'checks': {'passed': 12, 'failed': 0, 'pending': 0, 'total': 12},+ },+ ],+ });+ await tester.pump();+ await tester.pump();+ expect(rowText(tester, 'working'), contains('PR #2733 12 checks passed'));+ });++ testWidgets('clicking a row opens its chat', (tester) async {+ await show(tester, swarm());+ await tester.tap(row('review'));+ await tester.pump();+ expect(opened, ['review']);+ });++ testWidgets('a task that moves while it shows moves to its new group, and '+ 'the filters keep their values', (tester) async {+ final server = swarm();+ await show(tester, server);+ await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));+ await tester.pumpAndSettle();+ ((server.state['conversations'] as List).firstWhere(+ (g) => (g as Map)['id'] == 'working',+ ) as Map)['assignment']['status'] = 'review';+ server.revision++;+ await shown.refresh();+ await tester.pumpAndSettle();+ final review = tester.getTopLeft(header(SuperTabBacklogGroup.inReview));+ expect(tester.getTopLeft(row('working')).dy, greaterThan(review.dy));+ expect(find.text('5 tasks'), findsOneWidget);+ });++ testWidgets('no tasks, and none asked for by the reader, each say so', (+ tester,+ ) async {+ final server = ConversationServer();+ (server.state['conversations'] as List).removeWhere(+ (g) => (g as Map)['id'] == 'offline',+ );+ await show(tester, server);+ expect(find.text('No tasks'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ final other = swarm();+ for (final g in (other.state['conversations'] as List)) {+ (g as Map)['requesterId'] = 'pilot';+ }+ await show(tester, other);+ await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));+ await tester.pumpAndSettle();+ expect(find.text('No tasks you asked for'), findsOneWidget);+ expect(find.text('0 tasks'), findsOneWidget);+ });++ testWidgets('a shipped task whose agent was removed still shows', (+ tester,+ ) async {+ final server = swarm();+ server.state['agents'] = <dynamic>[];+ await show(tester, server);+ expect(rowText(tester, 'shipped'), contains('Agent unavailable'));+ });+ });+}diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dartindex 32dcc01b8..8b0b15088 100644--- a/desktop/test/super_tab_launch_test.dart+++ b/desktop/test/super_tab_launch_test.dart@@ -68,6 +68,13 @@ class SuperTabFixtureConnection extends WsConn {/// What this Mac's daemon remembers of its Harness Team account setup/// (`teamSetupStatus`); null answers as a daemon too old to say.Map<String, dynamic>? teamSetup;++ /// What this Mac's daemon answers whether its Harness Team account is wanted+ /// (`teamSetupCheck`); null answers as a daemon too old to say.+ Map<String, dynamic>? teamCheck;++ /// What starting the account's setup answers (`teamSetup`, `manual`).+ Map<String, dynamic> teamRun = {'state': 'started'};bool loseCreate = false, loseJoin = false;bool failNative = false;WsRequestFailure? backendFailure;@@ -191,6 +198,11 @@ class SuperTabFixtureConnection extends WsConn {if (teamSetup case final setup?) return {'ok': true, ...setup};throw const SuperTabFailure('INVALID_REQUEST', 'Unknown action.');}+ if (payload['action'] == 'teamSetup') return {'ok': true, ...teamRun};+ if (payload['action'] == 'teamSetupCheck') {+ if (teamCheck case final check?) return {'ok': true, ...check};+ throw const SuperTabFailure('INVALID_REQUEST', 'Unknown action.');+ }if (payload['action'] == 'prepareContribution') {if (prepared.add(payload['operationId']) || keepPreparing) {return {'ok': true, 'state': 'preparing'};diff --git a/desktop/test/super_tab_manage_page_test.dart b/desktop/test/super_tab_manage_page_test.dartindex 3597b839b..7d43cf637 100644--- a/desktop/test/super_tab_manage_page_test.dart+++ b/desktop/test/super_tab_manage_page_test.dart@@ -82,11 +82,17 @@ void main() {return (c: c, server: server);}- testWidgets('its four tabs, Devices only where this build has them', (+ testWidgets('its five tabs, Devices only where this build has them', (tester,) async {await show(tester);- for (final label in const ['Machines', 'Models', 'Devices', 'Swarm']) {+ for (final label in const [+ 'Machines',+ 'Models',+ 'Devices',+ 'Swarm',+ 'Backlog',+ ]) {expect(find.text(label), findsOneWidget, reason: label);}await tester.tap(find.text('Swarm'));diff --git a/desktop/test/team_account_lock_test.dart b/desktop/test/team_account_lock_test.dartnew file mode 100644index 000000000..094a45161--- /dev/null+++ b/desktop/test/team_account_lock_test.dart@@ -0,0 +1,883 @@+import 'dart:io';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_riverpod/flutter_riverpod.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/app_shell.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/auth/cli_login.dart';+import 'package:harness/core/config.dart';++import 'package:harness/core/models.dart';+import 'package:harness/settings/settings_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/machines.dart';+import 'package:harness/super_tabs/team_account_setup.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;+import 'support/capture.dart';+import 'support/rename_connection.dart';+import 'swarm_state_test.dart' show createApp;++/// This Mac's daemon for the Harness Team account's actions; no socket is+/// opened, and nothing is set up or signed out.+class _Daemon extends RenameConnection {+ final asked = <String>[];++ /// `teamSetupCheck`: whether the account is wanted here.+ Map<String, dynamic> check = {'ok': true, 'state': 'wanted'};++ /// `teamSetup` (`manual`): what starting it answers.+ Map<String, dynamic> run = {'ok': true, 'state': 'started'};++ /// `teamSetupStatus`, in turn; the last one repeats.+ final statuses = <Map<String, dynamic>>[+ {'ok': true, 'state': 'running'},+ ];++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ final action = '${payload['action']}';+ if (type == 'super_tabs' && action.startsWith('teamSetup')) {+ asked.add(action);+ return switch (action) {+ 'teamSetupCheck' => check,+ 'teamSetup' => run,+ 'teamSetupStatus' =>+ statuses.length > 1 ? statuses.removeAt(0) : statuses.single,+ _ => {'ok': true},+ };+ }+ return super.request(type, payload: payload, timeout: timeout);+ }+}++/// Never the real CLI: nothing here may sign this Mac out.+class _FakeCli extends CliLogin {+ @override+ Future<void> logout() async {}++ @override+ Future<CliAuthStatus> checkStatus() async => CliAuthStatus(loggedIn: true);+}++/// Set to a folder to write the PR's pictures there.+final shots = Platform.environment['TEAM_ACCOUNT_LOCK_SHOTS'];++const _wrongPassword =+ 'The Harness Team account was not finished: The administrator user name or '+ 'password was incorrect. (-60005). Run `harness team setup` again; it repairs what is there.';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ setUpAll(() => loadCaptureFonts(shots));+ late _Daemon daemon;+ late AppNotifier app;++ setUp(() {+ daemon = _Daemon();+ app = createApp(connectionForTest: (_) => daemon, connected: true);+ app.currentUser = const CurrentUserProfile(+ id: 'owner',+ email: '[email protected]',+ );+ app.machineStates['m']!.localOnly = true;+ app.teamAccountHereForTest = true;+ });+ tearDown(() => app.dispose());++ final navigator = GlobalKey<NavigatorState>();+ var taps = 0, shortcuts = 0;+ late FocusNode behind;++ /// The app's window as app_shell.dart builds it: the lock above the+ /// Navigator, so it covers every route and dialog too.+ Future<void> window(WidgetTester tester, AppNotifier app) async {+ taps = 0;+ shortcuts = 0;+ behind = FocusNode(debugLabel: 'behind');+ addTearDown(behind.dispose);+ await tester.pumpWidget(+ MaterialApp(+ navigatorKey: navigator,+ builder: (context, child) => TeamAccountSetupLock(+ app: app,+ operatingSystem: 'macos',+ child: child!,+ ),+ home: Scaffold(+ body: CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.keyK, meta: true): () =>+ shortcuts++,+ },+ child: Column(+ children: [+ TextButton(+ key: const Key('behind-button'),+ focusNode: behind,+ autofocus: true,+ onPressed: () => taps++,+ child: const Text('Behind'),+ ),+ const TextField(key: Key('behind-field')),+ ],+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ }++ Future<void> lock(WidgetTester tester) async {+ await app.offerTeamAccount('join', tabId: 'tab-1');+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsOneWidget);+ }++ /// Whether the focused widget sits under [finder].+ bool focusedIn(Finder finder) {+ final focused = FocusManager.instance.primaryFocus?.context;+ if (focused == null) return false;+ return finder.evaluate().any(+ (element) =>+ element == focused ||+ (focused as Element).debugGetDiagnosticChain().contains(element),+ );+ }++ /// Every label in the semantics tree a screen reader walks.+ List<String> spoken(WidgetTester tester) {+ final labels = <String>[];+ void walk(SemanticsNode node) {+ if (node.label.isNotEmpty) labels.add(node.label);+ node.visitChildren((child) {+ walk(child);+ return true;+ });+ }++ final root =+ tester.binding.rootPipelineOwner.semanticsOwner?.rootSemanticsNode;+ if (root != null) walk(root);+ for (final view in tester.binding.renderViews) {+ final node = view.owner?.semanticsOwner?.rootSemanticsNode;+ if (node != null) walk(node);+ }+ return labels;+ }++ String outcome(WidgetTester tester) => tester+ .widget<Text>(find.byKey(const Key('team-account-lock-outcome')))+ .data!;++ testWidgets('unlocked, it is not there and the app takes input', (+ tester,+ ) async {+ await window(tester, app);+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ await tester.tap(find.byKey(const Key('behind-button')));+ expect(taps, 1);+ });++ testWidgets(+ 'locked, nothing behind it takes a click, a key or focus, a dialog included',+ (tester) async {+ final semantics = tester.ensureSemantics();+ await window(tester, app);+ // A dialog open before the join, as a menu item's would be.+ var dialogTaps = 0;+ navigator.currentState!.push(+ DialogRoute<void>(+ context: navigator.currentContext!,+ builder: (_) => Dialog(+ child: TextButton(+ key: const Key('dialog-button'),+ onPressed: () => dialogTaps++,+ child: const Text('In a dialog'),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await lock(tester);++ await tester.tap(+ find.byKey(const Key('behind-button')),+ warnIfMissed: false,+ );+ await tester.tap(+ find.byKey(const Key('dialog-button')),+ warnIfMissed: false,+ );+ await tester.tap(+ find.byKey(const Key('behind-field')),+ warnIfMissed: false,+ );+ await tester.pump();+ expect(taps, 0);+ expect(dialogTaps, 0);++ for (var i = 0; i < 8; i++) {+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);+ await tester.pump();+ expect(focusedIn(find.byKey(const Key('team-account-lock'))), isTrue);+ }+ // Something behind asks for focus by itself (a terminal on output, a+ // dialog opening): it does not get it, and Enter presses nothing there.+ behind.requestFocus();+ await tester.pump();+ expect(focusedIn(find.byKey(const Key('team-account-lock'))), isTrue);+ navigator.currentState!.push(+ DialogRoute<void>(+ context: navigator.currentContext!,+ builder: (_) => Dialog(+ child: TextButton(+ key: const Key('late-dialog-button'),+ autofocus: true,+ onPressed: () => dialogTaps++,+ child: const Text('Opened while locked'),+ ),+ ),+ ),+ );+ await tester.pump();+ await tester.pump();+ expect(focusedIn(find.byKey(const Key('team-account-lock'))), isTrue);+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyK);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(shortcuts, 0);+ expect(taps, 0);+ expect(dialogTaps, 0);++ // A screen reader reads only the lock.+ final read = spoken(tester);+ expect(read.join('\n'), contains('Set up Harness Team on this Mac'));+ expect(read.join('\n'), isNot(contains('Behind')));+ expect(read.join('\n'), isNot(contains('In a dialog')));+ semantics.dispose();++ // Set up: the app is as it was, its dialogs still open over it.+ await app.teamAccountMade();+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ await tester.tap(find.byKey(const Key('late-dialog-button')));+ expect(dialogTaps, 1);+ },+ );++ testWidgets('there is no way to close it', (tester) async {+ await window(tester, app);+ await lock(tester);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ await tester.tapAt(const Offset(4, 4));+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsOneWidget);+ for (final label in ['Cancel', 'Not now', 'Close', 'OK']) {+ expect(find.text(label), findsNothing, reason: label);+ }+ expect(find.byKey(const Key('team-account-lock-remove')), findsNothing);+ expect(+ find.textContaining('This Mac joined a Swarm, so it needs Harness Team'),+ findsOneWidget,+ );+ });++ testWidgets('Continue starts setup, and success opens the app', (+ tester,+ ) async {+ daemon.statuses+ ..clear()+ ..addAll([+ {'ok': true, 'state': 'running'},+ {'ok': true, 'state': 'exists'},+ ]);+ await window(tester, app);+ await lock(tester);+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ expect(daemon.asked, ['teamSetupCheck', 'teamSetup']);+ expect(+ outcome(tester),+ 'macOS is asking for your password in a window titled “osascript”. '+ 'Setup then takes a minute or two, and Harness opens when it is done.',+ );+ expect(find.byType(CircularProgressIndicator), findsOneWidget);+ await tester.pump(const Duration(seconds: 2));+ expect(find.byKey(const Key('team-account-lock')), findsOneWidget);+ await tester.pump(const Duration(seconds: 2));+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ expect(app.teamSetupLocked, isFalse);+ await tester.tap(find.byKey(const Key('behind-button')));+ expect(taps, 1);+ });++ testWidgets('a Mac with the account already opens the app at Continue', (+ tester,+ ) async {+ daemon.run = {'ok': true, 'state': 'exists'};+ await window(tester, app);+ await lock(tester);+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ });++ testWidgets('a wrong password says so, and Try again asks again', (+ tester,+ ) async {+ daemon.statuses+ ..clear()+ ..add({'ok': true, 'state': 'failed', 'detail': _wrongPassword});+ await window(tester, app);+ await lock(tester);+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump(const Duration(seconds: 2));+ expect(outcome(tester), 'macOS did not accept that password. Try again.');+ expect(find.byKey(const Key('team-account-lock-remove')), findsNothing);+ daemon.statuses+ ..clear()+ ..add({'ok': true, 'state': 'running'});+ await tester.tap(find.byKey(const Key('team-account-lock-retry')));+ await tester.pump();+ expect(daemon.asked.where((a) => a == 'teamSetup'), hasLength(2));+ expect(find.byType(CircularProgressIndicator), findsOneWidget);+ });++ testWidgets('another failure says the daemon\'s sentence, with Try again', (+ tester,+ ) async {+ daemon.statuses+ ..clear()+ ..add({'ok': true, 'state': 'failed', 'detail': 'dscl exited 64.'});+ await window(tester, app);+ await lock(tester);+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump(const Duration(seconds: 2));+ expect(outcome(tester), 'Setup did not finish: dscl exited 64.');+ expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);+ });++ testWidgets(+ 'a closed password window offers Try again and, for a Mac without an administrator, the way out',+ (tester) async {+ daemon.statuses+ ..clear()+ ..add({'ok': true, 'state': 'declined'});+ await window(tester, app);+ await lock(tester);+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump(const Duration(seconds: 2));+ expect(+ outcome(tester),+ 'The password window was closed before setup finished.',+ );+ expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);+ expect(+ find.text(+ 'No administrator password for this Mac? Remove it from the Swarm. '+ 'You can add it again from Machines.',+ ),+ findsOneWidget,+ );+ expect(find.text('Remove this Mac from the Swarm'), findsOneWidget);+ },+ );++ testWidgets(+ 'where setup can never finish, it says why and offers only the way out',+ (tester) async {+ daemon.run = {'error': 'INVALID_REQUEST'};+ await window(tester, app);+ await lock(tester);+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump();+ expect(+ outcome(tester),+ 'This Mac\'s Harness is too old to set it up from here. Update Harness, '+ 'or run harness team setup in Terminal.',+ );+ expect(find.byKey(const Key('team-account-lock-retry')), findsNothing);+ expect(find.byKey(const Key('team-account-lock-remove')), findsOneWidget);+ },+ );++ testWidgets('Harness unreachable says so, with Try again', (tester) async {+ daemon.run = {'error': 'SERVICE_UNAVAILABLE'};+ await window(tester, app);+ await lock(tester);+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);+ expect(find.byKey(const Key('team-account-lock')), findsOneWidget);+ });++ testWidgets('Remove this Mac from the Swarm removes it and opens the app', (+ tester,+ ) async {+ final f = SuperTabLaunchFixture();+ f.app.teamAccountHereForTest = true;+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ // The Swarm lists this Mac, as the join added it.+ f.connection.server.state['machines'] = [+ {'machineId': 'm', 'name': 'Test host', 'contributorId': 'owner'},+ ];+ f.connection.teamCheck = {'state': 'wanted'};+ f.connection.teamRun = {'state': 'unsupported'};+ await f.app.offerTeamAccount('join', tabId: tabId);+ await window(tester, f.app);+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pumpAndSettle();+ expect(+ outcome(tester),+ 'Harness Team cannot be set up on this Mac right now.',+ );+ List<Object?> removals() => [+ for (final p in f.connection.server.posts)+ if ((p['command'] as Map?)?['type'] == 'machine.remove') p['command'],+ ];++ // Security review of #2779: removing deletes data. Nothing has focus on+ // Remove, so Enter does nothing, and one press only asks, naming the+ // Swarm.+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyEvent(LogicalKeyboardKey.space);+ await tester.pumpAndSettle();+ expect(removals(), isEmpty);+ await tester.tap(find.byKey(const Key('team-account-lock-remove')));+ await tester.pumpAndSettle();+ expect(removals(), isEmpty);+ expect(+ tester+ .widget<Text>(find.byKey(const Key('team-account-lock-confirm')))+ .data,+ 'Remove this Mac from Pilot? Its agents there stop, and teammates\' '+ 'work no longer runs on it. You can add it again from Machines.',+ );+ // Back asks nothing, and is where focus waits: Enter there removes nothing.+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(removals(), isEmpty);+ expect(find.byKey(const Key('team-account-lock-confirm')), findsNothing);+ expect(find.byKey(const Key('team-account-lock-remove')), findsOneWidget);++ await tester.tap(find.byKey(const Key('team-account-lock-remove')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const Key('team-account-lock-remove-confirm')));+ await tester.pumpAndSettle();+ expect(removals(), [+ {'type': 'machine.remove', 'machineId': 'm'},+ ]);+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ await tester.pumpWidget(const SizedBox());+ f.app.superTabs.dispose();+ f.dispose();+ await tester.pump();+ });++ testWidgets('a removal the Swarm refuses says why, and the lock stays', (+ tester,+ ) async {+ final f = SuperTabLaunchFixture();+ f.app.teamAccountHereForTest = true;+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ // The Swarm lists this Mac, as the join added it.+ f.connection.server.state['machines'] = [+ {'machineId': 'm', 'name': 'Test host', 'contributorId': 'owner'},+ ];+ f.connection.teamCheck = {'state': 'wanted'};+ f.connection.teamRun = {'state': 'unsupported'};+ await f.app.offerTeamAccount('join', tabId: tabId);+ f.connection.server.refuse = {+ 'code': 'FORBIDDEN',+ 'message': 'Only the Swarm owner can do that.',+ };+ await window(tester, f.app);+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const Key('team-account-lock-remove')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const Key('team-account-lock-remove-confirm')));+ await tester.pumpAndSettle();+ expect(find.text('Only the Swarm owner can do that.'), findsOneWidget);+ expect(find.byKey(const Key('team-account-lock')), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ f.app.superTabs.dispose();+ f.dispose();+ await tester.pump();+ });++ testWidgets(+ 'the app\'s own window is held, its screen still mounted under it',+ (tester) async {+ final own = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ cliLogin: _FakeCli(),+ connectionForTest: (_) => daemon,+ );+ addTearDown(own.dispose);+ const machine = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'Test host',+ );+ own.machines = [machine];+ own.machineStates['m'] = MachineState(machine)+ ..localOnly = true+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected;+ own.teamAccountHereForTest = true;+ own.status = AppStatus.authenticated;+ own.currentUser = const CurrentUserProfile(+ id: 'owner',+ email: '[email protected]',+ );+ await tester.pumpWidget(+ ProviderScope(+ overrides: [appStateProvider.overrideWithValue(own)],+ child: HarnessApp(+ authenticatedScreen: (_) => const SizedBox(key: Key('screen')),+ ),+ ),+ );+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ await own.offerTeamAccount('join', tabId: 'tab-1');+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsOneWidget);+ expect(find.byKey(const Key('screen')), findsOneWidget);++ // Review of #2779: the macOS app menu's rows (Settings, Check for+ // Updates, Keyboard Shortcuts…) arrive over a channel, not by focus.+ Future<void> appMenu(String action) async {+ // Not awaited: the action ends when what it opened is closed.+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(+ 'harness/app_menu',+ const StandardMethodCodec().encodeMethodCall(MethodCall(action)),+ (_) {},+ );+ await tester.pump();+ await tester.pump();+ }++ await appMenu('settings');+ expect(find.byType(SettingsScreen), findsNothing);+ await own.teamAccountMade();+ await tester.pump();+ await appMenu('settings');+ expect(find.byType(SettingsScreen), findsOneWidget);+ // Settings' own timers end with it.+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 5));+ },+ );++ // The window as people see it, over a stand-in for the app behind it.+ final scenes = <(String, Future<void> Function(WidgetTester))>[+ ('1-on-join', (_) async {}),+ (+ '2-macos-asking',+ (tester) async {+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ // Far enough into the spinner's turn that its arc shows.+ await tester.pump(const Duration(milliseconds: 600));+ },+ ),+ (+ '3-wrong-password',+ (tester) async {+ daemon.statuses+ ..clear()+ ..add({'ok': true, 'state': 'failed', 'detail': _wrongPassword});+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump(const Duration(seconds: 2));+ },+ ),+ (+ '4-password-window-closed',+ (tester) async {+ daemon.statuses+ ..clear()+ ..add({'ok': true, 'state': 'declined'});+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump(const Duration(seconds: 2));+ },+ ),+ (+ '5-cannot-set-up-here',+ (tester) async {+ daemon.run = {'error': 'INVALID_REQUEST'};+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump();+ },+ ),+ (+ '6-remove-asks-first',+ (tester) async {+ daemon.run = {'error': 'INVALID_REQUEST'};+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ await tester.pump();+ await tester.tap(find.byKey(const Key('team-account-lock-remove')));+ await tester.pump();+ // No Swarm answers here: its name is given up on, and it still asks.+ await tester.pump(const Duration(seconds: 6));+ await tester.pump();+ expect(+ find.byKey(const Key('team-account-lock-confirm')),+ findsOneWidget,+ );+ },+ ),+ ];+ for (final brightness in Brightness.values) {+ for (final (name, arrange) in scenes) {+ testWidgets('picture $name (${brightness.name})', (tester) async {+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ await tester.binding.setSurfaceSize(const Size(1000, 700));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => TeamAccountSetupLock(+ app: app,+ operatingSystem: 'macos',+ child: child!,+ ),+ home: Scaffold(+ body: Padding(+ padding: const EdgeInsets.all(24),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text('Pilot', style: grid.AppType.title()),+ const SizedBox(height: 12),+ for (final line in [+ 'Lead: the plan for the release is in the thread.',+ 'Ken: Looks good, go ahead.',+ 'Builder: PR #2779 is ready for review.',+ ])+ Padding(+ padding: const EdgeInsets.only(bottom: 8),+ child: Text(line, style: grid.AppType.body()),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ await lock(tester);+ await arrange(tester);+ await captureWindow(tester, shots, '$name-${brightness.name}');+ await tester.pumpWidget(const SizedBox());+ debugDefaultTargetPlatformOverride = null;+ }, skip: shots == null);+ }+ }++ // The task's Done when, end to end in one window (River, 11-03: the Tester+ // may not run the real setup on a shared Mac, so this walk is the check):+ // the Machines view as the app shows it, this Mac joining, the window over+ // it at once, nothing behind it reachable, a wrong password, Try again, the+ // right one, and the Mac set up in Machines.+ for (final brightness in Brightness.values) {+ testWidgets(+ 'join → window at once → wrong password → Try again → set up, and Machines says so (${brightness.name})',+ (tester) async {+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);+ Map<String, dynamic> pool(+ String id, {+ String? host,+ Map<String, dynamic>? teamWork,+ }) => {+ 'machineId': id,+ 'name': host == null ? 'Test host' : 'Test host · Team',+ 'contributorId': 'owner',+ 'scope': 'swarm',+ 'cwd': '/swarm',+ 'engines': ['codex'],+ 'maxAgents': 4,+ 'paused': false,+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},+ 'hostMachineId': ?host,+ 'teamWork': teamWork ?? {'allowed': true},+ };+ const notSetUp = {+ 'allowed': false,+ 'code': 'TEAM_ACCOUNT_REQUIRED',+ 'reason': 'Test host has no Harness Team account yet.',+ };+ final f = SuperTabLaunchFixture();+ f.app.teamAccountHereForTest = true;+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ // A Swarm with a teammate, whose agents would run on this Mac.+ (f.connection.server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ f.connection.server.state['machines'] = [pool('m', teamWork: notSetUp)];+ f.connection.teamCheck = {'state': 'wanted'};+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ var added = 0;+ await tester.binding.setSurfaceSize(const Size(1000, 700));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ Future<void> openMachines() async {+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => TeamAccountSetupLock(+ app: f.app,+ operatingSystem: 'macos',+ child: child!,+ ),+ home: Scaffold(+ body: SuperTabMachines(+ controller: c,+ onAddAgent: (_) => added++,+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ await openMachines();+ final problem = find.byKey(const ValueKey('super-machine-problem-m'));+ expect(+ tester.widget<Text>(problem).data,+ "Teammates' agents paused: not set up",+ );+ await captureWindow(+ tester,+ shots,+ 'walk-1-machines-not-set-up-${brightness.name}',+ );++ // Joined: the window is there at once, in the same frame.+ await f.app.offerTeamAccount('join', tabId: tabId);+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsOneWidget);+ await captureWindow(tester, shots, 'walk-2-joined-${brightness.name}');+ final lock = find.byKey(const Key('team-account-lock'));+ bool inLock() {+ final focused = FocusManager.instance.primaryFocus?.context;+ return focused != null &&+ lock.evaluate().any(+ (e) =>+ e == focused ||+ (focused as Element).debugGetDiagnosticChain().contains(e),+ );+ }++ // Nothing behind it: Tab, arrows and Escape stay in the window, a click+ // on the machine row does nothing.+ for (final key in [+ LogicalKeyboardKey.tab,+ LogicalKeyboardKey.arrowDown,+ LogicalKeyboardKey.arrowUp,+ LogicalKeyboardKey.arrowLeft,+ LogicalKeyboardKey.arrowRight,+ LogicalKeyboardKey.tab,+ LogicalKeyboardKey.escape,+ ]) {+ await tester.sendKeyEvent(key);+ await tester.pump();+ expect(inLock(), isTrue, reason: '$key');+ expect(lock, findsOneWidget, reason: '$key');+ }+ final expanded = c.isMachineExpanded('m');+ await tester.tap(+ find.byKey(const ValueKey('super-machine-m')),+ warnIfMissed: false,+ );+ await tester.pump();+ expect(c.isMachineExpanded('m'), expanded);+ expect(added, 0);++ // A wrong password: said, and Try again asks again.+ f.connection.teamSetup = {'state': 'running'};+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ f.connection.teamSetup = {'state': 'failed', 'detail': _wrongPassword};+ await tester.pump(const Duration(seconds: 2));+ await tester.pump();+ expect(+ outcome(tester),+ 'macOS did not accept that password. Try again.',+ );+ await captureWindow(+ tester,+ shots,+ 'walk-3-wrong-password-${brightness.name}',+ );++ // The right one: setup finishes, and the window goes.+ f.connection.teamSetup = {'state': 'running'};+ await tester.tap(find.byKey(const Key('team-account-lock-retry')));+ await tester.pump();+ expect(find.byType(CircularProgressIndicator), findsOneWidget);+ f.connection.teamSetup = {'state': 'exists'};+ await tester.pump(const Duration(seconds: 2));+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ expect(f.app.teamSetupLocked, isFalse);++ // Its Team account reports in, and Machines shows the Mac set up.+ f.connection.server.state['machines'] = [+ pool('m', teamWork: notSetUp),+ pool('m-team', host: 'm'),+ ];+ await c.refresh();+ // Machines, opened again: the Mac's row no longer says it is paused.+ await tester.pumpWidget(const SizedBox());+ await openMachines();+ expect(problem, findsNothing);+ await captureWindow(+ tester,+ shots,+ 'walk-4-machines-set-up-${brightness.name}',+ );++ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ f.dispose();+ await tester.pump();+ },+ );+ }+}diff --git a/desktop/test/team_account_offer_test.dart b/desktop/test/team_account_offer_test.dartindex 29ef952bf..6569cbdec 100644--- a/desktop/test/team_account_offer_test.dart+++ b/desktop/test/team_account_offer_test.dart@@ -1,4 +1,5 @@import 'dart:async';+import 'dart:convert';import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';@@ -6,16 +7,22 @@ import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';import 'package:harness/super_tabs/team_account_setup.dart';+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;import 'support/rename_connection.dart';-import 'swarm_state_test.dart' show createApp;+import 'swarm_state_test.dart' show MemoryStore, createApp;/// Records what this Mac's daemon is asked; no socket is opened.class _Daemon extends RenameConnection {final asked = <Map<String, dynamic>>[];Map<String, dynamic> answer = {'ok': true, 'state': 'wanted'};+/// Answers in turn before [answer]; a Completer's future is awaited.final queued = <Object>[];+ /// What `teamSetupStatus` answers: what this Mac's daemon remembers of the+ /// account's setup.+ Map<String, dynamic> status = {'ok': true, 'state': 'none'};+@overrideFuture<Map<String, dynamic>> request(String type, {@@ -25,6 +32,7 @@ class _Daemon extends RenameConnection {if (type == 'super_tabs' &&'${payload['action']}'.startsWith('teamSetup')) {asked.add(Map.of(payload));+ if (payload['action'] == 'teamSetupStatus') return Future.value(status);if (queued.isNotEmpty) {final next = queued.removeAt(0);return next is Completer<Map<String, dynamic>>@@ -52,11 +60,20 @@ void main() {TestWidgetsFlutterBinding.ensureInitialized();late _Daemon daemon;late AppNotifier app;+/// Which daemon process answers this Mac: a new one after a restart, null/// when its status could not be read.String? running = 'pid-1';- AppNotifier make(_Daemon daemon) {- final app = createApp(connectionForTest: (_) => daemon, connected: true);+ AppNotifier make(_Daemon daemon, {MemoryStore? store}) {+ final app = createApp(+ connectionForTest: (_) => daemon,+ connected: true,+ store: store,+ );+ app.currentUser = const CurrentUserProfile(+ id: 'owner',+ email: '[email protected]',+ );app.machineStates['m']!.localOnly = true;app.teamAccountHereForTest = true;app.daemonIdentityForTest = () async => running;@@ -71,21 +88,120 @@ void main() {});tearDown(() => app.dispose());- test('asks this Mac\'s own daemon whether it is wanted, and explains it only then', () async {+ test('asks this Mac\'s own daemon whether it is wanted, for the Swarm joined or added to', () async {final explained = <String>[];final listening = app.teamSetupAsks.listen(explained.add);await app.offerTeamAccount('join', tabId: 'tab-1');daemon.answer = {'ok': true, 'state': 'declined'};- await app.offerTeamAccount('contribute');+ await app.offerTeamAccount('contribute', tabId: 'tab-2');await pumpEventQueue();expect(daemon.asked, [{'action': 'teamSetupCheck', 'reason': 'join', 'tabId': 'tab-1'},- {'action': 'teamSetupCheck', 'reason': 'contribute'},+ {'action': 'teamSetupCheck', 'reason': 'contribute', 'tabId': 'tab-2'},]);- expect(explained, ['join']);+ // A join or a contribution locks the app instead (team_account_setup.dart+ // TeamAccountSetupLock): nothing is explained behind it.+ expect(explained, isEmpty);+ expect(app.teamSetupLocked, isTrue);await listening.cancel();});+ // Scholes 11-03: a Mac joined a Swarm and stayed "not set up" until someone+ // found its row in Machines. The window now opens on join and stays.+ test('a join locks the app once, however often it is asked, until the account exists', () async {+ var changes = 0;+ app.addListener(() => changes++);+ expect(app.teamSetupLocked, isFalse);+ await app.offerTeamAccount('join', tabId: 'tab-1');+ expect(app.teamSetupLocked, isTrue);+ final first = changes;+ await app.offerTeamAccount('join', tabId: 'tab-1');+ expect(changes, first, reason: 'the same Swarm again changes nothing');+ await app.offerTeamAccount('join', tabId: 'tab-2');+ expect(app.teamSetupLocked, isTrue);+ await app.teamAccountMade();+ expect(app.teamSetupLocked, isFalse);+ });++ test('a join on a Mac that has the account, or whose daemon cannot say, does not lock', () async {+ for (final answer in [+ {'ok': true, 'state': 'exists'},+ {'ok': true, 'state': 'unsupported'},+ {'ok': true, 'state': 'dedicated'},+ {'error': 'UNKNOWN_ACTION'},+ ]) {+ daemon.answer = answer;+ await app.offerTeamAccount('join', tabId: 'tab-1');+ expect(app.teamSetupLocked, isFalse, reason: '$answer');+ }+ });++ // A cancel remembered from before (the old "Not now", or macOS's prompt+ // closed) kept every later join from asking.+ test(+ 'a cancel or a failure remembered from before still locks a new join',+ () async {+ for (final state in ['declined', 'waiting', 'running', 'no-prompt']) {+ daemon.answer = {'ok': true, 'state': state};+ await app.offerTeamAccount('join', tabId: 'tab-1');+ expect(app.teamSetupLocked, isTrue, reason: state);+ await app.teamAccountMade();+ }+ },+ );++ test(+ 'the start check never locks: only a join or a contribution does',+ () async {+ await app.offerTeamAccount('startup');+ expect(app.teamSetupLocked, isFalse);+ },+ );++ test('the lock comes back after a restart, until the account exists', () async {+ final store = MemoryStore();+ final first = make(daemon, store: store);+ await first.offerTeamAccount('join', tabId: 'tab-1');+ expect(first.teamSetupLocked, isTrue);+ first.dispose();++ // Quit and opened again, the account still missing: locked as it connects.+ final again = _Daemon()..answer = {'ok': true, 'state': 'not-shared'};+ final second = make(again, store: store);+ addTearDown(second.dispose);+ expect(second.teamSetupLocked, isFalse);+ second.onMachineConnectedForTest('m');+ await until(() => second.teamSetupLocked);++ // Set up meanwhile (in Terminal): the next start is not locked, and+ // forgets it.+ final made = _Daemon()+ ..answer = {'ok': true, 'state': 'exists'}+ ..status = {'ok': true, 'state': 'exists'};+ final third = make(made, store: store);+ addTearDown(third.dispose);+ third.onMachineConnectedForTest('m');+ await until(() => made.asked.any((a) => a['action'] == 'teamSetupStatus'));+ await pumpEventQueue();+ expect(third.teamSetupLocked, isFalse);+ expect(+ store.values.keys.where((k) => k.startsWith('team_setup_lock')),+ isEmpty,+ );+ });++ test(+ 'another account signed in on this computer is not held by it',+ () async {+ await app.offerTeamAccount('join', tabId: 'tab-1');+ app.currentUser = const CurrentUserProfile(+ id: 'other',+ email: '[email protected]',+ );+ expect(app.teamSetupLocked, isFalse);+ },+ );+test('sets it up when the person asks, and remembers "Not now"', () async {daemon.answer = {'ok': true, 'state': 'started'};expect(await app.setUpTeamAccount(), 'started');@@ -105,17 +221,14 @@ void main() {expect(await app.setUpTeamAccount(), 'update');});- test(- 'asks nothing where the account cannot be made, or when the only machine here is another one',- () async {- app.teamAccountHereForTest = false;- await app.offerTeamAccount('join');- app.teamAccountHereForTest = true;- app.machineStates['m']!.localOnly = false;- await app.offerTeamAccount('join');- expect(daemon.asked, isEmpty);- },- );+ test('asks nothing where the account cannot be made, or when the only machine here is another one', () async {+ app.teamAccountHereForTest = false;+ await app.offerTeamAccount('join');+ app.teamAccountHereForTest = true;+ app.machineStates['m']!.localOnly = false;+ await app.offerTeamAccount('join');+ expect(daemon.asked, isEmpty);+ });// Linux and Windows make the same account a Mac does (plans of 2026-10-28;// Windows' daemon sets it up behind User Account Control). A phone, a tablet@@ -129,25 +242,28 @@ void main() {}});- test('never for a machine shared with this account, at a join or at start', () async {- final state = app.machineStates['m']!;- state.machine = Machine(- machineId: 'm',- authMode: MachineAuthMode.remote,- name: 'Dee\'s computer',- machineShare: const MachineShare(- ownerName: 'Dee',- ownerEmail: '[email protected]',- via: 'email',- added: true,- ),- );- expect(app.canSetUpTeamAccount, isFalse);- await app.offerTeamAccount('join');- app.onMachineConnectedForTest('m');- await Future<void>.delayed(const Duration(milliseconds: 20));- expect(daemon.asked, isEmpty);- });+ test(+ 'never for a machine shared with this account, at a join or at start',+ () async {+ final state = app.machineStates['m']!;+ state.machine = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'Dee\'s computer',+ machineShare: const MachineShare(+ ownerName: 'Dee',+ ownerEmail: '[email protected]',+ via: 'email',+ added: true,+ ),+ );+ expect(app.canSetUpTeamAccount, isFalse);+ await app.offerTeamAccount('join');+ app.onMachineConnectedForTest('m');+ await Future<void>.delayed(const Duration(milliseconds: 20));+ expect(daemon.asked, isEmpty);+ },+ );test('a daemon that refuses or cannot say is left alone', () async {daemon.answer = {'error': 'UNKNOWN_ACTION'};@@ -155,47 +271,57 @@ void main() {expect(daemon.asked, hasLength(1));});- test('checks once for each process of this Mac\'s daemon, as it connects', () async {- app.onMachineConnectedForTest('m');- app.onMachineConnectedForTest('m');- await until(() => daemon.asked.isNotEmpty);- await pumpEventQueue();- expect(daemon.asked, [startCheck]);- });+ test(+ 'checks once for each process of this Mac\'s daemon, as it connects',+ () async {+ app.onMachineConnectedForTest('m');+ app.onMachineConnectedForTest('m');+ await until(() => daemon.asked.isNotEmpty);+ await pumpEventQueue();+ expect(daemon.asked, [startCheck]);+ },+ );// Macs already in a Swarm met no join or contribute moment, and the one ask// a launch went to whichever daemon answered first: one still starting, or// the version from before an update, so nobody saw the prompt (2026-10-27).- test('checks again when this Mac\'s daemon has restarted, which decides', () async {- app.onMachineConnectedForTest('m');- await until(() => daemon.asked.length == 1);- await pumpEventQueue();- // A new daemon process, after an update for instance: asked again.- running = 'pid-2';- app.onMachineConnectedForTest('m');- await until(() => daemon.asked.length == 2);- expect(daemon.asked, everyElement(startCheck));- });+ test(+ 'checks again when this Mac\'s daemon has restarted, which decides',+ () async {+ app.onMachineConnectedForTest('m');+ await until(() => daemon.asked.length == 1);+ await pumpEventQueue();+ // A new daemon process, after an update for instance: asked again.+ running = 'pid-2';+ app.onMachineConnectedForTest('m');+ await until(() => daemon.asked.length == 2);+ expect(daemon.asked, everyElement(startCheck));+ },+ );// A start check runs for each daemon process, so a restart while the// explanation is still open must not show it a second time.- test('explains at start once a launch, though a restarted daemon still wants it', () async {- final explained = <String>[];- final listening = app.teamSetupAsks.listen(explained.add);- app.onMachineConnectedForTest('m');- await until(() => daemon.asked.length == 1);- await pumpEventQueue();- running = 'pid-2';- app.onMachineConnectedForTest('m');- await until(() => daemon.asked.length == 2);- await pumpEventQueue();- expect(explained, ['startup']);- // The person asking, by joining, is always explained.- await app.offerTeamAccount('join');- await pumpEventQueue();- expect(explained, ['startup', 'join']);- await listening.cancel();- });+ test(+ 'explains at start once a launch, though a restarted daemon still wants it',+ () async {+ final explained = <String>[];+ final listening = app.teamSetupAsks.listen(explained.add);+ app.onMachineConnectedForTest('m');+ await until(() => daemon.asked.length == 1);+ await pumpEventQueue();+ running = 'pid-2';+ app.onMachineConnectedForTest('m');+ await until(() => daemon.asked.length == 2);+ await pumpEventQueue();+ expect(explained, ['startup']);+ // The person joining is held by the lock instead, never explained again.+ await app.offerTeamAccount('join', tabId: 'tab-1');+ await pumpEventQueue();+ expect(explained, ['startup']);+ expect(app.teamSetupLocked, isTrue);+ await listening.cancel();+ },+ );test('checks one at a time', () async {final pending = Completer<Map<String, dynamic>>();@@ -255,32 +381,38 @@ void main() {await until(() => daemon.asked.length == 6);});- test('checks again, a few times, a daemon that could not answer yet', () async {- daemon.queued.addAll([- {'error': 'SERVICE_UNAVAILABLE'},- {'error': 'SERVICE_UNAVAILABLE'},- ]);- app.onMachineConnectedForTest('m');- // Two that could not say, then an answer.- await until(() => daemon.asked.length == 3);- await Future<void>.delayed(const Duration(milliseconds: 20));- expect(daemon.asked, hasLength(3));- });+ test(+ 'checks again, a few times, a daemon that could not answer yet',+ () async {+ daemon.queued.addAll([+ {'error': 'SERVICE_UNAVAILABLE'},+ {'error': 'SERVICE_UNAVAILABLE'},+ ]);+ app.onMachineConnectedForTest('m');+ // Two that could not say, then an answer.+ await until(() => daemon.asked.length == 3);+ await Future<void>.delayed(const Duration(milliseconds: 20));+ expect(daemon.asked, hasLength(3));+ },+ );// Review of #1790: a request still out at dispose resumed and scheduled a// retry on a disposed app.- test('schedules nothing after it is disposed, though a request was out', () async {- final own = _Daemon();- final other = make(own);- final pending = Completer<Map<String, dynamic>>();- own.queued.add(pending);- other.onMachineConnectedForTest('m');- await until(() => own.asked.isNotEmpty);- other.dispose();- pending.complete({'error': 'ACCOUNT_CHANGED'});- await Future<void>.delayed(const Duration(milliseconds: 30));- expect(own.asked, hasLength(1));- });+ test(+ 'schedules nothing after it is disposed, though a request was out',+ () async {+ final own = _Daemon();+ final other = make(own);+ final pending = Completer<Map<String, dynamic>>();+ own.queued.add(pending);+ other.onMachineConnectedForTest('m');+ await until(() => own.asked.isNotEmpty);+ other.dispose();+ pending.complete({'error': 'ACCOUNT_CHANGED'});+ await Future<void>.delayed(const Duration(milliseconds: 30));+ expect(own.asked, hasLength(1));+ },+ );Future<void> open(WidgetTester tester, {@@ -378,75 +510,80 @@ void main() {);});- testWidgets('on Linux the dialog says this computer, and the system asks for the password', (- tester,- ) async {- await open(tester, operatingSystem: 'linux');- expect(shown(tester), [- 'Set up Harness Team on this computer',- computerParagraph1,- 'Your system asks for your password once.',- paragraph3,- ]);- expect(find.text('Continue'), findsOneWidget);- expect(find.text('Cancel'), findsOneWidget);- await tester.tap(find.text('Cancel'));- await tester.pumpAndSettle();- expect(- await outcome(tester, 'linux', {'ok': true, 'state': 'started'}),- 'Your system is asking for your password. Setup then takes a minute or two. '- 'This computer\'s row updates when it is ready.',- );- // No desktop session to ask in (the owner's daemon under systemd --user, or SSH): the daemon answers `no-prompt` up- // front (cli/src/team/autoSetup.ts) and nothing runs, so the terminal is the way.- expect(- await outcome(tester, 'linux', {'ok': true, 'state': 'no-prompt'}),- 'Run harness team setup in a terminal on this computer.',- );- expect(- await outcome(tester, 'linux', {'ok': true, 'state': 'exists'}),- 'Harness Team is already set up on this computer.',- );- expect(- await outcome(tester, 'linux', {'error': 'INVALID_REQUEST'}),- 'This computer\'s Harness is too old to set it up from here. Update Harness, '- 'or run harness team setup in a terminal.',- );- expect(- await outcome(tester, 'linux', {'ok': true, 'state': 'unsupported'}),- 'Harness Team cannot be set up on this computer right now.',- );- });+ testWidgets(+ 'on Linux the dialog says this computer, and the system asks for the password',+ (tester) async {+ await open(tester, operatingSystem: 'linux');+ expect(shown(tester), [+ 'Set up Harness Team on this computer',+ computerParagraph1,+ 'Your system asks for your password once.',+ paragraph3,+ ]);+ expect(find.text('Continue'), findsOneWidget);+ expect(find.text('Cancel'), findsOneWidget);+ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();+ expect(+ await outcome(tester, 'linux', {'ok': true, 'state': 'started'}),+ 'Your system is asking for your password. Setup then takes a minute or two. '+ 'This computer\'s row updates when it is ready.',+ );+ // No desktop session to ask in (the owner's daemon under systemd --user, or SSH): the daemon answers `no-prompt` up+ // front (cli/src/team/autoSetup.ts) and nothing runs, so the terminal is the way.+ expect(+ await outcome(tester, 'linux', {'ok': true, 'state': 'no-prompt'}),+ 'Run harness team setup in a terminal on this computer.',+ );+ expect(+ await outcome(tester, 'linux', {'ok': true, 'state': 'exists'}),+ 'Harness Team is already set up on this computer.',+ );+ expect(+ await outcome(tester, 'linux', {'error': 'INVALID_REQUEST'}),+ 'This computer\'s Harness is too old to set it up from here. Update Harness, '+ 'or run harness team setup in a terminal.',+ );+ expect(+ await outcome(tester, 'linux', {'ok': true, 'state': 'unsupported'}),+ 'Harness Team cannot be set up on this computer right now.',+ );+ },+ );- testWidgets('on Windows the dialog says this computer, and User Account Control asks', (- tester,- ) async {- await open(tester, operatingSystem: 'windows', asked: true);- expect(shown(tester), [- 'Set up Harness Team on this computer',- computerParagraph1,- 'Windows asks for permission once (User Account Control).',- paragraph3,- ]);- expect(find.text('Not now'), findsOneWidget);- await tester.tap(find.text('Not now'));- await tester.pumpAndSettle();- daemon.asked.clear();- expect(- await outcome(tester, 'windows', {'ok': true, 'state': 'started'}),- 'Windows is asking for permission. Setup then takes a minute or two. '- 'This computer\'s row updates when it is ready.',- );- expect(- await outcome(tester, 'windows', {'ok': true, 'state': 'exists'}),- 'Harness Team is already set up on this computer.',- );- // A refusal says the daemon's own sentence, as on a Mac.- expect(- await outcome(tester, 'windows', {'error': 'NO_PROMPT', 'detail': 'The daemon\'s sentence.'}),- 'The daemon\'s sentence.',- );- });+ testWidgets(+ 'on Windows the dialog says this computer, and User Account Control asks',+ (tester) async {+ await open(tester, operatingSystem: 'windows', asked: true);+ expect(shown(tester), [+ 'Set up Harness Team on this computer',+ computerParagraph1,+ 'Windows asks for permission once (User Account Control).',+ paragraph3,+ ]);+ expect(find.text('Not now'), findsOneWidget);+ await tester.tap(find.text('Not now'));+ await tester.pumpAndSettle();+ daemon.asked.clear();+ expect(+ await outcome(tester, 'windows', {'ok': true, 'state': 'started'}),+ 'Windows is asking for permission. Setup then takes a minute or two. '+ 'This computer\'s row updates when it is ready.',+ );+ expect(+ await outcome(tester, 'windows', {'ok': true, 'state': 'exists'}),+ 'Harness Team is already set up on this computer.',+ );+ // A refusal says the daemon's own sentence, as on a Mac.+ expect(+ await outcome(tester, 'windows', {+ 'error': 'NO_PROMPT',+ 'detail': 'The daemon\'s sentence.',+ }),+ 'The daemon\'s sentence.',+ );+ },+ );testWidgets('explains the account and the "osascript" prompt before macOS asks',@@ -484,4 +621,128 @@ void main() {{'action': 'teamSetupDecline'},]);});++ group('Remove this Mac from the Swarm, the one way out', () {+ Map<String, dynamic> thisMac() => {+ 'machineId': 'm',+ 'name': 'Test host',+ 'contributorId': 'owner',+ 'teamWork': {'allowed': false, 'code': 'TEAM_ACCOUNT_REQUIRED'},+ };++ Future<SuperTabLaunchFixture> joined() async {+ final f = SuperTabLaunchFixture();+ f.app.teamAccountHereForTest = true;+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ f.connection.teamCheck = {'state': 'wanted'};+ // The Swarm lists this Mac, as the join added it.+ f.connection.server.state['machines'] = [thisMac()];+ await f.app.offerTeamAccount('join', tabId: tabId);+ expect(f.app.teamSetupLocked, isTrue);+ return f;+ }++ List<Object?> commands(SuperTabLaunchFixture f) =>+ f.connection.server.posts.map((p) => p['command']).toList();++ // Review of #2779: a lock whose Swarms all refused Remove held for good.+ test(+ 'a Swarm that no longer holds this Mac is let go without a command',+ () async {+ final f = await joined();+ f.connection.server.state['machines'] = [];+ expect(await f.app.removeLockedMachine(), isNull);+ expect(+ commands(f),+ isNot(contains(containsPair('type', 'machine.remove'))),+ );+ expect(f.app.teamSetupLocked, isFalse);+ f.app.superTabs.dispose();+ },+ );++ test('a Swarm already removing this Mac is let go', () async {+ final f = await joined();+ f.connection.server.state['machines'] = [+ {+ ...thisMac(),+ 'removal': {'requestedAt': 1},+ },+ ];+ // As the Swarm answers a second removal.+ f.connection.server.refuse = {+ 'code': 'MACHINE_REMOVING',+ 'message': 'This machine is already being removed.',+ };+ expect(await f.app.removeLockedMachine(), isNull);+ expect(f.app.teamSetupLocked, isFalse);+ f.app.superTabs.dispose();+ });++ test('a Swarm this person can no longer open is let go', () async {+ final f = await joined();+ (await f.app.superTabs.open(tabId)).accessRevoked = true;+ expect(await f.app.removeLockedMachine(), isNull);+ expect(f.app.teamSetupLocked, isFalse);+ f.app.superTabs.dispose();+ });++ Future<SuperTabLaunchFixture> restarted(List<Object?> machines) async {+ final f = SuperTabLaunchFixture();+ f.app.teamAccountHereForTest = true;+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ f.connection.teamSetup = {'state': 'none'};+ f.connection.server.state['machines'] = machines;+ f.store.values['team_setup_lock.owner'] = jsonEncode([tabId]);+ f.app.onMachineConnectedForTest('m');+ return f;+ }++ test(+ 'a lock restored for a Swarm that still holds this Mac holds',+ () async {+ final f = await restarted([thisMac()]);+ await until(() => f.app.teamSetupLocked);+ f.app.superTabs.dispose();+ },+ );++ test(+ 'a lock restored for a Swarm that no longer holds this Mac does not hold',+ () async {+ final f = await restarted([]);+ await until(() => !f.store.values.containsKey('team_setup_lock.owner'));+ expect(f.app.teamSetupLocked, isFalse);+ f.app.superTabs.dispose();+ },+ );++ test(+ 'removes this Mac from the Swarm it joined, and ends the lock',+ () async {+ final f = await joined();+ expect(await f.app.removeLockedMachine(), isNull);+ expect(+ f.connection.server.posts.map((p) => p['command']),+ contains(equals({'type': 'machine.remove', 'machineId': 'm'})),+ );+ expect(f.app.teamSetupLocked, isFalse);+ f.app.superTabs.dispose();+ },+ );++ test('a removal the Swarm refuses says why and keeps the lock', () async {+ final f = await joined();+ f.connection.server.refuse = {+ 'code': 'FORBIDDEN',+ 'message': 'Only the Swarm owner can do that.',+ };+ expect(+ await f.app.removeLockedMachine(),+ 'Only the Swarm owner can do that.',+ );+ expect(f.app.teamSetupLocked, isTrue);+ f.app.superTabs.dispose();+ });+ });}diff --git a/docs/plans/2026-11-03-manage-backlog-tab-plan.md b/docs/plans/2026-11-03-manage-backlog-tab-plan.mdnew file mode 100644index 000000000..ffbbbe6fa--- /dev/null+++ b/docs/plans/2026-11-03-manage-backlog-tab-plan.md@@ -0,0 +1,161 @@+# Manage ▸ Backlog: every task in the Swarm in one list: implementation plan++> Worked by this project's instructions (Engineer role): this plan is the pull request's first commit. Then each task+> is done test first, by one Engineer, with one Review step and one Test step on the pull request. Steps use checkbox+> (`- [ ]`) syntax.++**Goal:** a Backlog tab in Desktop Manage, after Swarm. It lists every task the reader can read, across projects,+grouped by state. Each row has two lines. It has filters for project, Mine and state, and a click on a row opens the+task's chat.++**Architecture:** the tab is a view over the Swarm snapshot the controller already holds, kept current by the change+reads it already makes. It adds no Swarm read and no timer. A pure function places each task in a group from its+assignment, liveness and shippedAt. The rows reuse the task line (`superTabTaskStatus`), the agent and machine names+(`snapshot.agentName`, `controller.sessionMachineName`) and the pull request state (`SuperTabCardPullRequest` over the+view's shared `SuperTabPullRequestFacts`). One getter is added: when a group last changed (`parts.groupChangedAt`), for+the row's last-activity time.++**Tech Stack:** Flutter 3.47.2 Desktop (`flutter_test`, `ConversationServer` fixture, headless screenshots).++**Spec:** task #2355 brief (Lead, 2026-11-03), and the mockup Scholes accepted in the project chat (2026-11-03 14:34 VN),+with "Waiting on someone" added:++```+ Machines Models Devices Swarm Backlog+ [All projects ▾] [Mine] [All states ▾] 30 tasks+ Waiting for a machine · 1+ #2347 New session starts on last project openharness · scholes+ no agent yet · waits on a Desktop engineer 5m+ Working · 9+ #2309 Sidebar task groups openharness · huy+ Thorne · Pro-9 · PR #2733 ● CI running 2m+```++## Global Constraints++- PR body first line: "Requested by [email protected] through Harness."+- Out of scope: editing or reassigning from the tab.+- Harness design language (desktop/design/desktop-design-system.md): flat list rows, two lines, color never the only+ signal, and the existing PR icon and check words.+- Groups, in this order: Waiting for a machine, Working, Waiting on someone, In review, Ready to merge, Shipped.+ "Waiting on someone" uses the same rule as Huy's sidebar groups (#2733, `superTabTaskGroupOf`): a liveness wait on a+ person. Its wording is the task line's (task_status.dart).+- Reads: only what changed since the last read. Nothing polls whole state (PRODUCT.md tech targets).+- Desktop tests use a memory store and a fake sign-in, never the real CLI.++## Design++- Growth: nothing is stored. The tab holds no state beyond its three filters, which live in memory and are not saved.+- Concurrency: N/A because it only reads the controller's snapshot on the UI thread, as the sidebar does.+- Read cost: no new Swarm read and no timer. Rows rebuild when the controller notifies, which happens on the change+ reads it already makes. CI state comes from the view's shared pull request facts, which already serve the live+ cards. The tab watches only open tasks' pull request URLs, only while it is on screen, and stops watching when it+ leaves. Those URLs are read in the facts' one batched call.+- Scale 10x: 300 tasks across 30 projects means one pass over the snapshot (grouping and sorting, linear in the+ tasks) and a lazily built list (`LaidOutListView`). The first metric to warn is the number of watched pull request+ URLs (GitHub calls per facts round). It is capped at the open tasks' pull requests, with shipped ones not watched.+- Compatibility: Desktop only. A backend without liveness or `shippedAt` still lists its tasks: the group falls back+ to the assignment's status.+- Migration + rollback: none.+- Audience: the server sends only groups the reader may read (visibleState). The tab also leaves out the lead chats,+ Buddy chats, steps (`reviewOf`) and private chats (`hiddenByBuddies`), as the sidebar does.+- Identity: N/A because nothing acts on anyone's behalf.+- Failure: no pull request facts (no `gh`, or a failed read) shows "PR #N" with no CI word, as the live cards do. A+ task in an unknown state is listed under Working with its raw status, never dropped.+- Platforms: Desktop (macOS, Linux, Windows) and the web at desktop width, where Manage exists. The phone has no+ Manage.++## Checked against ENGINEERING.md++1. Simple: one new view and one placement function, with no options. 2. Nothing left behind: no stubs; the Manage+"four tabs" test is updated. 3. Correct: each behavior has a failing test first (below). 4. Hot paths: Desktop+rendering; the list is built lazily, and the numbers are given for 300 tasks (Task 3). 5. Data: N/A, nothing stored.+6. Failures seen: a missing CI state reads as "PR #N" alone, and an unknown state is shown. 7. Secure: it reads only+what the server sends this reader. 8. Measurable: Desktop counts use only by fixed counter names that the backend's vocabulary accepts+(measurement/product_measurement.dart). A "Backlog opened" counter therefore needs a backend vocabulary change, which is+outside this task. It is left to the PM as a follow-up, and this PR adds no measure. 9. Architecture:+a shared Flutter screen, no new dependency. 10. Platforms: as above. 11. Readable: Naming System words (task, agent,+machine, pull request). 12. One pull request.++## Review Focus++1. A task moving between groups while the tab is open (a change read lands): the row moves, and the filters keep+ their values (Task 2 test).+2. A reader in many projects with no tasks: an empty state reads "No tasks", never a blank page (Task 2 test).+3. A shipped task whose agent was removed: the row still shows, with "Agent unavailable" (Task 2 test).+4. Mine when the reader asked for nothing: "No tasks you asked for", with the count 0 (Task 2 test).+5. Pull request facts unavailable: "PR #N" with no CI word, and no error (Task 2 test).++---++### Task 1: placing a task in its group, and the list of tasks++**Files:**+- Create: `desktop/lib/super_tabs/backlog.dart`+- Modify: `desktop/lib/super_tabs/controller.dart` (one getter, `groupChangedAt`)+- Test: `desktop/test/super_tab_backlog_test.dart`++**Interfaces:**+- Produces: `enum SuperTabBacklogGroup { waitingForMachine('Waiting for a machine'), working('Working'),+ waitingOnSomeone('Waiting on someone'), inReview('In review'), readyToMerge('Ready to merge'), shipped('Shipped') }`.+- Produces: `SuperTabBacklogGroup? superTabBacklogGroupOf(SuperTabConversation task)`. Null means not listed (a+ cancelled task). Precedence:+ 1. `shippedAt` set → shipped.+ 2. Status `done` → ready to merge.+ 3. Liveness `waiting`/`person`, or status `needs_human` or `blocked` → waiting on someone.+ 4. Status `review`, or liveness `waiting`/`review` or `revision` → in review.+ 5. No assignment, no agent, status `stopped` or `lost`, or liveness `waiting`/`queued` → waiting for a machine.+ 6. Anything else → working.+- Produces: `List<SuperTabConversation> superTabBacklogTasks(SuperTabController c)`. These are the tasks of every+ project, open and closed, held by the snapshot, filtered as the sidebar filters them, newest number first.+- Produces: `DateTime? SuperTabController.groupChangedAt(String groupId)`.++- [ ] **Step 1: failing tests:** `each state lands in its group` (a table of assignment, liveness and shippedAt rows+ to the expected group, including cancelled → null); `lists every readable task across projects, and no lead chat,+ Buddy chat, step or private chat`.+- [ ] **Step 2: run them and see them fail** (`flutter test test/super_tab_backlog_test.dart`).+- [ ] **Step 3: implement.**+- [ ] **Step 4: run them and see them pass.**+- [ ] **Step 5: commit** test first, then code.++### Task 2: the Backlog view and its tab++**Files:**+- Create: `desktop/lib/super_tabs/backlog_view.dart` (`SuperTabBacklogView`)+- Modify: `desktop/lib/super_tabs/manage_page.dart` (`SuperTabManageTab.backlog`, its tab after Swarm, its body, and+ an `onOpenConversation` callback)+- Modify: `desktop/lib/super_tabs/view.dart` (pass `_openConversation` and the shared pull request facts)+- Test: `desktop/test/super_tab_backlog_test.dart`, `desktop/test/super_tab_manage_page_test.dart` (five tabs)++**Interfaces:**+- Consumes: Task 1's functions.+- Produces: keys `super-manage-tab-backlog`, `super-backlog-row-<groupId>`, `super-backlog-group-<group.name>`,+ `super-backlog-project`, `super-backlog-mine` and `super-backlog-state`.++Each row shows:+- Line 1: `#N title`, then `project · requester` in the metadata style.+- Line 2: `agent · machine · PR #N <check word>`, then the task line's reason ("no agent yet" when there is none).+- Right side: the age since `groupChangedAt`.+- A group header reads `Label · count`.+- The header row shows the filters and "N tasks".++- [ ] **Step 1: failing tests:**+ - `groups in order with counts, each row its two lines`;+ - `Mine shows only the tasks the reader asked for`;+ - `the project and state filters narrow the list and the count`;+ - `a task the reader cannot read is absent` (a private group whose audience leaves the reader out);+ - `clicking a row opens its chat`;+ - Review Focus 1–5.+- [ ] **Step 2: run them and see them fail.**+- [ ] **Step 3: implement.**+- [ ] **Step 4: run them and see them pass.** Then run the manage, sidebar, activity and pull request test files, plus+ `laid_out_list_test`, and `python3 scripts/check-ui-style.py --only desktop/lib/super_tabs`.+- [ ] **Step 5: commit** test first, then code.++### Task 3: screenshots and numbers++- [ ] `desktop/test/super_tab_backlog_shots_test.dart` (`SUPER_TAB_BACKLOG_SHOTS=<dir>`): a Swarm with tasks in every+ group, all filters off, Mine on, and one project, in light and dark.+- [ ] A build-time measure: the Backlog with 300 tasks across 30 projects, the time to build its first frame and to+ rebuild after a change read, reported in the PR.+- [ ] Commit the PNGs in their own commit, link them in the PR body, and remove them in the next commit.diff --git a/docs/plans/2026-11-03-team-account-setup-lock-plan.md b/docs/plans/2026-11-03-team-account-setup-lock-plan.mdnew file mode 100644index 000000000..1a824201f--- /dev/null+++ b/docs/plans/2026-11-03-team-account-setup-lock-plan.md@@ -0,0 +1,174 @@+# Team account setup lock on join: implementation plan++> Way of working: this project's Engineer role (project instructions). Plan first, then each task test first: its+> failing test in one commit, the code that passes it in the next. No per-task review; the pull request's Review step is+> the one independent review.++**Goal:** On Desktop, when this Mac joins a Swarm project (or is added to one), the Harness Team account setup window+opens at once over the whole app and stays until setup succeeds. A wrong password says so and allows a retry.++**Architecture:** `AppNotifier` keeps which Swarms this Mac joined that still wait on its Team account. It stores them+on this computer so that a restart locks again, and clears them once this Mac's daemon reports the account `exists`.+`TeamAccountSetupLock` wraps the whole window above the Navigator, in `MaterialApp.builder`. While locked it covers+every route and dialog with a barrier, excludes them from focus, pointer and semantics, and shows the explanation from+`team_account_setup.dart`. It drives the same daemon actions as today (`teamSetupCheck`, `teamSetup` `manual`,+`teamSetupStatus`). The password is asked only by the system's own prompt (macOS `osascript`, polkit, UAC).++**Tech Stack:** Flutter 3.47.2 (desktop/), flutter_test widget tests. No CLI or backend change.++**Spec:** task #2418 brief, as changed by the PM in the task's thread on 2026-11-03 (Scholes's ask). The prompt opens on+join and blocks the whole app until setup succeeds; there is no banner and no dismiss. Phone and web stay as they are.+Only where setup can never finish here, the window says why and offers "Remove this Mac from the Swarm", never a plain+close.++## Global Constraints++- The password is never collected or stored by Harness; the system's own prompt only (cli/src/team/admin.ts).+- Desktop only: `AppNotifier.teamAccountOn` systems (macOS, Linux, Windows). The web build and the phone app never lock.+- Tests never sign this Mac out of the real CLI; they use `createApp` with a fake daemon connection and a memory store.+- No CLI change (Swarm code stays out of cli/src/core); no backend change.+- PR body first line: "Requested by [email protected] through Harness."+- Copy follows docs/naming-system.md: "Harness Team", "this Mac" / "this computer", "Swarm".++## Design (feature design rules)++- growth: one small list of Swarm ids per account on this computer; cleared when the account exists, or when this Mac is+ removed from those Swarms.+- concurrency: N/A because it is one in-process list on the UI isolate; joins add with set semantics.+- read cost: one local file read at connect. While the system prompt is open, this Mac's own daemon is asked for its+ status every 2 s. That stops once setup ends, and after the prompt's own 15-minute limit. Nothing reads the server.+- scale: N/A because the list holds one entry per Swarm joined at this computer.+- compatibility: an older daemon without `teamSetupCheck` answers an error. Nothing locks then, as today. Without+ `teamSetupStatus` the window keeps "macOS is asking…" and Try again.+- migration + rollback: no migration. Rolling back the app drops the lock; the stored list is ignored by older builds.+- audience: the lock follows only this computer's own daemon and this account; the server already decides what a+ machine without a Team account may run.+- identity: N/A because the setup runs as this Mac's own person, through the existing daemon action.+- failure: every end state says why (cancelled, password not accepted, failed with the daemon's detail, cannot set up+ here, Harness unreachable), with Try again or the one way out.+- platforms: macOS, Linux, Windows Desktop. Not web, not the phone.++## Review Focus++- A dialog or menu opened before the lock, or by a native menu item while locked: it must sit under the barrier and take+ no key or click. Covered by task 2's dialog-behind test.+- The ⌘⌥ keys that answer the daemon's line go through a global keyboard handler, not focus. While locked they must do+ nothing. Covered by task 3.+- Quitting and reopening during the lock: it locks again until the account exists. Covered by task 1's restart test.+- The person cancels macOS's prompt, or is not an administrator: Try again, plus the one way out. Covered by task 2.+- A second join while locked: one window, not two. Covered by task 1 ("once").++---++### Task 1: AppNotifier knows when this Mac must finish its Team account++**Files:**+- Modify: `desktop/lib/state/app_state.dart` (`offerTeamAccount`, `addMachineOnJoin`, the start offer)+- Test: `desktop/test/team_account_offer_test.dart`++**Interfaces:**+- Produces:+ - `bool get teamSetupLocked`: true while this Mac's own Team account is wanted for a Swarm it joined or was added to.+ - `Future<void> teamAccountMade()`: clears the lock and its stored list.+ - `Future<String?> removeLockedMachine()`: removes this Mac (`machine.remove`) from each Swarm the lock is for. Returns+ null when done, otherwise the Swarm's own sentence.+ - `offerTeamAccount('join' | 'contribute', tabId:)`: the daemon's check. `wanted`, `declined`, `waiting`, `running` or+ `no-prompt` locks (a cancel remembered from before does not let a new join through). `exists` and the rest do not.+ `startup` keeps today's dismissible explanation (`teamSetupAsks`), and never while locked.+ - Storage key `team_setup_lock.<accountId>`: a JSON list of Swarm ids.++- [ ] Step 1: failing tests:+ - `a join locks once, though asked twice` (two offers for the same Swarm and one for another give+ `teamSetupLocked == true` and no `teamSetupAsks` event).+ - `a join on a Mac with the account does not lock` (`exists`).+ - `a cancel remembered from before still locks a new join` (`declined`).+ - `the lock comes back after a restart until the account exists`: a new `AppNotifier` on the same memory store locks+ on connect when `teamSetupStatus` says `none`, and not when it says `exists`.+ - `teamAccountMade clears it`.+ - `removing this Mac from the Swarm clears it` (`machine.remove` sent for this Mac's id).+- [ ] Step 2: run `flutter test test/team_account_offer_test.dart`; expect FAIL (no `teamSetupLocked`).+- [ ] Step 3: implement in app_state.dart.+- [ ] Step 4: run the file; expect PASS.+- [ ] Step 5: commit.++### Task 2: the lock window over the whole app++**Files:**+- Modify: `desktop/lib/super_tabs/team_account_setup.dart` (add `TeamAccountSetupLock`; `_Words` gains the lock's+ sentences)+- Modify: `desktop/lib/app_shell.dart` (`MaterialApp.builder` wraps in the lock)+- Test: `desktop/test/team_account_lock_test.dart`++**Interfaces:**+- Consumes: task 1's `teamSetupLocked`, `teamAccountMade`, `removeLockedMachine`; existing `setUpTeamAccount`,+ `teamSetupStatus`.+- Produces: `TeamAccountSetupLock({required AppNotifier app, required Widget child, String? operatingSystem})`.+ Keys: `team-account-lock`, `team-account-lock-continue`, `team-account-lock-retry`, `team-account-lock-remove`,+ `team-account-lock-outcome`.++Window states and copy (Mac words; Linux and Windows use the existing "this computer" words):+- intro: today's title and three paragraphs; one button, Continue.+- waiting: today's `started` sentence, with a progress indicator; it asks this Mac's daemon every 2 s. `exists` closes+ the window (`teamAccountMade`); `failed`, `declined` or `none` after a run end it.+- password not accepted (failed, detail matching `-60005`, `incorrect` or `password`): "macOS did not accept that+ password. Try again." Try again.+- failed (other detail): "Setup did not finish: <detail>." Try again.+- cancelled (`declined`): "The password window was closed before setup finished." Try again. Then "No administrator+ password for this Mac? Remove it from the Swarm; you can add it again from Machines." and Remove this Mac from the+ Swarm.+- cannot here (`update`, `unsupported`, `no-prompt`): today's sentence. Remove this Mac from the Swarm only.+- unreachable: today's sentence. Try again.++- [ ] Step 1: failing tests:+ - `locked, nothing behind it takes a click, a key or focus`: a button, a text field and a CallbackShortcuts under the+ lock, and a dialog route pushed before it, take no tap, no Tab focus and no shortcut. `Semantics` behind it are+ excluded.+ - `there is no way to close it`: Escape and a barrier tap leave it, and it has no Cancel or Not now.+ - `Continue starts setup and success closes it` (`teamSetup` `manual`, then status `running`, then `exists`).+ - `a wrong password says so and Try again asks again`: status `failed` with -60005 detail shows the sentence, and Try+ again sends a second `teamSetup`.+ - `a cancel offers Try again and the one way out`; `cannot set up here offers only the way out`, and Remove closes it+ (sends `machine.remove`).+ - `unlocked, it is not there` (the child is reachable).+- [ ] Step 2: run; expect FAIL (no `TeamAccountSetupLock`).+- [ ] Step 3: implement. A `Stack`: the child in `ExcludeFocus` while locked; a non-dismissible `ModalBarrier`, which+ itself takes every pointer event and hides the app from a screen reader (an `IgnorePointer` and `ExcludeSemantics`+ around the child added nothing a test could see, so they were left out); the panel in a `FocusScope` with+ autofocus. The panel has no `Tooltip`+ (there is no Overlay above the Navigator). In app_shell.dart, `builder` wraps `framed` in the lock, reading the app+ through `Consumer`.+- [ ] Step 4: run the lock file and team_account_offer_test.dart; expect PASS.+- [ ] Step 5: commit.++### Task 3: global keys and the old dialog while locked++**Files:**+- Modify: `desktop/lib/screens/swarm_screen.dart` (`_noteKey`, the `teamSetupAsks` listener)+- Test: `desktop/test/team_account_lock_test.dart`++- [ ] Step 1: failing test `the daemon line's ⌘⌥ keys do nothing while locked`: a `SwarmScreen` key handler test with+ the app locked. If pumping SwarmScreen is too heavy, test an extracted `bool swarmKeysHeld(AppNotifier app)` that+ `_noteKey` returns early on.+- [ ] Step 2: run; expect FAIL.+- [ ] Step 3: `_noteKey` returns false at once while `app.teamSetupLocked`. The start explanation is not shown while+ locked.+- [ ] Step 4: run; expect PASS.+- [ ] Step 5: commit.++### Task 3b (review of #2779): the menu bar, the tab row, and Swarms that let this Mac go++- The lock is a `modal` titlebar cover in swarm_screen.dart (menus, key equivalents and the tab row grey out);+ `_onNative` and app_shell.dart's `runAppMenuAction` drop what arrives anyway. Tests: native_toolbar_sync_test.dart+ and the app-menu half of the lock test's shell case.+- On restore and before each Remove, a Swarm that no longer lists this Mac, is already removing it, or can no longer+ be opened is let go (`_swarmHolds`); one that cannot be read now keeps the lock. Tests: team_account_offer_test.dart.+- One headless walk of the Done when: join, the window at once, Tab, arrows, Escape and a click held, a wrong password,+ Try again, success, and Machines opened again without the paused line.++### Task 4: screenshots and the suite++- [ ] Light and dark screenshots of the lock (intro, waiting, password not accepted, cancelled) from a golden-style+ capture test run locally, committed for the PR, then removed in the next commit (pr-screenshots-via-commit).+- [ ] `flutter analyze`; `flutter test` for the touched files plus `super_tab_team_machine_test.dart`,+ `super_tab_add_computers_test.dart`, and the app_shell tests; then the whole desktop suite.+- [ ] Red/green evidence in a PR comment.