From ed29172fbb794bc2fd09387c37fa912d6a1cfda4 Mon Sep 17 00:00:00 2001 From: morgmart <98432065+morgmart@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:34:54 -0800 Subject: [PATCH] fix(mobile): name blocked agents clearly, let owners remove their agent from a DM (#9921) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem Two follow-ups to growable DMs on mobile, matching desktop block/buzz-app#3744: 1. When an agent's add policy blocks a DM, the message names the agent by display name only, so two agents called "Scout" read the same, and it never says whose owner to ask. 2. Once you add your own agent to a DM, you can't take it out. The relay allows it, but mobile hid Remove in every DM. ## Change **Name the blocked agent clearly.** The refusal now uses the app's identity labels for the agent and its owner: - Only its owner can add it, owner known: "Only Morgan can add Scout to a DM." - Only its owner can add it, owner unknown: "Only the owner of Scout can add it to a DM." - No one can add it: "Scout can't be added to a DM." - When adding to an existing DM, all start with "Couldn't add them." - If the name can't be read, it says "this agent". Labels are compared against the people in the DM, so two same-named agents read as "Morgan's Scout", and an agent that shares a person's name reads as "Scout (agent)". The owner is named only when it is verified from the agent's signed profile. **Let owners remove their own agent from a DM.** On a DM member's profile, an agent you verifiably own now has "Remove from DM", confirmed with "Remove from DM?". People never get Remove in a DM, and admin and role actions stay out of DMs, matching the relay rule. ## Screenshots Temporary widget renders with test data, not committed. The refusal render passes the shared wording a known owner and a disambiguated agent label; label resolution itself is covered by the tests below. ### Blocked agent | | Light | Dark | |---|---|---| | Narrow | ![refusal light narrow](https://github.com/user-attachments/assets/fe6b08c4-01d0-43c5-b6ba-5416ac07cecb) | ![refusal dark narrow](https://github.com/user-attachments/assets/ef30bd2a-4a3b-45dd-829c-25f956f023ed) | | Wide | ![refusal light wide](https://github.com/user-attachments/assets/9a193a12-5a6c-491d-af30-a95afb649b5e) | ![refusal dark wide](https://github.com/user-attachments/assets/eeab3f52-1556-4248-adc3-0e55b6511720) | ### Remove from DM | | Light | Dark | |---|---|---| | Row, narrow | ![row light narrow](https://github.com/user-attachments/assets/a4ec6a75-f749-4cb8-be0d-13c82427a292) | ![row dark narrow](https://github.com/user-attachments/assets/9ac8ee1d-152e-47ec-813b-7a61ccdbe15d) | | Row, wide | ![row light wide](https://github.com/user-attachments/assets/bf465fe0-8b3c-462b-82ce-2b1527056656) | ![row dark wide](https://github.com/user-attachments/assets/bc991265-3e49-4241-a3aa-c499aac4f3ee) | | Confirm, narrow | ![confirm light narrow](https://github.com/user-attachments/assets/8088a4da-a665-4591-95ae-1ecc984f77b1) | ![confirm dark narrow](https://github.com/user-attachments/assets/11a52247-dcf0-4105-be4d-9f3ba3f14838) | | Confirm, wide | ![confirm light wide](https://github.com/user-attachments/assets/281ba908-d187-4b8e-889e-baa4c81bd44d) | ![confirm dark wide](https://github.com/user-attachments/assets/537b2b49-78f6-4074-9ba8-fbce2f55b9a8) | ## Tests - Wording for every case, plus opening and adding with a verified owner, two same-named agents, an agent sharing a person's name, and owner unknown. - Remove from DM: the owner removes their agent after confirming; no Remove for another person's agent, an unowned agent, or a person. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> Signed-off-by: Tom Brow Co-authored-by: Carl Co-authored-by: Claude Opus 5.5 Co-authored-by: Tom Brow Co-authored-by: studio --- .../channels/channel_management_actions.dart | 90 ++++- .../channels/channel_management_provider.dart | 17 +- .../channel_member_profile_actions.dart | 72 ++-- .../channel_management_provider_test.dart | 56 +++ .../channel_member_profile_actions_test.dart | 116 +++++- .../channels_provider_join_cases.dart | 371 +++++++++++++++++- .../channels/channels_provider_test.dart | 1 + 7 files changed, 676 insertions(+), 47 deletions(-) diff --git a/mobile/lib/features/channels/channel_management_actions.dart b/mobile/lib/features/channels/channel_management_actions.dart index 1197ad5d45..bc5fc44841 100644 --- a/mobile/lib/features/channels/channel_management_actions.dart +++ b/mobile/lib/features/channels/channel_management_actions.dart @@ -49,6 +49,10 @@ class DmAddUnconfirmed implements Exception { String toString() => 'Added. Tap Add again to open the DM.'; } +/// How long a DM agent refusal waits for profiles before naming with what +/// it has. +const _refusalNamingDeadline = Duration(milliseconds: 1500); + class ChannelActions { final Ref _ref; final RelaySessionNotifier _session; @@ -199,7 +203,11 @@ class ChannelActions { } on StateError { rethrow; } catch (error) { - await _throwIfAgentRefused(relayErrorText(error), adding: false); + await _throwIfAgentRefused( + relayErrorText(error), + adding: false, + context: pubkeys, + ); rethrow; } _ensureCommunityValid(); @@ -323,7 +331,18 @@ class ChannelActions { reason == 'invalid: history must be "include", got "ask"')) { throw const DmNeedsHistoryChoice(); } - await _throwIfAgentRefused(reason, adding: true); + await _throwIfAgentRefused( + reason, + adding: true, + // channelById also finds a DM opened ahead of the list. + context: [ + ...?_ref + .read(channelsProvider.notifier) + .channelById(channelId) + ?.participantPubkeys, + ...pubkeys, + ], + ); throw Exception( reason.contains('at most 9 people') ? dmAdditionFailedMessage @@ -346,26 +365,70 @@ class ChannelActions { } /// Throws [DmAgentRefused] naming the agent when [reason] is an agent's - /// add-policy refusal of a DM. A failed name read still refuses, without - /// the name. + /// add-policy refusal of a DM. The agent and its verified owner are named + /// as the app's identity labels do, compared against [context] (the DM's + /// people, as its own label compares them) and this account, so namesakes + /// stay distinguishable, using whichever of them are cached. A failed name + /// read still refuses, without the name. Future _throwIfAgentRefused( String reason, { required bool adding, + required Iterable context, }) async { final refusal = dmAgentPolicyRefusal(reason); if (refusal == null) return; final cache = _ref.read(userCacheProvider.notifier); - final profile = await cache - .resolve([refusal.agent]) - .then((profiles) => profiles[refusal.agent]) - .catchError((Object _) => cache.get(refusal.agent)); + // The relay has already refused: profiles get one short deadline, then + // the message uses the best names loaded so far. + final deadline = Future.delayed(_refusalNamingDeadline); + Future load(Iterable keys) => keys.isEmpty + ? Future.value() + : Future.any([ + cache.resolve(keys.toList()).then((_) {}), + deadline, + ]).catchError((Object _) {}); + final keys = { + refusal.agent, + for (final key in [...context, ?_currentPubkey]) + if (isHexPubkey(key.toLowerCase())) key.toLowerCase(), + }; + // Wait only for names the sentence uses: the agent's, and its owner's + // when the refusal names who may add it. Other keys label from cache, + // except that a namesake in the context needs both agents' owners, read + // together, to tell the two apart. + await load([refusal.agent]); + var sources = _ref.read(identityNameSourcesProvider); + final owner = sources.factFor(refusal.agent)?.ownerPubkey; + String? nameOf(String? key) => + key == null ? null : sources.factFor(key)?.name.trim().toLowerCase(); + final clashing = {nameOf(refusal.agent), ?nameOf(owner)}; + final namesakes = [ + for (final key in keys) + if (key != refusal.agent && clashing.contains(nameOf(key))) key, + ]; + final owners = { + if (refusal.ownerOnly || namesakes.isNotEmpty) ?owner, + for (final key in namesakes) ?sources.factFor(key)?.ownerPubkey, + }; + if (owners.isNotEmpty) { + await load(owners); + sources = _ref.read(identityNameSourcesProvider); + } _ensureCommunityValid(); - final name = profile?.displayName; + final names = sources.scope( + {...keys, ...owners}, + agentPubkeys: {refusal.agent}, + ); throw DmAgentRefused( dmAgentRefusedMessage( adding: adding, ownerOnly: refusal.ownerOnly, - name: name != null && name.trim().isNotEmpty ? name : null, + agent: names.hasName(refusal.agent) + ? names.labelFor(refusal.agent) + : null, + owner: owner != null && names.hasName(owner) + ? names.labelFor(owner) + : null, ), ); } @@ -702,6 +765,13 @@ class ChannelActions { _ensureCommunityValid(); _ref.invalidate(channelMembersProvider(channelId)); _ref.invalidate(channelBotPubkeysProvider(channelId)); + // A DM's title and portraits come from the list's participants, which the + // relay republished before accepting the removal. List entries for other + // channels don't show members, so they need no re-read. + final channels = _ref.read(channelsProvider.notifier); + if (channels.channelById(channelId)?.isDm ?? false) { + unawaited(channels.refresh()); + } } /// [targetAuthor] fills the NIP-25 `p` tag, which Activity reads by `#p`. diff --git a/mobile/lib/features/channels/channel_management_provider.dart b/mobile/lib/features/channels/channel_management_provider.dart index a13fd0caef..fb9a8ab5d6 100644 --- a/mobile/lib/features/channels/channel_management_provider.dart +++ b/mobile/lib/features/channels/channel_management_provider.dart @@ -10,6 +10,7 @@ import '../../shared/channels/saved_message_store.dart'; import '../../shared/custom_emoji/custom_emoji.dart'; import '../../shared/custom_emoji/custom_emoji_provider.dart'; import '../../shared/crypto/nip_oa.dart'; +import '../../shared/identity_names/identity_names_provider.dart'; import '../../shared/me/me_sync.dart'; import '../../shared/me/me_groups.dart'; import '../../shared/mentions/agent_identity_provider.dart'; @@ -79,16 +80,20 @@ final _agentPolicyRefusal = RegExp( : (ownerOnly: match.group(1) == 'owner_only', agent: match.group(2)!); } -/// What to show for an agent's add-policy refusal of a DM, naming the agent -/// when its [name] is known, as desktop's `agentPolicyMessage` words it. +/// What to show for an agent's add-policy refusal of a DM. [agent] is the +/// agent's contextual identity label and [owner] its verified owner's, each +/// null while unknown, so the person knows exactly whose owner to ask. String dmAgentRefusedMessage({ required bool adding, required bool ownerOnly, - String? name, + String? agent, + String? owner, }) { - final refused = ownerOnly - ? 'Only ${name != null ? '$name’s' : 'this agent’s'} owner can add it to a DM.' - : '${name ?? 'This agent'} can’t be added to a DM.'; + final refused = !ownerOnly + ? '${agent ?? 'This agent'} can’t be added to a DM.' + : owner != null + ? 'Only $owner can add ${agent ?? 'this agent'} to a DM.' + : 'Only the owner of ${agent ?? 'this agent'} can add it to a DM.'; return '${adding ? 'Couldn’t add them. ' : ''}$refused'; } diff --git a/mobile/lib/features/channels/channel_member_profile_actions.dart b/mobile/lib/features/channels/channel_member_profile_actions.dart index 6d3dc2d6d1..45b56fce07 100644 --- a/mobile/lib/features/channels/channel_member_profile_actions.dart +++ b/mobile/lib/features/channels/channel_member_profile_actions.dart @@ -3,6 +3,8 @@ import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:buzz/shared/theme/buzz_icons.dart'; +import '../../shared/identity_names/identity_names.dart'; +import '../../shared/identity_names/identity_names_provider.dart'; import '../../shared/theme/theme.dart'; import '../../shared/widgets/app_list.dart'; import '../../shared/widgets/app_list_card.dart'; @@ -29,6 +31,7 @@ class ChannelMemberProfileActions extends HookConsumerWidget { final error = useState(null); final actor = ref.watch(currentPubkeyProvider)?.toLowerCase(); final roster = ref.watch(channelMembersProvider(channel.id)); + final names = ref.watch(identityNameSourcesProvider); final channels = ref.watch(channelsProvider).asData?.value; final currentChannel = channels @@ -36,14 +39,16 @@ class ChannelMemberProfileActions extends HookConsumerWidget { .firstOrNull ?? channel; final target = pubkey.toLowerCase(); + final isDm = currentChannel.isDm; + // A DM has no admins: its owner may only remove their own agent. ChannelMember? manageableMember( AsyncValue> snapshot, String? currentActor, Channel current, + IdentityNameSources sources, ) { - if (current.isDm || - current.isArchived || + if (current.isArchived || snapshot.isLoading || snapshot.hasError || currentActor == null || @@ -57,14 +62,34 @@ class ChannelMemberProfileActions extends HookConsumerWidget { final member = members .where((m) => m.pubkey.toLowerCase() == target) .firstOrNull; - if (viewer?.isElevated != true || member == null || member.isOwner) { - return null; + if (member == null) return null; + if (current.isDm) { + return sources.factFor(target)?.ownerPubkey == currentActor + ? member + : null; } + if (viewer?.isElevated != true || member.isOwner) return null; return member; } - final member = manageableMember(roster, actor, currentChannel); - if (member == null) return const SizedBox.shrink(); + final message = error.value; + final errorText = message == null + ? null + : Semantics( + liveRegion: true, + label: message, + child: ExcludeSemantics( + child: Text( + message, + style: context.textTheme.bodyMedium?.copyWith( + color: context.colors.error, + ), + ), + ), + ); + final member = manageableMember(roster, actor, currentChannel, names); + // A failure stays visible even while the rows wait on a reload. + if (member == null) return errorText ?? const SizedBox.shrink(); bool stillAllowed() { final latest = @@ -80,6 +105,7 @@ class ChannelMemberProfileActions extends HookConsumerWidget { ref.read(channelMembersProvider(channel.id)), actor, latest, + ref.read(identityNameSourcesProvider), )?.role == member.role; } @@ -95,11 +121,15 @@ class ChannelMemberProfileActions extends HookConsumerWidget { .labelFor(target); final confirmed = await showDestructiveConfirmation( context: context, - title: 'Remove from channel?', - message: 'Remove $label from ${currentChannel.name}?', + title: isDm ? 'Remove from DM?' : 'Remove from channel?', + message: isDm + ? 'Remove $label from this DM?' + : 'Remove $label from ${currentChannel.name}?', confirmLabel: 'Remove', ); - if (!context.mounted || confirmed != true || !stillAllowed()) return; + if (!context.mounted || confirmed != true) return; + // A change or a reload since confirming: say so, don't drop it. + if (!stillAllowed()) throw StateError('Removal no longer allowed'); await ref .read(channelActionsProvider) .removeMember(channelId: channel.id, pubkey: target); @@ -116,7 +146,9 @@ class ChannelMemberProfileActions extends HookConsumerWidget { } catch (_) { if (context.mounted) { error.value = role == null - ? 'Could not remove this person. Please try again.' + ? isDm + ? 'Could not remove this agent. Please try again.' + : 'Could not remove this person. Please try again.' : 'Could not change this role. Please try again.'; } } finally { @@ -130,13 +162,13 @@ class ChannelMemberProfileActions extends HookConsumerWidget { AppListCard( horizontalPadding: 0, children: [ - if (member.role != 'admin') + if (!isDm && member.role != 'admin') AppListRow( icon: BuzzIcons.shieldCheck, title: 'Make channel admin', onTap: busy.value ? null : () => perform(role: 'admin'), ), - if (member.role == 'admin' || member.role == 'guest') + if (!isDm && (member.role == 'admin' || member.role == 'guest')) AppListRow( icon: BuzzIcons.user, title: member.role == 'guest' @@ -146,7 +178,7 @@ class ChannelMemberProfileActions extends HookConsumerWidget { ), AppListRow( icon: BuzzIcons.userMinus, - title: 'Remove from channel', + title: isDm ? 'Remove from DM' : 'Remove from channel', titleColor: context.colors.error, onTap: busy.value ? null : () => perform(), ), @@ -160,19 +192,7 @@ class ChannelMemberProfileActions extends HookConsumerWidget { child: Center(child: Text('Updating…')), ), ), - if (error.value != null) - Semantics( - liveRegion: true, - label: error.value!, - child: ExcludeSemantics( - child: Text( - error.value!, - style: context.textTheme.bodyMedium?.copyWith( - color: context.colors.error, - ), - ), - ), - ), + ?errorText, ], ); } diff --git a/mobile/test/features/channels/channel_management_provider_test.dart b/mobile/test/features/channels/channel_management_provider_test.dart index 2aeb7b4614..0a18ca4cc2 100644 --- a/mobile/test/features/channels/channel_management_provider_test.dart +++ b/mobile/test/features/channels/channel_management_provider_test.dart @@ -920,6 +920,52 @@ void main() { ]); }); + test( + 'a DM removal refreshes the list so its participants drop the member', + () async { + final relay = FakeRelay(); + final container = ProviderContainer( + overrides: [ + ...relay.overrides, + channelsProvider.overrideWith(_CountingRefreshes.new), + ], + ); + addTearDown(container.dispose); + final connected = Completer(); + container.listen(relaySessionProvider, (_, state) { + if (state.status == SessionStatus.connected && !connected.isCompleted) { + connected.complete(); + } + }, fireImmediately: true); + await connected.future; + final channels = + container.read(channelsProvider.notifier) as _CountingRefreshes; + await container.read(channelsProvider.future); + // Only a DM's list entry shows its members; a channel's needs no + // re-read. + for (final (type, refreshes) in [('stream', 0), ('dm', 1)]) { + channels.state = AsyncData([ + Channel( + id: _channelId, + name: '', + channelType: type, + visibility: 'private', + description: '', + createdBy: 'owner', + createdAt: DateTime(2026), + memberCount: 3, + isMember: true, + ), + ]); + await container + .read(channelActionsProvider) + .removeMember(channelId: _channelId, pubkey: _memberPubkey); + expect(relay.published.last.kind, 9001); + expect(channels.refreshes, refreshes, reason: type); + } + }, + ); + test('conversion keeps unrelated labels and preserves access settings', () { expect(buildSoloConversionTags(_channelId, ['buzz.solo', 'project']), [ ['h', _channelId], @@ -1334,6 +1380,16 @@ class _HeldRosterRelaySession extends RelaySessionNotifier { state = const SessionState(status: SessionStatus.disconnected); } +class _CountingRefreshes extends ChannelsNotifier { + var refreshes = 0; + + @override + Future> build() async => const []; + + @override + Future refresh({bool fetchDirectory = false}) async => refreshes++; +} + class _ChannelsAfterLeave extends ChannelsNotifier { @override Future> build() async => const []; diff --git a/mobile/test/features/channels/channel_member_profile_actions_test.dart b/mobile/test/features/channels/channel_member_profile_actions_test.dart index 6d7198e1fd..300b184b28 100644 --- a/mobile/test/features/channels/channel_member_profile_actions_test.dart +++ b/mobile/test/features/channels/channel_member_profile_actions_test.dart @@ -5,6 +5,9 @@ import 'package:buzz/features/channels/channel.dart'; import 'package:buzz/features/channels/channel_management_provider.dart'; import 'package:buzz/features/channels/channel_member_profile_actions.dart'; import 'package:buzz/features/channels/channels_provider.dart'; +import 'package:buzz/shared/mentions/agent_identity_provider.dart'; +import 'package:buzz/shared/profile/user_cache_provider.dart'; +import 'package:buzz/shared/profile/user_profile.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; @@ -64,9 +67,11 @@ Future _pump( String actorRole = 'owner', String targetRole = 'member', String target = 'alice', + String actor = 'self', bool dm = false, bool archived = false, bool inSheet = false, + Map owners = const {}, _Actions? actions, Future> Function()? load, }) async { @@ -74,13 +79,14 @@ Future _pump( await tester.pumpWidget( ProviderScope( overrides: [ - currentPubkeyProvider.overrideWithValue('self'), + currentPubkeyProvider.overrideWithValue(actor), channelsProvider.overrideWith(() => _Channels(channel)), channelMembersProvider('test').overrideWith( (ref) async => load == null - ? [_member('self', actorRole), _member('alice', targetRole)] + ? [_member(actor, actorRole), _member('alice', targetRole)] : await load(), ), + agentOwnersProvider.overrideWith((ref) async => owners), channelActionsProvider.overrideWithValue(actions ?? _Actions()), ], child: MaterialApp( @@ -254,6 +260,112 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Make channel admin'), findsOneWidget); }); + group('in a DM', () { + // Ownership comes from verified naming facts, which need hex keys. + final me = 'e' * 64, agent = 'c' * 64; + Future pumpDm( + WidgetTester tester, { + String targetRole = 'bot', + Map owners = const {}, + bool inSheet = false, + _Actions? actions, + Future> Function()? load, + }) => _pump( + tester, + dm: true, + actor: me, + target: agent, + actorRole: 'member', + targetRole: targetRole, + owners: owners, + inSheet: inSheet, + actions: actions, + load: + load ?? + () async => [_member(me, 'member'), _member(agent, targetRole)], + ); + + testWidgets('the owner removes their own agent after confirming', ( + tester, + ) async { + final actions = _Actions(); + await pumpDm( + tester, + owners: {agent: me.toUpperCase()}, + inSheet: true, + actions: actions, + ); + expect(find.text('Make channel admin'), findsNothing); + expect(find.text('Remove from channel'), findsNothing); + await tester.tap(find.text('Remove from DM')); + await tester.pumpAndSettle(); + expect(find.text('Remove from DM?'), findsOneWidget); + expect(find.textContaining('from this DM?'), findsOneWidget); + await tester.tap(find.text('Remove')); + await tester.pumpAndSettle(); + expect(actions.calls, ['test:$agent:remove']); + expect(find.byType(ChannelMemberProfileActions), findsNothing); + }); + + testWidgets('a removal that can no longer be checked says to retry', ( + tester, + ) async { + final actions = _Actions(); + var loads = 0; + final container = await pumpDm( + tester, + owners: {agent: me}, + inSheet: true, + actions: actions, + load: () => loads++ == 0 + ? Future.value([_member(me, 'member'), _member(agent, 'bot')]) + : Completer>().future, + ); + await tester.tap(find.text('Remove from DM')); + await tester.pumpAndSettle(); + // The roster starts reloading while the confirmation is open. + container.invalidate(channelMembersProvider('test')); + await tester.tap(find.text('Remove')); + await tester.pump(); + expect(actions.calls, isEmpty); + expect( + find.text('Could not remove this agent. Please try again.'), + findsOneWidget, + ); + }); + + testWidgets( + 'an owned agent outside the directory gets Remove once its verified profile loads', + (tester) async { + final container = await pumpDm(tester); + await tester.pumpAndSettle(); + expect(find.text('Remove from DM'), findsNothing); + container + .read(userCacheProvider.notifier) + .put( + UserProfile(pubkey: agent, displayName: 'Scout', ownerPubkey: me), + ); + await tester.pumpAndSettle(); + expect(find.text('Remove from DM'), findsOneWidget); + }, + ); + + for (final scenario in ['other owner', 'unowned', 'person']) { + testWidgets('no Remove for $scenario', (tester) async { + await pumpDm( + tester, + targetRole: scenario == 'person' ? 'member' : 'bot', + owners: { + if (scenario == 'other owner') agent: 'd' * 64, + // A person has no verified owner; even an admin viewer is no use. + }, + ); + await tester.pumpAndSettle(); + expect(find.text('Remove from DM'), findsNothing); + expect(find.text('Remove from channel'), findsNothing); + }); + } + }); for (final role in ['member', 'admin', 'guest', 'bot']) { testWidgets('management rows for $role', (tester) async { await _pump(tester, targetRole: role); diff --git a/mobile/test/features/channels/channels_provider_join_cases.dart b/mobile/test/features/channels/channels_provider_join_cases.dart index 567c481e64..2b976f6bc9 100644 --- a/mobile/test/features/channels/channels_provider_join_cases.dart +++ b/mobile/test/features/channels/channels_provider_join_cases.dart @@ -485,6 +485,7 @@ void _confirmedJoinCases() { ]); final container = _buildContainer(session: session); addTearDown(container.dispose); + container.read(_testPubkeyProvider.notifier).set('9' * 64); container .read(userCacheProvider.notifier) .put(UserProfile(pubkey: scout, displayName: 'Scout')); @@ -497,7 +498,7 @@ void _confirmedJoinCases() { session: session, nsec: keys.nsec, ), - currentPubkey: 'me', + currentPubkey: '9' * 64, ), ), ); @@ -518,12 +519,12 @@ void _confirmedJoinCases() { await expectLater( open(), - shows('Only Scout’s owner can add it to a DM.'), + shows('Only the owner of Scout can add it to a DM.'), ); // Without a name to show, it says whose owner in general. await expectLater( open(), - shows('Only this agent’s owner can add it to a DM.'), + shows('Only the owner of this agent can add it to a DM.'), ); // Any other refusal is shown as before. await expectLater( @@ -555,6 +556,348 @@ void _confirmedJoinCases() { ); }); + test('a refused agent is named by its disambiguated label', () async { + final keys = nostr.Keys.generate(); + final scout = 'd' * 64; + final otherScout = 'c' * 64; + final alice = 'a' * 64; + final aliceAgent = 'b' * 64; + final morgan = '1' * 64; + final session = _WriterReplicaRelaySession(memberships: const []); + final container = _buildContainer(session: session); + addTearDown(container.dispose); + container.read(_testPubkeyProvider.notifier).set('9' * 64); + container.read(userCacheProvider.notifier) + ..put(UserProfile(pubkey: morgan, displayName: 'Morgan')) + ..put(UserProfile(pubkey: alice, displayName: 'Alice')) + ..put( + UserProfile(pubkey: scout, displayName: 'Scout', ownerPubkey: morgan), + ) + ..put( + UserProfile( + pubkey: otherScout, + displayName: 'Scout', + ownerPubkey: alice, + ), + ) + ..put(UserProfile(pubkey: aliceAgent, displayName: 'Alice')); + final actions = container.read( + Provider( + (ref) => ChannelActions( + ref: ref, + session: session, + signedEventRelay: SignedEventRelay( + session: session, + nsec: keys.nsec, + ), + currentPubkey: '9' * 64, + ), + ), + ); + Future open(String agent, List others, bool ownerOnly) { + session.dmOpenRefusals.add( + 'forbidden: policy:${ownerOnly ? 'owner_only' : 'nobody'} — no ' + '(agent $agent)', + ); + return actions.openDm(pubkeys: [agent, ...others]); + } + + Matcher shows(String message) => throwsA( + isA().having( + (error) => error.toString(), + 'message', + message, + ), + ); + + // Two agents named Scout differ by their owners, and the owner is + // named too. + await expectLater( + open(scout, [otherScout], true), + shows('Only Morgan can add Morgan’s Scout to a DM.'), + ); + await expectLater( + open(otherScout, [scout], false), + shows('Alice’s Scout can’t be added to a DM.'), + ); + // An agent sharing a person's name is marked as the agent. + await expectLater( + open(aliceAgent, [alice], true), + shows('Only the owner of Alice (agent) can add it to a DM.'), + ); + // A unique name stays plain, and an owner with no profile or no + // verified owner is not named. + await expectLater( + open(scout, [], true), + shows('Only Morgan can add Scout to a DM.'), + ); + container + .read(userCacheProvider.notifier) + .put(UserProfile(pubkey: scout, displayName: 'Scout')); + await expectLater( + open(scout, [], true), + shows('Only the owner of Scout can add it to a DM.'), + ); + + // A refusal waits only for the names its sentence uses. Naming a + // cached, uniquely named agent reads no profile, though its owner, + // the DM's other people and this account are uncached; a refusal that + // names who may add the agent still reads its owner. + final stranger = '7' * 64; + final unloadedOwner = '8' * 64; + container + .read(userCacheProvider.notifier) + .put( + UserProfile( + pubkey: scout, + displayName: 'Scout', + ownerPubkey: unloadedOwner, + ), + ); + List?> profileReads() => [ + for (final filter in session.historyFilters) + if (filter.kinds.contains(0)) filter.authors, + ]; + session.historyFilters.clear(); + await expectLater( + open(scout, [stranger], false), + shows('Scout can’t be added to a DM.'), + ); + expect(profileReads(), isEmpty); + await expectLater( + open(scout, [stranger], true), + shows('Only the owner of Scout can add it to a DM.'), + ); + expect(profileReads(), [ + [unloadedOwner], + ]); + }); + + group('a refused agent added to a DM', () { + const dmId = 'dm-ahead'; + final me = '9' * 64, scout = 'd' * 64, otherScout = 'c' * 64; + final morgan = '1' * 64, alice = 'a' * 64; + late _WriterReplicaRelaySession session; + late ProviderContainer container; + late ChannelActions actions; + setUp(() { + session = _WriterReplicaRelaySession(memberships: const []); + container = _buildContainer(session: session); + container.read(_testPubkeyProvider.notifier).set(me); + actions = container.read( + Provider( + (ref) => ChannelActions( + ref: ref, + session: session, + signedEventRelay: SignedEventRelay( + session: session, + nsec: nostr.Keys.generate().nsec, + ), + currentPubkey: me, + ), + ), + ); + // Opened from New Message before the channel list has it. + container + .read(channelsProvider.notifier) + .rememberOpened( + Channel( + id: dmId, + name: 'DM', + channelType: 'dm', + visibility: 'private', + description: '', + createdBy: me, + createdAt: DateTime(2025), + memberCount: 2, + participantPubkeys: [me, otherScout], + isMember: true, + ), + ); + }); + tearDown(() => container.dispose()); + + Future add() { + session.dmAddRefusals.add( + 'forbidden: policy:owner_only — no (agent $scout)', + ); + return actions.addToDm( + channelId: dmId, + pubkeys: [scout], + history: DmHistory.include, + ); + } + + test('compares against a DM opened ahead of the list', () async { + container.read(userCacheProvider.notifier) + ..put(UserProfile(pubkey: morgan, displayName: 'Morgan')) + ..put(UserProfile(pubkey: alice, displayName: 'Alice')) + ..put( + UserProfile( + pubkey: scout, + displayName: 'Scout', + ownerPubkey: morgan, + ), + ) + ..put( + UserProfile( + pubkey: otherScout, + displayName: 'Scout', + ownerPubkey: alice, + ), + ); + await expectLater( + add(), + throwsA( + isA().having( + (error) => error.toString(), + 'message', + 'Couldn’t add them. Only Morgan can add Morgan’s Scout to a DM.', + ), + ), + ); + }); + + test('loads every agent owner in one read', () async { + container.read(userCacheProvider.notifier) + ..put(UserProfile(pubkey: me, displayName: 'Me')) + ..put( + UserProfile( + pubkey: scout, + displayName: 'Scout', + ownerPubkey: morgan, + ), + ) + ..put( + UserProfile( + pubkey: otherScout, + displayName: 'Scout', + ownerPubkey: alice, + ), + ); + await expectLater(add(), throwsA(isA())); + expect(session.profileReads, [ + unorderedEquals([morgan, alice]), + ]); + }); + + test('tells two owners named Morgan apart', () async { + container.read(userCacheProvider.notifier) + ..put(UserProfile(pubkey: morgan, displayName: 'Morgan')) + ..put(UserProfile(pubkey: alice, displayName: 'Morgan')) + ..put( + UserProfile( + pubkey: scout, + displayName: 'Scout', + ownerPubkey: morgan, + ), + ) + ..put( + UserProfile( + pubkey: otherScout, + displayName: 'Scout', + ownerPubkey: alice, + ), + ); + await expectLater( + add(), + throwsA( + isA().having( + (error) => error.toString(), + 'message', + 'Couldn’t add them. Only Morgan · sl3h can add Morgan’s Scout · ' + 'dmpv to a DM.', + ), + ), + ); + }); + + for (final ownerOnly in [false, true]) { + test('waits for an owner already in the DM before naming ' + '(${ownerOnly ? 'owner_only' : 'nobody'})', () async { + // Bob adds Morgan's Scout to a DM with Morgan, not yet loaded, and + // Alice's Scout. + const withMorgan = 'dm-morgan'; + container + .read(channelsProvider.notifier) + .rememberOpened( + Channel( + id: withMorgan, + name: 'DM', + channelType: 'dm', + visibility: 'private', + description: '', + createdBy: me, + createdAt: DateTime(2025), + memberCount: 3, + participantPubkeys: [me, morgan, otherScout], + isMember: true, + ), + ); + final cache = container.read(userCacheProvider.notifier) + ..put(UserProfile(pubkey: alice, displayName: 'Alice')) + ..put( + UserProfile( + pubkey: scout, + displayName: 'Scout', + ownerPubkey: morgan, + ), + ) + ..put( + UserProfile( + pubkey: otherScout, + displayName: 'Scout', + ownerPubkey: alice, + ), + ); + session.onProfileRead = (authors) { + if (authors.contains(morgan)) { + cache.put(UserProfile(pubkey: morgan, displayName: 'Morgan')); + } + }; + await expectLater( + () { + session.dmAddRefusals.add( + 'forbidden: policy:${ownerOnly ? 'owner_only' : 'nobody'} — ' + 'no (agent $scout)', + ); + return actions.addToDm( + channelId: withMorgan, + pubkeys: [scout], + history: DmHistory.include, + ); + }(), + throwsA( + isA().having( + (error) => error.toString(), + 'message', + ownerOnly + ? 'Couldn’t add them. Only Morgan can add Morgan’s Scout ' + 'to a DM.' + : 'Couldn’t add them. Morgan’s Scout can’t be added to a DM.', + ), + ), + ); + }); + } + + test('names with what it has once profiles run late', () async { + session.profileReadsHang = true; + final clock = Stopwatch()..start(); + await expectLater( + add(), + throwsA( + isA().having( + (error) => error.toString(), + 'message', + startsWith('Couldn’t add them. Only the owner of '), + ), + ), + ); + expect(clock.elapsed, lessThan(const Duration(seconds: 4))); + }); + }); + test('a list rebuild during the join still shows the membership', () async { final session = _WriterReplicaRelaySession( memberships: const [], @@ -600,6 +943,28 @@ class _WriterReplicaRelaySession extends _FakeRelaySession { /// The relay's refusals of the next DM opens, in order, as their OK messages. final dmOpenRefusals = []; + /// The authors of each profile read, in order. + final profileReads = >[]; + + /// Whether profile reads never answer. + bool profileReadsHang = false; + + /// Called with each profile read's authors, before it answers. + void Function(List authors)? onProfileRead; + + @override + Future> fetchHistory( + NostrFilter filter, { + Duration timeout = const Duration(seconds: 8), + }) { + if (filter.kinds case [0]) { + profileReads.add([...?filter.authors]); + onProfileRead?.call([...?filter.authors]); + if (profileReadsHang) return Completer>().future; + } + return super.fetchHistory(filter, timeout: timeout); + } + @override Future publish( NostrEvent event, { diff --git a/mobile/test/features/channels/channels_provider_test.dart b/mobile/test/features/channels/channels_provider_test.dart index 2a3b54f917..fa391657c2 100644 --- a/mobile/test/features/channels/channels_provider_test.dart +++ b/mobile/test/features/channels/channels_provider_test.dart @@ -13,6 +13,7 @@ import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:buzz/features/activity/activity_page.dart'; +import 'package:buzz/features/channels/channel.dart'; import 'package:buzz/features/channels/channel_detail_page.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';