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.

Phone: change your username from You, as on Desktop (Tony, task 10) (#2479)

0xken15c4634dbd2759
diff --git a/mobile/lib/swarm/swarm_profile.dart b/mobile/lib/swarm/swarm_profile.dart
index 2a6c70d75..b4be0b217 100644
--- a/mobile/lib/swarm/swarm_profile.dart
+++ b/mobile/lib/swarm/swarm_profile.dart
@@ -76,6 +76,20 @@ class SwarmProfile {
},
});
+ /// Any member changes their own username, a viewer too (the server's
+ /// `member.username`), while this Swarm is still theirs to read.
+ bool get canRename =>
+ !reader.accessRevoked &&
+ reader.snapshot?.person(reader.accountId) != null;
+
+ /// The reader's own username, trimmed (the server lowercases it), or back
+ /// to their default when null. A refused or taken name comes back in the
+ /// server's words, as on the desktop (`profile_actions.dart`).
+ Future<String?> setUsername(String? username) => _send({
+ 'type': 'member.username',
+ 'username': username?.trim(),
+ }, viewer: true);
+
/// [preset], or back to the initial when null.
Future<String?> setAvatar(SuperTabPresetAvatar? preset) => _send({
'type': 'member.avatar',
@@ -106,8 +120,11 @@ class SwarmProfile {
}
}
- Future<String?> _send(Map<String, dynamic> command) async {
- if (!canEdit) return _readOnly;
+ Future<String?> _send(
+ Map<String, dynamic> command, {
+ bool viewer = false,
+ }) async {
+ if (!(viewer ? canRename : canEdit)) return _readOnly;
try {
await reader.request(
'POST',
@@ -116,6 +133,10 @@ class SwarmProfile {
);
} on SuperTabFailure catch (failure) {
return failure.message;
+ } catch (_) {
+ // A call lost on the way (a timeout, a socket dropped) is no answer:
+ // say so, rather than leave the sheet saving.
+ return _notSent;
}
await reader.refresh();
return null;
@@ -123,6 +144,7 @@ class SwarmProfile {
}
const _readOnly = 'You have read-only access to this Swarm.';
+const _notSent = 'Could not reach this Swarm. Try again.';
/// [picked] cropped to its middle square and drawn at [kSwarmAvatarPixels],
/// as a PNG: what any picture a person picks becomes before it leaves the
diff --git a/mobile/lib/swarm/swarm_profile_sheet.dart b/mobile/lib/swarm/swarm_profile_sheet.dart
index 0cb5d3adc..9e4a175ae 100644
--- a/mobile/lib/swarm/swarm_profile_sheet.dart
+++ b/mobile/lib/swarm/swarm_profile_sheet.dart
@@ -20,6 +20,7 @@ import 'swarm_profile.dart';
import 'swarm_reader.dart';
import 'swarm_session.dart';
import 'swarm_style.dart';
+import 'swarm_username_editor.dart';
/// One photo from the person's library, or null when they back out. Asked
/// no larger than an avatar needs, so a 12-megapixel photo is never decoded
@@ -50,8 +51,8 @@ Future<Uint8List?> readPickedSwarmPhoto(XFile? picked) async {
}
/// The person's own profile in the Swarm [swarmId], in a sheet over the
-/// page: a built-in picture or a photo of theirs, and a status that clears
-/// when they say — the desktop's profile (`profile_sheet.dart`) in the
+/// page: their username, a built-in picture or a photo of theirs, and a
+/// status that clears when they say — the desktop's profile (`profile_sheet.dart`) in the
/// phone's own way.
Future<void> showSwarmProfile(
BuildContext context, {
@@ -113,6 +114,9 @@ class _SwarmProfileSheetState extends State<SwarmProfileSheet> {
/// The editor took the person's status once, when it was first read.
bool _seeded = false;
bool _busy = false;
+
+ /// The username's own Save is on its way: [_busy] says it for the rest.
+ bool _naming = false;
String? _error;
@override
@@ -134,6 +138,18 @@ class _SwarmProfileSheetState extends State<SwarmProfileSheet> {
});
}
+ /// A refused name is said under its own field, not at the foot of the
+ /// sheet (the desktop's `_saveUsername`).
+ Future<String?> _saveUsername(SwarmProfile profile, String username) async {
+ setState(() {
+ _busy = _naming = true;
+ _error = null;
+ });
+ final error = await profile.setUsername(username);
+ if (mounted) setState(() => _busy = _naming = false);
+ return error;
+ }
+
Future<void> _photo(SwarmProfile profile) async {
final Uint8List? picked;
try {
@@ -246,7 +262,11 @@ class _SwarmProfileSheetState extends State<SwarmProfileSheet> {
),
),
Flexible(
- child: me == null || profile == null
+ child: reader?.accessRevoked ?? false
+ // Taken away while open: nothing of it stays, and no rows wait
+ // for a read that will not come.
+ ? const _Note('You can no longer see this Swarm.')
+ : me == null || profile == null
// Not read yet: rows on their way.
? SwarmSkeletonRows(id: 'swarm-profile-loading', round: true)
: SingleChildScrollView(child: _body(me, status, profile)),
@@ -308,6 +328,17 @@ class _SwarmProfileSheetState extends State<SwarmProfileSheet> {
],
),
),
+ // A viewer's name is theirs too, though they change nothing else.
+ // One field per reader: an answer sent under another account or
+ // Swarm never lands in this one.
+ SwarmUsernameEditor(
+ key: ObjectKey(profile.reader),
+ username: me.username,
+ // Typing goes on while its own Save is on its way, as on the desktop.
+ enabled: profile.canRename && (!_busy || _naming),
+ busy: _naming,
+ onSave: (username) => _saveUsername(profile, username),
+ ),
if (!profile.canEdit) _Note('You have read-only access to this Swarm.'),
const SwarmCaption('Picture'),
Wrap(
diff --git a/mobile/lib/swarm/swarm_username_editor.dart b/mobile/lib/swarm/swarm_username_editor.dart
new file mode 100644
index 000000000..e1c2880bd
--- /dev/null
+++ b/mobile/lib/swarm/swarm_username_editor.dart
@@ -0,0 +1,150 @@
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/app_type.dart';
+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
+
+import 'swarm_style.dart';
+
+/// The reader's username: the field, Save, and why a name was refused (taken,
+/// or not one a username can be), said under the field it is about — the
+/// desktop's `SuperTabUsernameEditor` in the phone's own way.
+class SwarmUsernameEditor extends StatefulWidget {
+ const SwarmUsernameEditor({
+ super.key,
+ required this.username,
+ required this.enabled,
+ required this.busy,
+ required this.onSave,
+ });
+
+ final String username;
+
+ /// The person may change it now: off while another change is saving, and
+ /// for a reader who is no longer in the Swarm.
+ final bool enabled;
+
+ /// This field's own Save is on its way.
+ final bool busy;
+
+ /// Saves the name; answers why it was refused, or null once saved.
+ final Future<String?> Function(String username) onSave;
+
+ @override
+ State<SwarmUsernameEditor> createState() => _SwarmUsernameEditorState();
+}
+
+class _SwarmUsernameEditorState extends State<SwarmUsernameEditor> {
+ late final _text = TextEditingController(text: widget.username);
+ String? _error;
+
+ /// The last name saved, until the server's version of it arrives.
+ String? _sent;
+
+ @override
+ void didUpdateWidget(SwarmUsernameEditor old) {
+ super.didUpdateWidget(old);
+ // A saved name comes back as the server keeps it (lowercased), but never
+ // over a newer edit typed while it was on its way.
+ final typed = _text.text.trim();
+ if (old.username == widget.username) return;
+ if (typed == old.username || typed == _sent) _text.text = widget.username;
+ _sent = null;
+ }
+
+ @override
+ void dispose() {
+ _text.dispose();
+ super.dispose();
+ }
+
+ bool get _changed {
+ final typed = _text.text.trim();
+ return typed.isNotEmpty && typed != widget.username;
+ }
+
+ bool get _can => widget.enabled && !widget.busy && _changed;
+
+ Future<void> _save() async {
+ if (!_can) return;
+ final error = await widget.onSave(_sent = _text.text.trim());
+ if (error != null) _sent = null;
+ // Closed, or the Swarm replaced, meanwhile: the answer is for nobody here.
+ if (mounted) setState(() => _error = error);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SwarmCaption('Username'),
+ Row(
+ children: [
+ Expanded(
+ child: TextField(
+ key: const ValueKey('swarm-username-field'),
+ controller: _text,
+ enabled: widget.enabled,
+ maxLength: 32,
+ autocorrect: false,
+ enableSuggestions: false,
+ textCapitalization: TextCapitalization.none,
+ textInputAction: TextInputAction.done,
+ style: AppType.body(color: AppPalette.textPrimary),
+ decoration: InputDecoration(
+ counterText: '',
+ filled: true,
+ fillColor: AppPalette.swarmField,
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(AppControl.radius),
+ borderSide: BorderSide.none,
+ ),
+ ),
+ onChanged: (_) => setState(() => _error = null),
+ onSubmitted: (_) => _save(),
+ ),
+ ),
+ const SizedBox(width: AppSpace.s),
+ SwarmButton(
+ key: const ValueKey('swarm-username-save'),
+ label: 'Save',
+ style: SwarmButtonStyle.fill,
+ busy: widget.busy,
+ busyLabel: 'Saving…',
+ onPressed: _can ? _save : null,
+ ),
+ ],
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ AppSpace.xs,
+ AppSpace.xs,
+ 0,
+ ),
+ child: Text(
+ 'How people see and tag you in this Swarm.',
+ style: AppType.caption(color: AppPalette.textSecondary),
+ ),
+ ),
+ if (_error case final error?)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ AppSpace.xs,
+ AppSpace.xs,
+ 0,
+ ),
+ child: Text(
+ error,
+ key: const ValueKey('swarm-username-error'),
+ style: AppType.caption(color: AppColors.danger),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_you_page.dart b/mobile/lib/swarm/swarm_you_page.dart
index 7ad9f6743..1b89b034d 100644
--- a/mobile/lib/swarm/swarm_you_page.dart
+++ b/mobile/lib/swarm/swarm_you_page.dart
@@ -26,8 +26,8 @@ import 'swarm_style.dart';
/// You, the person's own tab, as Tony's prototype C4 draws it (2026-10-30):
/// who they are in the Swarm Home shows — their face, their name and that
-/// Swarm — then their status, and Change for their profile, where it is set
-/// ([showSwarmProfile]); Your models, with how many of their own machines'
+/// Swarm — then their status and their username, each with Change for their
+/// profile, where it is set ([showSwarmProfile]); Your models, with how many of their own machines'
/// models the Swarms can use now, and Your devices, with how many of their
/// own computers are online; and Settings. Only what is theirs counts: not a
/// teammate's, not one shared with them, not a Harness Team account's (#2253's
@@ -102,6 +102,9 @@ class SwarmYouPage extends StatelessWidget {
void open(Widget page) => unawaited(
navigator.push(phoneRoute((_) => page, listensForItself: true)),
);
+ final profile = me == null
+ ? null
+ : () => unawaited(showSwarmProfile(context, swarmId: you!.id));
return [
_Me(
key: const ValueKey('swarm-you-me'),
@@ -114,9 +117,21 @@ class SwarmYouPage extends StatelessWidget {
_Status(
key: const ValueKey('swarm-you-status'),
me: me,
- onTap: me == null
- ? null
- : () => unawaited(showSwarmProfile(context, swarmId: you!.id)),
+ onTap: profile,
+ ),
+ ],
+ ),
+ const SwarmCaption('Username'),
+ SwarmGroup(
+ children: [
+ SwarmRow(
+ key: const ValueKey('swarm-you-username'),
+ leading: const _Glyph(LucideIcons.atSign300),
+ // How the Swarm tags them, as the server keeps it; nothing of a
+ // Swarm before it is read, or once it is taken away.
+ title: me?.username ?? 'Username',
+ trailing: profile == null ? null : const _Change(),
+ onTap: profile,
),
],
),
@@ -293,23 +308,7 @@ class _Status extends StatelessWidget {
),
),
title: title,
- trailing: onTap == null
- ? null
- : Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- 'Change',
- style: AppType.label(color: AppPalette.textSecondary),
- ),
- const SizedBox(width: AppSpace.xs),
- Icon(
- LucideIcons.chevronRight300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- ],
- ),
+ trailing: onTap == null ? null : const _Change(),
onTap: onTap,
);
if (me == null) return row('Set a status', known: false);
@@ -321,6 +320,28 @@ class _Status extends StatelessWidget {
}
}
+/// "Change ›", at the end of a row that opens the person's profile.
+class _Change extends StatelessWidget {
+ const _Change();
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text('Change', style: AppType.label(color: AppPalette.textSecondary)),
+ const SizedBox(width: AppSpace.xs),
+ Icon(
+ LucideIcons.chevronRight300,
+ size: 18,
+ color: AppPalette.textFaint,
+ ),
+ ],
+ );
+ }
+}
+
/// A row's glyph, in a 32-point box so the titles line up.
class _Glyph extends StatelessWidget {
const _Glyph(this.icon);
diff --git a/mobile/test/swarm/swarm_profile_sheet_test.dart b/mobile/test/swarm/swarm_profile_sheet_test.dart
index 46e9ba3ba..62a5386ed 100644
--- a/mobile/test/swarm/swarm_profile_sheet_test.dart
+++ b/mobile/test/swarm/swarm_profile_sheet_test.dart
@@ -394,7 +394,8 @@ void main() {
testWidgets('the title and the name are headings of 17; the status under '
'the name is a caption of 13', (tester) async {
- await open(tester);
+ // A username of its own: the field holding it is not the name.
+ await open(tester, extra: {'username': 'pm'});
for (final text in ['Your profile', 'person-me']) {
expect(styleOf(tester, text).fontSize, 17, reason: text);
diff --git a/mobile/test/swarm/swarm_username_shots_test.dart b/mobile/test/swarm/swarm_username_shots_test.dart
new file mode 100644
index 000000000..9080ae464
--- /dev/null
+++ b/mobile/test/swarm/swarm_username_shots_test.dart
@@ -0,0 +1,169 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_you_page.dart';
+import 'package:harness_mobile/terminal/terminal_font_store.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of the username on the phone (Tony 11-01, task 10):
+/// You with its Username row, then the profile with a taken name refused
+/// under its field. On a 390-point phone in both phone themes, from made-up
+/// data only, to the folder `SWARM_USERNAME_SHOTS` names.
+final shots = Platform.environment['SWARM_USERNAME_SHOTS'];
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in {
+ '.AppleSystemUIFont',
+ 'Roboto',
+ AppFont.sans,
+ ...AppFont.sansFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ // The tab's title is set in the terminal's face.
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ final terminal = terminalFontStore.value;
+ for (final family in {
+ '.AppleSystemUIFontMonospaced',
+ 'monospace',
+ AppFont.mono,
+ ...AppFont.monoFallback,
+ terminal.fontFamily,
+ ...terminal.fontFamilyFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('You and the profile with a taken name, in both phone themes', (
+ tester,
+ ) async {
+ addTearDown(tester.view.reset);
+ debugDisableShadows = false;
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ addTearDown(tester.view.resetPadding);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ const size = Size(390, 844);
+ tester.view
+ ..physicalSize = size * 3
+ ..devicePixelRatio = 3;
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Autonomous', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ final mine = {
+ ...person(me),
+ 'email': '[email protected]',
+ 'username': 'tony',
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(),
+ 'members': [part(me, 1, mine)],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/commands'] = (_) =>
+ throw const SuperTabFailure(
+ 'USERNAME_TAKEN',
+ 'dee is taken.',
+ statusCode: 409,
+ );
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => me,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ )..foreground = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmYouPage(),
+ ),
+ ),
+ );
+ await host.session!.inbox.refresh();
+ await tester.pumpAndSettle();
+ Future<void> capture(String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/username-390-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ expect(find.byKey(const ValueKey('swarm-you-username')), findsOneWidget);
+ await capture('you');
+ await tester.tap(find.byKey(const ValueKey('swarm-you-username')));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-username-field')),
+ 'dee',
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('swarm-username-save')));
+ await tester.pumpAndSettle();
+ expect(find.text('dee is taken.'), findsOneWidget);
+ // The keyboard's focus off, as after Done.
+ FocusManager.instance.primaryFocus?.unfocus();
+ await tester.pumpAndSettle();
+ await capture('taken');
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ }
+ debugDisableShadows = true;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_username_test.dart b/mobile/test/swarm/swarm_username_test.dart
new file mode 100644
index 000000000..eb346b4a5
--- /dev/null
+++ b/mobile/test/swarm/swarm_username_test.dart
@@ -0,0 +1,408 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/swarm/swarm_face.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_style.dart';
+import 'package:harness_mobile/swarm/swarm_you_page.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// The person's own username, changed from the phone as on the desktop: a
+/// Username row on You opens their profile, whose field saves through
+/// `member.username`; the server's refusal is said under the field, and the
+/// name it keeps shows at once.
+void main() {
+ late FakeSwarm swarm;
+ late SwarmHost host;
+ late ValueNotifier<String?> account;
+ late Map<String, dynamic> mine;
+
+ /// What the next command answers instead of the server's rules, once.
+ FutureOr<Object?> Function()? answer;
+
+ /// The parts read fails while this is set.
+ SuperTabFailure? partsFail;
+
+ // The backend's rules (backend/src/superTabs/usernames.ts).
+ final shape = RegExp(r'^[a-z0-9](?:[a-z0-9_-]|\.(?!\.)){0,30}[a-z0-9_-]$');
+ const shapeWords =
+ 'Use 2 to 32 letters, digits, dots, dashes or underscores, starting '
+ 'with a letter or digit, with no dot at the end or two in a row.';
+ final dee = {...person('person-dee'), 'username': 'dee'};
+
+ Object? setName(Map<String, dynamic> command) {
+ final name = (command['username'] as String).trim().toLowerCase();
+ if (!shape.hasMatch(name)) {
+ throw const SuperTabFailure(
+ 'INVALID_USERNAME',
+ shapeWords,
+ statusCode: 400,
+ );
+ }
+ if (name == 'dee' || name == 'river') {
+ throw SuperTabFailure(
+ 'USERNAME_TAKEN',
+ '$name is taken.',
+ statusCode: 409,
+ );
+ }
+ mine = {...mine, 'username': name};
+ return {'ok': true};
+ }
+
+ /// You, for a member with [role] named [username], on an iPhone's screen.
+ Future<void> pump(
+ WidgetTester tester, {
+ String role = 'owner',
+ String username = 'tony',
+ bool firstLoadFails = false,
+ }) async {
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ answer = null;
+ partsFail = firstLoadFails
+ ? const SuperTabFailure(
+ 'UNAVAILABLE',
+ 'Swarm is busy.',
+ statusCode: 503,
+ )
+ : null;
+ swarm = FakeSwarm();
+ mine = {
+ ...person(me, role: role),
+ 'email': '[email protected]',
+ 'username': username,
+ };
+ var version = 1;
+ swarm.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Autonomous', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) {
+ if (partsFail case final failure?) throw failure;
+ return {
+ ...firstLoad(),
+ 'members': [part(me, version, mine), part('person-dee', 1, dee)],
+ };
+ };
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(cursor: 'c${++version}'),
+ 'members': [part(me, version, mine)],
+ };
+ swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ swarm.routes['/api/super-tabs/$tab/commands'] = (body) {
+ final command = body!['command'] as Map<String, dynamic>;
+ if (answer case final once?) {
+ answer = null;
+ return once();
+ }
+ return switch (command['type']) {
+ 'member.username' => setName(command),
+ _ => {'ok': true},
+ };
+ };
+ account = ValueNotifier<String?>(me);
+ host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: swarm.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmYouPage(),
+ ),
+ );
+ unawaited(host.session!.inbox.refresh());
+ await tester.pumpAndSettle();
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+ Finder inside(String k, Finder matching) =>
+ find.descendant(of: key(k), matching: matching);
+ TextField field(WidgetTester tester) =>
+ tester.widget<TextField>(key('swarm-username-field'));
+ bool saveOn(WidgetTester tester) =>
+ tester.widget<SwarmButton>(key('swarm-username-save')).onPressed != null;
+ String? shownError() => key('swarm-username-error').evaluate().isEmpty
+ ? null
+ : (key('swarm-username-error').evaluate().single.widget as Text).data;
+
+ /// Lets a command and the read after it answer.
+ Future<void> settle(WidgetTester tester) async {
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ }
+
+ Future<void> openProfile(WidgetTester tester) async {
+ await tester.tap(key('swarm-you-username'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-username-field'), findsOneWidget);
+ }
+
+ Future<void> type(WidgetTester tester, String text) async {
+ await tester.enterText(key('swarm-username-field'), text);
+ await tester.pump();
+ }
+
+ Future<void> save(WidgetTester tester) async {
+ await tester.ensureVisible(key('swarm-username-save'));
+ await tester.tap(key('swarm-username-save'));
+ await settle(tester);
+ }
+
+ List<Map<String, dynamic>> renames() => [
+ for (final c in swarm.commands)
+ if (c['type'] == 'member.username') c,
+ ];
+
+ testWidgets('You shows the username, and Change opens the profile with '
+ 'it in its field', (tester) async {
+ await pump(tester);
+ expect(inside('swarm-you-username', find.text('tony')), findsOneWidget);
+ expect(inside('swarm-you-username', find.text('Change')), findsOneWidget);
+ await openProfile(tester);
+ expect(field(tester).controller!.text, 'tony');
+ expect(find.text('How people see and tag you in this Swarm.'), findsOne);
+ // Nothing changed, nothing to save.
+ expect(saveOn(tester), isFalse);
+ });
+
+ testWidgets('a name saved is the server\'s at once: in the field, on You '
+ 'and in what every screen reads', (tester) async {
+ await pump(tester);
+ await openProfile(tester);
+ await type(tester, ' Tony.B ');
+ expect(saveOn(tester), isTrue);
+ await save(tester);
+
+ expect(renames(), [
+ {'type': 'member.username', 'username': 'Tony.B'},
+ ]);
+ // Lowercased as the server keeps it.
+ expect(field(tester).controller!.text, 'tony.b');
+ expect(shownError(), isNull);
+ expect(
+ host.session!.inbox.reader(tab)!.snapshot!.person(me)!.username,
+ 'tony.b',
+ );
+ await tester.tap(key('swarm-profile-close'));
+ await tester.pumpAndSettle();
+ expect(inside('swarm-you-username', find.text('tony.b')), findsOneWidget);
+ });
+
+ testWidgets('a name the server refuses says why under its field, and '
+ 'nothing changes', (tester) async {
+ await pump(tester);
+ await openProfile(tester);
+ await type(tester, 'tony.');
+ await save(tester);
+
+ expect(shownError(), shapeWords);
+ // Under the field, not at the foot of the sheet.
+ expect(key('swarm-profile-error'), findsNothing);
+ expect(field(tester).controller!.text, 'tony.');
+ expect(
+ host.session!.inbox.reader(tab)!.snapshot!.person(me)!.username,
+ 'tony',
+ );
+ // Typing again clears it.
+ await type(tester, 'tony.c');
+ expect(shownError(), isNull);
+ });
+
+ testWidgets('a taken name says so, and the name stays theirs', (
+ tester,
+ ) async {
+ await pump(tester);
+ await openProfile(tester);
+ await type(tester, 'Dee');
+ await save(tester);
+
+ expect(shownError(), 'dee is taken.');
+ expect(
+ host.session!.inbox.reader(tab)!.snapshot!.person(me)!.username,
+ 'tony',
+ );
+ expect(saveOn(tester), isTrue);
+ });
+
+ testWidgets('offline: a call lost on the way says so, never stays Saving, '
+ 'and the next try goes through', (tester) async {
+ await pump(tester);
+ await openProfile(tester);
+ answer = () => throw TimeoutException('no answer');
+ await type(tester, 'tony.b');
+ await save(tester);
+
+ expect(shownError(), 'Could not reach this Swarm. Try again.');
+ expect(find.text('Saving…'), findsNothing);
+ expect(saveOn(tester), isTrue);
+
+ await save(tester);
+ expect(shownError(), isNull);
+ expect(field(tester).controller!.text, 'tony.b');
+ });
+
+ testWidgets('a viewer changes their own name, and nothing else', (
+ tester,
+ ) async {
+ await pump(tester, role: 'viewer');
+ await openProfile(tester);
+ expect(
+ find.text('You have read-only access to this Swarm.'),
+ findsOneWidget,
+ );
+ await type(tester, 'tony.v');
+ await save(tester);
+ expect(renames(), hasLength(1));
+ expect(field(tester).controller!.text, 'tony.v');
+
+ await tester.ensureVisible(key('swarm-avatar-preset-owl'));
+ await tester.tap(key('swarm-avatar-preset-owl'));
+ await settle(tester);
+ expect(swarm.commands.where((c) => c['type'] == 'member.avatar'), isEmpty);
+ });
+
+ testWidgets('access taken away while the profile is open: the field and '
+ 'the name go, with no rows left loading', (tester) async {
+ await pump(tester);
+ await openProfile(tester);
+ host.session!.inbox.reader(tab)!.revoke();
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-username-field'), findsNothing);
+ expect(key('swarm-profile-loading'), findsNothing);
+ expect(find.text('You can no longer see this Swarm.'), findsOneWidget);
+ await tester.tap(key('swarm-profile-close'));
+ await tester.pumpAndSettle();
+ // You keeps nothing of them, and offers no way in.
+ expect(inside('swarm-you-username', find.text('tony')), findsNothing);
+ expect(inside('swarm-you-username', find.text('Change')), findsNothing);
+ });
+
+ testWidgets('an answer that lands after access was taken away changes '
+ 'nothing and reads nothing', (tester) async {
+ await pump(tester);
+ await openProfile(tester);
+ final held = Completer<Object?>();
+ answer = () => held.future;
+ await type(tester, 'tony.b');
+ await tester.tap(key('swarm-username-save'));
+ await tester.pump();
+ expect(find.text('Saving…'), findsOneWidget);
+
+ host.session!.inbox.reader(tab)!.revoke();
+ await tester.pump();
+ final reads = swarm.calls.length;
+ held.completeError(
+ const SuperTabFailure('USERNAME_TAKEN', 'tony.b is taken.'),
+ );
+ await settle(tester);
+
+ expect(find.text('tony.b is taken.'), findsNothing);
+ expect(key('swarm-username-field'), findsNothing);
+ expect(swarm.calls.length, reads);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('an answer that lands after the account changed never shows '
+ 'in what is open now', (tester) async {
+ await pump(tester);
+ await openProfile(tester);
+ final held = Completer<Object?>();
+ answer = () => held.future;
+ await type(tester, 'tony.b');
+ await tester.tap(key('swarm-username-save'));
+ await tester.pump();
+
+ account.value = 'person-other';
+ await tester.pump();
+ held.completeError(
+ const SuperTabFailure('USERNAME_TAKEN', 'tony.b is taken.'),
+ );
+ await settle(tester);
+
+ expect(find.text('tony.b is taken.'), findsNothing);
+ expect(find.text('tony.b'), findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('a first read that failed and then recovers still lets them '
+ 'change it', (tester) async {
+ await pump(tester, firstLoadFails: true);
+ expect(inside('swarm-you-username', find.text('Change')), findsNothing);
+ await tester.tap(key('swarm-you-username'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-username-field'), findsNothing);
+
+ partsFail = null;
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(inside('swarm-you-username', find.text('tony')), findsOneWidget);
+ await openProfile(tester);
+ await type(tester, 'tony.b');
+ await save(tester);
+ expect(field(tester).controller!.text, 'tony.b');
+ });
+
+ testWidgets('a name at the 32-character limit saves, reads back, and '
+ 'saves again; one longer is cut to fit', (tester) async {
+ final longest = 'a' * 31 + 'z';
+ await pump(tester, username: longest);
+ await openProfile(tester);
+ expect(field(tester).controller!.text, longest);
+
+ final other = 'b' * 32;
+ // From empty: a field already at its limit keeps what it has.
+ await type(tester, '');
+ await type(tester, '${other}x');
+ // The field takes 32, as a username does.
+ expect(field(tester).controller!.text, other);
+ await save(tester);
+ expect(shownError(), isNull);
+ expect(field(tester).controller!.text, other);
+ expect(
+ host.session!.inbox.reader(tab)!.snapshot!.person(me)!.username,
+ other,
+ );
+ });
+
+ testWidgets('a newer edit typed while a save is on its way is kept', (
+ tester,
+ ) async {
+ await pump(tester);
+ await openProfile(tester);
+ final held = Completer<Object?>();
+ answer = () => held.future;
+ await type(tester, 'tony.b');
+ await tester.tap(key('swarm-username-save'));
+ await tester.pump();
+ await type(tester, 'tony.c');
+
+ mine = {...mine, 'username': 'tony.b'};
+ held.complete({'ok': true});
+ await settle(tester);
+ expect(field(tester).controller!.text, 'tony.c');
+ expect(saveOn(tester), isTrue);
+ });
+}