feat(mobile): name blocking agents, leave agents out of DM names (#9875)

## Problem

Two follow-ups to growable DMs (#9153), matching desktop
block/buzz-app#3744:

1. When an agent's add policy blocks a DM, mobile shows a generic error.
The person can't tell which agent blocked it or whose owner to ask.
2. DM names list every member, agents included, so a DM with one person
and their agent reads like a group, and "+N more" mixes agents with
people.

## Change

**Name the blocking agent.** The relay names the agent in that refusal
(#9601). Mobile shows the agent's name: "Only Scout's owner can add it
to a DM." or "Scout can't be added to a DM.", starting with "Couldn't
add them." when adding to an existing DM, and "this agent" when the name
can't be read. Against a relay without #9601, the error is the same as
before.

**Leave agents out of DM names.** A DM's name lists its people and never
its agents, unless no other person is in it (just you and agents), when
it names the agents. "+N more" counts people only. Member counts and
member lists still include agents. The shared DM label feeds the list,
headers, details and Activity. Agent means the profile's existing agent
flag; a profile that hasn't loaded yet counts as a person until it says
otherwise.

## Screenshots

Temporary headless renders with test data, not committed.

### Name the blocking agent

Add people, refused by an agent's owner-only setting:

| | Light | Dark |
|---|---|---|
| Narrow | ![light
narrow](https://github.com/user-attachments/assets/61bfbfe2-5882-456e-8bff-b42f7389aa06)
| ![dark
narrow](https://github.com/user-attachments/assets/d7ac0dca-9081-4cde-a403-cde492d2cf4f)
|
| Wide | ![light
wide](https://github.com/user-attachments/assets/cc9f5a0f-0f3a-4d80-8fc6-0937a2246462)
| ![dark
wide](https://github.com/user-attachments/assets/87b48014-9740-4e17-ad83-f5bac272dda8)
|

### DM names without agents

Ana alone, Ana with two agents (named "Ana", count still 3), and only
the two agents (named by them):

| | Light | Dark |
|---|---|---|
| Narrow | ![light
narrow](https://github.com/user-attachments/assets/b413dbc1-a2bc-4410-8be9-b1a219374349)
| ![dark
narrow](https://github.com/user-attachments/assets/75c9cbc3-432f-45c7-83a4-624f80752b97)
|
| Wide | ![light
wide](https://github.com/user-attachments/assets/ae57c305-f4e4-4e26-8ba0-ecbcd128137e)
| ![dark
wide](https://github.com/user-attachments/assets/a75efc90-6b20-4409-bdd5-682de1f0301f)
|

## Tests

- Blocking agent: an open and an add name the agent, fall back to "this
agent", and leave other refusals as they were.
- DM names: people and agents, only agents, more than three people and
agents, and a profile that hasn't loaded yet.

The lost-reply recovery was taken out after review. It comes back as a
relay change that answers a replayed signed command with its saved
result, so the app can resend the same event instead of guessing from
rosters.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
Co-authored-by: Carl <c217fe6b9d958f41c3a5e030dccc7f626775a923089cb6491305eade75ea1f1b@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
morgmart
2026-11-23 12:10:23 -08:00
committed by GitHub
parent 6017091936
commit 70bb7b7bec
6 changed files with 225 additions and 8 deletions

View File

@@ -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);
@@ -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
@@ -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.

View File

@@ -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';
@@ -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

View File

@@ -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,
@@ -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)

View File

@@ -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 [],
@@ -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, {
@@ -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(

View File

@@ -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';

View File

@@ -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');
@@ -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));
});
}