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: rename and archive chats from their ⋮, as on Desktop (Tony, task 11) (#2481)

0xken1530cfbc060071
diff --git a/mobile/lib/swarm/swarm_chat_manage.dart b/mobile/lib/swarm/swarm_chat_manage.dart
new file mode 100644
index 000000000..0f8eb4e4a
--- /dev/null
+++ b/mobile/lib/swarm/swarm_chat_manage.dart
@@ -0,0 +1,384 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/phone/phone_sheet.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_buddy.dart';
+import 'swarm_reader.dart';
+import 'swarm_request.dart';
+import 'swarm_style.dart';
+
+/// What the reader may do to chat [chatId] from its ⋮, as the desktop's chat
+/// menu offers it (`view.dart` `_options`): Rename and Archive in an ordinary
+/// project chat, for someone who may write; never in a project's own chat
+/// or a Buddy chat. Archive waits while the chat's task still runs; an
+/// archived chat offers Reopen alone, since the server changes nothing else
+/// of one (`ARCHIVED`). Null when there is nothing to offer, or the chat can
+/// no longer be read.
+({bool archived, bool archiveOn})? swarmChatManage(
+ SwarmReader reader,
+ String chatId,
+) {
+ final snapshot = reader.snapshot;
+ if (reader.accessRevoked || snapshot == null) return null;
+ final chat = snapshot.conversation(chatId);
+ if (chat == null ||
+ snapshot.isProjectLead(chatId) ||
+ chat.isBuddyChat ||
+ reader.buddies.chatOwners.containsKey(chatId) ||
+ !swarmCanWrite(reader)) {
+ return null;
+ }
+ final status = chat.assignment?['status'];
+ return (
+ archived: chat.archived,
+ archiveOn:
+ chat.archived ||
+ chat.assignment == null ||
+ const {'done', 'stopped', 'cancelled'}.contains(status),
+ );
+}
+
+/// The ⋮ sheet's rows for chat [chatId] ([swarmChatManage]): Rename and
+/// Archive, or Reopen. Each runs once the sheet has closed.
+List<PhoneSheetAction> swarmChatManageActions(
+ BuildContext context,
+ SwarmReader reader,
+ String chatId,
+) {
+ final manage = swarmChatManage(reader, chatId);
+ if (manage == null) return const [];
+ return [
+ if (!manage.archived)
+ PhoneSheetAction(
+ icon: LucideIcons.pencil300,
+ label: 'Rename',
+ onTap: () => unawaited(showSwarmRenameChat(context, reader, chatId)),
+ ),
+ PhoneSheetAction(
+ icon: manage.archived
+ ? LucideIcons.archiveRestore300
+ : LucideIcons.archive300,
+ label: manage.archived ? 'Reopen' : 'Archive',
+ enabled: manage.archiveOn,
+ onTap: () => unawaited(
+ manage.archived
+ ? _reopen(context, reader, chatId)
+ : confirmSwarmArchiveChat(context, reader, chatId),
+ ),
+ ),
+ ];
+}
+
+/// Renames chat [chatId] to [title], trimmed; null once the server kept it
+/// and the Swarm is read again, else the sentence to show.
+Future<String?> swarmRenameChat(
+ SwarmReader reader,
+ String chatId,
+ String title,
+) => _send(reader, chatId, {
+ 'type': 'conversation.rename',
+ 'conversationId': chatId,
+ 'title': title.trim(),
+});
+
+/// Archives chat [chatId], or reopens it when [archived] is false; null once
+/// the server kept it and the Swarm is read again, else the sentence to show.
+Future<String?> swarmArchiveChat(
+ SwarmReader reader,
+ String chatId, {
+ required bool archived,
+}) => _send(reader, chatId, {
+ 'type': 'conversation.archive',
+ 'conversationId': chatId,
+ 'archived': archived,
+});
+
+Future<String?> _send(
+ SwarmReader reader,
+ String chatId,
+ Map<String, dynamic> command,
+) async {
+ if (swarmChatManage(reader, chatId) == null) return _notAllowed;
+ try {
+ await reader.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
+ body: {'operationId': superTabOperationId(), 'command': command},
+ );
+ } on SuperTabFailure catch (failure) {
+ return failure.message;
+ } catch (_) {
+ // A call lost on the way (a timeout, a socket dropped) is no answer.
+ return _notSent;
+ }
+ await reader.refresh();
+ return null;
+}
+
+const _notAllowed = 'You can’t change this chat.';
+const _notSent = 'Could not reach this Swarm. Try again.';
+
+/// Says [error] at the foot of the screen, unless the screen is gone or
+/// the Swarm can no longer be read.
+void _tell(BuildContext context, SwarmReader reader, String? error) {
+ if (error == null || !context.mounted || reader.accessRevoked) return;
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(
+ key: const ValueKey('swarm-chat-manage-failed'),
+ content: Text(error),
+ ),
+ );
+}
+
+Future<void> _reopen(
+ BuildContext context,
+ SwarmReader reader,
+ String chatId,
+) async {
+ final error = await swarmArchiveChat(reader, chatId, archived: false);
+ if (context.mounted) _tell(context, reader, error);
+}
+
+/// Asks before archiving chat [chatId] (Tony's list; the desktop archives at
+/// once), then archives it: it leaves the lists for "Older". Nothing when
+/// they cancel, or when the chat could no longer be archived meanwhile.
+Future<void> confirmSwarmArchiveChat(
+ BuildContext context,
+ SwarmReader reader,
+ String chatId,
+) async {
+ if (!context.mounted) return;
+ final title = reader.snapshot?.conversation(chatId)?.title ?? '';
+ final archive = await showDialog<bool>(
+ context: context,
+ builder: (_) => _GoesWithChat(
+ reader: reader,
+ chatId: chatId,
+ child: Builder(
+ builder: (context) => AlertDialog(
+ title: Text(
+ 'Archive “$title”?',
+ key: const ValueKey('swarm-archive-title'),
+ style: AppType.heading(color: AppPalette.textPrimary),
+ ),
+ content: Text(
+ 'It leaves your chat lists. You can reopen it from Older.',
+ style: AppType.body(color: AppPalette.textSecondary),
+ ),
+ actions: [
+ SwarmButton(
+ key: const ValueKey('swarm-archive-cancel'),
+ label: 'Cancel',
+ style: SwarmButtonStyle.link,
+ onPressed: () => Navigator.of(context).pop(false),
+ ),
+ SwarmButton(
+ key: const ValueKey('swarm-archive-confirm'),
+ label: 'Archive',
+ style: SwarmButtonStyle.fill,
+ onPressed: () => Navigator.of(context).pop(true),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ if (archive != true || !context.mounted) return;
+ final error = await swarmArchiveChat(reader, chatId, archived: true);
+ if (context.mounted) _tell(context, reader, error);
+}
+
+/// Renames chat [chatId] in a dialog: its title to edit, Save, and the
+/// server's refusal under the field. It goes once the chat can no longer be
+/// renamed — access lost, archived elsewhere, or gone.
+Future<void> showSwarmRenameChat(
+ BuildContext context,
+ SwarmReader reader,
+ String chatId,
+) async {
+ if (!context.mounted) return;
+ await showDialog<void>(
+ context: context,
+ builder: (_) => _GoesWithChat(
+ reader: reader,
+ chatId: chatId,
+ rename: true,
+ child: SwarmRenameChatDialog(reader: reader, chatId: chatId),
+ ),
+ );
+}
+
+/// Closes the dialog it holds once chat [chatId] can no longer be changed
+/// that way: access lost, the chat gone, or (for [rename]) archived.
+class _GoesWithChat extends StatefulWidget {
+ const _GoesWithChat({
+ required this.reader,
+ required this.chatId,
+ required this.child,
+ this.rename = false,
+ });
+
+ final SwarmReader reader;
+ final String chatId;
+ final bool rename;
+ final Widget child;
+
+ @override
+ State<_GoesWithChat> createState() => _GoesWithChatState();
+}
+
+class _GoesWithChatState extends State<_GoesWithChat> {
+ bool _closed = false;
+
+ @override
+ void initState() {
+ super.initState();
+ widget.reader.addListener(_moved);
+ }
+
+ @override
+ void dispose() {
+ widget.reader.removeListener(_moved);
+ super.dispose();
+ }
+
+ void _moved() {
+ final manage = swarmChatManage(widget.reader, widget.chatId);
+ final still = manage != null && !(widget.rename && manage.archived);
+ if (still || _closed || !mounted) return;
+ _closed = true;
+ // Not while the reader tells its listeners: once this frame is done.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) Navigator.of(context).pop();
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) => widget.child;
+}
+
+/// What [showSwarmRenameChat] shows.
+class SwarmRenameChatDialog extends StatefulWidget {
+ const SwarmRenameChatDialog({
+ super.key,
+ required this.reader,
+ required this.chatId,
+ });
+
+ final SwarmReader reader;
+ final String chatId;
+
+ @override
+ State<SwarmRenameChatDialog> createState() => _SwarmRenameChatDialogState();
+}
+
+class _SwarmRenameChatDialogState extends State<SwarmRenameChatDialog> {
+ /// The backend's limit (commands.ts `title`).
+ static const _maxLength = 160;
+
+ late final _title = TextEditingController(
+ text: widget.reader.snapshot?.conversation(widget.chatId)?.title ?? '',
+ );
+ bool _saving = false;
+ String? _error;
+
+ @override
+ void dispose() {
+ _title.dispose();
+ super.dispose();
+ }
+
+ Future<void> _save() async {
+ if (_saving || _title.text.trim().isEmpty) return;
+ setState(() {
+ _saving = true;
+ _error = null;
+ });
+ final error = await swarmRenameChat(
+ widget.reader,
+ widget.chatId,
+ _title.text,
+ );
+ // Closed meanwhile (access lost, the chat gone): the answer is for nobody.
+ if (!mounted) return;
+ if (error == null) {
+ Navigator.of(context).pop();
+ return;
+ }
+ setState(() {
+ _saving = false;
+ _error = error;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final empty = _title.text.trim().isEmpty;
+ return AlertDialog(
+ title: Text(
+ 'Rename chat',
+ style: AppType.heading(color: AppPalette.textPrimary),
+ ),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ TextField(
+ key: const ValueKey('swarm-chat-title'),
+ controller: _title,
+ autofocus: true,
+ enabled: !_saving,
+ maxLength: _maxLength,
+ textCapitalization: TextCapitalization.sentences,
+ 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: (_) => unawaited(_save()),
+ ),
+ if (_error case final error?)
+ Padding(
+ padding: const EdgeInsets.only(top: AppSpace.s),
+ child: Text(
+ error,
+ key: const ValueKey('swarm-chat-title-error'),
+ style: AppType.caption(color: AppColors.danger),
+ ),
+ ),
+ ],
+ ),
+ actions: [
+ SwarmButton(
+ key: const ValueKey('swarm-chat-title-cancel'),
+ label: 'Cancel',
+ style: SwarmButtonStyle.link,
+ onPressed: _saving ? null : () => Navigator.of(context).pop(),
+ ),
+ SwarmButton(
+ key: const ValueKey('swarm-chat-title-save'),
+ label: 'Save',
+ style: SwarmButtonStyle.fill,
+ busy: _saving,
+ busyLabel: 'Saving…',
+ onPressed: _saving || empty ? null : () => unawaited(_save()),
+ ),
+ ],
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_chat_menu.dart b/mobile/lib/swarm/swarm_chat_menu.dart
index efe80e17a..35a3b4eea 100644
--- a/mobile/lib/swarm/swarm_chat_menu.dart
+++ b/mobile/lib/swarm/swarm_chat_menu.dart
@@ -9,6 +9,7 @@ import 'package:harness_mobile/shared/theme/app_icon_size.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/widgets/touch_target.dart';
+import 'swarm_chat_manage.dart';
import 'swarm_chat_notify.dart';
import 'swarm_reader.dart';
@@ -70,13 +71,16 @@ Future<void> swarmSetNotify(
}
/// The sheet of chat [chatId]'s Notifications, titled with its name: from
-/// its ⋮, or the project page's for its project chat. It goes once the chat
-/// can no longer be read — access lost, signed out, or the chat gone.
+/// its ⋮, or the project page's for its project chat. [actions], when
+/// given, go above them, worked out again as the chat changes. It goes once
+/// the chat can no longer be read — access lost, signed out, or the chat
+/// gone.
Future<void> showSwarmNotifySheet(
BuildContext context,
SwarmReader reader,
String chatId, {
void Function(Route<void> route)? onShown,
+ List<PhoneSheetAction> Function()? actions,
}) async {
Route<void>? sheet;
void moved() {
@@ -104,7 +108,7 @@ Future<void> showSwarmNotifySheet(
// A setting changed on another device meanwhile ticks here too.
rebuildOn: reader,
rows: () => (
- actions: const [],
+ actions: actions?.call() ?? const [],
sections: [swarmNotifySection(context, reader, chatId)],
),
);
@@ -113,9 +117,10 @@ Future<void> showSwarmNotifySheet(
}
}
-/// At the end of a chat's header: ⋮, whose sheet holds the chat's
-/// Notifications ([swarmNotifySection]), as the desktop's chat menu does for
-/// every chat a person reads, a viewer's too. Nothing while the chat is not
+/// At the end of a chat's header: ⋮, whose sheet holds Rename and Archive
+/// where the person may ([swarmChatManage]) and the chat's Notifications
+/// ([swarmNotifySection]), as the desktop's chat menu does for every chat a
+/// person reads, a viewer's too. Nothing while the chat is not
/// known. The sheet goes once the chat can no longer be read — access lost,
/// signed out, or the chat gone — or this header does.
class SwarmChatMenuButton extends StatefulWidget {
@@ -182,6 +187,9 @@ class _SwarmChatMenuButtonState extends State<SwarmChatMenuButton> {
widget.reader,
widget.chatId,
onShown: (route) => _sheet = route,
+ // Rename and Archive where the desktop's chat menu has them.
+ actions: () =>
+ swarmChatManageActions(context, widget.reader, widget.chatId),
).whenComplete(() => _sheet = null);
@override
diff --git a/mobile/test/swarm/swarm_chat_manage_shots_test.dart b/mobile/test/swarm/swarm_chat_manage_shots_test.dart
new file mode 100644
index 000000000..716eeaa16
--- /dev/null
+++ b/mobile/test/swarm/swarm_chat_manage_shots_test.dart
@@ -0,0 +1,177 @@
+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_session.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/terminal/terminal_font_store.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of Rename and Archive on the phone (Tony 11-01, task
+/// 11): the chat's ⋮ with them, Rename with a refusal under its field, and
+/// the Archive confirm. On a 390-point phone in both phone themes, from
+/// made-up data only, to the folder `SWARM_CHAT_MANAGE_SHOTS` names.
+final shots = Platform.environment['SWARM_CHAT_MANAGE_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('the chat menu, Rename and the Archive confirm, 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,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
+ groups: [groupData('g1', title: 'Fix login flake', number: 7)],
+ );
+ 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/conversations/g1/messages'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/commands'] = (_) =>
+ throw const SuperTabFailure(
+ 'INVALID_COMMAND',
+ 'Use a title of 160 characters or fewer.',
+ statusCode: 400,
+ );
+ 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 Scaffold(
+ body: SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
+ ),
+ ),
+ ),
+ );
+ 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/chat-manage-390-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ await tester.tap(find.byKey(const ValueKey('swarm-chat-menu')));
+ await tester.pumpAndSettle();
+ expect(find.text('Rename'), findsOneWidget);
+ await capture('menu');
+ await tester.tap(find.text('Rename'));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-chat-title')),
+ 'Fix the login flake on CI',
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('swarm-chat-title-save')));
+ await tester.pumpAndSettle();
+ FocusManager.instance.primaryFocus?.unfocus();
+ await tester.pumpAndSettle();
+ await capture('rename-refused');
+ await tester.tap(find.byKey(const ValueKey('swarm-chat-title-cancel')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('swarm-chat-menu')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Archive'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('swarm-archive-confirm')), findsOne);
+ await capture('archive-confirm');
+ await tester.tap(find.byKey(const ValueKey('swarm-archive-cancel')));
+ await tester.pumpAndSettle();
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ }
+ debugDisableShadows = true;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_chat_manage_test.dart b/mobile/test/swarm/swarm_chat_manage_test.dart
new file mode 100644
index 000000000..113d93933
--- /dev/null
+++ b/mobile/test/swarm/swarm_chat_manage_test.dart
@@ -0,0 +1,495 @@
+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/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/swarm/swarm_chat_manage.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_project_page.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Rename and Archive on the phone, as the desktop's chat menu has them
+/// (Tony 11-01, task 11): in the chat's ⋮, for someone who may write, in an
+/// ordinary project chat; Archive asks first, and the chat goes to "Older".
+void main() {
+ const chat = 'g1';
+ late FakeSwarm swarm;
+ late SwarmHost host;
+ late String title;
+ late bool archived;
+ String? status;
+ var version = 2;
+
+ /// What the next command answers instead of the server, once.
+ FutureOr<Object?> Function()? answer;
+
+ /// The parts read fails while this is set.
+ SuperTabFailure? partsFail;
+
+ Map<String, dynamic> chatData() => {
+ ...groupData(chat, title: title, number: 7, status: status),
+ 'archived': archived,
+ };
+
+ Future<void> pump(
+ WidgetTester tester, {
+ String role = 'owner',
+ String conversationId = chat,
+ String? taskStatus,
+ bool firstLoadFails = false,
+ bool settle = true,
+ }) async {
+ title = 'Fix login flake';
+ archived = false;
+ status = taskStatus;
+ version = 2;
+ answer = null;
+ partsFail = firstLoadFails
+ ? const SuperTabFailure(
+ 'UNAVAILABLE',
+ 'Swarm is busy.',
+ statusCode: 503,
+ )
+ : null;
+ swarm = FakeSwarm();
+ swarm.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) {
+ if (partsFail case final failure?) throw failure;
+ return {
+ ...firstLoad(groups: [chatData()]),
+ 'members': [part(me, 1, person(me, role: role))],
+ };
+ };
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) {
+ version++;
+ return changes(
+ cursor: 'c$version',
+ groups: [part(chat, version, chatData())],
+ );
+ };
+ swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ for (final id in [chat, leadChat]) {
+ swarm.routes['/api/super-tabs/$tab/conversations/$id/messages'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ }
+ 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();
+ }
+ switch (command['type']) {
+ case 'conversation.rename':
+ if (archived) {
+ throw const SuperTabFailure(
+ 'ARCHIVED',
+ 'Reopen this conversation before changing its work.',
+ );
+ }
+ title = command['title'] as String;
+ case 'conversation.archive':
+ archived = command['archived'] as bool;
+ }
+ return {'ok': true};
+ };
+ final account = ValueNotifier<String?>(me);
+ host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: swarm.request,
+ upload: refuseSwarmUpload,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: Scaffold(
+ body: SwarmConversationPage(
+ swarmId: tab,
+ conversationId: conversationId,
+ ),
+ ),
+ ),
+ );
+ // A failed read keeps its placeholders moving: no settling then.
+ if (settle) {
+ await tester.pumpAndSettle();
+ } else {
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+ }
+
+ SwarmReader reader() => host.session!.inbox.reader(tab)!;
+ Finder key(String value) => find.byKey(ValueKey(value));
+
+ Future<void> menu(WidgetTester tester) async {
+ await tester.tap(key('swarm-chat-menu'));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> settle(WidgetTester tester) async {
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> rename(WidgetTester tester) async {
+ await menu(tester);
+ await tester.tap(find.text('Rename'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-chat-title'), findsOneWidget);
+ }
+
+ List<Map<String, dynamic>> sent(String type) => [
+ for (final c in swarm.commands)
+ if (c['type'] == type) c,
+ ];
+
+ group('who may', () {
+ testWidgets('an owner of an ordinary chat gets Rename and Archive above '
+ 'Notifications', (tester) async {
+ await pump(tester);
+ await menu(tester);
+ expect(find.text('Rename'), findsOneWidget);
+ expect(find.text('Archive'), findsOneWidget);
+ expect(find.text('All new messages'), findsOneWidget);
+ });
+
+ testWidgets('a viewer gets Notifications alone', (tester) async {
+ await pump(tester, role: 'viewer');
+ await menu(tester);
+ expect(find.text('Rename'), findsNothing);
+ expect(find.text('Archive'), findsNothing);
+ expect(find.text('All new messages'), findsOneWidget);
+ });
+
+ testWidgets('the project\'s own chat is neither renamed nor archived '
+ 'here', (tester) async {
+ await pump(tester);
+ expect(swarmChatManage(reader(), leadChat), isNull);
+ expect(swarmChatManage(reader(), chat), isNotNull);
+ });
+
+ testWidgets('a Buddy chat is neither renamed nor archived here', (
+ tester,
+ ) async {
+ await pump(tester);
+ final buddyChat = reader().snapshot!.conversation(chat)!;
+ expect(buddyChat.isBuddyChat, isFalse);
+ // The same chat, sent as the reader's Buddy chat.
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ {...chatData(), 'kind': 'buddy', 'buddyOwnerId': me},
+ ],
+ ),
+ };
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(cursor: 'c9'),
+ 'reload': true,
+ };
+ await reader().refresh();
+ await tester.pumpAndSettle();
+ expect(reader().snapshot!.conversation(chat)!.isBuddyChat, isTrue);
+ expect(swarmChatManage(reader(), chat), isNull);
+ });
+
+ testWidgets('Archive is off while the chat\'s task still runs, and on '
+ 'once it is done', (tester) async {
+ await pump(tester, taskStatus: 'working');
+ expect(swarmChatManage(reader(), chat)!.archiveOn, isFalse);
+ await menu(tester);
+ await tester.tap(find.text('Archive'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-archive-confirm'), findsNothing);
+
+ status = 'done';
+ await reader().refresh();
+ await tester.pumpAndSettle();
+ expect(swarmChatManage(reader(), chat)!.archiveOn, isTrue);
+ });
+ });
+
+ group('rename', () {
+ testWidgets('a new title is the server\'s at once, in the header', (
+ tester,
+ ) async {
+ await pump(tester);
+ await rename(tester);
+ expect(
+ tester.widget<TextField>(key('swarm-chat-title')).controller!.text,
+ 'Fix login flake',
+ );
+ await tester.enterText(key('swarm-chat-title'), ' Login flake fix ');
+ await tester.pump();
+ await tester.tap(key('swarm-chat-title-save'));
+ await settle(tester);
+
+ expect(sent('conversation.rename'), [
+ {
+ 'type': 'conversation.rename',
+ 'conversationId': chat,
+ 'title': 'Login flake fix',
+ },
+ ]);
+ expect(key('swarm-chat-title'), findsNothing);
+ expect(reader().snapshot!.conversation(chat)!.title, 'Login flake fix');
+ // The header says it as the chat's number and title.
+ expect(find.text('#7 Login flake fix'), findsOneWidget);
+ });
+
+ testWidgets('a refused title says why under the field and stays open', (
+ tester,
+ ) async {
+ await pump(tester);
+ await rename(tester);
+ answer = () => throw const SuperTabFailure(
+ 'INVALID_COMMAND',
+ 'Use a title of 160 characters or fewer.',
+ statusCode: 400,
+ );
+ await tester.enterText(key('swarm-chat-title'), 'Another');
+ await tester.pump();
+ await tester.tap(key('swarm-chat-title-save'));
+ await settle(tester);
+
+ expect(
+ tester.widget<Text>(key('swarm-chat-title-error')).data,
+ 'Use a title of 160 characters or fewer.',
+ );
+ expect(key('swarm-chat-title'), findsOneWidget);
+ expect(reader().snapshot!.conversation(chat)!.title, 'Fix login flake');
+ });
+
+ testWidgets('an empty title cannot be saved', (tester) async {
+ await pump(tester);
+ await rename(tester);
+ await tester.enterText(key('swarm-chat-title'), ' ');
+ await tester.pump();
+ await tester.tap(key('swarm-chat-title-save'));
+ await settle(tester);
+ expect(sent('conversation.rename'), isEmpty);
+ });
+
+ testWidgets('offline: a call lost on the way says so, never stays '
+ 'Saving', (tester) async {
+ await pump(tester);
+ await rename(tester);
+ answer = () => throw TimeoutException('no answer');
+ await tester.enterText(key('swarm-chat-title'), 'Another');
+ await tester.pump();
+ await tester.tap(key('swarm-chat-title-save'));
+ await settle(tester);
+ expect(find.text('Could not reach this Swarm. Try again.'), findsOne);
+ expect(find.text('Saving…'), findsNothing);
+ });
+
+ testWidgets('a title at the 160-character limit saves; one longer is cut '
+ 'to fit', (tester) async {
+ await pump(tester);
+ await rename(tester);
+ final longest = 'a' * 160;
+ await tester.enterText(key('swarm-chat-title'), '');
+ await tester.enterText(key('swarm-chat-title'), '${longest}b');
+ await tester.pump();
+ await tester.tap(key('swarm-chat-title-save'));
+ await settle(tester);
+ expect(sent('conversation.rename').single['title'], longest);
+ expect(reader().snapshot!.conversation(chat)!.title, longest);
+ });
+ });
+
+ group('archive', () {
+ testWidgets('asks first; Cancel changes nothing', (tester) async {
+ await pump(tester);
+ await menu(tester);
+ await tester.tap(find.text('Archive'));
+ await tester.pumpAndSettle();
+ expect(find.text('Archive “Fix login flake”?'), findsOneWidget);
+ expect(
+ find.text('It leaves your chat lists. You can reopen it from Older.'),
+ findsOneWidget,
+ );
+ await tester.tap(key('swarm-archive-cancel'));
+ await settle(tester);
+ expect(sent('conversation.archive'), isEmpty);
+ expect(reader().snapshot!.conversation(chat)!.archived, isFalse);
+ });
+
+ testWidgets('Archive archives: the chat leaves the lists for Older, '
+ 'and its page says so', (tester) async {
+ await pump(tester);
+ await menu(tester);
+ await tester.tap(find.text('Archive'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-archive-confirm'));
+ await settle(tester);
+
+ expect(sent('conversation.archive'), [
+ {
+ 'type': 'conversation.archive',
+ 'conversationId': chat,
+ 'archived': true,
+ },
+ ]);
+ final snapshot = reader().snapshot!;
+ final work = swarmProjectWork(snapshot, snapshot.projects.single);
+ expect(work.active.map((g) => g.id), isNot(contains(chat)));
+ expect(work.older.map((g) => g.id), contains(chat));
+ expect(find.text('This chat is archived.'), findsOneWidget);
+
+ // Reopen from its ⋮, with no Rename while archived.
+ await menu(tester);
+ expect(find.text('Rename'), findsNothing);
+ await tester.tap(find.text('Reopen'));
+ await settle(tester);
+ expect(sent('conversation.archive').last['archived'], isFalse);
+ expect(reader().snapshot!.conversation(chat)!.archived, isFalse);
+ });
+
+ testWidgets('a refusal says why at the foot of the screen', (tester) async {
+ await pump(tester);
+ await menu(tester);
+ await tester.tap(find.text('Archive'));
+ await tester.pumpAndSettle();
+ answer = () => throw const SuperTabFailure(
+ 'WORK_ACTIVE',
+ 'Resolve the active assignment before archiving this conversation.',
+ );
+ await tester.tap(key('swarm-archive-confirm'));
+ await settle(tester);
+ expect(
+ find.text(
+ 'Resolve the active assignment before archiving this conversation.',
+ ),
+ findsOneWidget,
+ );
+ expect(reader().snapshot!.conversation(chat)!.archived, isFalse);
+ });
+ });
+
+ group('elsewhere and lost', () {
+ testWidgets('archived on another screen while Rename is open: the '
+ 'dialog goes, and the page says it is archived', (tester) async {
+ await pump(tester);
+ await rename(tester);
+ archived = true;
+ await reader().refresh();
+ await tester.pumpAndSettle();
+ expect(key('swarm-chat-title'), findsNothing);
+ expect(find.text('This chat is archived.'), findsOneWidget);
+ });
+
+ testWidgets('archived on another screen while the confirm is open: '
+ 'it goes, and nothing is sent', (tester) async {
+ await pump(tester);
+ await menu(tester);
+ await tester.tap(find.text('Archive'));
+ await tester.pumpAndSettle();
+ // Taken away from this person meanwhile: no longer theirs to archive.
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) {
+ version++;
+ return {
+ ...changes(cursor: 'c$version'),
+ 'members': [part(me, version, person(me, role: 'viewer'))],
+ };
+ };
+ await reader().refresh();
+ await tester.pumpAndSettle();
+ expect(key('swarm-archive-confirm'), findsNothing);
+ expect(sent('conversation.archive'), isEmpty);
+ });
+
+ testWidgets('access lost with Rename open: it closes, and nothing of '
+ 'the chat stays', (tester) async {
+ await pump(tester);
+ await rename(tester);
+ reader().revoke();
+ await tester.pumpAndSettle();
+ expect(key('swarm-chat-title'), findsNothing);
+ expect(key('swarm-chat-menu'), findsNothing);
+ expect(find.textContaining('Fix login flake'), findsNothing);
+ });
+
+ testWidgets('an answer that lands after access was lost shows nothing '
+ 'and reads nothing', (tester) async {
+ await pump(tester);
+ await rename(tester);
+ final held = Completer<Object?>();
+ answer = () => held.future;
+ await tester.enterText(key('swarm-chat-title'), 'Another');
+ await tester.pump();
+ await tester.tap(key('swarm-chat-title-save'));
+ await tester.pump();
+ reader().revoke();
+ await tester.pumpAndSettle();
+ final calls = swarm.calls.length;
+ held.completeError(
+ const SuperTabFailure('FORBIDDEN', 'You cannot read this Swarm.'),
+ );
+ await settle(tester);
+ expect(find.text('You cannot read this Swarm.'), findsNothing);
+ expect(swarm.calls.length, calls);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('an archive that lands after access was lost says nothing', (
+ tester,
+ ) async {
+ await pump(tester);
+ // Asked from a screen that stays (the page's own Scaffold), so only the
+ // lost access keeps the late refusal off it.
+ final screen = tester.element(find.byType(Scaffold).first);
+ unawaited(confirmSwarmArchiveChat(screen, reader(), chat));
+ await tester.pumpAndSettle();
+ final held = Completer<Object?>();
+ answer = () => held.future;
+ await tester.tap(key('swarm-archive-confirm'));
+ await tester.pump();
+ reader().revoke();
+ held.completeError(
+ const SuperTabFailure('FORBIDDEN', 'You cannot read this Swarm.'),
+ );
+ await settle(tester);
+ expect(find.text('You cannot read this Swarm.'), findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('a first read that failed and then recovers still offers '
+ 'Rename', (tester) async {
+ await pump(tester, firstLoadFails: true, settle: false);
+ expect(key('swarm-chat-menu'), findsNothing);
+ partsFail = null;
+ await reader().refresh();
+ await tester.pumpAndSettle();
+ await rename(tester);
+ });
+ });
+}