Files
buzz/mobile/test/shared/profile/user_cache_provider_test.dart
Tom Brow 52cbc61131 fix(mobile): name identity-link mention pills from their key (#9841)
Follow-up to [#9699 mention
typing](https://github.com/block/buzz/pull/9699), fixing two identity
problems found in its review.

**Identity-link pills name the key they open.** An edit writes each
mention as an identity link, `[@Name](nostr:npub1…)`, and every message
from any client draws such a link as a pill. Mobile showed the label
written in the link, so `[@Wes](nostr:<mallory>)` drew an ordinary
`@Wes` pill that opened Mallory's profile, and two namesakes in an
edited message both read `Scout`. The pill now shows the name its key
resolves to in the channel (with the namesake qualifier and agent icon),
as buzz-app's `ProfileMention` already does. The written label shows
only when the key has no name on this device (no profile, directory or
roster name), never a compact npub in its place. This holds whether or
not the link's key is also tagged. A pill requests its key's profile
when uncached, so a written label gives way to the key's name once it
loads.

Edits carry no `p` tag, so an identity-link pill resolves its own key.
In channel, thread and forum rows the pill watches that one key's
channel label (with the namesake qualifier and agent icon) and requests
the key's profile when it builds, so only links that actually draw a
pill cost a lookup, whatever Markdown surrounds them. Inbox and search
previews draw identity links the same way, taking keys from the preview
pieces they render. These keys never feed the text bindings, so plain
`@Name` text still binds only through signed tags.

**Typed names group the way the text scan reads them.** The composer
grouped the roster by `toLowerCase` while the scan folds names with
`foldMentionLabel`. With members `Sam` and `ſam`, typing `@ſam` sent
Sam's `p` tag. Grouping, lookup and the send-time key qualifier now all
fold, so namesakes under folding fail as ambiguous, as other namesakes
already do.

**Linked lookups stay current and bounded.** Pills and preview rows
request their keys through the profile cache's revalidation path. A name
restored from the last launch is revalidated, so a renamed key's link
shows its current name. A lookup that fails while offline is retried
once the relay reconnects, including when the reconnect comes while that
lookup is still on the wire. A key the relay says has no profile is not
asked for again for five minutes, and the cache remembers at most 1,000
such keys per community. Previews keep tilde and quoted code fences
literal and read blockquotes as the full message does, and load only the
links on lines they draw. Editing a message folds historical names the
way the scan does, so a name two tagged people share under folding seeds
no chip. Rendering binds signed names by the same fold, so with signed
`Sam` and `ſam` a plain `@Sam` stays text instead of drawing Sam's pill.

Desktop (buzz-app) already names identity-link chips from the key and
needs no change.

### Validation

Rows add no per-message work: message bodies are no longer scanned for
links. Each drawn identity-link pill adds one label watch for its own
key.

Added tests:
- [Channel page journey
step](mobile/test/features/channels/channel_detail_page_test.dart): an
edited message linking `[@Wes]` to Mallory's key draws `Mallory`, and
two edited `Scout` namesakes draw distinct qualified labels, through the
real channel row.
- [Channel page journey
step](mobile/test/features/channels/channel_detail_page_test.dart): a
link to a key with no name here keeps its written label.
- [Preview identity
link](mobile/test/features/channels/message_content/preview_text_test.dart):
an inbox/search preview shows the key's resolved name, or the written
label when unknown.
- [Preview
keys](mobile/test/features/channels/message_content/preview_text_test.dart):
a preview loads only links it draws (not ones in code or past its line
limit), including labels with brackets.

Full-app run (iOS simulator, debug build, signed in to a test
community): posted a message with a spoofed identity link, a link to a
key with no profile here, and a link inside inline code. The spoofed
link drew the key's real name as a pill and opened that person's
profile; the unknown key kept its written label; the code span stayed
raw. The same message drew matching pills in search results and in the
thread view.
- [Channel row
loads](mobile/test/features/channels/channel_detail_page_test.dart): a
row requests profiles only for links it draws as pills, not ones in a
quoted code fence or an HTML comment.
- [Folded chip
qualifiers](mobile/test/features/channels/compose_bar_test/exact_mention_tests.dart):
picked `@Sam` and `@ſam` chips both carry their keys on send.
- [Ambiguous typed names
table](mobile/test/features/channels/compose_bar_test/exact_mention_tests.dart):
`Sam` and `ſam` in either roster order now refuse `@ſam` as ambiguous.

- [Restart and reconnect
journey](mobile/test/features/channels/channel_detail_page_test.dart): a
restored old name and an offline first lookup both resolve after the
relay reconnects, on the same mounted pills, and a key with no profile
is not requested again.
- [Preview
fences](mobile/test/features/channels/message_content/preview_text_test.dart):
tilde and quoted fences keep links and Markdown literal and load no
keys.
- [Overtaken
lookup](mobile/test/shared/profile/user_cache_provider_test.dart): a
reconnect during a link's failing lookup asks once more after it
settles.
- [Folded signed
names](mobile/test/features/channels/message_content_exact_mentions_test.dart):
signed `Sam` and `ſam` in either tag order leave `@Sam` as text in the
message and its preview.
- [Folded edit
chips](mobile/test/features/channels/message_edit_sheet_test.dart):
`Sam` and `ſam` tagged in either order open as text, with no chip.
- [Non-member
labels](mobile/test/shared/identity_names/identity_names_test.dart): a
non-member labels the same with or without the roster shortcut,
including names shaped like qualifiers.

### Regressions

- **Performance:** rows do no new scanning; each drawn identity-link
pill adds one label watch. A non-member whose name can't collide no
longer re-resolves the whole roster.
- **Mention semantics:** unchanged for tagged mentions and plain text.
Only identity-link pills change, from the written label to the key's
resolved name.
- **Composer:** names that differ only under Unicode folding (`ſ`/`s`,
`µ`/`μ`, final `ς`/`σ`) are now one name when matching typed text, so a
typed one between two such members asks for a pick instead of silently
choosing one. Picked chips are unaffected.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz>
2026-11-20 17:21:54 -08:00

630 lines
21 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:buzz/shared/profile/user_cache_provider.dart';
import 'package:buzz/shared/profile/profile_event_parser.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:pointycastle/digests/sha256.dart';
void main() {
test('preload reports a profile batch failure', () async {
final container = ProviderContainer(
overrides: [
relaySessionProvider.overrideWith(_FailingProfileSession.new),
],
);
addTearDown(container.dispose);
final succeeded = await container.read(userCacheProvider.notifier).preload(
const ['agent'],
);
expect(succeeded, isFalse);
});
test('refresh queries profiles that are already cached', () async {
final session = _RecordingProfileSession();
final container = ProviderContainer(
overrides: [relaySessionProvider.overrideWith(() => session)],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
cache.cacheProfileEvent(
_profileEvent(id: 'cached-profile', createdAt: 1, name: 'Cached Human'),
);
final succeeded = await cache.refresh(const ['AGENT']);
expect(succeeded, isTrue);
expect(session.requestedFilter?.kinds, const [0]);
expect(session.requestedFilter?.authors, const ['agent']);
expect(session.requestedFilter?.limit, 1);
});
test('older refresh cannot overwrite a newer live profile', () async {
final refreshCompleter = Completer<List<NostrEvent>>();
final session = _RecordingProfileSession(result: refreshCompleter.future);
final container = ProviderContainer(
overrides: [relaySessionProvider.overrideWith(() => session)],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
final owner = nostr.Keys.generate();
final agent = nostr.Keys.generate();
final refresh = cache.refresh([agent.public]);
cache.cacheProfileEvent(
_profileEvent(
id: 'newer-agent',
pubkey: agent.public,
createdAt: 2,
name: 'Agent',
tags: [_authTag(owner, agent.public)],
),
);
refreshCompleter.complete([
_profileEvent(
id: 'older-human',
pubkey: agent.public,
createdAt: 1,
name: 'Human',
),
]);
expect(await refresh, isTrue);
expect(cache.state[agent.public]?.displayName, 'Agent');
expect(cache.state[agent.public]?.ownerPubkey, owner.public);
});
test('newer refresh can remove obsolete owner attribution', () async {
final owner = nostr.Keys.generate();
final agent = nostr.Keys.generate();
final session = _RecordingProfileSession(
result: Future.value([
_profileEvent(
id: 'newer-human',
pubkey: agent.public,
createdAt: 2,
name: 'Human',
),
]),
);
final container = ProviderContainer(
overrides: [relaySessionProvider.overrideWith(() => session)],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
cache.cacheProfileEvent(
_profileEvent(
id: 'older-agent',
pubkey: agent.public,
createdAt: 1,
name: 'Agent',
tags: [_authTag(owner, agent.public)],
),
);
expect(await cache.refresh([agent.public]), isTrue);
expect(cache.state[agent.public]?.displayName, 'Human');
expect(cache.state[agent.public]?.ownerPubkey, isNull);
});
test('non-profile history cannot poison profile order', () async {
final session = _RecordingProfileSession(
results: [
Future.value([
_profileEvent(
id: 'non-profile-newer',
createdAt: 3,
name: 'Ignored',
kind: 1,
),
]),
Future.value([
_profileEvent(id: 'valid-older', createdAt: 2, name: 'Valid'),
]),
],
);
final container = ProviderContainer(
overrides: [relaySessionProvider.overrideWith(() => session)],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
expect(await cache.refresh(const ['agent']), isTrue);
expect(cache.state['agent'], isNull);
expect(await cache.refresh(const ['agent']), isTrue);
expect(cache.state['agent']?.displayName, 'Valid');
});
for (final operation in ['refresh', 'preload', 'resolve']) {
test('$operation merges after parsing against newer live state', () async {
final started = Completer<void>();
final release = Completer<void>();
final session = _RecordingProfileSession(
result: Future.value([
_profileEvent(id: 'old', createdAt: 1, name: 'Old'),
]),
);
final container = ProviderContainer(
overrides: [
relaySessionProvider.overrideWith(() => session),
profileEventBatchParserProvider.overrideWithValue((events) async {
final parsed = await parseProfileEventBatch(events);
started.complete();
await release.future;
return parsed;
}),
],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
final result = switch (operation) {
'preload' => cache.preload(['agent']),
'resolve' => cache.resolve(['agent']).then((_) => true),
_ => cache.refresh(['agent']),
};
await started.future;
cache.cacheProfileEvent(
_profileEvent(id: 'new', createdAt: 2, name: 'Live'),
);
cache.cacheProfileEvent(
_profileEvent(
id: 'other',
pubkey: 'other',
createdAt: 1,
name: 'Other',
),
);
release.complete();
expect(await result, isTrue);
expect(cache.state['agent']?.displayName, 'Live');
expect(cache.state['other']?.displayName, 'Other');
});
test('$operation rejects a retired parsing completion', () async {
final started = Completer<void>();
final release = Completer<void>();
final session = _RecordingProfileSession(
result: Future.value([
_profileEvent(id: 'old', createdAt: 1, name: 'Previous community'),
]),
);
final container = ProviderContainer(
overrides: [
relaySessionProvider.overrideWith(() => session),
profileEventBatchParserProvider.overrideWithValue((events) async {
final parsed = await parseProfileEventBatch(events);
started.complete();
await release.future;
return parsed;
}),
],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
final result = switch (operation) {
'preload' => cache.preload(['agent']),
'resolve' => cache.resolve(['agent']).then((_) => true),
_ => cache.refresh(['agent']),
};
await started.future;
// This is the same dependency invalidation caused by community config.
container
.read(relayConfigProvider.notifier)
.update(baseUrl: 'https://next-community.invalid');
container.read(userCacheProvider);
release.complete();
if (operation == 'resolve') {
await expectLater(result, throwsStateError);
} else {
expect(await result, isFalse);
}
expect(container.read(userCacheProvider), isEmpty);
});
}
test(
'community change rejects an old network response before parsing',
() async {
final response = Completer<List<NostrEvent>>();
var parsed = false;
final container = ProviderContainer(
overrides: [
relaySessionProvider.overrideWith(
() => _RecordingProfileSession(result: response.future),
),
profileEventBatchParserProvider.overrideWithValue((events) async {
parsed = true;
return parseProfileEventBatch(events);
}),
],
);
addTearDown(container.dispose);
final result = container.read(userCacheProvider.notifier).refresh([
'agent',
]);
container
.read(relayConfigProvider.notifier)
.update(baseUrl: 'https://next-community.invalid');
container.read(userCacheProvider);
response.complete([_profileEvent(id: 'old', createdAt: 1, name: 'Old')]);
expect(await result, isFalse);
expect(parsed, isFalse);
expect(container.read(userCacheProvider), isEmpty);
},
);
test(
'parser failure reports refresh failure without modifying cache',
() async {
final container = ProviderContainer(
overrides: [
relaySessionProvider.overrideWith(
() => _RecordingProfileSession(
result: Future.value([
_profileEvent(id: 'next', createdAt: 2, name: 'Next'),
]),
),
),
profileEventBatchParserProvider.overrideWithValue(
(_) => Future.error(StateError('parse failed')),
),
],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
cache.cacheProfileEvent(
_profileEvent(id: 'cached', createdAt: 1, name: 'Cached'),
);
expect(await cache.refresh(['agent']), isFalse);
expect(cache.state['agent']?.displayName, 'Cached');
},
);
test('later refresh completion cannot roll back a newer refresh', () async {
final oldResponse = Completer<List<NostrEvent>>();
final session = _RecordingProfileSession(
results: [
oldResponse.future,
Future.value([_profileEvent(id: 'new', createdAt: 2, name: 'New')]),
],
);
final container = ProviderContainer(
overrides: [relaySessionProvider.overrideWith(() => session)],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
final old = cache.refresh(['agent']);
expect(await cache.refresh(['agent']), isTrue);
oldResponse.complete([_profileEvent(id: 'old', createdAt: 1, name: 'Old')]);
expect(await old, isTrue);
expect(cache.state['agent']?.displayName, 'New');
});
test('stale malformed profile is skipped before parsing', () async {
final container = ProviderContainer(
overrides: [
relaySessionProvider.overrideWith(
() => _RecordingProfileSession(
result: Future.value([
NostrEvent(
id: 'old',
pubkey: 'agent',
createdAt: 1,
kind: 0,
tags: [],
content: '{"name":42}',
sig: 'sig',
),
]),
),
),
],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
cache.cacheProfileEvent(
_profileEvent(id: 'new', createdAt: 2, name: 'New'),
);
expect(await cache.refresh(['agent']), isTrue);
expect(cache.state['agent']?.displayName, 'New');
});
test(
'refresh and preload share one verification worker and coalesce pending lookups',
() async {
final started = Completer<void>();
final release = Completer<void>();
var running = 0;
var maxRunning = 0;
var calls = 0;
final session = _RecordingProfileSession(
results: [
Future.value([
_profileEvent(id: 'a', pubkey: 'a', createdAt: 1, name: 'A'),
]),
Future.value([
_profileEvent(id: 'b', pubkey: 'b', createdAt: 1, name: 'B'),
]),
Future.value([
_profileEvent(id: 'c', pubkey: 'c', createdAt: 1, name: 'C'),
]),
],
);
final container = ProviderContainer(
overrides: [
relaySessionProvider.overrideWith(() => session),
profileEventBatchParserProvider.overrideWithValue((events) async {
running++;
if (running > maxRunning) maxRunning = running;
if (calls++ == 0) {
started.complete();
await release.future;
}
final parsed = await parseProfileEventBatch(events);
running--;
return parsed;
}),
],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
final first = cache.preload(['a']);
await started.future;
final refresh = cache.refresh(['b']);
final next = cache.preload(['c']);
final duplicate = cache.preload(['c']);
// Let the refresh reach the worker queue before releasing its predecessor.
await Future<void>.delayed(Duration.zero);
expect(calls, 1);
release.complete();
expect(
await Future.wait([first, refresh, next, duplicate]),
everyElement(isTrue),
);
expect(maxRunning, 1);
expect(calls, 3);
expect(session.requestCount, 3);
},
);
test('a preload never asks again for profiles already on the wire', () async {
final firstBatch = Completer<List<NostrEvent>>();
final session = _RecordingProfileSession(
results: [
firstBatch.future,
Future.value([
_profileEvent(id: 'c', pubkey: 'c', createdAt: 1, name: 'C'),
]),
],
);
final container = ProviderContainer(
overrides: [relaySessionProvider.overrideWith(() => session)],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
final first = cache.preload(['a', 'b']);
await session.firstRequest.future;
expect(session.requestCount, 1);
// b is on the wire; only c is new.
final again = cache.preload(['b']);
final more = cache.preload(['b', 'c']);
firstBatch.complete([
_profileEvent(id: 'a', pubkey: 'a', createdAt: 1, name: 'A'),
_profileEvent(id: 'b', pubkey: 'b', createdAt: 1, name: 'B'),
]);
expect(await Future.wait([first, again, more]), everyElement(isTrue));
expect(session.requestCount, 2);
expect(session.requestedFilter?.authors, ['c']);
expect(cache.state.keys, containsAll(['a', 'b', 'c']));
});
test('a link joining a pending preload is retried after reconnect', () async {
final firstBatch = Completer<List<NostrEvent>>();
final session = _RecordingProfileSession(
results: [
firstBatch.future,
Future.value([
_profileEvent(id: 'a', pubkey: 'a', createdAt: 1, name: 'A'),
]),
],
);
final container = ProviderContainer(
overrides: [relaySessionProvider.overrideWith(() => session)],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
final preload = cache.preload(['a']);
await session.firstRequest.future;
// The link shares the batch on the wire instead of asking again.
expect(cache.needsLinkedLookup('a'), isTrue);
cache.requestLinked(['a']);
expect(cache.needsLinkedLookup('a'), isFalse);
expect(session.requestCount, 1);
firstBatch.completeError('offline');
expect(await preload, isFalse);
session.setStatus(SessionStatus.disconnected);
session.setStatus(SessionStatus.connected);
// The retry rides the next coalesced batch.
await session.secondRequest.future;
expect(session.requestCount, 2);
expect(session.requestedFilter?.authors, ['a']);
expect(await cache.preload(['a']), isTrue);
expect(session.requestCount, 2);
expect(cache.state.keys, contains('a'));
});
test('a reconnect during a failing link lookup retries after it', () async {
final firstBatch = Completer<List<NostrEvent>>();
final session = _RecordingProfileSession(
results: [
firstBatch.future,
Future.value([
_profileEvent(id: 'a', pubkey: 'a', createdAt: 1, name: 'A'),
]),
],
);
final container = ProviderContainer(
overrides: [relaySessionProvider.overrideWith(() => session)],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
cache.requestLinked(['a']);
await session.firstRequest.future;
// The relay reconnects before the old request gives up.
session.setStatus(SessionStatus.reconnecting);
session.setStatus(SessionStatus.connected);
expect(session.requestCount, 1);
firstBatch.completeError('socket replaced');
await session.secondRequest.future;
expect(session.requestCount, 2);
expect(session.requestedFilter?.authors, ['a']);
expect(await cache.preload(['a']), isTrue);
expect(cache.state.keys, contains('a'));
});
test(
'refresh verifies real OA batch while allowing main-isolate timers',
() async {
final owner = nostr.Keys.generate();
final agents = List.generate(16, (_) => nostr.Keys.generate());
final events = [
for (final agent in agents)
_profileEvent(
id: agent.public,
pubkey: agent.public,
createdAt: 1,
name: 'Synthetic',
tags: [_authTag(owner, agent.public)],
),
];
var timerRanBeforeParsingCompleted = false;
final container = ProviderContainer(
overrides: [
relaySessionProvider.overrideWith(
() => _RecordingProfileSession(result: Future.value(events)),
),
profileEventBatchParserProvider.overrideWithValue((events) async {
var timerRan = false;
final timer = Timer(Duration.zero, () => timerRan = true);
final parsed = await parseProfileEventBatch(events);
timerRanBeforeParsingCompleted = timerRan;
timer.cancel();
return parsed;
}),
],
);
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
expect(await cache.refresh(agents.map((a) => a.public).toList()), isTrue);
expect(timerRanBeforeParsingCompleted, isTrue);
for (final agent in agents) {
expect(cache.state[agent.public]?.ownerPubkey, owner.public);
}
},
);
test('same-second profile tie keeps the lowest event id', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final cache = container.read(userCacheProvider.notifier);
cache.cacheProfileEvent(
_profileEvent(id: 'b', createdAt: 1, name: 'Larger ID'),
);
cache.cacheProfileEvent(
_profileEvent(id: 'a', createdAt: 1, name: 'Lower ID'),
);
cache.cacheProfileEvent(
_profileEvent(id: 'c', createdAt: 1, name: 'Later Larger ID'),
);
expect(cache.state['agent']?.displayName, 'Lower ID');
});
}
NostrEvent _profileEvent({
required String id,
required int createdAt,
required String name,
String pubkey = 'agent',
List<List<String>> tags = const [],
int kind = 0,
}) => NostrEvent(
id: id,
pubkey: pubkey,
createdAt: createdAt,
kind: kind,
tags: tags,
content: jsonEncode({'name': name}),
sig: 'sig',
);
List<String> _authTag(nostr.Keys owner, String agentPubkey) {
final digest = SHA256Digest().process(
Uint8List.fromList(
utf8.encode('nostr:agent-auth:${agentPubkey.toLowerCase()}:'),
),
);
final message = digest
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
.join();
final signature = nostr.Schnorr.sign(
secretKey: owner.secret,
message: message,
);
return ['auth', owner.public, '', signature];
}
class _RecordingProfileSession extends RelaySessionNotifier {
_RecordingProfileSession({
Future<List<NostrEvent>>? result,
List<Future<List<NostrEvent>>>? results,
}) : _results = [...?results, ?result];
final List<Future<List<NostrEvent>>> _results;
NostrFilter? requestedFilter;
int requestCount = 0;
final firstRequest = Completer<void>();
final secondRequest = Completer<void>();
@override
SessionState build() => const SessionState(status: SessionStatus.connected);
@override
Future<List<NostrEvent>> fetchHistory(
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) async {
requestCount++;
requestedFilter = filter;
if (!firstRequest.isCompleted) firstRequest.complete();
if (requestCount == 2) secondRequest.complete();
return _results.isEmpty ? const [] : _results.removeAt(0);
}
void setStatus(SessionStatus status) => state = SessionState(status: status);
}
class _FailingProfileSession extends RelaySessionNotifier {
@override
SessionState build() => const SessionState(status: SessionStatus.connected);
@override
Future<List<NostrEvent>> fetchHistory(
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) => Future.error('profile unavailable');
}