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
Phone: invite people and revoke invitations, as Desktop's Share Swarm (Tony, task 9) (#2480)
harness-for-autonomous[bot]d4cc91df09be
diff --git a/mobile/lib/logging/redact.dart b/mobile/lib/logging/redact.dartindex e6d428801..ffc342e50 100644--- a/mobile/lib/logging/redact.dart+++ b/mobile/lib/logging/redact.dart@@ -42,7 +42,10 @@ String summariseForLog(Object? value, {int maxLength = 1200}) {return text.length <= maxLength ? text : '${text.substring(0, maxLength)}…';}-/// [value] rendered for a log, with any entry whose KEY looks secret replaced.+/// [value] rendered for a log, with any entry whose KEY looks secret replaced,+/// and any secret a value's TEXT carries blanked ([redactSecretsInText]): a+/// field named for what it is, not for the secret in it — a Swarm's `joinUrl`+/// with its `?token=` — is caught by its text.////// Recurses into maps and lists so a secret nested a level or two down is/// caught too.@@ -68,7 +71,9 @@ String redactValue(Object? value) {// frames) and printing it whole turns one line into a page.return '[${value.length} item${value.length == 1 ? '' : 's'}]';}- final text = '$value';+ // Blanked before it is clipped: a clip that cuts a `Bearer` token to fewer+ // characters than its rule needs would keep that start on disk.+ final text = redactSecretsInText('$value');return text.length <= _maxValue ? text : '${text.substring(0, _maxValue)}…';}diff --git a/mobile/lib/swarm/swarm_invites.dart b/mobile/lib/swarm/swarm_invites.dartnew file mode 100644index 000000000..99ad88856--- /dev/null+++ b/mobile/lib/swarm/swarm_invites.dart@@ -0,0 +1,307 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import 'model.dart';+import 'swarm_reader.dart';+import 'swarm_request.dart';+import 'swarm_session.dart';++/// The access an invitation gives, in the desktop's words+/// (`desktop/lib/super_tabs/sharing.dart`).+const swarmInviteRoles = <(String, String)>[+ ('collaborator', 'Can collaborate'),+ ('viewer', 'Can view'),+];++String swarmInviteRoleName(String role) =>+ role == 'viewer' ? 'Can view' : 'Can collaborate';++/// The address the desktop takes before it sends an invitation; the backend+/// takes up to 320 characters (commands.ts `invite.create`).+final swarmInviteEmail = RegExp(r'^[^\s@]+@[^\s@]+\.[^\s@]+$');+const swarmInviteEmailMax = 320;++/// Whether the person reading [reader] may invite people to its Swarm and+/// revoke their invitations: its owner alone, as on the desktop, which shows+/// Invite and Revoke only to them — and the backend lists invitations only to+/// them (model.ts). Nobody may once the read is taken away.+bool swarmMayInvite(SwarmReader? reader) {+ if (reader == null || reader.accessRevoked) return false;+ final owner = reader.snapshot?.ownerId;+ return owner != null && owner.isNotEmpty && owner == reader.accountId;+}++/// One invitation waiting to be accepted, as the Swarm's owner reads it.+/// Accepted or revoked, it leaves the Swarm's list (commands.ts).+class SwarmPendingInvite {+ const SwarmPendingInvite({+ required this.id,+ required this.email,+ required this.role,+ required this.expiresAt,+ });++ final String id, email, role;+ final DateTime expiresAt;++ /// [row] of a Swarm's invitations; null when it is not one.+ static SwarmPendingInvite? read(Map<String, dynamic> row) {+ if (row+ case {+ 'id': final String id,+ 'email': final String email,+ 'role': final String role,+ 'expiresAt': final num expiresAt,+ }+ when id.isNotEmpty &&+ email.contains('@') &&+ swarmInviteRoles.any((r) => r.$1 == role)) {+ return SwarmPendingInvite(+ id: id,+ email: email,+ role: role,+ expiresAt: DateTime.fromMillisecondsSinceEpoch(+ expiresAt.toInt(),+ isUtc: true,+ ),+ );+ }+ return null;+ }++ bool expired(DateTime now) => !expiresAt.isAfter(now);+}++/// The invitations [snapshot] holds, in the Swarm's order.+List<SwarmPendingInvite> swarmPendingInvites(SuperTabSnapshot snapshot) => [+ for (final row in snapshot.invitations) ?SwarmPendingInvite.read(row),+];++/// "Can view · Expires in 6 days", or "· Expired" once it can no longer be+/// accepted (an hourly sweep then takes it away).+String swarmInviteDetail(SwarmPendingInvite invite, DateTime now) {+ final left = invite.expiresAt.difference(now);+ final when = left <= Duration.zero+ ? 'Expired'+ : left.inDays >= 1+ ? 'Expires in ${_count(left.inDays + (left.inHours % 24 >= 12 ? 1 : 0), 'day')}'+ : left.inHours >= 1+ ? 'Expires in ${_count(left.inHours, 'hour')}'+ : 'Expires soon';+ return '${swarmInviteRoleName(invite.role)} · $when';+}++String _count(int n, String unit) => '$n $unit${n == 1 ? '' : 's'}';++/// What the person sends with the share sheet for [invite]: it carries no+/// link or secret. The invitation waits in the invited account's own app,+/// as the desktop's does.+String swarmInviteNote(String swarmName, SwarmPendingInvite invite) =>+ 'I invited you to $swarmName in Harness. Open Harness signed in as '+ '${invite.email} to accept.';++/// [value] as Swarm [tabId]'s join link (`harness://swarm/join/<id>`, with+/// its token when the link has one), or null when it is anything else: the+/// desktop's `SwarmJoinLink.parse`, and its check that the link is this+/// Swarm's.+String? swarmJoinUrl(Object? value, String tabId) {+ if (value is! String || value.length > 240) return null;+ final uri = Uri.tryParse(value);+ if (uri == null ||+ uri.scheme != 'harness' ||+ uri.host != 'swarm' ||+ uri.hasPort ||+ uri.userInfo.isNotEmpty ||+ uri.hasFragment ||+ uri.pathSegments.length != 2 ||+ uri.pathSegments.first != 'join' ||+ uri.pathSegments.last != tabId ||+ !RegExp(r'^[A-Za-z0-9_-]{1,160}$').hasMatch(tabId)) {+ return null;+ }+ final query = uri.queryParametersAll;+ if (query.isEmpty && !uri.hasQuery) return value;+ final tokens = query['token'];+ if (query.length != 1 ||+ tokens == null ||+ tokens.length != 1 ||+ !RegExp(r'^[A-Za-z0-9_-]{43}$').hasMatch(tokens.single)) {+ return null;+ }+ return value;+}++/// The Swarm owner's invitations from the phone, over one read of the Swarm+/// ([reader]): invite someone by email (`invite.create`), revoke an+/// invitation (`invite.revoke`), and the Swarm's join link when its general+/// access has one — the desktop's Share Swarm, without changing the general+/// access, which stays on the desktop.+///+/// Each command goes under one receipt. An answer that never came keeps it,+/// and nothing else is sent until [check] sends it again: a retry is the same+/// invitation, never a second one. Nothing is sent, and no late answer is+/// taken, once the read is replaced, taken away or no longer the owner's+/// ([live]); the join link is held in memory only while this is.+class SwarmInvites extends ChangeNotifier {+ SwarmInvites({required this.session, required this.reader});++ final SwarmSession session;+ final SwarmReader reader;++ bool _disposed = false;++ /// What was sent and not yet answered either way.+ ({String operationId, Map<String, dynamic> command})? _pending;++ /// A command's answer is awaited.+ bool sending = false;++ /// Why the last command did not go through, as a sentence.+ String? error;++ /// The Swarm's join link, when its general access has one.+ String? link;++ /// The link is being read, or could not be: neither is "no link".+ bool readingLink = false, linkFailed = false;+ int _linkReads = 0;++ String get _path => '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}';++ /// The read this was made over is still the session's, readable, and its+ /// person still the Swarm's owner.+ bool get live =>+ !_disposed &&+ identical(session.inbox.reader(reader.tabId), reader) &&+ swarmMayInvite(reader);++ /// A command is on its way or unconfirmed: nothing else is sent.+ bool get busy => sending || _pending != null;++ /// A command was sent and its answer never came.+ bool get unconfirmed => _pending != null && !sending;++ /// Invites [email] with [role]. True once the backend took it.+ Future<bool> invite(String email, String role) => _send({+ 'type': 'invite.create',+ 'email': email.trim(),+ 'role': role,+ // As the desktop sends it: an invitation lands in the Swarm, not in a+ // chat, and the backend keeps this legacy landing (commands.ts).+ 'conversationId': 'lead',+ });++ /// Revokes [invite], unless it already left the list (accepted or revoked+ /// meanwhile): there is nothing to revoke then.+ Future<bool> revoke(SwarmPendingInvite invite) {+ final snapshot = reader.snapshot;+ if (snapshot == null ||+ !swarmPendingInvites(snapshot).any((i) => i.id == invite.id)) {+ return Future.value(false);+ }+ return _send({'type': 'invite.revoke', 'inviteId': invite.id});+ }++ /// Sends the unconfirmed command again under its receipt.+ Future<bool> check() => _pending == null ? Future.value(false) : _send(null);++ Future<bool> _send(Map<String, dynamic>? command) async {+ if (!live || sending || (command != null && _pending != null)) {+ return false;+ }+ final pending = _pending ??= (+ operationId: superTabOperationId(),+ command: command!,+ );+ sending = true;+ error = null;+ notifyListeners();+ try {+ await reader.request(+ 'POST',+ '$_path/commands',+ body: {'operationId': pending.operationId, 'command': pending.command},+ );+ if (!live) return false;+ _pending = null;+ unawaited(reader.refresh());+ return true;+ } on SuperTabFailure catch (failure) {+ if (!live) return false;+ if (_refused(failure)) {+ _pending = null;+ error = _why(failure, pending.command['type']);+ } else {+ error = _unconfirmed(pending.command['type']);+ }+ return false;+ } catch (_) {+ if (live) error = _unconfirmed(pending.command['type']);+ return false;+ } finally {+ if (!_disposed) {+ sending = false;+ notifyListeners();+ }+ }+ }++ /// The backend answered and said no: the command did not run. No answer,+ /// a server fault, a timeout or a rate limit leaves it unknown.+ static bool _refused(SuperTabFailure failure) =>+ failure.statusCode >= 400 &&+ failure.statusCode < 500 &&+ !const {408, 429}.contains(failure.statusCode);++ static String _unconfirmed(Object? type) => type == 'invite.revoke'+ ? 'Could not confirm the revoke. Check it again.'+ : 'Could not confirm this invitation. Check it again.';++ static String _why(SuperTabFailure failure, Object? type) =>+ switch (failure.code) {+ 'OWNER_REQUIRED' ||+ 'FORBIDDEN' => 'Only the Swarm’s owner can manage invitations.',+ 'ALREADY_MEMBER' => 'This person is already in this Swarm.',+ // A server without these commands. Any other refusal, an address it+ // will not take included, is the server's own words.+ 'UNKNOWN_COMMAND' =>+ type == 'invite.revoke'+ ? 'This Swarm’s server can’t revoke invitations from here.'+ : 'This Swarm’s server can’t send invitations from here.',+ _ => failure.message,+ };++ /// Reads the Swarm's join link. A server without sharing links has none;+ /// a read that fails says so, and is tried again only when asked.+ Future<void> readLink() async {+ if (!live) return;+ final read = ++_linkReads;+ readingLink = true;+ linkFailed = false;+ notifyListeners();+ String? found;+ var failed = false;+ try {+ final answer = superTabMap(await reader.request('GET', '$_path/sharing'));+ found = swarmJoinUrl(answer['joinUrl'], reader.tabId);+ } on SuperTabFailure catch (failure) {+ failed = failure.statusCode != 404 && failure.code != 'NOT_FOUND';+ } catch (_) {+ failed = true;+ }+ if (!live || read != _linkReads) return;+ link = found;+ linkFailed = failed;+ readingLink = false;+ notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ link = null;+ _pending = null;+ super.dispose();+ }+}diff --git a/mobile/lib/swarm/swarm_invites_sheet.dart b/mobile/lib/swarm/swarm_invites_sheet.dartnew file mode 100644index 000000000..05e661dea--- /dev/null+++ b/mobile/lib/swarm/swarm_invites_sheet.dart@@ -0,0 +1,536 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:share_plus/share_plus.dart';++import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'swarm_invites.dart';+import 'swarm_leaderboard.dart' show SwarmProjectSheetFrame, swarmSheetRoute;+import 'swarm_reader.dart';+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';++/// Hands [text] to the phone's share sheet, anchored at [origin] for an iPad,+/// where it is a popover.+typedef SwarmShare = Future<void> Function(String text, {Rect? origin});++Future<void> swarmShareSheet(String text, {Rect? origin}) async {+ try {+ await SharePlus.instance.share(+ ShareParams(text: text, sharePositionOrigin: origin),+ );+ } catch (_) {+ // No share sheet came up: the person can press Share again.+ }+}++/// Invite people, as the desktop's Humans board has it: shown only to the+/// Swarm's owner, the one person who may invite there ([swarmMayInvite]), and+/// gone as soon as they no longer may. It opens [SwarmInvitesSheet] over+/// [reader], once at a time.+class SwarmInviteButton extends StatefulWidget {+ const SwarmInviteButton({+ super.key,+ required this.session,+ required this.reader,+ this.share = swarmShareSheet,+ });++ final SwarmSession session;+ final SwarmReader reader;+ final SwarmShare share;++ @override+ State<SwarmInviteButton> createState() => _SwarmInviteButtonState();+}++class _SwarmInviteButtonState extends State<SwarmInviteButton> {+ ModalRoute<void>? _open;++ Future<void> _show() async {+ if (_open != null || !swarmMayInvite(widget.reader)) return;+ final route = swarmSheetRoute<void>(+ context,+ builder: (_) => SwarmInvitesSheet(+ session: widget.session,+ reader: widget.reader,+ share: widget.share,+ ),+ );+ _open = route;+ await Navigator.of(context).push(route);+ if (identical(_open, route)) _open = null;+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: widget.reader,+ builder: (context, _) => swarmMayInvite(widget.reader)+ ? SwarmIconButton(+ key: const ValueKey('swarm-invite-people'),+ icon: LucideIcons.userPlus300,+ label: 'Invite people',+ onPressed: () => unawaited(_show()),+ )+ : const SizedBox.shrink(),+ );+}++/// The Swarm owner's Share Swarm on the phone, from the leaderboard's Invite+/// people:+/// the desktop's (`desktop/lib/super_tabs/sharing.dart`) email, access and+/// Invite; the invitations waiting, each with its access and when it expires,+/// to share a note about or revoke, after a confirmation; and the Swarm's+/// join link to share, when its general access has one.+///+/// It closes, keeping nothing typed or read, once the account's session, the+/// Swarm's read, or the person's being its owner is gone.+class SwarmInvitesSheet extends StatefulWidget {+ const SwarmInvitesSheet({+ super.key,+ required this.session,+ required this.reader,+ this.share = swarmShareSheet,+ this.now = DateTime.now,+ });++ final SwarmSession session;++ /// The Swarm's read as the sheet opened: one replaced since is another+ /// read, and the sheet goes rather than send through either.+ final SwarmReader reader;+ final SwarmShare share;+ final DateTime Function() now;++ @override+ State<SwarmInvitesSheet> createState() => _SwarmInvitesSheetState();+}++class _SwarmInvitesSheetState extends State<SwarmInvitesSheet> {+ final _email = TextEditingController();+ String _role = 'collaborator';+ String? _emailError;+ late final SwarmInvites _invites;+ bool _closing = false;++ /// The confirmation up over the sheet, if any: it goes with the sheet.+ ModalRoute<void>? _confirm;++ @override+ void initState() {+ super.initState();+ _invites = SwarmInvites(session: widget.session, reader: widget.reader);+ _email.addListener(_edited);+ if (_invites.live) unawaited(_invites.readLink());+ }++ void _edited() {+ if (mounted) setState(() {});+ }++ @override+ void dispose() {+ _email.dispose();+ _invites.dispose();+ super.dispose();+ }++ /// Closes the sheet once, after the frame it went blank in, with the+ /// confirmation over it.+ void _close() {+ if (_closing) return;+ _closing = true;+ // What was typed goes with it, without drawing again mid-frame.+ _email+ ..removeListener(_edited)+ ..clear();+ final confirm = _confirm;+ _confirm = null;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (confirm != null && confirm.isActive) {+ confirm.navigator?.removeRoute(confirm);+ }+ if (!mounted) return;+ final route = ModalRoute.of(context);+ if (route == null || !route.isActive) return;+ if (route.isCurrent) {+ Navigator.of(context).pop();+ } else {+ Navigator.of(context).removeRoute(route);+ }+ });+ }++ Future<void> _invite() async {+ if (_invites.busy || !_invites.live) return;+ final email = _email.text.trim();+ if (!swarmInviteEmail.hasMatch(email)) {+ setState(() => _emailError = 'Enter an email address.');+ return;+ }+ setState(() => _emailError = null);+ final sent = await _invites.invite(email, _role);+ // Typed over meanwhile: what was typed since stays.+ if (sent && mounted && !_closing && _email.text.trim() == email) {+ _email.clear();+ }+ }++ Future<void> _revoke(SwarmPendingInvite invite) async {+ if (_invites.busy || !_invites.live) return;+ final route = DialogRoute<bool>(+ context: context,+ builder: (context) => AlertDialog(+ title: Text(+ 'Revoke invitation?',+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ content: Text(+ '${invite.email} will no longer be able to join with it.',+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ actions: [+ SwarmButton(+ key: const ValueKey('swarm-invite-revoke-cancel'),+ label: 'Cancel',+ style: SwarmButtonStyle.link,+ onPressed: () => Navigator.of(context).pop(false),+ ),+ SwarmButton(+ key: const ValueKey('swarm-invite-revoke-confirm'),+ label: 'Revoke',+ style: SwarmButtonStyle.fill,+ onPressed: () => Navigator.of(context).pop(true),+ ),+ ],+ ),+ );+ _confirm = route;+ final revoke = await Navigator.of(context).push(route);+ if (identical(_confirm, route)) _confirm = null;+ // Gone while it asked: nothing is sent.+ if (revoke != true || !mounted || _closing) return;+ await _invites.revoke(invite);+ }++ Rect? _origin(BuildContext context) {+ final box = context.findRenderObject() as RenderBox?;+ return box == null || !box.attached+ ? null+ : box.localToGlobal(Offset.zero) & box.size;+ }++ void _share(BuildContext context, String text) {+ if (!_invites.live) return;+ unawaited(widget.share(text, origin: _origin(context)));+ }++ Future<void> _pickRole() async {+ final role = await showModalBottomSheet<String>(+ context: context,+ backgroundColor: AppGlass.rowFill,+ shape: AppControl.sheetShape,+ showDragHandle: true,+ builder: (context) => SafeArea(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.m,+ 0,+ AppSpace.m,+ AppSpace.m,+ ),+ child: SwarmGroup(+ children: [+ for (final (value, label) in swarmInviteRoles)+ SwarmRow(+ key: ValueKey('swarm-invite-role-$value'),+ title: label,+ trailing: value == _role+ ? Icon(+ LucideIcons.check300,+ size: 18,+ color: AppPalette.swarmAccent,+ )+ : const SizedBox.shrink(),+ onTap: () => Navigator.of(context).pop(value),+ ),+ ],+ ),+ ),+ ),+ );+ if (role != null && mounted && !_closing) setState(() => _role = role);+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final session = widget.session;+ return ListenableBuilder(+ listenable: Listenable.merge([session.inbox, widget.reader, _invites]),+ builder: (context, _) {+ // Signed out, another account, Swarm off, the read replaced or taken+ // away, or the person no longer the Swarm's owner: nothing of it+ // stays, and the sheet goes.+ if (_closing || SwarmScope.of(context) != session || !_invites.live) {+ _close();+ return const SizedBox.shrink();+ }+ final snapshot = widget.reader.snapshot!;+ final now = widget.now();+ final invites = swarmPendingInvites(snapshot);+ final busy = _invites.busy;+ final field = InputDecoration(+ hintText: 'Email address',+ hintStyle: TextStyle(color: AppPalette.textFaint),+ filled: true,+ fillColor: AppPalette.swarmField,+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(AppControl.radius),+ borderSide: BorderSide.none,+ ),+ );+ return SwarmProjectSheetFrame(+ title: 'Share Swarm',+ closeKey: 'swarm-invites-close',+ child: ListView(+ key: const ValueKey('swarm-invites'),+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ AppSpace.s,+ AppSpace.m,+ MediaQuery.viewInsetsOf(context).bottom ++ MediaQuery.paddingOf(context).bottom ++ AppSpace.xl,+ ),+ children: [+ TextField(+ key: const ValueKey('swarm-invite-email'),+ controller: _email,+ enabled: !busy,+ autocorrect: false,+ enableSuggestions: false,+ keyboardType: TextInputType.emailAddress,+ textInputAction: TextInputAction.send,+ inputFormatters: [+ LengthLimitingTextInputFormatter(swarmInviteEmailMax),+ ],+ onSubmitted: (_) => unawaited(_invite()),+ style: AppType.body(color: AppPalette.textPrimary),+ decoration: field,+ ),+ if (_emailError case final error?)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ AppSpace.xs,+ AppSpace.xs,+ 0,+ ),+ child: SwarmRow.line(+ error,+ key: const ValueKey('swarm-invite-email-error'),+ color: AppColors.danger,+ ),+ ),+ const SizedBox(height: AppSpace.s),+ Row(+ children: [+ SwarmButton(+ key: const ValueKey('swarm-invite-role'),+ label: swarmInviteRoleName(_role),+ style: SwarmButtonStyle.link,+ icon: LucideIcons.chevronDown300,+ onPressed: busy ? null : () => unawaited(_pickRole()),+ ),+ const Spacer(),+ SwarmButton(+ key: const ValueKey('swarm-invite-send'),+ label: 'Invite',+ style: SwarmButtonStyle.fill,+ busy: _invites.sending,+ busyLabel: 'Sending…',+ onPressed: busy || _email.text.trim().isEmpty+ ? null+ : () => unawaited(_invite()),+ ),+ ],+ ),+ if (_invites.error case final error?)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ AppSpace.s,+ AppSpace.xs,+ 0,+ ),+ child: SwarmRow.line(+ error,+ key: const ValueKey('swarm-invite-error'),+ lines: 3,+ ),+ ),+ if (_invites.unconfirmed)+ Align(+ alignment: Alignment.centerLeft,+ child: SwarmButton(+ key: const ValueKey('swarm-invite-check'),+ label: 'Check pending invitation',+ style: SwarmButtonStyle.link,+ onPressed: () => unawaited(_invites.check()),+ ),+ ),+ SwarmCaption(+ 'Invited',+ key: const ValueKey('swarm-invites-caption'),+ ),+ if (invites.isEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: SwarmRow.line(+ 'No invitations waiting.',+ key: const ValueKey('swarm-invites-none'),+ ),+ )+ else+ SwarmGroup(+ children: [+ for (final invite in invites)+ _InviteRow(+ key: ValueKey('swarm-invite-${invite.id}'),+ invite: invite,+ detail: swarmInviteDetail(invite, now),+ expired: invite.expired(now),+ busy: busy,+ onShare: (context) => _share(+ context,+ swarmInviteNote(snapshot.name, invite),+ ),+ onRevoke: () => unawaited(_revoke(invite)),+ ),+ ],+ ),+ ..._link(context),+ ],+ ),+ );+ },+ );+ }++ /// The Swarm's join link, to share, when its general access has one; why+ /// it could not be read, with Try again. Nothing while it is read, and+ /// nothing when there is none: the general access is set on the desktop.+ List<Widget> _link(BuildContext context) {+ if (_invites.link case final link?) {+ return [+ const SizedBox(height: AppSpace.l),+ Builder(+ builder: (context) => Align(+ alignment: Alignment.centerLeft,+ child: SwarmButton(+ key: const ValueKey('swarm-invite-share-link'),+ label: 'Share link',+ icon: LucideIcons.link2300,+ onPressed: _invites.busy ? null : () => _share(context, link),+ ),+ ),+ ),+ ];+ }+ if (_invites.linkFailed && !_invites.readingLink) {+ return [+ const SizedBox(height: AppSpace.l),+ Row(+ children: [+ Expanded(+ child: SwarmRow.line(+ 'Could not read this Swarm’s link.',+ key: const ValueKey('swarm-invite-link-error'),+ lines: 2,+ ),+ ),+ SwarmButton(+ key: const ValueKey('swarm-invite-link-retry'),+ label: 'Try again',+ onPressed: () => unawaited(_invites.readLink()),+ ),+ ],+ ),+ ];+ }+ return const [];+ }+}++/// One invitation waiting: the address over its access and when it expires,+/// then Share and Revoke.+class _InviteRow extends StatelessWidget {+ const _InviteRow({+ super.key,+ required this.invite,+ required this.detail,+ required this.expired,+ required this.busy,+ required this.onShare,+ required this.onRevoke,+ });++ final SwarmPendingInvite invite;+ final String detail;+ final bool expired, busy;+ final void Function(BuildContext context) onShare;+ final VoidCallback onRevoke;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.fromLTRB(AppSpace.l, AppSpace.m, 0, AppSpace.m),+ child: Row(+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ invite.email,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.label(color: AppPalette.textPrimary),+ ),+ const SizedBox(height: 2),+ SwarmRow.line(+ detail,+ key: ValueKey('swarm-invite-detail-${invite.id}'),+ color: expired ? AppColors.danger : null,+ ),+ ],+ ),+ ),+ // An expired invitation can no longer be accepted: nothing to tell.+ if (!expired)+ Builder(+ builder: (context) => SwarmButton(+ key: ValueKey('swarm-invite-share-${invite.id}'),+ label: 'Share',+ style: SwarmButtonStyle.link,+ onPressed: busy ? null : () => onShare(context),+ ),+ ),+ SwarmButton(+ key: ValueKey('swarm-invite-revoke-${invite.id}'),+ label: 'Revoke',+ style: SwarmButtonStyle.link,+ onPressed: busy ? null : onRevoke,+ ),+ ],+ ),+ );+}diff --git a/mobile/lib/swarm/swarm_leaderboard.dart b/mobile/lib/swarm/swarm_leaderboard.dartindex 36639b410..c9c1e08c3 100644--- a/mobile/lib/swarm/swarm_leaderboard.dart+++ b/mobile/lib/swarm/swarm_leaderboard.dart@@ -13,6 +13,7 @@ import 'package:harness_mobile/shared/widgets/skeleton.dart';import 'package:harness_mobile/shared/widgets/touch_target.dart';import 'identity.dart';+import 'swarm_invites_sheet.dart';import 'model.dart';import 'swarm_leaderboard_reader.dart';import 'swarm_reader.dart';@@ -389,6 +390,7 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {),title: 'Leaderboard',subtitle: project?.name,+ trailing: _inviteButton(),),Expanded(child: board),],@@ -409,11 +411,17 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {return SwarmProjectSheetFrame(title: 'Leaderboard',closeKey: 'swarm-leaderboard-close',- trailing: _WeekButton(- label: swarmWeekName(reader?.week, current),- onTap: reader == null- ? null- : () => unawaited(_pickWeek(context, reader, current)),+ trailing: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ ?_inviteButton(),+ _WeekButton(+ label: swarmWeekName(reader?.week, current),+ onTap: reader == null+ ? null+ : () => unawaited(_pickWeek(context, reader, current)),+ ),+ ],),child: RefreshIndicator(// The Swarm names its people, and the board scores them.@@ -636,6 +644,14 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {);}+ /// Invite people beside the people, as on the desktop's Humans board: it+ /// shows only to the Swarm's owner ([SwarmInviteButton]).+ Widget? _inviteButton() {+ final session = _session, swarm = _swarm;+ if (session == null || swarm == null || _lost) return null;+ return SwarmInviteButton(session: session, reader: swarm);+ }+/// The four weeks the board keeps, this one first, in a sheet.Future<void> _pickWeek(BuildContext context,diff --git a/mobile/test/logging/redact_test.dart b/mobile/test/logging/redact_test.dartindex b942cf5a6..13e1a1d1f 100644--- a/mobile/test/logging/redact_test.dart+++ b/mobile/test/logging/redact_test.dart@@ -130,4 +130,46 @@ void main() {expect(redactSecretsInText(line), line);});});++ group('a Swarm join link, by its text', () {+ final token = 'Ab3_' * 10 + 'xyz';++ /// What a computer answers the phone's read of a Swarm's sharing, as+ /// `WsConn.request` logs it (`← super_tabs …`).+ Map<String, dynamic> answer(String tabId) => {+ 'value': {+ 'revision': 3,+ 'access': {'mode': 'link', 'role': 'viewer'},+ 'joinUrl': 'harness://swarm/join/$tabId?token=$token',+ },+ };++ test(+ 'its token never reaches the line, under a field not named for it',+ () {+ final line = '← super_tabs ${summariseForLog(answer('tab-1'))}';+ expect(line, isNot(contains(token)));+ expect(line, isNot(contains(token.substring(0, 8))));+ expect(+ line,+ contains('joinUrl: harness://swarm/join/tab-1?token=<redacted>'),+ );+ },+ );++ test('a long Swarm id: the clipped link keeps none of its token', () {+ // The token starts just before the 120th character, where a value is+ // clipped.+ final line = summariseForLog(answer('a' * 80));+ expect(line, isNot(contains(token.substring(0, 6))));+ expect(line, contains('?token=<redacted>'));+ });++ test('a value is blanked before it is clipped', () {+ // Clipped first, this token would keep two characters, fewer than the+ // `Bearer` rule needs to recognise it, and they would be written.+ final line = redactValue({'detail': '${'x' * 111}Bearer ab3defghijk'});+ expect(line, isNot(contains('Bearer ab')));+ });+ });}diff --git a/mobile/test/swarm/swarm_invites_shots_test.dart b/mobile/test/swarm/swarm_invites_shots_test.dartnew file mode 100644index 000000000..d5a973595--- /dev/null+++ b/mobile/test/swarm/swarm_invites_shots_test.dart@@ -0,0 +1,194 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_leaderboard.dart';+import 'package:harness_mobile/swarm/swarm_leaderboard_reader.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/terminal/terminal_font_store.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Set to a folder to write the phone's Share Swarm screenshots there, light+/// and dark, over a scripted backend: never a real Swarm.+final shots = Platform.environment['SWARM_INVITES_SHOTS'];++void main() {+ final now = DateTime.now().toUtc();+ final day = const Duration(days: 1).inMilliseconds;++ setUpAll(() async {+ if (shots == null || !Platform.isMacOS) return;+ final sf = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ // Every name the app's text asks for: the reading face and its+ // fallbacks, and the terminal's, which the top bar's title is set in. A+ // name left out draws as solid blocks.+ for (final family in {+ '.AppleSystemUIFont',+ 'Roboto',+ AppFont.sans,+ ...AppFont.sansFallback,+ }) {+ await (FontLoader(family)..addFont(Future.value(sf))).load();+ }+ final mono = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),+ );+ final terminal = terminalFontStore.value;+ for (final family in {+ '.AppleSystemUIFontMonospaced',+ 'monospace',+ AppFont.mono,+ ...AppFont.monoFallback,+ terminal.fontFamily,+ ...terminal.fontFamilyFallback,+ }) {+ await (FontLoader(family)..addFont(Future.value(mono))).load();+ }+ final manifest =+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;+ for (final entry in manifest.cast<Map<String, dynamic>>()) {+ final loader = FontLoader(entry['family'] as String);+ for (final font in (entry['fonts'] as List).cast<Map>()) {+ loader.addFont(rootBundle.load(font['asset'] as String));+ }+ await loader.load();+ }+ });++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ head: {+ ...headData(),+ 'invitations': [+ {+ 'id': 'i1',+ 'email': '[email protected]',+ 'role': 'viewer',+ 'conversationId': leadChat,+ 'expiresAt': now.millisecondsSinceEpoch + 6 * day + 3600000,+ },+ {+ 'id': 'i2',+ 'email': '[email protected]',+ 'role': 'collaborator',+ 'conversationId': leadChat,+ 'expiresAt': now.millisecondsSinceEpoch - day,+ },+ ],+ },+ ),+ 'members': [+ part(me, 1, person(me)),+ part('diego', 1, person('diego', role: 'collaborator')),+ part('ken', 1, person('ken', role: 'collaborator')),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ final monday = swarmWeekOf(now);+ fake.routes['/api/super-tabs/$tab/leaderboard?projectId=$project'] = (_) =>+ leaderboardData(+ week: monday,+ people: [+ {+ ...scoreData('diego', points: 28, rank: 1, shipped: 8),+ 'displayName': 'Diego',+ },+ {+ ...scoreData('ken', points: 21, rank: 2, shipped: 3),+ 'displayName': 'Ken',+ },+ {+ ...scoreData(me, points: 6, rank: 3, unblocked: 2),+ 'displayName': 'Dee',+ },+ ],+ );+ fake.routes['/api/super-tabs/$tab/sharing'] = (_) => {+ 'revision': 1,+ 'access': {'mode': 'link', 'role': 'viewer'},+ 'joinUrl': 'harness://swarm/join/$tab?token=${'A' * 43}',+ };+ return fake;+ }++ testWidgets('screenshots for review', (tester) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ await host.session!.inbox.refresh();+ await host.session!.inbox.reader(tab)!.refresh();+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmLeaderboardPage(swarmId: tab, projectId: project),+ ),+ ),+ );+ await tester.pumpAndSettle();+ Future<void> shoot(String name) => tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$shots/phone-invites-$name-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ });+ await shoot('leaderboard');+ await tester.tap(find.byKey(const ValueKey('swarm-invite-people')));+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 20)),+ );+ await tester.pumpAndSettle();+ await shoot('sheet');+ await tester.tap(find.byKey(const ValueKey('swarm-invite-revoke-i1')));+ await tester.pumpAndSettle();+ await shoot('revoke');+ await tester.pumpWidget(const SizedBox());+ host.dispose();+ // What the reads left waiting runs out before the next palette.+ await tester.pump(const Duration(minutes: 1));+ }+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_invites_test.dart b/mobile/test/swarm/swarm_invites_test.dartnew file mode 100644index 000000000..930b13829--- /dev/null+++ b/mobile/test/swarm/swarm_invites_test.dart@@ -0,0 +1,708 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_invites.dart';+import 'package:harness_mobile/swarm/swarm_invites_sheet.dart';+import 'package:harness_mobile/swarm/swarm_leaderboard.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Inviting people and revoking invitations from the phone, as the desktop's+/// Share Swarm does (`desktop/lib/super_tabs/sharing.dart`): only for the+/// Swarm's owner, one receipt per invitation, a revoke behind a confirmation,+/// a note and the join link through the share sheet, and nothing kept or+/// sent once the person may no longer invite.+void main() {+ // 1 November 2026, 09:00 UTC.+ final now = DateTime.utc(2026, 11, 1, 9);+ final day = const Duration(days: 1).inMilliseconds;+ final token = 'A' * 43;+ final joinUrl = 'harness://swarm/join/$tab?token=$token';+ const commands = '/api/super-tabs/$tab/commands';+ const sharing = '/api/super-tabs/$tab/sharing';++ Map<String, dynamic> invitation(+ String id,+ String email, {+ String role = 'collaborator',+ int? expiresAt,+ }) => {+ 'id': id,+ 'email': email,+ 'role': role,+ 'conversationId': leadChat,+ 'expiresAt': expiresAt ?? now.millisecondsSinceEpoch + 6 * day,+ };++ Map<String, dynamic> head({+ String ownerId = me,+ List<Map<String, dynamic>> invitations = const [],+ }) => {...headData(ownerId: ownerId), 'invitations': invitations};++ /// A Swarm [owner] owns, with [invitations] waiting, General access giving+ /// [link], and every command taken.+ FakeSwarm backend({+ String owner = me,+ List<Map<String, dynamic>> invitations = const [],+ String? link,+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': owner},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ head: head(ownerId: owner, invitations: invitations),+ ),+ 'members': [+ part(me, 1, person(me, role: owner == me ? 'owner' : 'collaborator')),+ if (owner != me) part(owner, 1, person(owner)),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes[commands] = (_) => {'result': {}};+ fake.routes[sharing] = (_) => {+ 'revision': 1,+ 'access': {'mode': link == null ? 'invited' : 'link', 'role': 'viewer'},+ 'joinUrl': link,+ };+ return fake;+ }++ /// The next read of the Swarm brings [data] as its head.+ void nextHead(FakeSwarm fake, Map<String, dynamic> data, {int version = 2}) {+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c$version'),+ 'head': part('head', version, data),+ };+ }++ Future<SwarmHost> host(+ FakeSwarm fake, {+ ValueNotifier<String?>? signedIn,+ }) async {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = signedIn ?? ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await host.session!.inbox.refresh();+ await host.session!.inbox.reader(tab)?.refresh();+ return host;+ }++ final shared = <({String text, Rect? origin})>[];+ Future<void> share(String text, {Rect? origin}) async =>+ shared.add((text: text, origin: origin));+ setUp(shared.clear);++ /// The project's leaderboard under the signed-in shell, as a page or as+ /// the sheet its menu opens ([asSheet]).+ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ ValueNotifier<String?>? signedIn,+ bool asSheet = false,+ }) async {+ final shell = await host(fake, signedIn: signedIn);+ final board = SwarmLeaderboardPage(+ swarmId: tab,+ projectId: project,+ sheet: asSheet,+ now: () => now,+ );+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: shell, child: child!),+ home: asSheet ? Scaffold(body: board) : board,+ ),+ );+ await tester.pumpAndSettle();+ return shell;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ group('who may invite', () {+ test('the Swarm’s owner alone, and nobody once the read is gone', () async {+ final owned = await host(backend());+ final reader = owned.session!.inbox.reader(tab)!;+ expect(swarmMayInvite(reader), isTrue);+ reader.revoke();+ expect(swarmMayInvite(reader), isFalse);++ final theirs = await host(backend(owner: 'diego'));+ expect(swarmMayInvite(theirs.session!.inbox.reader(tab)), isFalse);+ expect(swarmMayInvite(null), isFalse);+ });++ testWidgets('the leaderboard shows Invite people to the owner only', (+ tester,+ ) async {+ await pump(tester, backend(owner: 'diego'));+ expect(key('swarm-invite-people'), findsNothing);+ await pump(tester, backend(owner: 'diego'), asSheet: true);+ expect(key('swarm-invite-people'), findsNothing);++ await pump(tester, backend());+ expect(key('swarm-invite-people'), findsOneWidget);+ await pump(tester, backend(), asSheet: true);+ expect(key('swarm-invite-people'), findsOneWidget);++ // It opens Share Swarm.+ await tester.tap(key('swarm-invite-people'));+ await tester.runAsync(settle);+ await tester.pumpAndSettle();+ expect(find.text('Share Swarm'), findsOneWidget);+ });++ testWidgets('a first read that fails and then recovers still offers it', (+ tester,+ ) async {+ final fake = backend();+ final answer = fake.routes['/api/super-tabs/$tab/parts']!;+ var fail = true;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) => fail+ ? throw const SuperTabFailure(+ 'BACKEND_UNAVAILABLE',+ 'Could not reach this Swarm.',+ statusCode: 503,+ )+ : answer(body);+ final shell = await pump(tester, fake);+ expect(key('swarm-invite-people'), findsNothing);++ fail = false;+ await tester.runAsync(() => shell.session!.inbox.reader(tab)!.refresh());+ await tester.pumpAndSettle();+ expect(key('swarm-invite-people'), findsOneWidget);+ });++ testWidgets(+ 'ownership passed on while the leaderboard is up takes it away',+ (tester) async {+ final fake = backend();+ final shell = await pump(tester, fake);+ expect(key('swarm-invite-people'), findsOneWidget);++ nextHead(fake, head(ownerId: 'diego'));+ await tester.runAsync(+ () => shell.session!.inbox.reader(tab)!.refresh(),+ );+ await tester.pumpAndSettle();+ expect(key('swarm-invite-people'), findsNothing);+ },+ );+ });++ group('what an invitation reads as', () {+ test('its access and when it expires, or that it has', () {+ SwarmPendingInvite at(int ms, {String role = 'viewer'}) =>+ SwarmPendingInvite.read(+ invitation('i', '[email protected]', role: role, expiresAt: ms),+ )!;+ final base = now.millisecondsSinceEpoch;+ expect(+ swarmInviteDetail(at(base + 6 * day), now),+ 'Can view · Expires in 6 days',+ );+ expect(+ swarmInviteDetail(at(base + day, role: 'collaborator'), now),+ 'Can collaborate · Expires in 1 day',+ );+ expect(+ swarmInviteDetail(at(base + 3 * 3600000), now),+ 'Can view · Expires in 3 hours',+ );+ expect(swarmInviteDetail(at(base), now), 'Can view · Expired');+ expect(at(base).expired(now), isTrue);+ });++ test('a row that is not an invitation is left out', () {+ expect(SwarmPendingInvite.read({'id': 'i', 'email': 'x'}), isNull);+ expect(+ SwarmPendingInvite.read({+ ...invitation('i', '[email protected]'),+ 'role': 'owner',+ }),+ isNull,+ );+ });++ test('a join link counts only as this Swarm’s', () {+ expect(swarmJoinUrl(joinUrl, tab), joinUrl);+ expect(swarmJoinUrl('harness://swarm/join/$tab', tab), isNotNull);+ expect(+ swarmJoinUrl('harness://swarm/join/other?token=$token', tab),+ isNull,+ );+ expect(+ swarmJoinUrl('harness://swarm/join/$tab?token=short', tab),+ isNull,+ );+ expect(swarmJoinUrl('https://swarm/join/$tab?token=$token', tab), isNull);+ expect(swarmJoinUrl(null, tab), isNull);+ });++ test('the note shared carries no link or secret', () {+ final note = swarmInviteNote(+ 'Phone Swarm',+ SwarmPendingInvite.read(invitation('i', '[email protected]'))!,+ );+ expect(note, contains('[email protected]'));+ expect(note, contains('Phone Swarm'));+ expect(note, isNot(contains('harness://')));+ });+ });++ group('sending', () {+ Future<(SwarmInvites, FakeSwarm)> invites(FakeSwarm fake) async {+ final shell = await host(fake);+ final session = shell.session!;+ final controller = SwarmInvites(+ session: session,+ reader: session.inbox.reader(tab)!,+ );+ addTearDown(controller.dispose);+ return (controller, fake);+ }++ List<Map<String, dynamic>?> sent(FakeSwarm fake) => [+ for (final call in fake.calls)+ if (call.path == commands) call.body,+ ];++ test(+ 'an invitation goes as the desktop sends it, and the Swarm is read again',+ () async {+ final (controller, fake) = await invites(backend());+ fake.calls.clear();+ expect(await controller.invite(' [email protected] ', 'viewer'), isTrue);+ expect(fake.commands.single, {+ 'type': 'invite.create',+ 'email': '[email protected]',+ 'role': 'viewer',+ 'conversationId': 'lead',+ });+ await settle();+ expect(+ fake.paths.where((p) => p.startsWith('/api/super-tabs/$tab/changes')),+ isNotEmpty,+ );+ expect(controller.busy, isFalse);+ },+ );++ test('an answer that never came is checked under the same receipt, never sent twice', () async {+ final fake = backend();+ var down = true;+ fake.routes[commands] = (_) => down+ ? throw const SuperTabFailure(+ 'BACKEND_UNAVAILABLE',+ 'Down',+ statusCode: 503,+ )+ : {'result': {}};+ final (controller, _) = await invites(fake);+ expect(await controller.invite('[email protected]', 'viewer'), isFalse);+ expect(controller.unconfirmed, isTrue);+ expect(+ controller.error,+ 'Could not confirm this invitation. Check it again.',+ );+ // Another invitation waits until this one is known.+ expect(await controller.invite('[email protected]', 'viewer'), isFalse);+ expect(sent(fake), hasLength(1));++ down = false;+ expect(await controller.check(), isTrue);+ final bodies = sent(fake);+ expect(bodies, hasLength(2));+ expect(bodies[1]!['operationId'], bodies[0]!['operationId']);+ expect(bodies[1]!['command'], bodies[0]!['command']);+ expect(controller.unconfirmed, isFalse);+ });++ test('a refusal lets the receipt go and says why', () async {+ final fake = backend();+ fake.routes[commands] = (_) => throw const SuperTabFailure(+ 'ALREADY_MEMBER',+ 'This person is already in the Super Tab.',+ statusCode: 409,+ );+ final (controller, _) = await invites(fake);+ expect(await controller.invite('[email protected]', 'viewer'), isFalse);+ expect(controller.unconfirmed, isFalse);+ expect(controller.busy, isFalse);+ expect(controller.error, 'This person is already in this Swarm.');+ });++ test(+ 'a server without the commands says so, and has no link to share',+ () async {+ final fake = backend();+ fake.routes[commands] = (_) => throw const SuperTabFailure(+ 'UNKNOWN_COMMAND',+ 'Unknown command',+ statusCode: 400,+ );+ fake.routes[sharing] = (_) => throw const SuperTabFailure(+ 'NOT_FOUND',+ 'Not found',+ statusCode: 404,+ );+ final (controller, _) = await invites(fake);+ expect(await controller.invite('[email protected]', 'viewer'), isFalse);+ expect(+ controller.error,+ 'This Swarm’s server can’t send invitations from here.',+ );+ await controller.readLink();+ expect(controller.link, isNull);+ expect(controller.linkFailed, isFalse);+ },+ );++ test('an address the server will not take is told in its words', () async {+ final fake = backend();+ fake.routes[commands] = (_) => throw const SuperTabFailure(+ 'VALIDATION_ERROR',+ 'Invalid email address',+ statusCode: 400,+ );+ final (controller, _) = await invites(fake);+ expect(await controller.invite('ana@acme', 'viewer'), isFalse);+ expect(controller.error, 'Invalid email address');+ expect(controller.unconfirmed, isFalse);+ });++ test(+ 'a revoke of an invitation already accepted or revoked sends nothing',+ () async {+ final (controller, fake) = await invites(backend());+ final gone = SwarmPendingInvite.read(invitation('gone', '[email protected]'))!;+ expect(await controller.revoke(gone), isFalse);+ expect(fake.commands, isEmpty);+ },+ );++ test('an answer after access ended changes nothing', () async {+ final fake = backend();+ final answer = Completer<Object?>();+ fake.routes[commands] = (_) => answer.future;+ final (controller, _) = await invites(fake);+ final reader = controller.reader;+ final sending = controller.invite('[email protected]', 'viewer');+ await settle();+ reader.revoke();+ fake.calls.clear();+ answer.completeError(+ const SuperTabFailure('BACKEND_UNAVAILABLE', 'Down', statusCode: 503),+ );+ expect(await sending, isFalse);+ expect(controller.error, isNull);+ expect(controller.live, isFalse);+ // Nothing more is sent, and nothing read again.+ expect(await controller.check(), isFalse);+ expect(fake.calls, isEmpty);+ });++ test(+ 'a link read that lands after the read was replaced is dropped',+ () async {+ final fake = backend(link: joinUrl);+ final answer = Completer<Object?>();+ fake.routes[sharing] = (_) => answer.future;+ final (controller, _) = await invites(fake);+ final reading = controller.readLink();+ await settle();+ controller.reader.revoke();+ answer.complete({+ 'revision': 1,+ 'access': {'mode': 'link', 'role': 'viewer'},+ 'joinUrl': joinUrl,+ });+ await reading;+ expect(controller.link, isNull);+ },+ );++ test('a link read that fails says so, and Try again finds it', () async {+ final fake = backend(link: joinUrl);+ var down = true;+ fake.routes[sharing] = (_) => down+ ? throw const SuperTabFailure(+ 'BACKEND_UNAVAILABLE',+ 'Down',+ statusCode: 503,+ )+ : {+ 'revision': 1,+ 'access': {'mode': 'link', 'role': 'viewer'},+ 'joinUrl': joinUrl,+ };+ final (controller, _) = await invites(fake);+ await controller.readLink();+ expect(controller.linkFailed, isTrue);+ expect(controller.link, isNull);+ down = false;+ await controller.readLink();+ expect(controller.linkFailed, isFalse);+ expect(controller.link, joinUrl);+ });+ });++ group('Share Swarm', () {+ /// Share Swarm over a blank page, opened by its test button, sharing+ /// through [share].+ Future<SwarmHost> sheet(+ WidgetTester tester,+ FakeSwarm fake, {+ ValueNotifier<String?>? signedIn,+ }) async {+ final shell = await host(fake, signedIn: signedIn);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) =>+ SwarmScope(notifier: shell, child: child!),+ home: Builder(+ builder: (context) => Scaffold(+ body: TextButton(+ key: const ValueKey('open'),+ onPressed: () => Navigator.of(context).push(+ swarmTestSheetRoute(+ context,+ SwarmInvitesSheet(+ session: shell.session!,+ reader: shell.session!.inbox.reader(tab)!,+ share: share,+ now: () => now,+ ),+ ),+ ),+ child: const Text('open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(key('open'));+ await tester.runAsync(settle);+ await tester.pumpAndSettle();+ return shell;+ }++ testWidgets(+ 'invites by email with the access picked, then clears the field',+ (tester) async {+ final fake = backend();+ await sheet(tester, fake);+ expect(find.text('Share Swarm'), findsOneWidget);++ await tester.enterText(key('swarm-invite-email'), 'not an address');+ await tester.pump();+ await tester.tap(key('swarm-invite-send'));+ await tester.pumpAndSettle();+ expect(key('swarm-invite-email-error'), findsOneWidget);+ expect(fake.commands, isEmpty);++ await tester.tap(key('swarm-invite-role'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-invite-role-viewer'));+ await tester.pumpAndSettle();+ expect(find.text('Can view'), findsOneWidget);++ await tester.enterText(key('swarm-invite-email'), '[email protected]');+ await tester.pump();+ await tester.tap(key('swarm-invite-send'));+ await tester.runAsync(settle);+ await tester.pumpAndSettle();+ expect(fake.commands.single, {+ 'type': 'invite.create',+ 'email': '[email protected]',+ 'role': 'viewer',+ 'conversationId': 'lead',+ });+ expect(+ tester.widget<TextField>(key('swarm-invite-email')).controller!.text,+ isEmpty,+ );+ },+ );++ testWidgets(+ 'lists each invitation with its expiry; an expired one has no Share',+ (tester) async {+ await sheet(+ tester,+ backend(+ invitations: [+ invitation('i1', '[email protected]', role: 'viewer'),+ invitation(+ 'i2',+ '[email protected]',+ expiresAt: now.millisecondsSinceEpoch - 1,+ ),+ ],+ ),+ );+ expect(find.text('Can view · Expires in 6 days'), findsOneWidget);+ expect(find.text('Can collaborate · Expired'), findsOneWidget);+ expect(key('swarm-invite-share-i1'), findsOneWidget);+ expect(key('swarm-invite-share-i2'), findsNothing);+ expect(key('swarm-invite-revoke-i2'), findsOneWidget);+ },+ );++ testWidgets(+ 'Share hands a note with no secret to the share sheet; Share link the join link',+ (tester) async {+ await sheet(+ tester,+ backend(+ invitations: [invitation('i1', '[email protected]')],+ link: joinUrl,+ ),+ );+ await tester.tap(key('swarm-invite-share-i1'));+ await tester.pumpAndSettle();+ expect(+ shared.single.text,+ swarmInviteNote(+ 'Phone Swarm',+ SwarmPendingInvite.read(invitation('i1', '[email protected]'))!,+ ),+ );+ expect(shared.single.text, isNot(contains(token)));++ await tester.tap(key('swarm-invite-share-link'));+ await tester.pumpAndSettle();+ expect(shared.last.text, joinUrl);+ },+ );++ testWidgets('no Share link when General access has none', (tester) async {+ final fake = backend(invitations: [invitation('i1', '[email protected]')]);+ await sheet(tester, fake);+ expect(fake.paths, contains(sharing));+ expect(key('swarm-invite-share-link'), findsNothing);+ expect(key('swarm-invite-link-error'), findsNothing);+ });++ testWidgets('Revoke asks first: Cancel sends nothing, Revoke revokes', (+ tester,+ ) async {+ final fake = backend(invitations: [invitation('i1', '[email protected]')]);+ await sheet(tester, fake);+ await tester.tap(key('swarm-invite-revoke-i1'));+ await tester.pumpAndSettle();+ expect(find.text('Revoke invitation?'), findsOneWidget);+ await tester.tap(key('swarm-invite-revoke-cancel'));+ await tester.pumpAndSettle();+ expect(fake.commands, isEmpty);++ await tester.tap(key('swarm-invite-revoke-i1'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-invite-revoke-confirm'));+ await tester.runAsync(settle);+ await tester.pumpAndSettle();+ expect(fake.commands.single, {'type': 'invite.revoke', 'inviteId': 'i1'});+ });++ testWidgets(+ 'access taken away while it asks closes the sheet and its question, and sends nothing',+ (tester) async {+ final fake = backend(+ invitations: [invitation('i1', '[email protected]')],+ link: joinUrl,+ );+ final shell = await sheet(tester, fake);+ await tester.enterText(key('swarm-invite-email'), '[email protected]');+ await tester.tap(key('swarm-invite-revoke-i1'));+ await tester.pumpAndSettle();+ expect(find.text('Revoke invitation?'), findsOneWidget);++ shell.session!.inbox.reader(tab)!.revoke();+ await tester.pumpAndSettle();+ expect(find.text('Revoke invitation?'), findsNothing);+ expect(find.text('Share Swarm'), findsNothing);+ expect(find.text('[email protected]'), findsNothing);+ expect(find.text('[email protected]'), findsNothing);+ expect(fake.commands, isEmpty);+ },+ );++ testWidgets('ownership passed on closes it', (tester) async {+ final fake = backend(invitations: [invitation('i1', '[email protected]')]);+ final shell = await sheet(tester, fake);+ nextHead(fake, head(ownerId: 'diego'));+ await tester.runAsync(() => shell.session!.inbox.reader(tab)!.refresh());+ await tester.pumpAndSettle();+ expect(find.text('Share Swarm'), findsNothing);+ expect(find.text('[email protected]'), findsNothing);+ });++ testWidgets('signing out closes it', (tester) async {+ final account = ValueNotifier<String?>(me);+ await sheet(+ tester,+ backend(invitations: [invitation('i1', '[email protected]')]),+ signedIn: account,+ );+ account.value = null;+ await tester.pumpAndSettle();+ expect(find.text('Share Swarm'), findsNothing);+ expect(find.text('[email protected]'), findsNothing);+ });++ testWidgets(+ 'an invitation answered after the sheet closed changes nothing',+ (tester) async {+ final fake = backend();+ final answer = Completer<Object?>();+ fake.routes[commands] = (_) => answer.future;+ final shell = await sheet(tester, fake);+ await tester.enterText(key('swarm-invite-email'), '[email protected]');+ await tester.pump();+ await tester.tap(key('swarm-invite-send'));+ await tester.pump();+ expect(find.text('Sending…'), findsOneWidget);+ // Still readable, but no longer theirs to invite to.+ nextHead(fake, head(ownerId: 'diego'));+ await tester.runAsync(+ () => shell.session!.inbox.reader(tab)!.refresh(),+ );+ await tester.pumpAndSettle();+ expect(find.text('Share Swarm'), findsNothing);+ fake.calls.clear();+ answer.complete({'result': {}});+ await tester.runAsync(settle);+ await tester.pumpAndSettle();+ // The answer is not taken: nothing is read again for it.+ expect(fake.calls, isEmpty);+ },+ );+ });+}++/// A bottom sheet route as the leaderboard opens Share Swarm in.+Route<void> swarmTestSheetRoute(BuildContext context, Widget sheet) =>+ ModalBottomSheetRoute<void>(+ isScrollControlled: true,+ builder: (_) => sheet,+ );