Files
buzz/mobile/lib/features/channels/dm_channel_labels.dart
Logan Johnson 82656ffea0 fix(mobile): standardize public-key identity display on npub (#7493)
🤖

## Summary

In the mobile app, anyone who hasn't set a display name shows up as a
raw 64-character hex key (e.g. `3a5d4f9c…`) — unreadable, and
unrecognizable as the same identity across screens. Profile and Settings
also let you copy that raw hex. Nostr public keys have a standard
readable form — `npub1…`, the same encoding other Nostr apps and our
desktop app already display. This PR makes every mobile identity surface
render npub instead:

- **Unnamed people everywhere** — message and thread authors, reactions,
typing indicators, member lists, channel details, DM headers and tiles,
inbox, search, forum cards, Pulse notes and reply context, mention
suggestions, and invite rows — now show a compact npub label: first 8 +
last 4 characters of the full npub joined by an ellipsis
(`npub1abcd…wxyz`), the same truncation desktop uses. Previously these
showed truncated raw hex.
- **DM fallback avatars and blank names** — 1:1 DM tiles and headers key
their fallback avatar to the same non-self counterpart the label names,
including self-first participant order; a self-DM keeps its
hex-key-derived initial. Blank or whitespace-only display names fall
back to the compact npub instead of rendering empty, while nonblank
authored names render verbatim (padding included).
- **Profile sheet → "Copy public key"** now copies the full canonical
npub — never raw hex. When the identity string isn't a valid public key,
the copy tile is disabled, so a malformed key never reaches the
clipboard.
- **Settings → Identity (pubkey)** displays and copies the full npub; an
invalid identity reads "Identity unavailable" with copy disabled.
- **Invalid identities never leak truncated raw hex** into the UI
anywhere — they render a neutral "Unknown identity" label.
- **Unchanged on purpose:** display names and verified handles (NIP-05 —
the `name@domain` badge) still render as before. Unnamed avatars keep
distinct per-key initials, derived from the underlying hex key rather
than the npub — otherwise every unnamed key would render the same "N"
initial. Event IDs are not public keys, so they keep their hex
truncation (in Pulse's "Replying to", the parent author shows npub while
an event-id fallback still shows hex). The nevent share link, private
keys, and internal hex storage are untouched. Inputs that accept a key
(invite/member entry) accept both hex and npub and keep working in hex
internally.

### Related issue

N/A. Searched open issues/PRs for npub identity display on mobile —
closest related: none found. Desktop's parallel npub standardization
lives in the stacked desktop PRs (#7488 foundation, #7489 controls,
#7495 display surfaces); this is the independent mobile slice (based
directly on `main`, not on those branches).

### Testing

At exact head `5a620e420a1fd57d9d8011ac26434eed32fcf765` (base: `main`
`44316ff72`; 40 files, +1,345/−154):

- Full mobile suite: 2,098 tests passing (`cd mobile && flutter test`);
`flutter analyze` clean; `dart format --set-exit-if-changed .` clean —
the same checks CI runs.
- Widget/unit coverage at production seams: compact labels and hex-keyed
avatar initials for DM headers/tiles, member rows, mention suggestions,
and Pulse reply context; DM fallback avatars keyed to the labeled
counterpart (self-first order and self-DMs); blank/whitespace
display-name npub fallback with nonblank authored labels verbatim,
including the Activity inbox sender and profile-sheet heading (each with
its own empty/whitespace production-seam regression); full-npub copy and
disabled-copy semantics in profile and settings; invalid-key
suppression; and hex↔npub input round-trips.

Verified via unit and widget tests — no device/simulator validation is
claimed.

### Task provenance

Buzz channel: `1f0e4a3d-7e01-4efe-bb16-843b357f85c9`

Task:
buzz://message?channel=1f0e4a3d-7e01-4efe-bb16-843b357f85c9&id=86b34eb4bd84a1472419e9af22636c011c0fe273e3c196f967d7a36996e149b6

---------

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-09-09 14:08:24 -04:00

129 lines
4.6 KiB
Dart

import '../../shared/utils/string_utils.dart';
import 'channel.dart';
const int _dmParticipantPreviewLimit = 3;
bool isGenericDmChannelName(String name) {
final normalized = name.trim().toLowerCase();
if (normalized.isEmpty ||
normalized == 'dm' ||
normalized == 'direct message' ||
normalized == 'direct messages') {
return true;
}
return RegExp(r'^group dm\s*(\(\d+\))?$').hasMatch(normalized);
}
String formatDmParticipantDisplayName(List<String> displayNames) {
final visible = displayNames.take(_dmParticipantPreviewLimit).toList();
final hiddenCount = displayNames.length - visible.length;
return hiddenCount > 0
? [...visible, '+$hiddenCount more'].join(', ')
: visible.join(', ');
}
String resolveDmChannelDisplayLabel(Channel channel, {String? currentPubkey}) {
if (!channel.isDm || !isGenericDmChannelName(channel.name)) {
return channel.name;
}
final normalizedCurrent = currentPubkey?.toLowerCase();
final participants = <({String label, String? pubkey})>[
for (var index = 0; index < channel.participantPubkeys.length; index++)
(
label: index < channel.participants.length
? channel.participants[index]
: shortPubkey(channel.participantPubkeys[index]),
pubkey: channel.participantPubkeys[index].toLowerCase(),
),
];
final displayParticipants = normalizedCurrent == null
? participants
: participants
.where((participant) => participant.pubkey != normalizedCurrent)
.toList();
final labels = <String>{
for (final participant
in displayParticipants.isNotEmpty ? displayParticipants : participants)
participant.label,
}.toList();
return labels.isNotEmpty
? formatDmParticipantDisplayName(labels)
: channel.name;
}
/// Avatar initial for the DM's visible counterpart.
///
/// Mirrors [resolveDmChannelDisplayLabel]'s participant selection: the
/// first participant that is not [currentPubkey], since member order does
/// not guarantee the counterpart is listed first — otherwise the avatar
/// could identify the current user while the label beside it identifies
/// the counterpart. When every participant is the current user (a
/// self-DM), the label names the current user too, so the avatar keys off
/// that same first participant instead of its label's first character.
///
/// A resolved display name keeps its name-derived initial. A label that
/// fell back to the compact npub form of the participant's key is keyed to
/// the hex public key instead — the npub form starts with `npub1`, so every
/// unnamed participant would otherwise render `N`.
String dmAvatarInitial(Channel channel, {String? currentPubkey}) {
final normalizedCurrent = currentPubkey?.toLowerCase();
var index = 0;
while (normalizedCurrent != null &&
index < channel.participantPubkeys.length &&
channel.participantPubkeys[index].toLowerCase() == normalizedCurrent) {
index++;
}
if (index >= channel.participantPubkeys.length) {
// No participant pubkeys (labels only): fall back to the first
// participant label, like the channel label does when the non-self
// list is empty.
if (channel.participantPubkeys.isEmpty) {
final label = channel.participants.isNotEmpty
? channel.participants.first
: '';
return label.isNotEmpty ? label[0].toUpperCase() : '?';
}
// Keys exist but every participant is the current user (a self-DM):
// the label names the current user, so key the avatar to that same
// first participant with the shared provenance rule below — the hex
// key for a compact npub label, the authored name otherwise.
index = 0;
}
final pubkey = channel.participantPubkeys[index];
final label = index < channel.participants.length
? channel.participants[index]
: shortPubkey(pubkey);
if (pubkey.isNotEmpty && label == shortPubkey(pubkey)) {
return pubkey[0].toUpperCase();
}
return label.isNotEmpty ? label[0].toUpperCase() : '?';
}
List<Channel> sortDmChannelsByDisplayLabel(
Iterable<Channel> channels, {
String? currentPubkey,
}) {
final sorted = channels.toList();
sorted.sort((left, right) {
final leftLabel = resolveDmChannelDisplayLabel(
left,
currentPubkey: currentPubkey,
);
final rightLabel = resolveDmChannelDisplayLabel(
right,
currentPubkey: currentPubkey,
);
final labelCompare = leftLabel.toLowerCase().compareTo(
rightLabel.toLowerCase(),
);
if (labelCompare != 0) return labelCompare;
return left.id.compareTo(right.id);
});
return sorted;
}