Files
buzz/mobile/lib/shared/identity_names/identity_name_policy.dart
Logan Johnson efe04288ea 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 <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-09-29 12:21:14 -04:00

240 lines
7.4 KiB
Dart

import 'package:flutter/foundation.dart';
import '../utils/string_utils.dart';
/// Pinned version of the portable identity-name contract implemented here.
///
/// Spec and fixtures:
/// https://github.com/block/buzz-app/blob/92c2fb2/src/bundled/identity-naming/README.md
const identityNamePolicyVersion = 1;
/// One naming fact for an identity. [pubkey] and [ownerPubkey] must be valid
/// 64-character hex public keys (either case); callers choose names and
/// fallbacks first.
@immutable
class NamingIdentity {
final String pubkey;
final String name;
final bool isAgent;
final String? ownerPubkey;
const NamingIdentity({
required this.pubkey,
required this.name,
this.isAgent = false,
this.ownerPubkey,
});
@override
bool operator ==(Object other) =>
other is NamingIdentity &&
other.pubkey == pubkey &&
other.name == name &&
other.isAgent == isAgent &&
other.ownerPubkey == ownerPubkey;
@override
int get hashCode => Object.hash(pubkey, name, isAgent, ownerPubkey);
}
/// A resolved display label. [qualifier] is only the key suffix, when added.
@immutable
class ResolvedIdentityName {
final String name;
final String? qualifier;
const ResolvedIdentityName(this.name, [this.qualifier]);
@override
bool operator ==(Object other) =>
other is ResolvedIdentityName &&
other.name == name &&
other.qualifier == qualifier;
@override
int get hashCode => Object.hash(name, qualifier);
@override
String toString() => 'ResolvedIdentityName($name, $qualifier)';
}
// ECMAScript String.prototype.trim code points, as the contract requires.
// Dart's String.trim also removes U+0085, which the contract keeps.
bool _isContractWhitespace(int unit) =>
(unit >= 0x09 && unit <= 0x0D) ||
unit == 0x20 ||
unit == 0xA0 ||
unit == 0x1680 ||
(unit >= 0x2000 && unit <= 0x200A) ||
unit == 0x2028 ||
unit == 0x2029 ||
unit == 0x202F ||
unit == 0x205F ||
unit == 0x3000 ||
unit == 0xFEFF;
/// Trims [value] exactly as the identity-name contract specifies.
String trimIdentityName(String value) {
var start = 0;
var end = value.length;
while (start < end && _isContractWhitespace(value.codeUnitAt(start))) {
start++;
}
while (end > start && _isContractWhitespace(value.codeUnitAt(end - 1))) {
end--;
}
return value.substring(start, end);
}
final RegExp _hexKey = RegExp(r'^[0-9a-fA-F]{64}$');
void _requireKey(String key, String name) {
if (!_hexKey.hasMatch(key)) {
throw ArgumentError.value(key, name, 'not a 64-character hex public key');
}
}
class _Row {
final String key;
final NamingIdentity identity;
final String original;
final int priority;
final bool mine;
String base;
String label;
int length = 0;
String? suffix;
_Row({
required this.key,
required this.identity,
required this.original,
required this.priority,
required this.mine,
}) : base = original,
label = original;
}
/// Resolves distinct display labels for the selected identities.
///
/// Display policy only: a readable owner or key suffix grants no authority.
/// Implements contextual identity names v1 (see [identityNamePolicyVersion]).
/// Omitting [candidates] selects every supplied fact; an empty set selects
/// none.
///
/// Every supplied key — each fact's [NamingIdentity.pubkey] and
/// [NamingIdentity.ownerPubkey], [viewer], and each candidate — must be a
/// valid public key. The contract leaves invalid keys to the caller, so this
/// throws [ArgumentError] before resolving anything rather than returning a
/// label for a value that is not an identity.
Map<String, ResolvedIdentityName> resolveIdentityNames(
List<NamingIdentity> identities, {
String? viewer,
Iterable<String>? candidates,
}) {
for (final identity in identities) {
_requireKey(identity.pubkey, 'pubkey');
if (identity.ownerPubkey case final owner?) {
_requireKey(owner, 'ownerPubkey');
}
}
if (viewer != null) _requireKey(viewer, 'viewer');
final selected = candidates?.map((key) {
_requireKey(key, 'candidates');
return key.toLowerCase();
}).toSet();
final normalizedViewer = viewer?.toLowerCase();
// Last fact per key: the preferred alias and the owner-lookup name.
final preferred = <String, NamingIdentity>{
for (final identity in identities) identity.pubkey.toLowerCase(): identity,
};
// One working row per (key, trimmed name); the last fact supplies metadata.
final aliases = <(String, String), NamingIdentity>{};
for (final identity in identities) {
final key = (
identity.pubkey.toLowerCase(),
trimIdentityName(identity.name),
);
aliases[key] = identity;
}
final rows = <_Row>[
for (final MapEntry(key: (key, name), value: identity) in aliases.entries)
if (selected == null || selected.contains(key))
() {
final owner = identity.ownerPubkey?.toLowerCase();
final mine =
normalizedViewer != null &&
(key == normalizedViewer || owner == normalizedViewer);
return _Row(
key: key,
identity: identity,
original: name,
mine: mine,
priority: identity.isAgent
? (mine ? 2 : 3)
: (key == normalizedViewer ? 0 : 1),
);
}(),
];
final npubs = <String, String>{};
String npubFor(String key) => npubs[key] ??= fullNpub(key)!;
while (true) {
final groups = <String, List<_Row>>{};
for (final row in rows) {
(groups[row.label] ??= []).add(row);
}
final collisions = [
for (final group in groups.values)
if (group.map((row) => row.key).toSet().length > 1) group,
];
if (collisions.isEmpty) break;
for (final group in collisions) {
final best = group
.map((row) => row.priority)
.reduce((a, b) => a < b ? a : b);
final winners = {
for (final row in group)
if (row.priority == best) row.key,
};
final changing = [
for (final row in group)
if (winners.length != 1 || !winners.contains(row.key)) row,
];
final groupHasHuman = group.any((row) => !row.identity.isAgent);
var qualified = false;
for (final row in changing) {
if (!row.identity.isAgent || row.length != 0) continue;
final ownerKey = row.identity.ownerPubkey?.toLowerCase();
final ownerFact = ownerKey == null ? null : preferred[ownerKey];
final owner = ownerFact == null ? '' : trimIdentityName(ownerFact.name);
final readable = !row.mine && owner.isNotEmpty
? '$owner\u2019s ${row.original}'
: groupHasHuman
? '${row.original} (agent)'
: row.base;
if (readable != row.base) {
row.base = readable;
row.label = readable;
qualified = true;
}
}
if (qualified) continue;
for (final row in changing) {
row.length = row.length == 0 ? 4 : row.length + 1;
final npub = npubFor(row.key);
row.suffix = row.length <= npub.length
? npub.substring(npub.length - row.length)
: '$npub \u00b7 ${row.length - npub.length}';
row.label = '${row.base} \u00b7 ${row.suffix}';
}
}
}
return {
for (final row in rows)
if (row.original == trimIdentityName(preferred[row.key]!.name))
row.key: ResolvedIdentityName(row.label, row.suffix),
};
}