Skip to content

Commit efe0428

Browse files
loganjLarry
andauthored
feat(mobile): add the contextual identity-name resolver (#7894)
🤖 ## Summary When two identities share a display name, Buzz mobile shows the same label for both. A reader cannot tell a person from an agent, or one person's agent from another's. For example, a channel can show three agents and one human all named "murderbot". This PR adds the naming rules that fix this, without changing any screen yet. It ports the contextual identity-name contract (v1) from the desktop app to Dart. Given the identities shown together, the resolver gives each public key a distinct label: - A human keeps the plain name. Agents that share it get a qualifier. - The viewer's own agents are named before other people's agents. - An agent is qualified by its owner's name first ("Wes's Honey"). A short public-key suffix is added only if that is still ambiguous ("baxen's murderbot · xa8v"). It also adds two providers that screens will use: - `channelIdentityNamesProvider` compares names against a channel's members, plus any referenced non-member such as an old author or an outside mention. - `watchIdentityNames` compares a set of identities shown together outside a channel, and loads their profiles. The next PRs in this stack connect these to the screens. Part 1 of 3: #7894 (resolver) → #7895 (conversations) → #7896 (lists, Search, Pulse). ### Related issue Related to #2910 (default "Fizz" agents from different users collide in one channel). ### Testing - The contract's 31 portable fixture cases run against the production resolver. The fixture file is copied unchanged from the contract, so reviewers can skip it. - Unit tests cover owner and suffix qualification, the viewer's own identities, and invalid public keys. - Provider tests check that a channel keeps its names while its roster reloads, that an offline cached bot still counts as an agent, and that changing relay or account never shows the old roster. - `flutter analyze` is clean. No UI change, so there are no screenshots. --------- Signed-off-by: Logan Johnson <[email protected]> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
1 parent bba75a7 commit efe0428

9 files changed

Lines changed: 2824 additions & 0 deletions
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import 'dart:collection';
2+
3+
import 'package:flutter/foundation.dart';
4+
import 'package:hooks_riverpod/hooks_riverpod.dart';
5+
6+
import '../../shared/identity_names/identity_names.dart';
7+
import '../../shared/identity_names/identity_names_provider.dart';
8+
import '../../shared/mentions/agent_identity_provider.dart';
9+
import 'channel_management_provider.dart';
10+
import 'channels_provider.dart';
11+
12+
/// Contextual identity labels for one channel, thread, or DM.
13+
///
14+
/// The comparison context is the channel's members; a referenced non-member
15+
/// (historical author, outside mention) is compared against the members plus
16+
/// itself. Watch one label with
17+
/// `ref.watch(channelIdentityNamesProvider(id).select((n) => n.labelFor(pk)))`.
18+
final channelIdentityNamesProvider = Provider.autoDispose
19+
.family<IdentityNames, String>((ref, channelId) {
20+
final sources = ref.watch(identityNameSourcesProvider);
21+
final members =
22+
watchLatestChannelMembers(ref, channelId) ??
23+
(ref.watch(channelsProvider).asData == null
24+
? const <ChannelMember>[]
25+
: ref
26+
.read(channelsProvider.notifier)
27+
.cachedMembersForChannel(channelId));
28+
final names = sources.scope(
29+
[for (final member in members) member.pubkey],
30+
// The roster's own bot roles stay available offline, when the
31+
// relay-backed bot lookup and agent directory are empty.
32+
agentPubkeys: {
33+
...ref.watch(agentMentionPubkeysProvider(channelId)),
34+
for (final member in members)
35+
if (member.isBot) member.pubkey,
36+
},
37+
fallbackNames: {
38+
for (final member in members) member.pubkey: ?member.displayName,
39+
},
40+
);
41+
loadIdentityNameOwners(ref, sources, names.candidates);
42+
return names;
43+
});
44+
45+
/// Watches one identity's contextual label in [channelId].
46+
String watchChannelIdentityLabel(
47+
WidgetRef ref,
48+
String channelId,
49+
String pubkey,
50+
) => ref.watch(
51+
channelIdentityNamesProvider(
52+
channelId,
53+
).select((names) => names.labelFor(pubkey)),
54+
);
55+
56+
/// Watches contextual labels for [pubkeys] in [channelId], keyed by
57+
/// lowercase pubkey. Rebuilds only when one of these labels changes.
58+
Map<String, String> watchChannelIdentityLabels(
59+
WidgetRef ref,
60+
String channelId,
61+
Iterable<String> pubkeys,
62+
) {
63+
final keys = {for (final pubkey in pubkeys) pubkey.toLowerCase()};
64+
if (keys.isEmpty) return const {};
65+
return ref.watch(
66+
channelIdentityNamesProvider(channelId).select(
67+
(names) => _LabelMap({for (final key in keys) key: names.labelFor(key)}),
68+
),
69+
);
70+
}
71+
72+
class _LabelMap extends UnmodifiableMapView<String, String> {
73+
_LabelMap(super.labels);
74+
75+
@override
76+
bool operator ==(Object other) =>
77+
other is Map<String, String> && mapEquals(this, other);
78+
79+
@override
80+
int get hashCode => Object.hashAllUnordered(
81+
entries.map((entry) => Object.hash(entry.key, entry.value)),
82+
);
83+
}

‎mobile/lib/features/channels/channel_management_provider.dart‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -586,6 +586,24 @@ final channelMembersProvider = FutureProvider.autoDispose
586586
return members;
587587
});
588588

589+
/// The latest roster for [channelId] in the current relay, account, and
590+
/// channel scope, or null if none has loaded in that scope yet.
591+
///
592+
/// While [channelMembersProvider] reloads (for example after a kind:39002
593+
/// update), this keeps the roster from the last completed load in the same
594+
/// scope instead of dropping it. Another relay or account never sees it.
595+
List<ChannelMember>? watchLatestChannelMembers(Ref ref, String channelId) {
596+
final loaded = ref.watch(channelMembersProvider(channelId)).asData?.value;
597+
if (loaded != null) return loaded;
598+
return ref
599+
.read(_channelMembersSnapshotCacheProvider)
600+
.read(
601+
relayBaseUrl: ref.watch(relayConfigProvider).baseUrl,
602+
pubkey: ref.watch(myPubkeyProvider)?.toLowerCase(),
603+
channelId: channelId,
604+
);
605+
}
606+
589607
/// Channel canvas (kind:40100 for the channel).
590608
final channelCanvasProvider = FutureProvider.family<ChannelCanvas, String>((
591609
ref,
Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
import 'package:flutter/foundation.dart';
2+
3+
import '../utils/string_utils.dart';
4+
5+
/// Pinned version of the portable identity-name contract implemented here.
6+
///
7+
/// Spec and fixtures:
8+
/// https://github.com/block/buzz-app/blob/92c2fb2/src/bundled/identity-naming/README.md
9+
const identityNamePolicyVersion = 1;
10+
11+
/// One naming fact for an identity. [pubkey] and [ownerPubkey] must be valid
12+
/// 64-character hex public keys (either case); callers choose names and
13+
/// fallbacks first.
14+
@immutable
15+
class NamingIdentity {
16+
final String pubkey;
17+
final String name;
18+
final bool isAgent;
19+
final String? ownerPubkey;
20+
21+
const NamingIdentity({
22+
required this.pubkey,
23+
required this.name,
24+
this.isAgent = false,
25+
this.ownerPubkey,
26+
});
27+
28+
@override
29+
bool operator ==(Object other) =>
30+
other is NamingIdentity &&
31+
other.pubkey == pubkey &&
32+
other.name == name &&
33+
other.isAgent == isAgent &&
34+
other.ownerPubkey == ownerPubkey;
35+
36+
@override
37+
int get hashCode => Object.hash(pubkey, name, isAgent, ownerPubkey);
38+
}
39+
40+
/// A resolved display label. [qualifier] is only the key suffix, when added.
41+
@immutable
42+
class ResolvedIdentityName {
43+
final String name;
44+
final String? qualifier;
45+
46+
const ResolvedIdentityName(this.name, [this.qualifier]);
47+
48+
@override
49+
bool operator ==(Object other) =>
50+
other is ResolvedIdentityName &&
51+
other.name == name &&
52+
other.qualifier == qualifier;
53+
54+
@override
55+
int get hashCode => Object.hash(name, qualifier);
56+
57+
@override
58+
String toString() => 'ResolvedIdentityName($name, $qualifier)';
59+
}
60+
61+
// ECMAScript String.prototype.trim code points, as the contract requires.
62+
// Dart's String.trim also removes U+0085, which the contract keeps.
63+
bool _isContractWhitespace(int unit) =>
64+
(unit >= 0x09 && unit <= 0x0D) ||
65+
unit == 0x20 ||
66+
unit == 0xA0 ||
67+
unit == 0x1680 ||
68+
(unit >= 0x2000 && unit <= 0x200A) ||
69+
unit == 0x2028 ||
70+
unit == 0x2029 ||
71+
unit == 0x202F ||
72+
unit == 0x205F ||
73+
unit == 0x3000 ||
74+
unit == 0xFEFF;
75+
76+
/// Trims [value] exactly as the identity-name contract specifies.
77+
String trimIdentityName(String value) {
78+
var start = 0;
79+
var end = value.length;
80+
while (start < end && _isContractWhitespace(value.codeUnitAt(start))) {
81+
start++;
82+
}
83+
while (end > start && _isContractWhitespace(value.codeUnitAt(end - 1))) {
84+
end--;
85+
}
86+
return value.substring(start, end);
87+
}
88+
89+
final RegExp _hexKey = RegExp(r'^[0-9a-fA-F]{64}$');
90+
91+
void _requireKey(String key, String name) {
92+
if (!_hexKey.hasMatch(key)) {
93+
throw ArgumentError.value(key, name, 'not a 64-character hex public key');
94+
}
95+
}
96+
97+
class _Row {
98+
final String key;
99+
final NamingIdentity identity;
100+
final String original;
101+
final int priority;
102+
final bool mine;
103+
String base;
104+
String label;
105+
int length = 0;
106+
String? suffix;
107+
108+
_Row({
109+
required this.key,
110+
required this.identity,
111+
required this.original,
112+
required this.priority,
113+
required this.mine,
114+
}) : base = original,
115+
label = original;
116+
}
117+
118+
/// Resolves distinct display labels for the selected identities.
119+
///
120+
/// Display policy only: a readable owner or key suffix grants no authority.
121+
/// Implements contextual identity names v1 (see [identityNamePolicyVersion]).
122+
/// Omitting [candidates] selects every supplied fact; an empty set selects
123+
/// none.
124+
///
125+
/// Every supplied key — each fact's [NamingIdentity.pubkey] and
126+
/// [NamingIdentity.ownerPubkey], [viewer], and each candidate — must be a
127+
/// valid public key. The contract leaves invalid keys to the caller, so this
128+
/// throws [ArgumentError] before resolving anything rather than returning a
129+
/// label for a value that is not an identity.
130+
Map<String, ResolvedIdentityName> resolveIdentityNames(
131+
List<NamingIdentity> identities, {
132+
String? viewer,
133+
Iterable<String>? candidates,
134+
}) {
135+
for (final identity in identities) {
136+
_requireKey(identity.pubkey, 'pubkey');
137+
if (identity.ownerPubkey case final owner?) {
138+
_requireKey(owner, 'ownerPubkey');
139+
}
140+
}
141+
if (viewer != null) _requireKey(viewer, 'viewer');
142+
final selected = candidates?.map((key) {
143+
_requireKey(key, 'candidates');
144+
return key.toLowerCase();
145+
}).toSet();
146+
final normalizedViewer = viewer?.toLowerCase();
147+
// Last fact per key: the preferred alias and the owner-lookup name.
148+
final preferred = <String, NamingIdentity>{
149+
for (final identity in identities) identity.pubkey.toLowerCase(): identity,
150+
};
151+
// One working row per (key, trimmed name); the last fact supplies metadata.
152+
final aliases = <(String, String), NamingIdentity>{};
153+
for (final identity in identities) {
154+
final key = (
155+
identity.pubkey.toLowerCase(),
156+
trimIdentityName(identity.name),
157+
);
158+
aliases[key] = identity;
159+
}
160+
final rows = <_Row>[
161+
for (final MapEntry(key: (key, name), value: identity) in aliases.entries)
162+
if (selected == null || selected.contains(key))
163+
() {
164+
final owner = identity.ownerPubkey?.toLowerCase();
165+
final mine =
166+
normalizedViewer != null &&
167+
(key == normalizedViewer || owner == normalizedViewer);
168+
return _Row(
169+
key: key,
170+
identity: identity,
171+
original: name,
172+
mine: mine,
173+
priority: identity.isAgent
174+
? (mine ? 2 : 3)
175+
: (key == normalizedViewer ? 0 : 1),
176+
);
177+
}(),
178+
];
179+
final npubs = <String, String>{};
180+
String npubFor(String key) => npubs[key] ??= fullNpub(key)!;
181+
182+
while (true) {
183+
final groups = <String, List<_Row>>{};
184+
for (final row in rows) {
185+
(groups[row.label] ??= []).add(row);
186+
}
187+
final collisions = [
188+
for (final group in groups.values)
189+
if (group.map((row) => row.key).toSet().length > 1) group,
190+
];
191+
if (collisions.isEmpty) break;
192+
for (final group in collisions) {
193+
final best = group
194+
.map((row) => row.priority)
195+
.reduce((a, b) => a < b ? a : b);
196+
final winners = {
197+
for (final row in group)
198+
if (row.priority == best) row.key,
199+
};
200+
final changing = [
201+
for (final row in group)
202+
if (winners.length != 1 || !winners.contains(row.key)) row,
203+
];
204+
final groupHasHuman = group.any((row) => !row.identity.isAgent);
205+
var qualified = false;
206+
for (final row in changing) {
207+
if (!row.identity.isAgent || row.length != 0) continue;
208+
final ownerKey = row.identity.ownerPubkey?.toLowerCase();
209+
final ownerFact = ownerKey == null ? null : preferred[ownerKey];
210+
final owner = ownerFact == null ? '' : trimIdentityName(ownerFact.name);
211+
final readable = !row.mine && owner.isNotEmpty
212+
? '$owner\u2019s ${row.original}'
213+
: groupHasHuman
214+
? '${row.original} (agent)'
215+
: row.base;
216+
if (readable != row.base) {
217+
row.base = readable;
218+
row.label = readable;
219+
qualified = true;
220+
}
221+
}
222+
if (qualified) continue;
223+
for (final row in changing) {
224+
row.length = row.length == 0 ? 4 : row.length + 1;
225+
final npub = npubFor(row.key);
226+
row.suffix = row.length <= npub.length
227+
? npub.substring(npub.length - row.length)
228+
: '$npub \u00b7 ${row.length - npub.length}';
229+
row.label = '${row.base} \u00b7 ${row.suffix}';
230+
}
231+
}
232+
}
233+
234+
return {
235+
for (final row in rows)
236+
if (row.original == trimIdentityName(preferred[row.key]!.name))
237+
row.key: ResolvedIdentityName(row.label, row.suffix),
238+
};
239+
}

0 commit comments

Comments
 (0)