Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 40 additions & 6 deletions mobile/lib/features/channels/channel_management_actions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -186,13 +186,21 @@ class ChannelActions {
);
NostrEvent result;
try {
result = await submit(includeHistory: includeHistory);
} catch (error) {
if (!includeHistory || relayErrorText(error) != _onlyPeopleShareHistory) {
rethrow;
try {
result = await submit(includeHistory: includeHistory);
} catch (error) {
if (!includeHistory ||
relayErrorText(error) != _onlyPeopleShareHistory) {
rethrow;
}
_ensureCommunityValid();
result = await submit(includeHistory: false);
}
_ensureCommunityValid();
result = await submit(includeHistory: false);
} on StateError {
rethrow;
} catch (error) {
await _throwIfAgentRefused(relayErrorText(error), adding: false);
rethrow;
}
_ensureCommunityValid();
final response = parseCommandResponse(result.content);
Expand Down Expand Up @@ -315,6 +323,7 @@ class ChannelActions {
reason == 'invalid: history must be "include", got "ask"')) {
throw const DmNeedsHistoryChoice();
}
await _throwIfAgentRefused(reason, adding: true);
throw Exception(
reason.contains('at most 9 people')
? dmAdditionFailedMessage
Expand All @@ -336,6 +345,31 @@ class ChannelActions {
return openAddedDm(id);
}

/// 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.
Future<void> _throwIfAgentRefused(
String reason, {
required bool adding,
}) 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));
_ensureCommunityValid();
final name = profile?.displayName;
throw DmAgentRefused(
dmAgentRefusedMessage(
adding: adding,
ownerOnly: refusal.ownerOnly,
name: name != null && name.trim().isNotEmpty ? name : null,
),
);
}

/// Confirms through the writer that the current user is in the DM
/// [channelId] an add landed in, and returns it, without sending the add
/// again. Throws [DmAddUnconfirmed] when it cannot be confirmed or shown.
Expand Down
40 changes: 40 additions & 0 deletions mobile/lib/features/channels/channel_management_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import '../../shared/custom_emoji/custom_emoji.dart';
import '../../shared/custom_emoji/custom_emoji_provider.dart';
import '../../shared/crypto/nip_oa.dart';
import '../../shared/mentions/agent_identity_provider.dart';
import '../../shared/profile/user_cache_provider.dart';
import '../../shared/relay/relay.dart';
import '../../shared/utils/string_utils.dart';
import '../../shared/verified_profiles/verified_profile.dart';
Expand Down Expand Up @@ -49,6 +50,45 @@ class DmNeedsHistoryChoice implements Exception {
const DmNeedsHistoryChoice();
}

/// An agent's add policy refused it a DM open or add. [message] names the
/// agent, so the person knows whose owner to ask.
class DmAgentRefused implements Exception {
const DmAgentRefused(this.message);

final String message;

@override
String toString() => message;
}

/// The relay names the agent whose add policy refused a DM open or add,
/// after its policy code.
final _agentPolicyRefusal = RegExp(
r'^(?:forbidden: )?policy:(owner_only|nobody)\b.*\(agent ([0-9a-f]{64})\)$',
);

/// The policy and agent of an agent's add-policy refusal of a DM, from the
/// relay's [reason], as desktop's `agentPolicyRefusal` reads it.
({bool ownerOnly, String agent})? dmAgentPolicyRefusal(String reason) {
final match = _agentPolicyRefusal.firstMatch(reason);
return match == null
? null
: (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.
String dmAgentRefusedMessage({
required bool adding,
required bool ownerOnly,
String? name,
}) {
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.';
return '${adding ? 'Couldn’t add them. ' : ''}$refused';
}

/// Raised when one or more kind:9000 adds were rejected, keyed by pubkey.
///
/// Callers surface [message] to the user — a relay rejection here (e.g. a plain
Expand Down
16 changes: 14 additions & 2 deletions mobile/lib/features/channels/dm_channel_labels.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ IdentityNames dmParticipantNames(Channel channel, IdentityNameSources names) =>
);

/// The DM's display label. With [names], participant labels follow the
/// contextual identity-name policy, so namesakes stay distinguishable.
/// contextual identity-name policy, so namesakes stay distinguishable, and
/// agents are left out unless no other person is in the DM. "+N more"
/// counts people only; member counts and lists still include agents.
String resolveDmChannelDisplayLabel(
Channel channel, {
String? currentPubkey,
Expand All @@ -62,11 +64,21 @@ String resolveDmChannelDisplayLabel(
),
];

final displayParticipants = normalizedCurrent == null
final others = normalizedCurrent == null
? participants
: participants
.where((participant) => participant.pubkey != normalizedCurrent)
.toList();
// The name lists people, never agents, unless no other person is in it.
// A profile not loaded yet counts as a person until it says otherwise.
final people = others
.where(
(participant) =>
participant.pubkey == null ||
participantNames?.isAgent(participant.pubkey!) != true,
)
.toList();
final displayParticipants = people.isNotEmpty ? people : others;
final labels = <String>{
for (final participant
in displayParticipants.isNotEmpty ? displayParticipants : participants)
Expand Down
92 changes: 92 additions & 0 deletions mobile/test/features/channels/channels_provider_join_cases.dart
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,92 @@ void _confirmedJoinCases() {
},
);

test('an agent policy refusal of a DM open or add names the agent', () async {
final keys = nostr.Keys.generate();
final scout = 'd' * 64;
final unknown = 'e' * 64;
final session = _WriterReplicaRelaySession(memberships: const [])
..dmOpenRefusals.addAll([
'forbidden: policy:owner_only — only the agent owner can add this agent (agent $scout)',
'forbidden: policy:owner_only — only the agent owner can add this agent (agent $unknown)',
'restricted: no',
])
..dmAddRefusals.addAll([
'forbidden: policy:nobody — this agent has disabled external channel additions (agent $scout)',
'forbidden: policy:nobody — this agent has disabled external channel additions',
]);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
container
.read(userCacheProvider.notifier)
.put(UserProfile(pubkey: scout, displayName: 'Scout'));
final actions = container.read(
Provider<ChannelActions>(
(ref) => ChannelActions(
ref: ref,
session: session,
signedEventRelay: SignedEventRelay(
session: session,
nsec: keys.nsec,
),
currentPubkey: 'me',
),
),
);
Matcher shows(String message) => throwsA(
isA<DmAgentRefused>().having(
(error) => error.toString(),
'message',
message,
),
);
Future<void> open() =>
actions.openDm(pubkeys: [scout], includeHistory: true);
Future<void> add() => actions.addToDm(
channelId: _otherJoinedChannel,
pubkeys: [scout],
history: DmHistory.ask,
);

await expectLater(
open(),
shows('Only Scout’s owner 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.'),
);
// Any other refusal is shown as before.
await expectLater(
open(),
throwsA(
isA<Exception>()
.having((e) => e is DmAgentRefused, 'named', isFalse)
.having(
(e) => e.toString(),
'message',
'Exception: restricted: no',
),
),
);
await expectLater(
add(),
shows('Couldn’t add them. Scout can’t be added to a DM.'),
);
// A relay that names no agent refuses as before.
await expectLater(
add(),
throwsA(
isA<Exception>().having(
(error) => error.toString(),
'message',
'Exception: Couldn’t add them. Try again.',
),
),
);
});

test('a list rebuild during the join still shows the membership', () async {
final session = _WriterReplicaRelaySession(
memberships: const [],
Expand Down Expand Up @@ -511,6 +597,9 @@ class _WriterReplicaRelaySession extends _FakeRelaySession {
/// The relay's refusals of the next DM adds, in order, as their OK messages.
final dmAddRefusals = <String>[];

/// The relay's refusals of the next DM opens, in order, as their OK messages.
final dmOpenRefusals = <String>[];

@override
Future<NostrEvent> publish(
NostrEvent event, {
Expand All @@ -521,6 +610,9 @@ class _WriterReplicaRelaySession extends _FakeRelaySession {
if (event.kind == 41011 && dmAddRefusals.isNotEmpty) {
throw Exception(dmAddRefusals.removeAt(0));
}
if (event.kind == 41010 && dmOpenRefusals.isNotEmpty) {
throw Exception(dmOpenRefusals.removeAt(0));
}
final response = dmAddResponse;
if (event.kind == 41011 && response != null) {
return NostrEvent(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import 'package:buzz/shared/read_state/read_state_format.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/read_state/read_state_provider.dart';
import 'package:buzz/shared/profile/user_cache_provider.dart';
import 'package:buzz/shared/profile/user_profile.dart';
import 'package:buzz/features/activity/activity_provider.dart';
import 'package:buzz/features/activity/inbox_item.dart';
import 'package:buzz/features/activity/inbox_read_state.dart';
Expand Down
38 changes: 38 additions & 0 deletions mobile/test/features/channels/dm_channel_labels_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'package:buzz/features/channels/channel.dart';
import 'package:buzz/features/channels/dm_channel_labels.dart';
import 'package:buzz/shared/identity_names/identity_names.dart';
import 'package:buzz/shared/profile/user_profile.dart';
import 'package:buzz/shared/utils/string_utils.dart';
import 'package:flutter_test/flutter_test.dart';

String _key(int number) => number.toRadixString(16).padLeft(64, '0');
Expand Down Expand Up @@ -167,4 +168,41 @@ void main() {
);
},
);

test('a DM is named by its people, never its agents, unless it has none', () {
final me = _key(1);
final ana = _key(2), ben = _key(3), cy = _key(4), dee = _key(5);
final bot = _key(6), helper = _key(7), unloaded = _key(8);
final names = IdentityNameSources(
profiles: {
for (final (key, name) in [
(ana, 'Ana'),
(ben, 'Ben'),
(cy, 'Cy'),
(dee, 'Dee'),
])
key: UserProfile(pubkey: key, displayName: name),
bot: UserProfile(pubkey: bot, displayName: 'Bot', ownerPubkey: me),
helper: UserProfile(
pubkey: helper,
displayName: 'Helper',
ownerPubkey: me,
),
},
);
String label(List<String> keys) => resolveDmChannelDisplayLabel(
_dm('dm', keys: [me, ...keys]),
currentPubkey: me,
names: names,
);

// People and agents: only the people.
expect(label([bot, ana]), 'Ana');
// Only agents: no other person, so the agents.
expect(label([bot, helper]), 'Bot, Helper');
// More than three people and agents: "+N more" counts people only.
expect(label([bot, ana, ben, helper, cy, dee]), 'Ana, Ben, Cy, +1 more');
// A profile not loaded yet is named until it says it is an agent.
expect(label([bot, unloaded]), shortPubkey(unloaded));
});
}
Loading