Skip to content

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

Swarm phone: direct reads and instant Home (#2459)

tony496s02747260dfba
diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dart
index 396072ec1..07403a0a5 100644
--- a/mobile/lib/api/api_client.dart
+++ b/mobile/lib/api/api_client.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:convert';
import 'dart:typed_data';
import 'package:dio/dio.dart';
@@ -342,6 +343,49 @@ class ApiClient {
final data = unwrapApiResponse(res) as Map<String, dynamic>;
return (data['transcript'] as String? ?? '').trim();
}
+ // -- Swarm reads (the viewer's own session signs them) --
+
+ /// One read of the Swarm ([path], `/api/super-tabs…`), straight from the
+ /// backend with this viewer's own sign-in, as the web build reads it
+ /// (docs/specs/2026-10-30-web-swarm-direct.md). Answers the backend's value,
+ /// read as `backend()` in cli/src/superTabs/wire.ts reads it, so it is the
+ /// value a machine would have forwarded. A refusal throws a [SuperTabFailure]
+ /// carrying the backend's code and status; no answer at all throws what the
+ /// transport threw.
+ Future<Object?> swarmRead(String path) async {
+ final response = await _dio.get<dynamic>(path);
+ final status = response.statusCode ?? 0;
+ var body = response.data;
+ if (body is String) {
+ try {
+ body = jsonDecode(body);
+ } on FormatException {
+ // A proxy's page, not the backend's answer: refused below by its status.
+ }
+ }
+ if (status == 426) {
+ throw const SuperTabFailure(
+ 'UPDATE_REQUIRED',
+ 'Update Harness to keep using this Swarm.',
+ statusCode: 426,
+ );
+ }
+ final envelope = body is Map ? body : const <String, Object?>{};
+ if (status < 200 || status >= 300 || envelope['success'] != true) {
+ final error = envelope['error'];
+ final code = error is Map ? error['code'] : envelope['code'];
+ final message = error is Map ? error['message'] : envelope['message'];
+ throw SuperTabFailure(
+ code is String && code.isNotEmpty ? code : 'BACKEND_UNAVAILABLE',
+ message is String && message.isNotEmpty
+ ? message
+ : 'Could not reach this Swarm.',
+ statusCode: status,
+ );
+ }
+ return envelope['data'];
+ }
+
// -- Swarm chat files (backend only: the viewer's own SSO session signs it) --
/// Sends one file for a message in [conversationId] of Swarm [tabId] and
@@ -357,7 +401,7 @@ class ApiClient {
/// attachment. A larger file still is refused before anything is sent.
///
/// Straight to the backend with the token this viewer holds, unlike every
- /// other Swarm call, which one of the account's machines forwards
+ /// other Swarm command, which one of the account's machines forwards
/// (`AppNotifier.swarmRequest`): the backend takes a chat file only from the
/// client itself, and a machine forwards only JSON. [onProgress] is told the
/// part sent, from 0 to 1. A refusal throws a [SuperTabFailure] carrying the
diff --git a/mobile/lib/auth/auth_session.dart b/mobile/lib/auth/auth_session.dart
index c8bee3f58..631d490df 100644
--- a/mobile/lib/auth/auth_session.dart
+++ b/mobile/lib/auth/auth_session.dart
@@ -31,6 +31,7 @@ class AuthSession {
static const _expiresAt = 'auth_access_token_expires_at';
static const _issuer = 'auth_session_issuer';
static const _ssoClientId = 'auth_sso_client_id';
+ static const _accountId = 'auth_account_id';
AuthSession({LocalKeyValueStore? storage})
: _storage = storage ?? HarnessFileStore.shared;
@@ -45,6 +46,8 @@ class AuthSession {
SessionIssuer issuer = SessionIssuer.sso,
String? ssoClientId,
}) async {
+ // First: a new token must never be found beside the last account's id.
+ await _storage.delete(_accountId);
await _storage.write(_access, token);
await _storage.write(_issuer, issuer.name);
if (refreshToken != null && refreshToken.isNotEmpty) {
@@ -133,7 +136,15 @@ class AuthSession {
);
}
+ /// Whose this sign-in is, as the account last said: what lets a launch open
+ /// what it kept for that account before the account has answered again. Null
+ /// until then. A renewal keeps it, being the same sign-in; a new sign-in and a
+ /// sign-out forget it.
+ Future<String?> accountId() => _storage.read(_accountId);
+ Future<void> saveAccountId(String id) => _storage.write(_accountId, id);
+
Future<void> clear() async {
+ await _storage.delete(_accountId);
await _storage.delete(_access);
await _storage.delete(_refresh);
await _storage.delete(_env);
diff --git a/mobile/lib/demo/sample_notifier.dart b/mobile/lib/demo/sample_notifier.dart
index 14ad83712..b42eea162 100644
--- a/mobile/lib/demo/sample_notifier.dart
+++ b/mobile/lib/demo/sample_notifier.dart
@@ -175,6 +175,10 @@ class SampleNotifier extends AppNotifier {
@override
Future<void> retryMachines() async => notifyListeners();
+ /// The sample has no account to read.
+ @override
+ bool get accountReading => false;
+
/// The sample's computers are always reached, and their agents are already here: there is
/// nothing to dial or re-ask when Find opens.
@override
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 6cab0370c..743e7cc08 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -104,7 +104,8 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
notices.openedDevice.addListener(_openNoticedDevice);
final state = WidgetsBinding.instance.lifecycleState;
_swarm = SwarmHost(
- accountId: () => widget.notifier.currentUser?.id,
+ accountId: () => widget.notifier.swarmAccountId,
+ accountReading: () => widget.notifier.accountReading,
account: widget.notifier,
request: widget.notifier.swarmRequest,
upload: widget.notifier.swarmUpload,
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 1c19ba398..b7e3d7205 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -11,7 +11,7 @@ import '../measurement/setup_transport.dart';
import 'dart:async';
import 'dart:convert' show jsonDecode, jsonEncode;
-import 'dart:math' show Random;
+import 'dart:math' show Random, min;
import 'package:dio/dio.dart';
import 'package:xterm/xterm.dart' show RemoteScrollMemory, Terminal;
@@ -572,6 +572,9 @@ class AppNotifier extends ChangeNotifier {
// The copies large chat files were kept in went with the chats that held them.
unawaited(clearSwarmPickerCopies());
_profileInFlight = null;
+ _profileAgain?.cancel();
+ _profileFailures = 0;
+ _keptAccountId = null;
_retryInFlight = null;
machinesLoading = false;
_registeringDevice = false;
@@ -1870,6 +1873,11 @@ class AppNotifier extends ChangeNotifier {
// appear as soon as the local state is restored, and these two now overlap.
await StartupTrace.time('boot.restoreLocalState', _restorePaneLayout);
if (!_authWorkCurrent(revision)) return;
+ // Before the shell is up, so its first frame can already open what Swarm
+ // kept for this account. Only a nicety: nothing here is worth a failed boot.
+ final kept = await session.accountId().catchError((Object _) => null);
+ if (!_authWorkCurrent(revision)) return;
+ _keptAccountId = kept;
_bootStatusMessage = null;
status = AppStatus.authenticated;
notifyListeners();
@@ -1903,6 +1911,35 @@ class AppNotifier extends ChangeNotifier {
if (_authWorkCurrent(revision)) notifyListeners();
}
+ /// Signed in, and who as is still to come: the shell is up before the account
+ /// is read, and a read that fails is tried again ([_profileNotRead]).
+ bool get accountReading =>
+ status == AppStatus.authenticated &&
+ currentUser == null &&
+ _keptAccountId == null;
+
+ /// The account this sign-in last said it was, until it says so again.
+ String? _keptAccountId;
+
+ /// Whose Swarm to open: the account, or before it has answered, who this
+ /// sign-in last said it was: a launch's kept Home need not wait on
+ /// `/api/auth/me` with everything it needs on disk.
+ /// Should the account answer otherwise, its answer wins and Swarm starts over
+ /// ([SwarmHost]), taking what it kept with it.
+ String? get swarmAccountId =>
+ currentUser?.id ??
+ (status == AppStatus.authenticated ? _keptAccountId : null);
+
+ void _keepAccount(String id) {
+ if (id == _keptAccountId) return;
+ _keptAccountId = id;
+ unawaited(
+ session.saveAccountId(id).catchError((Object error) {
+ appLog.warn('auth', 'Account id not kept', error: error);
+ }),
+ );
+ }
+
/// Who is signed in, from the account. Shared by the boot path and by the
/// retry path, because a profile the boot could not read is asked for again
/// there — and a session that never learns its own account has an empty
@@ -1925,23 +1962,48 @@ class AppNotifier extends ChangeNotifier {
if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
return;
}
- if (me != null) {
+ if (me == null) {
+ _profileNotRead(revision, null);
+ } else {
+ _profileFailures = 0;
currentUser = CurrentUserProfile.fromMe(me);
// Made by a sign-in in this run, or coming back to it.
onboardingMeasurement.accountCreated(currentUser?.createdAt);
// A sign-in by hand: the device log keeps which account it was made to.
if (currentUser?.id case final id?) {
unawaited(_deviceLog?.signedInAs(id));
+ _keepAccount(id);
}
notifyListeners();
}
} catch (error) {
- if (_authWorkCurrent(revision)) {
- debugPrint('bootstrap: profile unavailable: $error');
- }
+ if (_authWorkCurrent(revision)) _profileNotRead(revision, error);
}
}
+ Timer? _profileAgain;
+
+ /// Reads of the profile that failed in a row: the first goes in the log.
+ int _profileFailures = 0;
+
+ /// A read that brought no account: asked for again, less often each time,
+ /// from 5 seconds up to a minute. Swarm waits on it, and nothing else asks
+ /// while the machines are well.
+ void _profileNotRead(int revision, Object? error) {
+ if (_profileFailures == 0) {
+ appLog.warn('auth', 'Account not read', error: error);
+ }
+ final wait = min(60, 5 << min(_profileFailures, 4));
+ _profileFailures++;
+ _profileAgain?.cancel();
+ _profileAgain = Timer(Duration(seconds: wait), () {
+ if (_disposed || !_authWorkCurrent(revision) || currentUser != null) {
+ return;
+ }
+ unawaited(_loadProfile());
+ });
+ }
+
/// The session went away while the app was already running — send the user to the signed-out screen with a
/// reason, and stop the background work that can only fail from here.
///
@@ -6359,12 +6421,20 @@ class AppNotifier extends ChangeNotifier {
return best;
}
- /// One Swarm backend call ([method] on [path], `/api/super-tabs…`), forwarded by one of the
- /// account's own machines with its session (`super_tabs`, `action: backend`,
- /// cli/src/superTabs/service.ts). The phone holds no Swarm credential: the machine checks that
- /// this connection is its owner's, and the backend what that account may read. Answers the
- /// backend's value; a refusal — the backend's, the machine's, or none to ask — is a
- /// [SuperTabFailure], and an answer that lands after the account changed is dropped.
+ /// One Swarm backend call ([method] on [path], `/api/super-tabs…`). Answers the backend's value;
+ /// a refusal — the backend's, the machine's, or none to ask — is a [SuperTabFailure], and an
+ /// answer that lands after the account changed is dropped.
+ ///
+ /// A read goes straight to the backend with the phone's own sign-in
+ /// ([ApiClient.swarmRead]), as the web build's does: on the iPhone (2026-10-31) a launch's first
+ /// list took 9 seconds through the machines, 6 of them on a Team sign-in's refusals and the wait
+ /// for the next machine, where the same backend answers the phone in 400 ms. What the backend
+ /// refuses stands, being about this person; with no answer, or one that says nothing of them
+ /// ([_swarmReadTriesMachine]), the read goes on through a machine as below.
+ ///
+ /// A command, and a read going on, is forwarded by one of the account's own machines with its
+ /// session (`super_tabs`, `action: backend`, cli/src/superTabs/service.ts): the machine checks
+ /// that this connection is its owner's, and the backend what that account may read.
///
/// A refusal is asked again through each other machine that is up, one after another, up to
/// [_swarmAsksPerCall] in all. One that answers shows the refusals before it were those
@@ -6391,6 +6461,31 @@ class AppNotifier extends ChangeNotifier {
String path, {
Map<String, dynamic>? body,
}) async {
+ if (method == 'GET') {
+ final revision = _authRevision;
+ void stillThisAccount() {
+ if (!_authWorkCurrent(revision)) {
+ throw const SuperTabFailure(
+ 'ACCOUNT_CHANGED',
+ 'The account changed. Open Swarm again.',
+ );
+ }
+ }
+
+ try {
+ final value = await api.swarmRead(path);
+ stillThisAccount();
+ _swarmReadFailed = false;
+ return value;
+ } on SuperTabFailure catch (refusal) {
+ stillThisAccount();
+ if (!_swarmReadTriesMachine(refusal)) rethrow;
+ _swarmReadGoesOn(refusal);
+ } catch (error) {
+ stillThisAccount();
+ _swarmReadGoesOn(error);
+ }
+ }
var machine = _swarmMachine() ?? await _swarmMachineBack();
if (machine == null) throw _swarmNoComputer();
final asked = <MachineState>{}, refused = <MachineState>[];
@@ -6430,6 +6525,29 @@ class AppNotifier extends ChangeNotifier {
Error.throwWithStackTrace(failure, trace);
}
+ /// Whether a machine might still read what the phone's own read could not: the backend was not
+ /// there to say (no status, a 5xx), or its answer was about this sign-in or this phone, not about
+ /// what the person may read (an expired session, a rate limit, a session of a limited kind).
+ static bool _swarmReadTriesMachine(SuperTabFailure refusal) =>
+ refusal.statusCode == 0 ||
+ refusal.statusCode >= 500 ||
+ refusal.statusCode == 401 ||
+ refusal.statusCode == 429 ||
+ refusal.code == 'TEAM_SESSION_LIMITED';
+
+ /// Whether the phone's own reads are failing: logged as they start to, not once per read.
+ bool _swarmReadFailed = false;
+
+ void _swarmReadGoesOn(Object failure) {
+ if (_swarmReadFailed) return;
+ _swarmReadFailed = true;
+ appLog.warn(
+ 'swarm',
+ 'Swarm read from the backend failed, asking a machine',
+ error: failure,
+ );
+ }
+
/// Sends one Swarm chat file to the backend ([SwarmUpload]): straight from this phone with its own
/// sign-in ([ApiClient.uploadSwarmAttachment]), not through a machine as [swarmRequest] goes — the
/// backend takes a chat file only from the client, and a machine forwards only JSON. An answer
@@ -11119,6 +11237,7 @@ class AppNotifier extends ChangeNotifier {
// went to their computer to sign it in.
_rereadMachinesWhileDeaf();
_startDeafPoll();
+ if (currentUser == null) unawaited(_loadProfile());
}
// The zoo too, for the same reason: a `zoo_changed` sent while the phone
// was in a pocket reached nobody.
@@ -11354,6 +11473,7 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
+ _profileAgain?.cancel();
launchMeasurement?.dispose();
productConnections.dispose();
productResumes.dispose();
diff --git a/mobile/lib/swarm/swarm_asks.dart b/mobile/lib/swarm/swarm_asks.dart
index 5244992ff..a358dedcc 100644
--- a/mobile/lib/swarm/swarm_asks.dart
+++ b/mobile/lib/swarm/swarm_asks.dart
@@ -3,6 +3,8 @@ import 'dart:async';
import 'package:collection/collection.dart' show DeepCollectionEquality;
import 'package:flutter/foundation.dart';
+import 'package:harness_mobile/logging/app_log.dart';
+
import 'model.dart';
import 'swarm_reader.dart';
import 'swarm_request.dart';
@@ -321,10 +323,18 @@ class SwarmAsks extends ChangeNotifier {
}
}
if (changed) notifyListeners();
- } catch (_) {
+ } catch (failure) {
if (_disposed || reader.generation != generation) return true;
const failed = 'Could not load what is waiting for you. Try again.';
final told = error == failed && _failed && _settled == generation;
+ // Once per failure, not once per poll.
+ if (!told) {
+ appLog.warn(
+ 'swarm',
+ 'What waits in ${reader.tabId} not read',
+ error: failure,
+ );
+ }
error = failed;
_failed = true;
_settled = generation;
diff --git a/mobile/lib/swarm/swarm_home_rows.dart b/mobile/lib/swarm/swarm_home_rows.dart
index d75db17f8..fb553e9b2 100644
--- a/mobile/lib/swarm/swarm_home_rows.dart
+++ b/mobile/lib/swarm/swarm_home_rows.dart
@@ -6,10 +6,10 @@ import 'package:harness_mobile/phone/fzf.dart' show fzfAge;
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/shared/widgets/skeleton.dart';
import 'package:harness_mobile/shared/widgets/touch_target.dart';
import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
-import 'model.dart';
import 'swarm_home_list.dart';
import 'swarm_inbox.dart';
import 'swarm_row.dart';
@@ -17,8 +17,8 @@ import 'swarm_style.dart';
import 'swarm_unread.dart';
import 'team_glance.dart';
-/// The rows of Swarm Home: a project with its people's faces, how many agents
-/// are running and when it last moved, its tile a dot and its name a
+/// The rows of Swarm Home: a project with how many people read it, how many
+/// agents are running and when it last moved, its tile a dot and its name a
/// channel's, as C1 draws them (2026-10-30); the projects quiet for a day
/// folded in one row.
@@ -75,87 +75,20 @@ class SwarmTeamDots extends StatelessWidget {
}
}
-/// A project's people and its team on Home: up to [shown] faces, each over the
-/// one before it, then how many agents are running ([SwarmTeamGlance.running]).
-class SwarmTeamFaces extends StatelessWidget {
- const SwarmTeamFaces(
- this.glance, {
- super.key,
- required this.people,
- this.swarmName,
- });
-
- /// The most faces a row draws.
- static const shown = 5;
-
- /// As tall as the words beside it, so the row is as tall as its skeleton.
- static const _size = 18.0;
-
- /// From one face to the next: less than [_size], so they overlap, yet each
- /// initial stays whole.
- static const _step = 15.0;
-
- final SwarmTeamGlance glance;
-
- /// The project's people ([swarmProjectPeople]), in the order to draw them.
- final List<SuperTabPerson> people;
-
- /// Words after the count, the first to go when the row is short: the Swarm,
- /// where Home shows several.
- final String? swarmName;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final faces = people.take(shown).toList();
- final words = [glance.running, ?swarmName].join(' · ');
- return Semantics(
- label: [for (final person in faces) person.username, words].join(', '),
- excludeSemantics: true,
- child: Row(
- children: [
- if (faces.isNotEmpty) ...[
- SizedBox(
- key: const ValueKey('swarm-team-faces'),
- width: _size + _step * (faces.length - 1),
- height: _size,
- child: Stack(
- children: [
- for (final (i, person) in faces.indexed)
- Positioned(
- left: _step * i,
- child: SwarmAvatar(
- key: ValueKey('swarm-team-face-${person.id}'),
- id: person.id,
- name: person.username,
- picture: person.avatar,
- size: _size,
- // The row's own colour, so each face cuts into the
- // one under it.
- ring: AppGlass.rowFill,
- ),
- ),
- ],
- ),
- ),
- const SizedBox(width: AppSpace.s),
- ],
- Flexible(
- child: Text(
- words,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.caption(
- color: AppPalette.textSecondary,
- height: 1.35,
- ),
- ),
- ),
- ],
- ),
- );
- }
-}
+/// A project's line on Home: "5 humans • 8 agents running", leaving out what
+/// is none, then its Swarm, the first to go when the row is short, where Home
+/// shows several. Empty with nothing to say.
+String swarmProjectLine({
+ required int humans,
+ required SwarmTeamGlance glance,
+ String? swarmName,
+}) => [
+ if (humans > 0) swarmHumans(humans),
+ ?glance.running,
+ ?swarmName,
+].join(_lineGap);
+
+const _lineGap = ' • ';
/// What a need asks, as its Home row's title: a decision's question, a tag's
/// words, the question work waits on (or the work itself).
@@ -168,19 +101,20 @@ String swarmNeedAsk(SwarmNeed need) => switch (need) {
/// One project on Home, as C1 draws it: a dot in the colour of how its team
/// is ([swarmProjectColor]), its name as a channel's ("#openharness") — bold
-/// and bright with something new in it, quiet otherwise — its people's faces
-/// and how many agents are running ([SwarmTeamFaces]), and at its right how
-/// long ago it last moved, over the tags waiting in it ("@2", filled) or,
-/// unread, a dot. A tap opens it; a long press offers its pin
-/// ([onLongPress]).
+/// and bright with something new in it, quiet otherwise — how many people read
+/// it and how many agents are running ([swarmProjectLine]), and at its right
+/// how long ago it last moved, over the tags waiting in it ("@2", filled) or,
+/// unread, a dot; a skeleton in their place while what waits is on its way
+/// ([tagsLoading]). A tap opens it; a long press offers its pin ([onLongPress]).
class SwarmHomeProjectRow extends StatelessWidget {
const SwarmHomeProjectRow({
super.key,
required this.project,
required this.glance,
- required this.people,
+ required this.humans,
required this.now,
this.swarmName,
+ this.tagsLoading = false,
required this.onTap,
this.onLongPress,
});
@@ -188,12 +122,15 @@ class SwarmHomeProjectRow extends StatelessWidget {
final SwarmHomeProject project;
final SwarmTeamGlance glance;
- /// Its people ([swarmProjectPeople]).
- final List<SuperTabPerson> people;
+ /// How many people read it ([swarmProjectPeople]).
+ final int humans;
final DateTime now;
/// Its Swarm, where Home shows several.
final String? swarmName;
+
+ /// What waits in its Swarm is not read yet: its tags may still come.
+ final bool tagsLoading;
final VoidCallback onTap;
final VoidCallback? onLongPress;
@@ -206,6 +143,11 @@ class SwarmHomeProjectRow extends StatelessWidget {
final at? => fzfAge(at.toLocal(), now.toLocal()),
null => '',
};
+ final line = swarmProjectLine(
+ humans: humans,
+ glance: glance,
+ swarmName: swarmName,
+ );
return _Tap(
onTap: onTap,
onLongPress: onLongPress,
@@ -253,12 +195,24 @@ class SwarmHomeProjectRow extends StatelessWidget {
),
),
),
- const SizedBox(height: 3),
- SwarmTeamFaces(glance, people: people, swarmName: swarmName),
+ if (line.isNotEmpty) ...[
+ const SizedBox(height: 3),
+ Text(
+ line,
+ key: const ValueKey('swarm-project-line'),
+ semanticsLabel: line.replaceAll(_lineGap, ', '),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ height: 1.35,
+ ),
+ ),
+ ],
],
),
),
- if (age.isNotEmpty || bright) ...[
+ if (age.isNotEmpty || bright || tagsLoading) ...[
const SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
@@ -275,6 +229,15 @@ class SwarmHomeProjectRow extends StatelessWidget {
if (news.tags > 0) ...[
const SizedBox(height: 4),
SwarmTags(news.tags, filled: true),
+ ] else if (tagsLoading) ...[
+ const SizedBox(height: 4),
+ // As big as the filled tags it stands for.
+ const Skeleton(
+ key: ValueKey('swarm-project-tags-loading'),
+ width: 36,
+ height: 20,
+ radius: 10,
+ ),
] else if (news.bold) ...[
const SizedBox(height: 8),
ExcludeSemantics(
diff --git a/mobile/lib/swarm/swarm_home_top.dart b/mobile/lib/swarm/swarm_home_top.dart
index 13cc787ec..60bf9c787 100644
--- a/mobile/lib/swarm/swarm_home_top.dart
+++ b/mobile/lib/swarm/swarm_home_top.dart
@@ -7,6 +7,7 @@ import 'package:harness_mobile/phone/fzf.dart' show fzfAge;
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/shared/widgets/skeleton.dart';
import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
import 'model.dart';
@@ -22,6 +23,11 @@ import 'swarm_style.dart';
/// (2026-10-30): the Swarm switcher in its title ([showSwarmSwitcher]) and
/// While you were away ([SwarmAwayCard]).
+/// Whether the account's Swarms are still to come, a failed read still trying:
+/// never from a server without the list, which no read will bring.
+bool swarmHomeListing(SwarmInbox inbox) =>
+ !inbox.loaded && inbox.swarms.isEmpty && inbox.error != swarmServerTooOld;
+
/// Whether Home offers Swarm [swarmId]: the account's, and its read not
/// taken away, though the list may still have it until it is read again.
bool swarmHomeOffers(SwarmInbox inbox, String swarmId) =>
@@ -115,6 +121,13 @@ class _Switcher extends StatelessWidget {
),
children: [
const _Grabber(),
+ if (swarmHomeListing(inbox))
+ const SkeletonBlock(
+ child: SwarmSkeletonRow(
+ key: ValueKey('swarm-switch-loading'),
+ titleOnly: true,
+ ),
+ ),
if (inbox.swarms.length > 1)
SwarmRow(
key: const ValueKey('swarm-switch-all'),
@@ -203,7 +216,7 @@ int swarmDoneSince(SuperTabSnapshot snapshot, DateTime since) => snapshot
/// While you were away, as C1 draws it: how long the person was away, from
/// leaving the app ([since]) to coming back ([back]), then the work done
/// since ([done], green) and what needs them now ([needs], yellow), each a
-/// dash while it is not known. A tap opens what needs them ([onTap]).
+/// skeleton until it is known. A tap opens what needs them ([onTap]).
class SwarmAwayCard extends StatelessWidget {
const SwarmAwayCard({
super.key,
@@ -311,24 +324,28 @@ class _Stat extends StatelessWidget {
required this.color,
});
- /// Null while it is not known: a dash.
+ /// Null until it is known: a skeleton as tall as the figure.
final int? count;
final String label;
final Color color;
@override
- Widget build(BuildContext context) => Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- count?.toString() ?? '–',
- style: AppType.title(
- color: (count ?? 0) > 0 ? color : AppPalette.textSecondary,
- fontWeight: AppFont.semibold,
- height: 1.2,
- ),
- ),
- Text(label, style: AppType.caption(color: AppPalette.textSecondary)),
- ],
- );
+ Widget build(BuildContext context) {
+ final count = this.count;
+ final style = AppType.title(
+ color: (count ?? 0) > 0 ? color : AppPalette.textSecondary,
+ fontWeight: AppFont.semibold,
+ height: 1.2,
+ );
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (count == null)
+ SkeletonText(style: style, width: 28)
+ else
+ Text('$count', style: style),
+ Text(label, style: AppType.caption(color: AppPalette.textSecondary)),
+ ],
+ );
+ }
}
diff --git a/mobile/lib/swarm/swarm_page.dart b/mobile/lib/swarm/swarm_page.dart
index bb429574c..477b96d70 100644
--- a/mobile/lib/swarm/swarm_page.dart
+++ b/mobile/lib/swarm/swarm_page.dart
@@ -10,8 +10,8 @@ import 'package:harness_mobile/phone/tty.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/shared/widgets/skeleton.dart';
-import 'model.dart';
import 'swarm_conversation_page.dart' show openSwarmConversation;
import 'swarm_home_list.dart';
import 'swarm_home_rows.dart';
@@ -70,7 +70,9 @@ bool swarmHomeListed(SwarmInbox inbox, String swarmId, String projectId) {
/// yet (Lead, 2026-10-30): the phone reads no chat by chat for them.
///
/// Pushed over another page it has a back button instead of the switcher.
-/// Reads the account's [SwarmSession] from the shell; with none, says why.
+/// Reads the account's [SwarmSession] from the shell; with none, its skeleton
+/// while the account is on its way ([SwarmScope.accountComingOf]), else says
+/// why.
class SwarmPage extends StatefulWidget {
const SwarmPage({super.key, this.now = DateTime.now});
@@ -251,7 +253,13 @@ class _SwarmPageState extends State<SwarmPage> {
),
Expanded(
child: session == null
- ? const _Unavailable()
+ ? SwarmScope.accountComingOf(context)
+ ? ListView(
+ key: const ValueKey('swarm-account-coming'),
+ padding: _listPadding(context),
+ children: _reading(first: true),
+ )
+ : const _Unavailable()
: ListenWhileInSight(
listenable: listens!,
// Before there is a Swarm to show, a start screen in
@@ -262,16 +270,7 @@ class _SwarmPageState extends State<SwarmPage> {
onRefresh: () => _pulled(context, session),
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
- // The last row clears the floating +.
- padding: EdgeInsets.fromLTRB(
- AppSpace.m,
- 0,
- AppSpace.m,
- MediaQuery.paddingOf(context).bottom +
- SwarmNewMessageButton.size +
- AppSpace.l +
- AppSpace.xl,
- ),
+ padding: _listPadding(context),
children: _body(context, session),
),
),
@@ -283,6 +282,17 @@ class _SwarmPageState extends State<SwarmPage> {
);
}
+ /// Around Home's rows: the last clears the floating +.
+ EdgeInsets _listPadding(BuildContext context) => EdgeInsets.fromLTRB(
+ AppSpace.m,
+ 0,
+ AppSpace.m,
+ MediaQuery.paddingOf(context).bottom +
+ SwarmNewMessageButton.size +
+ AppSpace.l +
+ AppSpace.xl,
+ );
+
/// Home's top bar. At the root, the tab's title: the Swarm shown and a
/// button to switch it; pushed over another page, back and "Swarm".
Widget _topBar(BuildContext context, {required bool pushed}) {
@@ -295,15 +305,38 @@ class _SwarmPageState extends State<SwarmPage> {
title: 'Swarm',
);
}
- if (session == null) return const SwarmTabHeader('Swarm');
+ if (session == null) {
+ if (!SwarmScope.accountComingOf(context)) {
+ return const SwarmTabHeader('Swarm');
+ }
+ // Where the Swarm's name will be: its button has nothing to switch yet.
+ return SwarmTabHeader(
+ 'Swarm',
+ loading: true,
+ leading: _loadingTile,
+ titleLabel: 'Loading your Swarm',
+ onTitle: () {},
+ );
+ }
final shown = _shown(session);
final title = swarmHomeTitle(session.inbox, shown);
// The one Swarm named has its tile; All Swarms has none.
final named = swarmHomeNamed(session.inbox, shown);
+ // A start screen in the body has no Swarm coming to name.
+ final listing =
+ swarmHomeListing(session.inbox) &&
+ swarmStartView(context, session) == null;
return SwarmTabHeader(
title,
- leading: named == null ? null : SwarmProjectTile(named.name),
- titleLabel: 'Swarm: $title. Switch Swarm',
+ loading: listing,
+ leading: listing
+ ? _loadingTile
+ : named == null
+ ? null
+ : SwarmProjectTile(named.name),
+ titleLabel: listing
+ ? 'Loading your Swarm. Switch Swarm'
+ : 'Swarm: $title. Switch Swarm',
onTitle: () => unawaited(showSwarmSwitcher(context, session)),
);
}
@@ -327,7 +360,11 @@ class _SwarmPageState extends State<SwarmPage> {
// was until then. Only a server without the list says so, as no read will
// ever bring its rows.
if (!inbox.loaded && inbox.swarms.isEmpty) {
+ final away = swarmHomeListing(inbox)
+ ? _awayCard(context, session, const [], null, widget.now())
+ : null;
return [
+ ?away,
if (inbox.error == swarmServerTooOld)
Padding(
padding: const EdgeInsets.fromLTRB(
@@ -343,7 +380,7 @@ class _SwarmPageState extends State<SwarmPage> {
),
)
else
- ..._reading(),
+ ..._reading(first: away == null),
];
}
final shown = _shown(session);
@@ -360,8 +397,8 @@ class _SwarmPageState extends State<SwarmPage> {
/// While you were away, once the person has been gone [SwarmPage.awayAfter]
/// or more: the work done since in the Swarms shown and what needs them
- /// there now, each unknown while a Swarm, or what waits in it, is not read.
- /// A tap opens Activity.
+ /// there now, each a skeleton while the Swarms, or what waits in them, are
+ /// not read. A tap opens Activity.
Widget? _awayCard(
BuildContext context,
SwarmSession session,
@@ -381,13 +418,14 @@ class _SwarmPageState extends State<SwarmPage> {
return null;
}
final inbox = session.inbox;
- // A Swarm not read, or out of reach, leaves the work done unknown.
- int? done = 0;
- for (final swarm in shown) {
+ final listing = swarmHomeListing(inbox);
+ // A Swarm not read leaves the work done unknown; one no read will bring is
+ // left out, or its skeleton would never end.
+ int? done = listing ? null : 0;
+ for (final swarm in listing ? const <SwarmListing>[] : shown) {
final reader = inbox.reader(swarm.id);
- final snapshot = reader == null || reader.accessRevoked
- ? null
- : reader.snapshot;
+ if (reader != null && _ended(reader)) continue;
+ final snapshot = reader?.snapshot;
done = snapshot == null ? null : done! + swarmDoneSince(snapshot, since);
if (done == null) break;
}
@@ -400,7 +438,9 @@ class _SwarmPageState extends State<SwarmPage> {
back: back,
done: done,
// None found is not none waiting until all of it is read.
- needs: needs > 0 || _needsRead(inbox, shown) ? needs : null,
+ needs: !listing && (needs > 0 || _needsRead(inbox, shown))
+ ? needs
+ : null,
onTap: () {
if (!showSwarmTab(context, SwarmTab.activity)) {
openSwarmNeeds(context, swarmId: picked);
@@ -411,9 +451,10 @@ class _SwarmPageState extends State<SwarmPage> {
}
/// Pinned, then Projects: every project of the Swarms shown, grouped by
- /// [swarmHomeLists]; a Swarm still to be read has rows on their way, one
- /// that could not be read says so. The first caption is the screen's
- /// [first] thing, with nothing over it.
+ /// [swarmHomeLists]; a Swarm still to be read has rows on their way, a
+ /// failed read still trying too, as it is in the log. One no read will bring
+ /// says so. The first caption is the screen's [first] thing, with nothing
+ /// over it.
List<Widget> _projects(
BuildContext context,
SwarmSession session,
@@ -437,11 +478,13 @@ class _SwarmPageState extends State<SwarmPage> {
final several = shown.length > 1;
final projects = <SwarmHomeProject>[];
final glances = <String, SwarmTeamGlance>{};
- final people = <String, List<SuperTabPerson>>{};
+ final humans = <String, int>{};
final names = <String, String>{};
final reading = <String>[];
final failed = <(String, String)>[];
+ final asking = <String>{};
for (final swarm in shown) {
+ if (inbox.asks(swarm.id)?.loading ?? false) asking.add(swarm.id);
switch (inbox.reader(swarm.id)) {
case final SwarmReader reader when reader.snapshot != null:
final snapshot = reader.snapshot!;
@@ -456,11 +499,12 @@ class _SwarmPageState extends State<SwarmPage> {
);
projects.add(row);
glances[row.key] = swarmTeamGlance(snapshot, projectId: project.id);
- people[row.key] = swarmProjectPeople(snapshot, project);
+ humans[row.key] = swarmProjectPeople(snapshot, project).length;
names[row.key] = swarm.name;
}
- case SwarmReader(error: final error?):
- failed.add((swarm.id, error));
+ case final SwarmReader reader
+ when _ended(reader) && reader.error != null:
+ failed.add((swarm.id, reader.error!));
case _:
reading.add(swarm.id);
}
@@ -470,9 +514,10 @@ class _SwarmPageState extends State<SwarmPage> {
key: ValueKey('swarm-project-${project.swarmId}-${project.project.id}'),
project: project,
glance: glances[project.key]!,
- people: people[project.key]!,
+ humans: humans[project.key]!,
now: now,
swarmName: several ? names[project.key] : null,
+ tagsLoading: asking.contains(project.swarmId),
onTap: () => _openProject(context, project.swarmId, project.project.id),
onLongPress: () => unawaited(_pin(context, session, project)),
);
@@ -516,18 +561,14 @@ class _SwarmPageState extends State<SwarmPage> {
SwarmCaption('Projects', first: first && lists.pinned.isEmpty),
for (final (i, id) in reading.indexed) ...[
if (projects.isNotEmpty || i > 0) const SizedBox(height: 8),
- SwarmSkeletonRows(id: 'swarm-projects-loading-$id'),
+ SwarmSkeletonRows(id: 'swarm-projects-loading-$id', dot: true),
],
for (final (id, error) in failed) ...[
const SizedBox(height: 8),
SwarmGroup(
key: ValueKey('swarm-projects-error-$id'),
children: [
- SwarmRow(
- title: error,
- detail: SwarmRow.line('Pull down to try again.'),
- onTap: null,
- ),
+ SwarmRow(title: error, onTap: null),
],
),
],
@@ -576,17 +617,31 @@ class _SwarmPageState extends State<SwarmPage> {
}
/// Home before the list answers: the projects as rows on their way.
- List<Widget> _reading() => [
- const SwarmCaption('Projects', first: true),
- SwarmSkeletonRows(id: 'swarm-projects-loading'),
+ List<Widget> _reading({required bool first}) => [
+ SwarmCaption('Projects', first: first),
+ SwarmSkeletonRows(id: 'swarm-projects-loading', dot: true),
];
}
+/// A Swarm's tile on its way.
+const _loadingTile = Skeleton(
+ width: 32,
+ height: 32,
+ radius: AppCard.insetRadius,
+);
+
+/// Whether no read will bring this Swarm: the reader may no longer read it, or
+/// the backend needs a newer build, with nothing read before then.
+bool _ended(SwarmReader reader) =>
+ reader.snapshot == null && (reader.accessRevoked || reader.updateRequired);
+
/// Whether what waits on the person in every Swarm [shown] is read: the
-/// Swarm, and what waits in it since it was last read in full.
+/// Swarm, and what waits in it since it was last read in full. One no read
+/// will bring has nothing more to wait for.
bool _needsRead(SwarmInbox inbox, List<SwarmListing> shown) => shown.every(
(swarm) => switch (inbox.reader(swarm.id)) {
+ final reader? when _ended(reader) => true,
SwarmReader(snapshot: _?, accessRevoked: false) => switch (inbox.asks(
swarm.id,
)) {
diff --git a/mobile/lib/swarm/swarm_project_team.dart b/mobile/lib/swarm/swarm_project_team.dart
index 5aa04c1e6..f05e40d72 100644
--- a/mobile/lib/swarm/swarm_project_team.dart
+++ b/mobile/lib/swarm/swarm_project_team.dart
@@ -24,7 +24,7 @@ import 'team_glance.dart';
/// "3 humans · 5 agents", the people and agents of a project in words; the
/// agents left out when there are none, as the team's line then says so.
String swarmProjectHeads({required int humans, required int agents}) => [
- humans == 1 ? '1 human' : '$humans humans',
+ swarmHumans(humans),
if (agents > 0) agents == 1 ? '1 agent' : '$agents agents',
].join(' · ');
diff --git a/mobile/lib/swarm/swarm_reader.dart b/mobile/lib/swarm/swarm_reader.dart
index 8b68cf684..90391cd2a 100644
--- a/mobile/lib/swarm/swarm_reader.dart
+++ b/mobile/lib/swarm/swarm_reader.dart
@@ -3,6 +3,8 @@ import 'dart:isolate';
import 'package:flutter/foundation.dart';
+import 'package:harness_mobile/logging/app_log.dart';
+
import 'model.dart';
import 'parts.dart';
import 'swarm_buddy.dart';
@@ -240,6 +242,10 @@ class SwarmReader extends ChangeNotifier {
error = 'Could not reach this Swarm. Try again.';
changed = true;
}
+ // Once per failure, not once per poll. Home shows its skeleton meanwhile.
+ if (error case final failed? when failed != failedBefore) {
+ appLog.warn('swarm', 'Swarm $tabId not read: $failed');
+ }
if (changed || error != failedBefore) notifyListeners();
}
diff --git a/mobile/lib/swarm/swarm_session.dart b/mobile/lib/swarm/swarm_session.dart
index c9cff986b..bb5400ed2 100644
--- a/mobile/lib/swarm/swarm_session.dart
+++ b/mobile/lib/swarm/swarm_session.dart
@@ -216,6 +216,7 @@ class SwarmSession extends ChangeNotifier {
class SwarmHost extends ChangeNotifier {
SwarmHost({
required this.accountId,
+ this.accountReading,
required this.account,
required this.request,
this.upload = refuseSwarmUpload,
@@ -239,6 +240,10 @@ class SwarmHost extends ChangeNotifier {
/// The signed-in account's id; null while nobody is.
final String? Function() accountId;
+ /// Whether someone is signed in and [accountId] is on its way; null where
+ /// nobody can tell, and no account is taken to be coming.
+ final bool Function()? accountReading;
+
/// Tells when [accountId] may have changed.
final Listenable account;
final SwarmRequest request;
@@ -277,6 +282,13 @@ class SwarmHost extends ChangeNotifier {
SwarmSession? session;
bool _foreground = true;
+ /// No session yet, only because the account is on its way: Swarm is on and
+ /// someone is signed in, so Home shows its skeleton, not that Swarm is off.
+ bool get accountComing =>
+ session == null &&
+ features.isOn(PhoneExperiment.swarm) &&
+ (accountReading?.call() ?? false);
+
/// Whether Swarm was on at the last [_update]; null before the first.
bool? _on;
@@ -301,6 +313,8 @@ class SwarmHost extends ChangeNotifier {
// frame, so this is known, and what an earlier run kept goes. A missing
// account is not: the signed-in shell is up before the account is read.
if (!on && wasOn != false) unawaited(homeCache.clear());
+ // No session either way, but [accountComing] may have moved with it.
+ if (wasOn != null && on != wasOn) notifyListeners();
return;
}
// Signed out, another account, or Swarm turned off: nothing of it stays.
@@ -348,6 +362,15 @@ class SwarmScope extends InheritedNotifier<SwarmHost> {
?.notifier
?.session;
+ /// Whether there is no session only because the account is on its way
+ /// ([SwarmHost.accountComing]); false outside the shell.
+ static bool accountComingOf(BuildContext context) =>
+ context
+ .dependOnInheritedWidgetOfExactType<SwarmScope>()
+ ?.notifier
+ ?.accountComing ??
+ false;
+
/// How an avatar photo goes up ([SwarmHost.uploadAvatar]); null outside
/// the shell or where none can.
static SwarmAvatarUpload? uploadAvatarOf(BuildContext context) => context
diff --git a/mobile/lib/swarm/swarm_style.dart b/mobile/lib/swarm/swarm_style.dart
index 77f732b66..9d488adef 100644
--- a/mobile/lib/swarm/swarm_style.dart
+++ b/mobile/lib/swarm/swarm_style.dart
@@ -134,6 +134,7 @@ class SwarmTabHeader extends StatelessWidget {
this.onTitle,
this.titleLabel,
this.subtitle,
+ this.loading = false,
});
final String title;
@@ -143,18 +144,28 @@ class SwarmTabHeader extends StatelessWidget {
final String? titleLabel;
final String? subtitle;
+ /// The title is on its way: a bar as tall as its words in their place.
+ final bool loading;
+
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
- final text = Text(
- title,
- key: const ValueKey('swarm-title'),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: Tty.of(context)
- .style(size: 20, weight: FontWeight.w600)
- .copyWith(height: 1.2),
- );
+ final style = Tty.of(
+ context,
+ ).style(size: 20, weight: FontWeight.w600).copyWith(height: 1.2);
+ final text = loading
+ ? SkeletonText(
+ key: const ValueKey('swarm-title-loading'),
+ style: style,
+ width: 120,
+ )
+ : Text(
+ title,
+ key: const ValueKey('swarm-title'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: style,
+ );
final onTitle = this.onTitle;
final head = _title(text, onTitle);
return ConstrainedBox(
@@ -342,12 +353,14 @@ class SwarmGroup extends StatelessWidget {
/// left, a bar for its title and a longer one for the line under it, each as
/// tall as the line it stands for ([SkeletonText]), so nothing moves when the
/// row arrives. It stands for a card's row (`SwarmRow`) with a line under its
-/// title — a need's, a project's on Home — or its title alone ([titleOnly]).
+/// title — a need's — or its title alone ([titleOnly]), or a project's on Home
+/// ([dot]).
class SwarmSkeletonRow extends StatelessWidget {
const SwarmSkeletonRow({
super.key,
this.round = false,
this.titleOnly = false,
+ this.dot = false,
this.width = .45,
});
@@ -357,6 +370,10 @@ class SwarmSkeletonRow extends StatelessWidget {
/// The row it stands for has no line under its title.
final bool titleOnly;
+ /// A project's small dot on Home ([SwarmHomeProjectRow]) rather than a tile,
+ /// in the room that row keeps for it.
+ final bool dot;
+
/// The title bar's share of the row's words.
final double width;
@@ -374,13 +391,23 @@ class SwarmSkeletonRow extends StatelessWidget {
),
child: Row(
children: [
- Skeleton(
- width: 32,
- height: 32,
- radius: 8,
- shape: round ? BoxShape.circle : BoxShape.rectangle,
- ),
- const SizedBox(width: 12),
+ if (dot) ...[
+ const SizedBox(
+ width: 16,
+ child: Center(
+ child: Skeleton(width: 8, height: 8, shape: BoxShape.circle),
+ ),
+ ),
+ const SizedBox(width: AppSpace.s),
+ ] else ...[
+ Skeleton(
+ width: 32,
+ height: 32,
+ radius: 8,
+ shape: round ? BoxShape.circle : BoxShape.rectangle,
+ ),
+ const SizedBox(width: 12),
+ ],
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -413,6 +440,7 @@ class SwarmSkeletonRows extends StatelessWidget {
this.rows = 2,
this.round = false,
this.titleOnly = false,
+ this.dot = false,
}) : super(key: ValueKey(id));
final String id;
@@ -424,6 +452,9 @@ class SwarmSkeletonRows extends StatelessWidget {
/// Rows with no line under their titles ([SwarmSkeletonRow.titleOnly]).
final bool titleOnly;
+ /// Projects' dots on Home ([SwarmSkeletonRow.dot]).
+ final bool dot;
+
@override
Widget build(BuildContext context) {
final children = [
@@ -434,6 +465,7 @@ class SwarmSkeletonRows extends StatelessWidget {
key: ValueKey('$id-$i'),
round: round,
titleOnly: titleOnly,
+ dot: dot,
width: i.isEven ? .45 : .6,
),
),
@@ -450,7 +482,6 @@ class SwarmAvatar extends StatelessWidget {
required this.id,
required this.name,
this.size = 32,
- this.ring,
this.picture,
this.status,
});
@@ -458,9 +489,6 @@ class SwarmAvatar extends StatelessWidget {
final String id, name;
final double size;
- /// A ring of this colour around it, where avatars overlap.
- final Color? ring;
-
/// What they chose to wear; null wears the initial.
final SuperTabAvatarPicture? picture;
@@ -494,19 +522,7 @@ class SwarmAvatar extends StatelessWidget {
name: name,
size: size,
status: status,
- face: ring == null
- ? face
- : DecoratedBox(
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- border: Border.all(
- color: ring!,
- width: 2,
- strokeAlign: BorderSide.strokeAlignOutside,
- ),
- ),
- child: face,
- ),
+ face: face,
);
}
}
diff --git a/mobile/lib/swarm/team_glance.dart b/mobile/lib/swarm/team_glance.dart
index fc2dd0a1d..b3595ddf0 100644
--- a/mobile/lib/swarm/team_glance.dart
+++ b/mobile/lib/swarm/team_glance.dart
@@ -56,15 +56,17 @@ class SwarmTeamGlance {
: parts.map((part) => part.text).join(' · ');
/// "5 agents running", counting who [working] counts: what a project's row
- /// on Home says of its team.
- late final String running = switch (working) {
- _ when agents.isEmpty => 'No agents yet',
- 0 => 'No agents running',
+ /// on Home says of its team. Null with nobody running.
+ late final String? running = switch (working) {
+ 0 => null,
1 => '1 agent running',
final n => '$n agents running',
};
}
+/// "1 human", "3 humans".
+String swarmHumans(int count) => count == 1 ? '1 human' : '$count humans';
+
const _finished = {'done', 'stopped', 'cancelled'};
/// The team of [snapshot], or of its project [projectId]: an agent is in the
diff --git a/mobile/test/api/api_client_test.dart b/mobile/test/api/api_client_test.dart
index b044903dd..a96da726f 100644
--- a/mobile/test/api/api_client_test.dart
+++ b/mobile/test/api/api_client_test.dart
@@ -146,6 +146,85 @@ void main() {
Map<String, Object?> ok(Object? data) => {'success': true, 'data': data};
+ group('a Swarm read', () {
+ test('answers the value, signed with this sign-in, its query kept', () async {
+ backend.answer = (_, _) => (status: 200, body: ok({'tabs': <Object>[]}));
+
+ final value = await client(_Tokens(['t1'])).swarmRead(
+ '/api/super-tabs/t/changes?cursor=c1',
+ );
+
+ expect(value, {'tabs': <Object>[]});
+ final request = backend.requests.single;
+ expect(request.method, 'GET');
+ expect(request.path, '/api/super-tabs/t/changes');
+ expect(request.query, {'cursor': 'c1'});
+ expect(request.headers.value('authorization'), 'Bearer t1');
+ });
+
+ test('with no credentials never reaches the backend', () async {
+ final api = ApiClient(
+ config: const AppConfig(apiBaseUrl: 'https://api.invalid'),
+ session: AuthSession(storage: MemoryKeyValueStore()),
+ httpClientAdapter: backend,
+ );
+ await expectLater(api.swarmRead('/api/super-tabs/list'), throwsStateError);
+ expect(backend.requests, isEmpty);
+ });
+
+ Matcher failure(String code, int status, [String? message]) =>
+ isA<SuperTabFailure>()
+ .having((f) => f.code, 'code', code)
+ .having((f) => f.statusCode, 'statusCode', status)
+ .having(
+ (f) => f.message,
+ 'message',
+ message ?? isNotEmpty,
+ );
+
+ test("a refusal carries the backend's code, status and words", () async {
+ backend.answer = (_, _) => (
+ status: 403,
+ body: {
+ 'success': false,
+ 'error': {'code': 'FORBIDDEN', 'message': 'Not a member.'},
+ },
+ );
+
+ await expectLater(
+ client(_Tokens(['t1'])).swarmRead('/api/super-tabs/t/parts'),
+ throwsA(failure('FORBIDDEN', 403, 'Not a member.')),
+ );
+ });
+
+ test('426 asks for an update, whatever the body says', () async {
+ backend.answer = (_, _) => (status: 426, body: {'success': false});
+
+ await expectLater(
+ client(_Tokens(['t1'])).swarmRead('/api/super-tabs/list'),
+ throwsA(failure('UPDATE_REQUIRED', 426)),
+ );
+ });
+
+ test('a 502 from a proxy, not JSON, keeps its status', () async {
+ backend.answer = (_, _) => (status: 502, body: '<html>Bad gateway</html>');
+
+ await expectLater(
+ client(_Tokens(['t1'])).swarmRead('/api/super-tabs/list'),
+ throwsA(failure('BACKEND_UNAVAILABLE', 502)),
+ );
+ });
+
+ test('a 200 that does not say success is no answer', () async {
+ backend.answer = (_, _) => (status: 200, body: {'data': 'stray'});
+
+ await expectLater(
+ client(_Tokens(['t1'])).swarmRead('/api/super-tabs/list'),
+ throwsA(failure('BACKEND_UNAVAILABLE', 200)),
+ );
+ });
+ });
+
group('signing', () {
test(
'a real API call without credentials fails before transport',
diff --git a/mobile/test/app_state_phone_paths_test.dart b/mobile/test/app_state_phone_paths_test.dart
index 774a041ac..41479fb30 100644
--- a/mobile/test/app_state_phone_paths_test.dart
+++ b/mobile/test/app_state_phone_paths_test.dart
@@ -4,6 +4,7 @@ import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/core/local_key_value_store.dart';
import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/logging/app_log.dart';
import 'package:harness_mobile/settings/config_store.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/state/desk_sync.dart';
@@ -310,6 +311,97 @@ void main() {
expect(rig.app.currentUser, isNull);
});
+ group('the account this sign-in last said it was', () {
+ test('a first launch knows nobody until the account says', () async {
+ final rig = viewerApp();
+ addTearDown(rig.app.dispose);
+ final profile = Completer<Map<String, dynamic>?>();
+ rig.api.onProfile = () => profile.future;
+
+ await rig.app.bootstrap();
+
+ expect(rig.app.swarmAccountId, isNull);
+ expect(rig.app.accountReading, isTrue);
+
+ profile.complete(rig.api.profile);
+ await settle();
+
+ expect(rig.app.swarmAccountId, 'u1');
+ expect(await rig.app.session.accountId(), 'u1');
+ expect(rig.app.accountReading, isFalse);
+ });
+
+ test('the next launch has it before the account answers', () async {
+ final rig = viewerApp();
+ addTearDown(rig.app.dispose);
+ await rig.app.session.saveAccountId('u1');
+ final seen = <String?>[];
+ rig.app.addListener(() {
+ if (rig.app.status == AppStatus.authenticated) {
+ seen.add(rig.app.swarmAccountId);
+ }
+ });
+ final profile = Completer<Map<String, dynamic>?>();
+ rig.api.onProfile = () => profile.future;
+
+ await rig.app.bootstrap();
+
+ expect(rig.app.currentUser, isNull);
+ expect(rig.app.swarmAccountId, 'u1');
+ expect(rig.app.accountReading, isFalse);
+ expect(seen.first, 'u1', reason: 'from the first frame of the shell');
+ });
+
+ test('the account naming another wins, and is what the next launch '
+ 'reads', () async {
+ final rig = viewerApp();
+ addTearDown(rig.app.dispose);
+ await rig.app.session.saveAccountId('u1');
+ final profile = Completer<Map<String, dynamic>?>();
+ rig.api.onProfile = () => profile.future;
+
+ await rig.app.bootstrap();
+ profile.complete({
+ 'user': {'id': 'u2', 'email': '[email protected]'},
+ });
+ await settle();
+
+ expect(rig.app.swarmAccountId, 'u2');
+ expect(await rig.app.session.accountId(), 'u2');
+ });
+
+ test('is no one once signed out, and a late profile brings it not '
+ 'back', () async {
+ final rig = viewerApp();
+ addTearDown(rig.app.dispose);
+ await rig.app.session.saveAccountId('u1');
+ final profile = Completer<Map<String, dynamic>?>();
+ rig.api.onProfile = () => profile.future;
+
+ await rig.app.bootstrap();
+ await rig.app.session.clear();
+ await rig.app.logout();
+ profile.complete(rig.api.profile);
+ await settle();
+
+ expect(rig.app.swarmAccountId, isNull);
+ expect(await rig.app.session.accountId(), isNull);
+ });
+
+ test('names no one while the app is not signed in', () async {
+ final rig = viewerApp();
+ addTearDown(rig.app.dispose);
+ await rig.app.session.saveAccountId('u1');
+ rig.api.onProfile = () => Completer<Map<String, dynamic>?>().future;
+
+ await rig.app.bootstrap();
+ expect(rig.app.swarmAccountId, 'u1');
+ rig.app.status = AppStatus.unauthenticated;
+
+ expect(rig.app.swarmAccountId, isNull);
+ });
+ });
+
test('a profile that cannot be read leaves the app signed in', () async {
final rig = viewerApp();
addTearDown(rig.app.dispose);
@@ -494,6 +586,131 @@ void main() {
});
group('the timers', () {
+ test('a profile read that fails is asked for again, less often each time, '
+ 'and goes in the log once; a read that works ends it', () {
+ fakeAsync((async) {
+ final before = appLog;
+ final log = _Log();
+ appLog = log;
+ addTearDown(() => appLog = before);
+ final rig = viewerApp();
+ final failure = StateError('No profile');
+ rig.api.onProfile = () async => throw failure;
+
+ rig.app.bootstrap();
+ async.flushMicrotasks();
+ expect(rig.api.profileReads, 1);
+ expect(rig.app.status, AppStatus.authenticated);
+ expect(rig.app.accountReading, isTrue);
+
+ async.elapse(const Duration(seconds: 4));
+ expect(rig.api.profileReads, 1);
+ async.elapse(const Duration(seconds: 1));
+ expect(rig.api.profileReads, 2, reason: 'after 5 seconds');
+ async.elapse(const Duration(seconds: 9));
+ expect(rig.api.profileReads, 2);
+ async.elapse(const Duration(seconds: 1));
+ expect(rig.api.profileReads, 3, reason: '10 seconds after that');
+ expect(rig.app.accountReading, isTrue);
+ expect(log.errors, [failure], reason: 'once, not once per read');
+
+ rig.api.onProfile = null;
+ async.elapse(const Duration(seconds: 20));
+ expect(rig.api.profileReads, 4, reason: '20 seconds after that');
+ expect(rig.app.currentUser, isNotNull);
+ expect(rig.app.accountReading, isFalse);
+
+ async.elapse(const Duration(minutes: 5));
+ expect(rig.api.profileReads, 4, reason: 'read: nothing asks again');
+
+ rig.app.dispose();
+ });
+ });
+
+ test('a profile read keeps failing: asked for once a minute at most', () {
+ fakeAsync((async) {
+ final rig = viewerApp();
+ rig.api.onProfile = () async => throw StateError('No profile');
+
+ rig.app.bootstrap();
+ async.flushMicrotasks();
+ // 5 + 10 + 20 + 40 seconds, then each minute.
+ async.elapse(const Duration(seconds: 75));
+ expect(rig.api.profileReads, 5);
+ async.elapse(const Duration(seconds: 59));
+ expect(rig.api.profileReads, 5);
+ async.elapse(const Duration(seconds: 1));
+ expect(rig.api.profileReads, 6);
+
+ rig.app.dispose();
+ });
+ });
+
+ test('an account that gives no profile is asked for again too', () {
+ fakeAsync((async) {
+ final rig = viewerApp();
+ rig.api.profile = null;
+
+ rig.app.bootstrap();
+ async.flushMicrotasks();
+ expect(rig.app.accountReading, isTrue);
+ expect(rig.app.lastError, isNull);
+ async.elapse(const Duration(seconds: 5));
+ expect(rig.api.profileReads, 2);
+
+ rig.app.dispose();
+ });
+ });
+
+ test('signed out or disposed, nothing asks for the profile again', () {
+ fakeAsync((async) {
+ final rig = viewerApp();
+ rig.api.onProfile = () async => throw StateError('No profile');
+ rig.app.bootstrap();
+ async.flushMicrotasks();
+
+ rig.app.logout();
+ async.flushMicrotasks();
+ final reads = rig.api.profileReads;
+ expect(rig.app.accountReading, isFalse, reason: 'nobody signed in');
+ async.elapse(const Duration(minutes: 5));
+ expect(rig.api.profileReads, reads);
+ rig.app.dispose();
+
+ final other = viewerApp();
+ other.api.onProfile = () async => throw StateError('No profile');
+ other.app.bootstrap();
+ async.flushMicrotasks();
+ other.app.dispose();
+ async.elapse(const Duration(minutes: 5));
+ expect(other.api.profileReads, 1);
+ });
+ });
+
+ test('back in front with no account yet, it is read at once', () {
+ fakeAsync((async) {
+ final rig = viewerApp();
+ rig.api.onProfile = () async => throw StateError('No profile');
+ rig.app.bootstrap();
+ async.flushMicrotasks();
+ rig.app.handleAppPaused();
+ expect(rig.api.profileReads, 1);
+
+ rig.api.onProfile = null;
+ rig.app.handleAppResumed();
+ async.flushMicrotasks();
+ expect(rig.api.profileReads, 2);
+ expect(rig.app.currentUser, isNotNull);
+
+ rig.app.handleAppPaused();
+ rig.app.handleAppResumed();
+ async.flushMicrotasks();
+ expect(rig.api.profileReads, 2, reason: 'known: not read again');
+
+ rig.app.dispose();
+ });
+ });
+
test(
'an offline machine something waits on is asked about every few seconds',
() {
@@ -620,3 +837,18 @@ class _Unreadable implements LocalKeyValueStore {
@override
Future<void> delete(String key) async => throw StateError('locked');
}
+
+class _Log implements AppLog {
+ final errors = <Object?>[];
+
+ @override
+ void record(
+ AppLogLevel level,
+ String category,
+ String message, {
+ Object? error,
+ StackTrace? stackTrace,
+ }) {
+ if (category == 'auth') errors.add(error);
+ }
+}
diff --git a/mobile/test/sample_runtime_test.dart b/mobile/test/sample_runtime_test.dart
index f6f95538d..8517b9f3f 100644
--- a/mobile/test/sample_runtime_test.dart
+++ b/mobile/test/sample_runtime_test.dart
@@ -11,6 +11,11 @@ void main() {
});
tearDown(() => runtime.dispose());
+ test('the sample has no account on its way for Swarm to wait for', () {
+ expect(runtime.notifier.currentUser, isNull);
+ expect(runtime.notifier.accountReading, isFalse);
+ });
+
test('sample folders and git metadata come from fixtures', () async {
final home = await connection.request(
'fs_list_dir',
diff --git a/mobile/test/swarm/swarm_asks_test.dart b/mobile/test/swarm/swarm_asks_test.dart
index 373942642..d372e9f36 100644
--- a/mobile/test/swarm/swarm_asks_test.dart
+++ b/mobile/test/swarm/swarm_asks_test.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/logging/app_log.dart';
import 'package:harness_mobile/swarm/swarm_asks.dart';
import 'package:harness_mobile/swarm/swarm_reader.dart';
import 'package:harness_mobile/swarm/swarm_request.dart';
@@ -236,6 +237,28 @@ void main() {
expect(r.asks.error, isNotNull);
});
+ test('goes in the log once, however many reads of the asks fail', () async {
+ final before = appLog;
+ final log = _Log();
+ appLog = log;
+ addTearDown(() => appLog = before);
+ final r = rig(decisions: 1);
+ final failure = const SuperTabFailure('INTERNAL', 'Broken');
+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) =>
+ throw failure;
+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+
+ await r.reader.refresh();
+ await settle();
+ await r.reader.refresh();
+ await settle();
+
+ expect(r.asks.error, isNotNull);
+ expect(log.errors, [failure]);
+ });
+
test('ends when the Swarm itself could not be read', () async {
final r = rig();
r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>
@@ -726,3 +749,16 @@ void main() {
},
);
}
+
+class _Log implements AppLog {
+ final errors = <Object?>[];
+
+ @override
+ void record(
+ AppLogLevel level,
+ String category,
+ String message, {
+ Object? error,
+ StackTrace? stackTrace,
+ }) => errors.add(error);
+}
diff --git a/mobile/test/swarm/swarm_home_account_test.dart b/mobile/test/swarm/swarm_home_account_test.dart
new file mode 100644
index 000000000..618e637f3
--- /dev/null
+++ b/mobile/test/swarm/swarm_home_account_test.dart
@@ -0,0 +1,188 @@
+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_page.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Swarm Home on opening the app: the signed-in shell is up before the account
+/// is read, and that is no reason to say Swarm is off.
+void main() {
+ Finder key(String value) => find.byKey(ValueKey(value));
+
+ Future<void> frames(WidgetTester tester) async {
+ for (var i = 0; i < 5; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ 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();
+ return fake;
+ }
+
+ Future<SwarmHost> pump(
+ WidgetTester tester, {
+ required ValueNotifier<String?> account,
+ bool Function()? reading,
+ ExperimentalFeaturesStore? features,
+ }) async {
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ accountReading: reading,
+ account: account,
+ request: backend().request,
+ notices: SilentSystemNotices(),
+ features:
+ features ??
+ (ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm}),
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmPage(),
+ ),
+ );
+ await frames(tester);
+ return host;
+ }
+
+ testWidgets('while the account is on its way, Home is skeletons and never '
+ 'says Swarm is off', (tester) async {
+ final account = ValueNotifier<String?>(null);
+ final host = await pump(tester, account: account, reading: () => true);
+
+ expect(host.session, isNull);
+ expect(key('swarm-unavailable'), findsNothing);
+ expect(find.textContaining('Swarm is off'), findsNothing);
+ expect(key('swarm-title-loading'), findsOneWidget);
+ expect(key('swarm-title'), findsNothing);
+ expect(key('swarm-projects-loading'), findsOneWidget);
+ });
+
+ testWidgets('the account read: the Swarm comes where its skeleton was', (
+ tester,
+ ) async {
+ final account = ValueNotifier<String?>(null);
+ var reading = true;
+ final host = await pump(tester, account: account, reading: () => reading);
+ final title = tester.getTopLeft(key('swarm-title-loading'));
+ final rows = tester.getTopLeft(key('swarm-projects-loading'));
+
+ reading = false;
+ account.value = me;
+ await tester.pumpAndSettle();
+
+ expect(host.session, isNotNull);
+ expect(key('swarm-account-coming'), findsNothing);
+ expect(key('swarm-unavailable'), findsNothing);
+ expect(tester.widget<Text>(key('swarm-title')).data, 'Phone Swarm');
+ expect(tester.getTopLeft(key('swarm-title')).dx, closeTo(title.dx, .01));
+ expect(
+ tester.getTopLeft(key('swarm-project-$tab-$project')).dx,
+ closeTo(rows.dx, .01),
+ );
+ });
+
+ testWidgets('a kept account opens Swarm with no skeleton of the account, and '
+ 'the account naming another starts over', (tester) async {
+ final account = ValueNotifier<String?>(me);
+ final host = await pump(tester, account: account, reading: () => false);
+ final kept = host.session;
+
+ expect(kept?.accountId, me);
+ expect(key('swarm-account-coming'), findsNothing);
+ expect(key('swarm-unavailable'), findsNothing);
+
+ account.value = 'someone-else';
+ await frames(tester);
+
+ expect(host.session?.accountId, 'someone-else');
+ expect(identical(host.session, kept), isFalse);
+ });
+
+ testWidgets('a tap on the title with no account yet does nothing', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ account: ValueNotifier<String?>(null),
+ reading: () => true,
+ );
+
+ await tester.tap(key('swarm-title-button'));
+ await frames(tester);
+
+ expect(tester.takeException(), isNull);
+ expect(key('swarm-switch-join'), findsNothing);
+ });
+
+ testWidgets('with Swarm off, says so even while the account is read', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ account: ValueNotifier<String?>(null),
+ reading: () => true,
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore()),
+ );
+
+ expect(key('swarm-unavailable'), findsOneWidget);
+ expect(key('swarm-title-loading'), findsNothing);
+ expect(key('swarm-projects-loading'), findsNothing);
+ });
+
+ testWidgets('signed out, says so: no account is coming', (tester) async {
+ await pump(
+ tester,
+ account: ValueNotifier<String?>(null),
+ reading: () => false,
+ );
+
+ expect(key('swarm-unavailable'), findsOneWidget);
+ expect(key('swarm-title-loading'), findsNothing);
+ });
+
+ testWidgets('where nobody can tell an account is coming, says so', (
+ tester,
+ ) async {
+ await pump(tester, account: ValueNotifier<String?>(null));
+
+ expect(key('swarm-unavailable'), findsOneWidget);
+ expect(key('swarm-title-loading'), findsNothing);
+ });
+
+ testWidgets('Swarm turned on while the account is read: the skeletons, at '
+ 'once', (tester) async {
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore());
+ await pump(
+ tester,
+ account: ValueNotifier<String?>(null),
+ reading: () => true,
+ features: features,
+ );
+ expect(key('swarm-unavailable'), findsOneWidget);
+
+ await features.set(PhoneExperiment.swarm, true);
+ await frames(tester);
+
+ expect(key('swarm-unavailable'), findsNothing);
+ expect(key('swarm-projects-loading'), findsOneWidget);
+ });
+}
diff --git a/mobile/test/swarm/swarm_home_instant_test.dart b/mobile/test/swarm/swarm_home_instant_test.dart
index b888b60b5..4fac99294 100644
--- a/mobile/test/swarm/swarm_home_instant_test.dart
+++ b/mobile/test/swarm/swarm_home_instant_test.dart
@@ -136,10 +136,10 @@ void main() {
expect(
find.descendant(
of: key('swarm-project-$tab-$project'),
- matching: find.text('No agents running'),
+ matching: find.text('1 human'),
),
findsOneWidget,
- reason: 'its team, Nova waiting on the person',
+ reason: 'its people; Nova waits on the person, so none is running',
);
expect(
[for (final need in host.session!.inbox.needs) need.conversationId],
diff --git a/mobile/test/swarm/swarm_home_test.dart b/mobile/test/swarm/swarm_home_test.dart
index 22cfab24a..2e86faa18 100644
--- a/mobile/test/swarm/swarm_home_test.dart
+++ b/mobile/test/swarm/swarm_home_test.dart
@@ -11,6 +11,7 @@ import 'package:harness_mobile/phone/phone_navigation.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart'
show AppFont, AppPalette;
+import 'package:harness_mobile/shared/widgets/skeleton.dart';
import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
import 'package:harness_mobile/swarm/swarm_home_rows.dart';
import 'package:harness_mobile/swarm/swarm_inbox.dart';
@@ -523,6 +524,7 @@ void main() {
await pump(tester, fake);
expect(key('swarm-projects-loading'), findsNothing);
+ expect(key('swarm-title-loading'), findsNothing, reason: 'none will come');
final line = tester.widget<Text>(key('swarm-too-old'));
expect(line.data, swarmServerTooOld);
expect(line.style?.color, isNot(AppColors.danger));
@@ -559,8 +561,9 @@ void main() {
Future<void> away(
WidgetTester tester,
Duration later,
- void Function(Duration) wait,
- ) async {
+ void Function(Duration) wait, {
+ bool settle = true,
+ }) async {
for (final state in [
AppLifecycleState.inactive,
AppLifecycleState.hidden,
@@ -574,7 +577,8 @@ void main() {
]) {
tester.binding.handleAppLifecycleStateChanged(state);
}
- await tester.pumpAndSettle();
+ // A skeleton breathes for as long as it shows: nothing settles under it.
+ settle ? await tester.pumpAndSettle() : await frames(tester);
}
/// Work its agent said Done at [at].
@@ -720,29 +724,93 @@ void main() {
unawaited(host.session!.inbox.refresh());
await frames(tester);
- expect(inside('swarm-away-needs', find.text('–')), findsOneWidget);
+ expect(inside('swarm-away-needs', find.byType(SkeletonText)), findsOne);
expect(inside('swarm-away-needs', find.text('0')), findsNothing);
gate.complete();
- await tester.pumpAndSettle();
+ await frames(tester);
- expect(inside('swarm-away-needs', find.text('–')), findsOneWidget);
+ expect(inside('swarm-away-needs', find.byType(SkeletonText)), findsOne);
expect(inside('swarm-away-needs', find.text('0')), findsNothing);
});
- testWidgets('the work done is a dash while a Swarm shown is not read', (
- tester,
- ) async {
+ testWidgets('the figures are skeletons while a Swarm shown is not read, '
+ 'its rows on their way, and the failure says nothing', (tester) async {
var now = _halfHourIn();
final fake = backend()
..routes['/api/super-tabs/$tab/parts'] = (_) =>
throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);
- await pump(tester, fake, now: () => now);
- await away(tester, const Duration(hours: 1), (d) => now = now.add(d));
+ await pump(tester, fake, now: () => now, settle: false);
+ await away(
+ tester,
+ const Duration(hours: 1),
+ (d) => now = now.add(d),
+ settle: false,
+ );
+
+ expect(inside('swarm-away-done', find.byType(SkeletonText)), findsOne);
+ expect(inside('swarm-away-needs', find.byType(SkeletonText)), findsOne);
+ expect(key('swarm-projects-loading-$tab'), findsOneWidget);
+ expect(key('swarm-projects-error-$tab'), findsNothing);
+ expect(find.text('Broken'), findsNothing);
+ });
+
+ testWidgets('back from away before the list answers: the card, its figures '
+ 'skeletons, never a false none; the figures once it is read', (
+ tester,
+ ) async {
+ var now = _halfHourIn();
+ final fake = backend();
+ final gate = Completer<void>();
+ final listed = fake.routes['/api/super-tabs/list']!;
+ fake.routes['/api/super-tabs/list'] = (body) async {
+ await gate.future;
+ return listed(body);
+ };
+ await pump(tester, fake, now: () => now, settle: false);
+ await away(
+ tester,
+ const Duration(hours: 1),
+ (d) => now = now.add(d),
+ settle: false,
+ );
+
+ expect(key('swarm-projects-loading'), findsOneWidget);
+ expect(inside('swarm-away-done', find.byType(SkeletonText)), findsOne);
+ expect(inside('swarm-away-needs', find.byType(SkeletonText)), findsOne);
+ expect(inside('swarm-away', find.text('0')), findsNothing);
+
+ gate.complete();
+ await tester.pumpAndSettle();
+
+ expect(inside('swarm-away', find.byType(SkeletonText)), findsNothing);
+ });
+
+ testWidgets('a Swarm no read will bring says why, and leaves no skeleton '
+ 'for ever', (tester) async {
+ var now = _halfHourIn();
+ final fake = backend()
+ ..routes['/api/super-tabs/$tab/parts'] = (_) => throw SuperTabFailure(
+ 'UPDATE_REQUIRED',
+ 'Update',
+ statusCode: 426,
+ );
+ await pump(tester, fake, now: () => now, settle: false);
+ await away(
+ tester,
+ const Duration(hours: 1),
+ (d) => now = now.add(d),
+ settle: false,
+ );
- expect(inside('swarm-away-done', find.text('–')), findsOneWidget);
- expect(inside('swarm-away-needs', find.text('–')), findsOneWidget);
- expect(find.text('Pull down to try again.'), findsOneWidget);
+ expect(key('swarm-projects-error-$tab'), findsOneWidget);
+ expect(
+ find.text('Update Harness to keep using this Swarm.'),
+ findsOneWidget,
+ );
+ expect(key('swarm-projects-loading-$tab'), findsNothing);
+ expect(inside('swarm-away-done', find.text('0')), findsOneWidget);
+ expect(inside('swarm-away', find.byType(SkeletonText)), findsNothing);
});
});
@@ -768,7 +836,7 @@ void main() {
expect(key('swarm-title-button'), findsOneWidget);
});
- testWidgets("a project's row draws who reads it and counts who is running: "
+ testWidgets("a project's row counts who reads it and who is running: "
'a private one only its owner and members', (tester) async {
final fake = backend();
Map<String, dynamic> inProject(String id, String visibility) => {
@@ -809,23 +877,19 @@ void main() {
};
await pump(tester, fake);
- List<String> faces(String row) => [
- for (final avatar in tester.widgetList<SwarmAvatar>(
- inside(row, find.byType(SwarmAvatar)),
- ))
- avatar.id,
- ];
const publicRow = 'swarm-project-$tab-$project';
const privateRow = 'swarm-project-$tab-$web';
- expect(faces(publicRow), [me, 'person-other', 'person-third']);
- expect(faces(privateRow), [me, 'person-other']);
- expect(inside(publicRow, find.text('1 agent running')), findsOneWidget);
- expect(inside(privateRow, find.text('No agents yet')), findsOneWidget);
+ expect(
+ inside(publicRow, find.text('3 humans • 1 agent running')),
+ findsOneWidget,
+ );
+ expect(inside(privateRow, find.text('2 humans')), findsOneWidget);
+ expect(inside(publicRow, find.byType(SwarmAvatar)), findsNothing);
});
testWidgets('a project the Lead tagged the person in is bold and bright '
- 'with @N filled; the rest are quiet; each has its people, how many '
- 'agents are running and when it last moved', (tester) async {
+ 'with @N filled; the rest are quiet; each has how many people read '
+ 'it and when it last moved', (tester) async {
final semantics = tester.ensureSemantics();
await pump(tester, backend());
@@ -840,8 +904,7 @@ void main() {
expect(weightOf(tester, webRow, 'Web'), isNot(AppFont.semibold));
expect(inside(webRow, find.textContaining('@')), findsNothing);
for (final row in [mobileRow, webRow]) {
- expect(inside(row, find.text('No agents running')), findsOneWidget);
- expect(inside(row, key('swarm-team-face-$me')), findsOneWidget);
+ expect(inside(row, find.text('1 human')), findsOneWidget);
expect(inside(row, find.byType(SwarmTeamDots)), findsNothing);
}
expect(inside(mobileRow, find.text('30m')), findsOneWidget);
@@ -1360,7 +1423,7 @@ void main() {
expect(inside(mobileRow, find.text('#Mobile')), findsOneWidget);
expect(inside(backendRow, find.text('#Backend')), findsOneWidget);
expect(
- inside(backendRow, find.textContaining(' · Work Swarm')),
+ inside(backendRow, find.textContaining(' • Work Swarm')),
findsOneWidget,
);
@@ -2496,6 +2559,97 @@ void main() {
double height(WidgetTester tester, String k) =>
tester.getSize(key(k)).height;
+ testWidgets('before the list answers, the title and its tile are '
+ 'skeletons; the Swarm then names them', (tester) async {
+ final fake = backend();
+ final listed = hold(fake, '/api/super-tabs/list');
+ await pump(tester, fake, settle: false);
+
+ expect(key('swarm-title-loading'), findsOneWidget);
+ expect(key('swarm-title'), findsNothing);
+ expect(
+ inside('swarm-title-button', find.byType(Skeleton)),
+ findsWidgets,
+ );
+ expect(find.text('Swarm'), findsNothing, reason: 'no word for a name');
+
+ listed.complete();
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-title-loading'), findsNothing);
+ expect(tester.widget<Text>(key('swarm-title')).data, 'Phone Swarm');
+ expect(
+ inside('swarm-title-button', find.byType(SwarmProjectTile)),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a start screen has no Swarm coming: the title is no skeleton',
+ (tester) async {
+ final fake = backend();
+ final listed = hold(fake, '/api/super-tabs/list');
+ await pump(
+ tester,
+ fake,
+ computers: _Computers(const []),
+ settle: false,
+ );
+
+ expect(find.byType(SwarmStartView), findsOneWidget);
+ expect(key('swarm-title-loading'), findsNothing);
+ expect(tester.widget<Text>(key('swarm-title')).data, 'Swarm');
+
+ listed.complete();
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets('the switcher opened before the list answers has a row on its '
+ 'way, and the Swarm in its place after', (tester) async {
+ final fake = backend();
+ final listed = hold(fake, '/api/super-tabs/list');
+ await pump(tester, fake, settle: false);
+
+ await tester.tap(key('swarm-title-button'));
+ await frames(tester);
+ expect(key('swarm-switch-loading'), findsOneWidget);
+ expect(key('swarm-switch-join'), findsOneWidget);
+
+ listed.complete();
+ await frames(tester);
+ await frames(tester);
+ expect(key('swarm-switch-loading'), findsNothing);
+ expect(key('swarm-switch-$tab'), findsOneWidget);
+ });
+
+ testWidgets('a row has a skeleton where its tags go until what waits is '
+ 'read, then its tags, or nothing', (tester) async {
+ final fake = backend();
+ final asked = hold(fake, '/api/super-tabs/$tab/mentions?state=waiting');
+ final host = await pump(tester, fake, settle: false);
+ await frames(tester);
+ const mobileRow = 'swarm-project-$tab-$project';
+ const webRow = 'swarm-project-$tab-$web';
+
+ expect(host.session!.inbox.asks(tab)!.loading, isTrue);
+ for (final row in [mobileRow, webRow]) {
+ expect(inside(row, key('swarm-project-tags-loading')), findsOneWidget);
+ expect(inside(row, find.byType(SwarmTags)), findsNothing);
+ }
+ final tall = tester.getSize(key(mobileRow)).height;
+
+ asked.complete();
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-project-tags-loading'), findsNothing);
+ expect(inside(mobileRow, find.byType(SwarmTags)), findsOneWidget);
+ expect(inside(webRow, find.byType(SwarmTags)), findsNothing);
+ expect(
+ tester.getSize(key(mobileRow)).height,
+ closeTo(tall, .01),
+ reason: 'the tags come where the skeleton was',
+ );
+ });
+
testWidgets('before the list answers, the projects are skeleton rows, '
'and nothing says it is reading', (tester) async {
final fake = backend();
@@ -2524,6 +2678,17 @@ void main() {
final listed = hold(fake, '/api/super-tabs/list');
await pump(tester, fake, settle: false);
final row = height(tester, 'swarm-projects-loading-0');
+ final loading = find.byKey(
+ const ValueKey('swarm-projects-loading-0'),
+ );
+ final dot = tester.getCenter(
+ find.descendant(of: loading, matching: find.byType(Skeleton)).first,
+ );
+ final title = tester.getTopLeft(
+ find
+ .descendant(of: loading, matching: find.byType(SkeletonText))
+ .first,
+ );
listed.complete();
await tester.pumpAndSettle();
@@ -2533,6 +2698,17 @@ void main() {
closeTo(row, .01),
reason: 'its title and its team, as the skeleton draws them',
);
+ const webRow = 'swarm-project-$tab-$web';
+ expect(
+ tester.getCenter(inside(webRow, key('swarm-project-dot'))).dx,
+ closeTo(dot.dx, .01),
+ reason: 'the dot stays where its skeleton was',
+ );
+ expect(
+ tester.getTopLeft(inside(webRow, find.text('#Web'))).dx,
+ closeTo(title.dx, .01),
+ reason: 'the title stays where its bar was',
+ );
});
}
@@ -2573,16 +2749,25 @@ void main() {
expect(key('swarm-project-$tab-$project'), findsOneWidget);
});
- testWidgets('a Swarm that could not be read says so, with no skeleton '
- 'left', (tester) async {
- final fake = backend()
- ..routes['/api/super-tabs/$tab/parts'] = (_) =>
- throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);
- await pump(tester, fake);
+ testWidgets('a Swarm that could not be read stays on its way, saying '
+ 'nothing, until a read works', (tester) async {
+ final fake = backend();
+ final parts = fake.routes['/api/super-tabs/$tab/parts']!;
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) =>
+ throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);
+ final host = await pump(tester, fake, settle: false);
+
+ expect(host.session!.inbox.reader(tab)!.error, 'Broken');
+ expect(key('swarm-projects-loading-$tab'), findsOneWidget);
+ expect(key('swarm-projects-error-$tab'), findsNothing);
+ expect(find.text('Broken'), findsNothing);
+
+ fake.routes['/api/super-tabs/$tab/parts'] = parts;
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
expect(key('swarm-projects-loading-$tab'), findsNothing);
- expect(key('swarm-projects-error-$tab'), findsOneWidget);
- expect(find.text('Pull down to try again.'), findsOneWidget);
+ expect(key('swarm-project-$tab-$project'), findsOneWidget);
});
});
diff --git a/mobile/test/swarm/swarm_inbox_test.dart b/mobile/test/swarm/swarm_inbox_test.dart
index 4c3576b48..3c8299bf5 100644
--- a/mobile/test/swarm/swarm_inbox_test.dart
+++ b/mobile/test/swarm/swarm_inbox_test.dart
@@ -763,6 +763,23 @@ void main() {
addTearDown(() => appLog = before);
});
+ test('a Swarm that could not be read, once however many reads fail', () async {
+ final fake = backend({'a': []});
+ fake.routes['/api/super-tabs/a/parts'] = (_) =>
+ throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);
+ final i = inbox(fake);
+
+ await i.refresh();
+ final reader = i.reader('a')!;
+ await reader.refresh();
+ await reader.refresh();
+
+ expect(reader.error, 'Broken');
+ expect(log.events, hasLength(1));
+ expect(log.events.single.level, AppLogLevel.warn);
+ expect(log.events.single.message, contains('Swarm a not read: Broken'));
+ });
+
test('what threw, with its stack, once however many polls fail, and '
'again after a read that worked', () async {
final fake = backend({'a': []});
diff --git a/mobile/test/swarm/swarm_new_message_test.dart b/mobile/test/swarm/swarm_new_message_test.dart
index 1dbcfb92c..68d6282dc 100644
--- a/mobile/test/swarm/swarm_new_message_test.dart
+++ b/mobile/test/swarm/swarm_new_message_test.dart
@@ -1103,9 +1103,18 @@ void main() {
final load = fake.routes['/api/super-tabs/$tab/parts']!;
fake.routes['/api/super-tabs/$tab/parts'] = (_) =>
throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);
- final host = await pump(tester, fake);
+ // Home's skeleton breathes while it shows: nothing settles under it.
+ Future<void> frames() async {
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ final host = await pump(tester, fake, settle: false);
+ await frames();
expect(key('swarm-new-message'), findsOneWidget);
- await open(tester);
+ await tester.tap(key('swarm-new-message'));
+ await frames();
expect(key('swarm-new-message-loading'), findsNothing);
expect(key('swarm-new-message-none'), findsNothing);
diff --git a/mobile/test/swarm/swarm_new_project_test.dart b/mobile/test/swarm/swarm_new_project_test.dart
index 8ceb5a86d..dc5ab1d41 100644
--- a/mobile/test/swarm/swarm_new_project_test.dart
+++ b/mobile/test/swarm/swarm_new_project_test.dart
@@ -764,6 +764,7 @@ void main() {
WidgetTester tester,
List<NewProjectSwarm> swarms, {
ValueNotifier<String?>? account,
+ bool settle = true,
}) async {
tester.view.physicalSize = const Size(1170, 2532);
tester.view.devicePixelRatio = 3;
@@ -789,7 +790,7 @@ void main() {
),
),
);
- await tester.pumpAndSettle();
+ if (settle) await tester.pumpAndSettle();
return host;
}
@@ -845,8 +846,10 @@ void main() {
testWidgets('a Swarm whose first read failed offers it once its read '
'recovers', (tester) async {
final swarm = NewProjectSwarm()..unreadable = true;
- final host = await pump(tester, [swarm]);
- expect(key('swarm-projects-error-$tab'), findsOneWidget);
+ final host = await pump(tester, [swarm], settle: false);
+ // A skeleton breathes for as long as it shows: nothing settles under it.
+ await pumpFor(tester);
+ expect(key('swarm-projects-loading-$tab'), findsOneWidget);
expect(key('swarm-new-project'), findsNothing);
swarm.unreadable = false;
diff --git a/mobile/test/swarm/swarm_project_line_test.dart b/mobile/test/swarm/swarm_project_line_test.dart
new file mode 100644
index 000000000..7ebad0378
--- /dev/null
+++ b/mobile/test/swarm/swarm_project_line_test.dart
@@ -0,0 +1,184 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/parts.dart';
+import 'package:harness_mobile/swarm/swarm_home_list.dart';
+import 'package:harness_mobile/swarm/swarm_home_rows.dart';
+import 'package:harness_mobile/swarm/swarm_row.dart';
+import 'package:harness_mobile/swarm/swarm_style.dart';
+import 'package:harness_mobile/swarm/swarm_unread.dart';
+import 'package:harness_mobile/swarm/team_glance.dart';
+
+import 'swarm_fixture.dart';
+
+/// A project's subtitle on Swarm Home: how many humans read it and how many
+/// agents are running, leaving out what is none.
+void main() {
+ final now = DateTime(2026, 10, 27, 9);
+
+ SuperTabSnapshot read({int running = 0, int idle = 0}) {
+ final busy = [for (var i = 0; i < running; i++) 'busy-$i'];
+ return SuperTabSnapshot.fromJson(
+ SuperTabParts.firstLoad(
+ firstLoad(
+ agents: [
+ for (final id in busy) agent(id),
+ for (var i = 0; i < idle; i++) agent('idle-$i'),
+ ],
+ groups: [
+ for (final id in busy)
+ groupData(
+ 'work-$id',
+ title: 'Task of $id',
+ agentIds: [id],
+ status: 'working',
+ workerId: id,
+ ),
+ ],
+ ),
+ ).state,
+ );
+ }
+
+ SwarmTeamGlance glance({int running = 0, int idle = 0}) =>
+ swarmTeamGlance(read(running: running, idle: idle), now: now);
+
+ const line = ValueKey('swarm-project-line');
+
+ Future<void> pump(
+ WidgetTester tester, {
+ int humans = 0,
+ int running = 0,
+ String? swarmName,
+ double width = 390,
+ }) {
+ final snapshot = read(running: running);
+ return tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ // Scrolled, as Home's rows are: a row takes no more height than it
+ // needs.
+ body: SingleChildScrollView(
+ child: Align(
+ alignment: Alignment.topLeft,
+ child: SizedBox(
+ width: width,
+ child: SwarmHomeProjectRow(
+ key: const ValueKey('row'),
+ project: SwarmHomeProject(
+ swarmId: 'tab',
+ project: snapshot.projects.first,
+ active: null,
+ news: swarmNoNews,
+ ),
+ glance: swarmTeamGlance(snapshot, now: now),
+ humans: humans,
+ now: now,
+ swarmName: swarmName,
+ onTap: () {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ group('swarmProjectLine', () {
+ test('counts humans and the agents running, with a bullet between', () {
+ expect(
+ swarmProjectLine(humans: 5, glance: glance(running: 8)),
+ '5 humans • 8 agents running',
+ );
+ });
+
+ test('says one human and one agent in the singular', () {
+ expect(
+ swarmProjectLine(humans: 1, glance: glance(running: 1)),
+ '1 human • 1 agent running',
+ );
+ });
+
+ test('leaves out the agents when none is running, idle or not', () {
+ expect(swarmProjectLine(humans: 3, glance: glance()), '3 humans');
+ expect(swarmProjectLine(humans: 3, glance: glance(idle: 2)), '3 humans');
+ });
+
+ test('leaves out the humans when there are none', () {
+ expect(
+ swarmProjectLine(humans: 0, glance: glance(running: 2)),
+ '2 agents running',
+ );
+ });
+
+ test('is empty with nothing to say', () {
+ expect(swarmProjectLine(humans: 0, glance: glance()), isEmpty);
+ });
+
+ test('ends in the Swarm, with or without counts', () {
+ expect(
+ swarmProjectLine(
+ humans: 2,
+ glance: glance(running: 3),
+ swarmName: 'Acme',
+ ),
+ '2 humans • 3 agents running • Acme',
+ );
+ expect(
+ swarmProjectLine(humans: 0, glance: glance(), swarmName: 'Acme'),
+ 'Acme',
+ );
+ });
+ });
+
+ group('the row', () {
+ testWidgets('draws the line and no faces', (tester) async {
+ await pump(tester, humans: 5, running: 2);
+
+ expect(find.text('5 humans • 2 agents running'), findsOneWidget);
+ expect(find.byType(SwarmAvatar), findsNothing);
+ });
+
+ testWidgets('with nothing to say draws no line and keeps its height', (
+ tester,
+ ) async {
+ await pump(tester);
+
+ expect(find.byKey(line), findsNothing);
+ expect(
+ tester.getSize(find.byKey(const ValueKey('row'))).height,
+ SwarmRow.height,
+ );
+ });
+
+ testWidgets('is heard without the bullet', (tester) async {
+ final semantics = tester.ensureSemantics();
+ await pump(tester, humans: 5, running: 2, swarmName: 'Acme');
+
+ expect(
+ find.bySemanticsLabel(RegExp('5 humans, 2 agents running, Acme')),
+ findsOneWidget,
+ );
+ semantics.dispose();
+ });
+
+ testWidgets('a long line ellipsizes, the Swarm the first to go', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ humans: 12,
+ running: 12,
+ swarmName: 'A Swarm with a name far too long for one row of a phone',
+ width: 240,
+ );
+
+ expect(tester.takeException(), isNull);
+ final text = tester.widget<Text>(find.byKey(line));
+ expect(text.maxLines, 1);
+ expect(text.overflow, TextOverflow.ellipsis);
+ expect(text.data, startsWith('12 humans • 12 agents running • '));
+ });
+ });
+}
diff --git a/mobile/test/swarm/swarm_request_test.dart b/mobile/test/swarm/swarm_request_test.dart
index 7c6e597be..511157d94 100644
--- a/mobile/test/swarm/swarm_request_test.dart
+++ b/mobile/test/swarm/swarm_request_test.dart
@@ -5,6 +5,7 @@ import 'dart:typed_data';
import 'package:dio/dio.dart' show CancelToken;
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/logging/app_log.dart';
import 'package:harness_mobile/swarm/swarm_conversation.dart';
import 'package:harness_mobile/swarm/swarm_file_picker.dart'
show swarmPickerCopyFolders;
@@ -17,13 +18,188 @@ import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';
import '../viewer_app_fixture.dart';
import 'swarm_fixture.dart' show changes, firstLoad, groupData, me, tab;
-/// How the phone reaches the Swarm: one of the account's own machines
-/// forwards the call to the backend with its session (`super_tabs`,
-/// `action: backend` in cli/src/superTabs/service.ts), as the web build does.
-/// The phone holds no Swarm credential of its own.
+/// How the phone reaches the Swarm: a read goes straight to the backend with
+/// the phone's own sign-in, as the web build's does, and on through a machine
+/// when that says nothing of the person. A command, and a read going on, is
+/// forwarded by one of the account's own machines with its session
+/// (`super_tabs`, `action: backend` in cli/src/superTabs/service.ts). The tests
+/// outside the first group have no sign-in to read with (`FakeApi.swarmRead`),
+/// so their reads all go on through the machines.
void main() {
Map<String, dynamic> forwarded(Object? value) => {'ok': true, 'value': value};
+ group('a read goes to the backend itself', () {
+ const path = '/api/super-tabs/list';
+ SuperTabFailure refusal(String code, int status) =>
+ SuperTabFailure(code, 'Refused: $code', statusCode: status);
+
+ test('and with an answer, no machine is asked', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => {'tabs': <Object>[], 'next': null};
+
+ final value = await rig.app.swarmRequest('GET', path);
+
+ expect(value, {'tabs': <Object>[], 'next': null});
+ expect(rig.api.swarmReads, [path]);
+ expect(rig.conn('m').payloadsOf('super_tabs'), isEmpty);
+ });
+
+ test('so it needs no computer connected', () async {
+ final rig = await signedInWith({});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => {'tabs': <Object>[]};
+
+ expect(await rig.app.swarmRequest('GET', path), {'tabs': <Object>[]});
+ });
+
+ test('a value of null is an answer, not a reason to ask a machine', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => null;
+
+ expect(await rig.app.swarmRequest('GET', path), isNull);
+ expect(rig.conn('m').payloadsOf('super_tabs'), isEmpty);
+ });
+
+ test('its query goes with it', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => <String, Object?>{};
+
+ await rig.app.swarmRequest('GET', '/api/super-tabs/t/changes?cursor=c1');
+
+ expect(rig.api.swarmReads, ['/api/super-tabs/t/changes?cursor=c1']);
+ });
+
+ test('a command never does: a machine forwards it', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => fail('a command is not a read');
+ rig.conn('m').answers['super_tabs'] = (_) => forwarded({'result': {}});
+
+ await rig.app.swarmRequest(
+ 'POST',
+ '/api/super-tabs/t/commands',
+ body: {'operationId': 'op'},
+ );
+
+ expect(rig.api.swarmReads, isEmpty);
+ expect(rig.conn('m').payloadsOf('super_tabs'), hasLength(1));
+ });
+
+ for (final (code, status) in const [
+ ('FORBIDDEN', 403),
+ ('NOT_FOUND', 404),
+ ('UPDATE_REQUIRED', 426),
+ ('INVALID_REQUEST', 400),
+ ]) {
+ test('what it refuses stands: $code $status', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => throw refusal(code, status);
+ rig.conn('m').answers['super_tabs'] = (_) => forwarded('from a machine');
+
+ await expectLater(
+ rig.app.swarmRequest('GET', path),
+ throwsA(
+ isA<SuperTabFailure>()
+ .having((f) => f.code, 'code', code)
+ .having((f) => f.statusCode, 'statusCode', status),
+ ),
+ );
+ expect(rig.conn('m').payloadsOf('super_tabs'), isEmpty);
+ });
+ }
+
+ for (final (name, failure) in <(String, Object)>[
+ ('no status', refusal('BACKEND_UNAVAILABLE', 0)),
+ ('a 500', refusal('INTERNAL', 500)),
+ ('a 503', refusal('BACKEND_UNAVAILABLE', 503)),
+ ('an expired session', refusal('UNAUTHORIZED', 401)),
+ ('a rate limit', refusal('RATE_LIMITED', 429)),
+ ('a session of a limited kind', refusal('TEAM_SESSION_LIMITED', 403)),
+ ('no answer at all', const SocketException('offline')),
+ ('no sign-in to read with', StateError('no token source')),
+ ]) {
+ test('$name: a machine reads it instead', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => throw failure;
+ rig.conn('m').answers['super_tabs'] = (_) => forwarded('from a machine');
+
+ expect(await rig.app.swarmRequest('GET', path), 'from a machine');
+ expect(rig.conn('m').payloadsOf('super_tabs'), hasLength(1));
+ });
+ }
+
+ test('no answer and no computer: no computer', () async {
+ final rig = await signedInWith({});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => throw const SocketException('offline');
+
+ await expectLater(
+ rig.app.swarmRequest('GET', path),
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.code,
+ 'code',
+ 'MACHINE_UNAVAILABLE',
+ ),
+ ),
+ );
+ });
+
+ for (final (name, finish) in <(String, void Function(Completer<Object?>))>[
+ ('an answer', (held) => held.complete({'tabs': <Object>[]})),
+ ('a failure', (held) => held.completeError(StateError('late'))),
+ ]) {
+ test('$name that lands after sign-out is dropped', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ final held = Completer<Object?>();
+ rig.api.onSwarmRead = (_) => held.future;
+
+ final read = rig.app.swarmRequest('GET', path);
+ await rig.app.logout();
+ finish(held);
+
+ await expectLater(
+ read,
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.code,
+ 'code',
+ 'ACCOUNT_CHANGED',
+ ),
+ ),
+ );
+ });
+ }
+
+ test('failing again and again goes in the log once, and again only after '
+ 'it answered', () async {
+ final before = appLog;
+ final log = _SwarmLog();
+ appLog = log;
+ addTearDown(() => appLog = before);
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.conn('m').answers['super_tabs'] = (_) => forwarded('from a machine');
+
+ rig.api.onSwarmRead = (_) async => throw StateError('down');
+ await rig.app.swarmRequest('GET', path);
+ await rig.app.swarmRequest('GET', path);
+ expect(log.errors, hasLength(1));
+
+ rig.api.onSwarmRead = (_) async => 'back';
+ await rig.app.swarmRequest('GET', path);
+ rig.api.onSwarmRead = (_) async => throw StateError('down again');
+ await rig.app.swarmRequest('GET', path);
+ expect(log.errors, hasLength(2));
+ });
+ });
+
test(
'a read goes through a connected machine and answers its value',
() async {
@@ -795,3 +971,18 @@ void main() {
});
});
}
+
+class _SwarmLog implements AppLog {
+ final errors = <Object?>[];
+
+ @override
+ void record(
+ AppLogLevel level,
+ String category,
+ String message, {
+ Object? error,
+ StackTrace? stackTrace,
+ }) {
+ if (category == 'swarm') errors.add(error);
+ }
+}
diff --git a/mobile/test/swarm/swarm_screens_test.dart b/mobile/test/swarm/swarm_screens_test.dart
index 98f66cbff..81492294c 100644
--- a/mobile/test/swarm/swarm_screens_test.dart
+++ b/mobile/test/swarm/swarm_screens_test.dart
@@ -254,9 +254,9 @@ void main() {
reason: "River's tag, waiting in it",
);
expect(
- find.descendant(of: row, matching: find.byType(SwarmTeamFaces)),
+ find.descendant(of: row, matching: find.text('1 human')),
findsOneWidget,
- reason: "its people's faces and how many agents are running",
+ reason: 'how many people read it, with no agent running',
);
});
diff --git a/mobile/test/swarm/swarm_snapshot_glance_test.dart b/mobile/test/swarm/swarm_snapshot_glance_test.dart
index 30805cba3..8e81ceb12 100644
--- a/mobile/test/swarm/swarm_snapshot_glance_test.dart
+++ b/mobile/test/swarm/swarm_snapshot_glance_test.dart
@@ -82,12 +82,7 @@ void main() {
expect(glance.line, '1 waiting');
final row = tester
- .widget<SwarmTeamFaces>(
- find.descendant(
- of: key('swarm-project-$tab-$project'),
- matching: find.byType(SwarmTeamFaces),
- ),
- )
+ .widget<SwarmHomeProjectRow>(key('swarm-project-$tab-$project'))
.glance;
expect(reader.snapshot, same(read), reason: 'still the same read');
diff --git a/mobile/test/swarm/swarm_team_faces_test.dart b/mobile/test/swarm/swarm_team_faces_test.dart
deleted file mode 100644
index 7bf50965e..000000000
--- a/mobile/test/swarm/swarm_team_faces_test.dart
+++ /dev/null
@@ -1,217 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/shared/theme/app_theme.dart' show AppGlass;
-import 'package:harness_mobile/swarm/model.dart';
-import 'package:harness_mobile/swarm/parts.dart';
-import 'package:harness_mobile/swarm/swarm_home_rows.dart';
-import 'package:harness_mobile/swarm/swarm_style.dart';
-import 'package:harness_mobile/swarm/team_glance.dart';
-
-import 'swarm_fixture.dart';
-
-/// A project's subtitle on Swarm Home: up to five faces, each over the one
-/// before it, then how many agents are running.
-void main() {
- final now = DateTime(2026, 10, 27, 9);
-
- SwarmTeamGlance glance({int running = 0, int idle = 0}) {
- final busy = [for (var i = 0; i < running; i++) 'busy-$i'];
- return swarmTeamGlance(
- SuperTabSnapshot.fromJson(
- SuperTabParts.firstLoad(
- firstLoad(
- agents: [
- for (final id in busy) agent(id),
- for (var i = 0; i < idle; i++) agent('idle-$i'),
- ],
- groups: [
- for (final id in busy)
- groupData(
- 'work-$id',
- title: 'Task of $id',
- agentIds: [id],
- status: 'working',
- workerId: id,
- ),
- ],
- ),
- ).state,
- ),
- now: now,
- );
- }
-
- List<SuperTabPerson> people(int count) => [
- for (var i = 0; i < count; i++)
- SuperTabPerson.fromJson({...person('p$i'), 'username': 'name$i'}),
- ];
-
- Finder face(int i) => find.byKey(ValueKey('swarm-team-face-p$i'));
-
- Future<void> pump(
- WidgetTester tester,
- SwarmTeamFaces faces, {
- double width = 300,
- }) => tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: Align(
- alignment: Alignment.topLeft,
- child: SizedBox(width: width, child: faces),
- ),
- ),
- ),
- );
-
- testWidgets('draws five faces at most, the first five', (tester) async {
- await pump(tester, SwarmTeamFaces(glance(), people: people(7)));
-
- for (var i = 0; i < 5; i++) {
- expect(face(i), findsOneWidget, reason: 'face $i');
- }
- expect(face(5), findsNothing);
- expect(face(6), findsNothing);
- });
-
- testWidgets('each face overlaps the one before it and is drawn over it', (
- tester,
- ) async {
- await pump(tester, SwarmTeamFaces(glance(), people: people(5)));
-
- for (var i = 1; i < 5; i++) {
- final step =
- tester.getTopLeft(face(i)).dx - tester.getTopLeft(face(i - 1)).dx;
- expect(step, greaterThan(0), reason: 'to the right of the one before');
- expect(
- step,
- lessThan(tester.getSize(face(i - 1)).width),
- reason: 'overlapping the one before',
- );
- }
- final painted = [
- for (final child
- in tester
- .widget<Stack>(
- find.descendant(
- of: find.byKey(const ValueKey('swarm-team-faces')),
- matching: find.byType(Stack),
- ),
- )
- .children)
- ((child as Positioned).child.key! as ValueKey<String>).value,
- ];
- expect(painted, [
- for (var i = 0; i < 5; i++) 'swarm-team-face-p$i',
- ], reason: 'a Stack paints its last child on top');
- expect(
- tester.widget<SwarmAvatar>(face(1)).ring,
- AppGlass.rowFill,
- reason: "the row's colour cuts each face into the one under it",
- );
- });
-
- testWidgets('the faces are as wide as they are many, the count after them', (
- tester,
- ) async {
- await pump(tester, SwarmTeamFaces(glance(running: 2), people: people(2)));
-
- final faces = find.byKey(const ValueKey('swarm-team-faces'));
- expect(
- tester.getTopRight(faces).dx,
- tester.getTopRight(face(1)).dx,
- reason: 'no gap kept for faces that are not there',
- );
- expect(
- tester.getTopLeft(find.text('2 agents running')).dx,
- greaterThan(tester.getTopRight(faces).dx),
- );
- });
-
- testWidgets('a face wears the person: their picture and their initial', (
- tester,
- ) async {
- final wearing = SuperTabPerson.fromJson({
- ...person('p0'),
- 'username': 'river',
- 'avatar': {'kind': 'preset', 'key': 'fox'},
- });
- await pump(tester, SwarmTeamFaces(glance(), people: [wearing]));
-
- final avatar = tester.widget<SwarmAvatar>(face(0));
- expect(avatar.id, 'p0');
- expect(avatar.name, 'river');
- expect((avatar.picture! as SuperTabPresetAvatar).key, 'fox');
- expect(avatar.status, isNull, reason: 'no status at this size');
- });
-
- testWidgets('no people: only the count, with no gap before it', (
- tester,
- ) async {
- await pump(tester, SwarmTeamFaces(glance(running: 1), people: const []));
-
- expect(find.byKey(const ValueKey('swarm-team-faces')), findsNothing);
- expect(tester.getTopLeft(find.text('1 agent running')).dx, 0);
- });
-
- testWidgets(
- 'with several Swarms, the Swarm comes after the count, the first to go',
- (tester) async {
- await pump(
- tester,
- SwarmTeamFaces(
- glance(running: 3),
- people: people(1),
- swarmName: 'Acme',
- ),
- );
-
- expect(find.text('3 agents running · Acme'), findsOneWidget);
- },
- );
-
- testWidgets('heard as the names and the count, never the faces one by one', (
- tester,
- ) async {
- final semantics = tester.ensureSemantics();
- await pump(
- tester,
- SwarmTeamFaces(glance(running: 2), people: people(7), swarmName: 'Acme'),
- );
-
- expect(
- find.bySemanticsLabel(
- 'name0, name1, name2, name3, name4, 2 agents running · Acme',
- ),
- findsOneWidget,
- );
- semantics.dispose();
- });
-
- testWidgets('a long line ellipsizes rather than pushing the faces out', (
- tester,
- ) async {
- await pump(
- tester,
- SwarmTeamFaces(
- glance(running: 12),
- people: people(5),
- swarmName: 'A Swarm with a name far too long for one row of a phone',
- ),
- width: 180,
- );
-
- expect(tester.takeException(), isNull);
- expect(
- tester.getTopRight(face(4)).dx,
- lessThan(180),
- reason: 'the faces keep their room',
- );
- final line = tester.widget<Text>(find.textContaining('12 agents running'));
- expect(line.overflow, TextOverflow.ellipsis);
- expect(
- line.data,
- startsWith('12 agents running'),
- reason: 'what is cut is the Swarm, never the count',
- );
- });
-}
diff --git a/mobile/test/swarm/team_glance_test.dart b/mobile/test/swarm/team_glance_test.dart
index b9654bb7c..5ddddbf85 100644
--- a/mobile/test/swarm/team_glance_test.dart
+++ b/mobile/test/swarm/team_glance_test.dart
@@ -147,14 +147,14 @@ void main() {
});
test('running counts the agents working, in words', () {
- String running(
+ String? running(
List<Map<String, dynamic>> agents, [
List<Map<String, dynamic>> groups = const [],
]) =>
swarmTeamGlance(swarm(agents: agents, groups: groups), now: now).running;
- expect(running([]), 'No agents yet');
- expect(running([agent('a1')]), 'No agents running', reason: 'idle');
+ expect(running([]), isNull, reason: 'no agents');
+ expect(running([agent('a1')]), isNull, reason: 'idle');
expect(
running([agent('a1')], [working('a1', 'working')]),
'1 agent running',
@@ -178,7 +178,7 @@ void main() {
],
[working('a1', 'working')],
),
- 'No agents running',
+ isNull,
reason: 'who is down is not running, whatever work it holds',
);
});
diff --git a/mobile/test/viewer/auth_session_test.dart b/mobile/test/viewer/auth_session_test.dart
index d75540ac6..36c3329c7 100644
--- a/mobile/test/viewer/auth_session_test.dart
+++ b/mobile/test/viewer/auth_session_test.dart
@@ -77,6 +77,58 @@ void main() {
expect(await session.autonomousEnv(), 'prod');
});
+ group('whose sign-in it is', () {
+ test('unknown until the account says', () async {
+ await session.saveLogin(token: 't');
+ expect(await session.accountId(), isNull);
+
+ await session.saveAccountId('person-a');
+ expect(await session.accountId(), 'person-a');
+ });
+
+ test('a renewal is the same sign-in: kept', () async {
+ await session.saveLogin(token: 't');
+ await session.saveAccountId('person-a');
+
+ await session.saveRefresh(token: 'renewed', autonomousEnv: 'prod');
+
+ expect(await session.accountId(), 'person-a');
+ });
+
+ test('a new sign-in may be anyone: forgotten', () async {
+ await session.saveLogin(token: 't');
+ await session.saveAccountId('person-a');
+
+ await session.saveLogin(token: 'someone-else');
+
+ expect(await session.accountId(), isNull);
+ });
+
+ test('forgotten before the new token is written, so a sign-in cut short '
+ 'cannot pair them', () async {
+ await session.saveLogin(token: 't');
+ await session.saveAccountId('person-a');
+ final failing = _FailingOnAccess(storage);
+
+ await expectLater(
+ AuthSession(storage: failing).saveLogin(token: 'someone-else'),
+ throwsStateError,
+ );
+
+ expect(await session.accountId(), isNull);
+ expect(await session.accessToken(), 't');
+ });
+
+ test('a sign-out forgets it', () async {
+ await session.saveLogin(token: 't');
+ await session.saveAccountId('person-a');
+
+ await session.clear();
+
+ expect(await session.accountId(), isNull);
+ });
+ });
+
test('clearing leaves nothing of the session behind', () async {
await session.saveLogin(
token: 't',
@@ -85,8 +137,24 @@ void main() {
expiresIn: 60,
issuer: SessionIssuer.emailCode,
);
+ await session.saveAccountId('person-a');
storage.values['unrelated'] = 'kept';
await session.clear();
expect(storage.values, {'unrelated': 'kept'});
});
}
+
+/// A store that dies on writing the access token: a sign-in cut short there.
+class _FailingOnAccess extends MemoryKeyValueStore {
+ _FailingOnAccess(this.real);
+ final MemoryKeyValueStore real;
+
+ @override
+ Future<void> delete(String key) => real.delete(key);
+
+ @override
+ Future<void> write(String key, String value) async {
+ if (key == 'auth_access_token') throw StateError('disk full');
+ await real.write(key, value);
+ }
+}
diff --git a/mobile/test/viewer_app_fixture.dart b/mobile/test/viewer_app_fixture.dart
index 2ecd4cf3e..251b70dfe 100644
--- a/mobile/test/viewer_app_fixture.dart
+++ b/mobile/test/viewer_app_fixture.dart
@@ -224,6 +224,19 @@ class FakeApi extends ApiClient {
return answer == null ? profile : await answer();
}
+ /// The Swarm reads asked of the backend itself.
+ final swarmReads = <String>[];
+
+ /// Answers them when set. Unset, this client has no sign-in to read with, so
+ /// the read goes on through a machine.
+ Future<Object?> Function(String path)? onSwarmRead;
+
+ @override
+ Future<Object?> swarmRead(String path) {
+ swarmReads.add(path);
+ return onSwarmRead?.call(path) ?? super.swarmRead(path);
+ }
+
@override
Future<Map<String, dynamic>?> desk() async => _deskDocument;