Files
buzz/mobile/test/features/channels/dm_open_latency_test.dart
morgmart 10dd70f152 feat(mobile): add people and agents to a DM (#9153)
## Summary

Mobile part of growable DMs. A DM's details page now has an **Add**
action where channels show Edit.

- Adding only agents joins them to this DM with its history. No question
is asked, matching desktop.
- Adding a person asks first. **Include history** adds them to this DM
with its earlier messages. **Start a new DM** opens a DM of the people,
without the agents or history, and the app moves to it. If that DM
already exists, the relay returns it.
- In a DM of just you and your agents, adding a person skips the
question and opens a DM of you and that person. The relay enforces this
too.
- Both choices send kind 41011. Only Include history carries the
`["history","include"]` tag, per the relay's opt-in rule in #9125.
Without the tag, the relay forks.
- iOS shows a native alert. Android uses the standard adaptive dialog.
- The relay's moderation DM shows no Add, recognized by the relay's
NIP-11 signer key. The relay refuses adds there anyway.
- Leave stays as it is. #9125 lets the relay accept a member's own leave
from a DM.

The question is asked before the sheet shows its busy state, so
"Adding…" only appears after a choice.

### Related issue

Depends on #9125 (relay) and pairs with block/buzz-app#2670 (desktop).
Spec: Growable DMs.

### Testing

- New widget tests: agents join with history and no question; adding a
person to a DM of two or more people asks; adding a person to an
agent-only DM opens a new DM without asking; Include history keeps this
DM; Start a new DM sends no tag and opens the new DM; Cancel adds no one
and leaves Add enabled; a DM member sees Add (not Edit) on the details
page and it opens the add sheet; the moderation DM shows no Add.
- `flutter analyze` is clean. The DM sheet, details and confirmation
dialog tests pass on 90d9c56d8 (rebased on main). The iOS alert merged
with main's non-destructive confirm option. The 90d9c56d8 push skipped
the pre-push hook because `flutter analyze` fails on main itself
(`native_media_headers_test.dart` references an undefined
`videoPreviewFrameLoaderProvider`, from #9144); the full channels suite
passed on 9421a7976, and the push hook runs the mobile checks.
- The screenshots below come from a temporary headless widget render
with test data. It is not committed. The iOS native alert can't render
headlessly, so the dialog shots show the Android dialog.

| | Light | Dark |
|---|---|---|
| Details, narrow | ![DM details light
narrow](https://github.com/user-attachments/assets/aae0c1af-752b-4a1e-b57f-da2546b5a096)
| ![DM details dark
narrow](https://github.com/user-attachments/assets/b5606c11-586a-46a7-b45c-69d4408a7549)
|
| Details, wide | ![DM details light
wide](https://github.com/user-attachments/assets/8ad307d0-aa7c-4015-a05c-c73d2e83e92b)
| ![DM details dark
wide](https://github.com/user-attachments/assets/c76fc6c7-8cef-45a6-af74-c18f1815ba82)
|
| Choice, narrow | ![History choice light
narrow](https://github.com/user-attachments/assets/f62e4386-98d4-412c-8dab-80409dbdce0d)
| ![History choice dark
narrow](https://github.com/user-attachments/assets/7c7ec457-df04-468f-bfa3-d708c592c749)
|
| Choice, wide | ![History choice light
wide](https://github.com/user-attachments/assets/16a88fd3-f57f-4295-92c0-9f8f1a94e85e)
| ![History choice dark
wide](https://github.com/user-attachments/assets/ba50e718-956a-4d9f-bff1-8f836e95a491)
|

Not yet done: a human test on a device against a relay running #9125.

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

---------

Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Carl <c217fe6b9d958f41c3a5e030dccc7f626775a923089cb6491305eade75ea1f1b@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-22 21:07:55 -08:00

275 lines
8.1 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:buzz/features/channels/channel_management_provider.dart';
import 'package:buzz/features/channels/channels_provider.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;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test(
'opening a DM finishes while the full channel list is stalled',
() async {
final keys = nostr.Keys.generate();
final session = _DmSession(keys.public);
final container = ProviderContainer(
retry: (_, _) => null,
overrides: [
relaySessionProvider.overrideWith(() => session),
myPubkeyProvider.overrideWithValue(keys.public),
],
);
addTearDown(container.dispose);
container.listen(channelsProvider, (_, _) {});
await session.listStarted.future;
var valid = true;
final actions = container.read(
Provider(
(ref) => ChannelActions(
ref: ref,
session: session,
signedEventRelay: SignedEventRelay(
session: session,
nsec: keys.nsec,
),
currentPubkey: keys.public,
isCommunityValid: () => valid,
),
),
);
final opened = await actions
.openDm(pubkeys: [_peer], waitForChannelList: false)
.timeout(const Duration(seconds: 2));
expect(opened.id, _dmId);
expect(opened.isDm, isTrue);
expect(opened.isMember, isTrue);
expect(opened.participantPubkeys, [keys.public, _peer]);
expect(session.published.single.kind, 41010);
expect(session.published.single.tags, [
['p', _peer],
]);
// Composers find it before the list has it, so sends there can check
// mentions and address the DM.
expect(
container.read(channelsProvider.notifier).channelById(_dmId)?.id,
_dmId,
);
// The sidebar still reconciles, in the background, once the stalled
// initial load settles.
session.stalledList.complete(const []);
await pumpEventQueue();
expect(session.listLoads, 2);
session.stalledList = Completer();
// New Message asks the relay for the DM these people share, which
// named agents join with its history, and opens the DM it returns.
expect(
(await actions.openDm(
pubkeys: [_peer],
waitForChannelList: false,
includeHistory: true,
)).id,
_dmId,
);
expect(session.published.last.kind, 41010);
expect(session.published.last.tags, [
['p', _peer],
['history', 'include'],
]);
// The relay lets only people share a DM's history, so an agent signed
// in here has the tagged open refused and opens the DM without it.
session.refusal = "forbidden: only people can share a DM's history";
expect(
(await actions.openDm(
pubkeys: [_peer],
waitForChannelList: false,
includeHistory: true,
)).id,
_dmId,
);
expect(session.published.last.kind, 41010);
expect(session.published.last.tags, [
['p', _peer],
]);
// A DM the relay confirms but the caller cannot read fails visibly.
session.member = false;
await expectLater(
actions.openDm(pubkeys: [_peer], waitForChannelList: false),
throwsStateError,
);
// A reopen whose unhide snapshot the relay failed to publish fails
// visibly instead of opening a DM the sidebar still hides.
session.member = true;
session.hidden = {_dmId};
await expectLater(
actions.openDm(pubkeys: [_peer], waitForChannelList: false),
throwsStateError,
);
expect(session.visibilityReads, greaterThan(0));
// A newly created DM cannot be in an older snapshot, so it skips that
// read and cannot fail on it after the relay created the DM.
session.created = true;
final reads = session.visibilityReads;
expect(
(await actions.openDm(pubkeys: [_peer], waitForChannelList: false)).id,
_dmId,
);
expect(session.visibilityReads, reads);
session.created = false;
session.hidden = {};
// Hidden-DM resurfacing keeps waiting for the list that clears its
// hidden state, so it cannot outrun its own retry coalescing.
session.member = true;
var resurfaced = false;
unawaited(
actions.openDm(pubkeys: [_peer]).then((_) => resurfaced = true),
);
await pumpEventQueue();
expect(resurfaced, isFalse);
// A community switch during the targeted read cancels the open.
session.onRead = () => valid = false;
await expectLater(
actions.openDm(pubkeys: [_peer], waitForChannelList: false),
throwsStateError,
);
},
);
}
const _dmId = 'dm-id';
const _peer =
'1111111111111111111111111111111111111111111111111111111111111111';
class _DmSession extends RelaySessionNotifier {
_DmSession(this.self);
final String self;
bool member = true;
Set<String> hidden = {};
bool created = false;
int visibilityReads = 0;
void Function()? onRead;
final published = <NostrEvent>[];
String? refusal;
Completer<List<NostrEvent>> stalledList = Completer();
final listStarted = Completer<void>();
int listLoads = 0;
@override
SessionState build() => const SessionState(status: SessionStatus.connected);
@override
Future<List<NostrEvent>> queryRelay(
List<NostrFilter> filters, {
Duration timeout = const Duration(seconds: 8),
}) async {
// Every full channel-list load starts with this membership query.
expect(filters.single.tags, {
'#p': [self],
});
listLoads++;
if (!listStarted.isCompleted) listStarted.complete();
return stalledList.future;
}
@override
Future<NostrEvent> publish(
NostrEvent event, {
Duration timeout = const Duration(seconds: 8),
Future<bool> Function()? mayPublish,
}) async {
published.add(event);
final refused = refusal;
if (refused != null && event.tags.any((tag) => tag[0] == 'history')) {
refusal = null;
throw Exception(refused);
}
return NostrEvent(
id: event.id,
pubkey: event.pubkey,
createdAt: event.createdAt,
kind: event.kind,
tags: event.tags,
content:
'response:${jsonEncode({'channel_id': _dmId, 'created': created})}',
sig: event.sig,
);
}
@override
Future<List<NostrEvent>> fetchHistory(
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) async {
if (filter.kinds.single == EventKind.dmVisibility) {
visibilityReads++;
expect(filter.tags, {
'#p': [self],
});
return [
NostrEvent(
id: 'visibility',
pubkey: 'relay',
createdAt: 1,
kind: EventKind.dmVisibility,
tags: [
['p', self],
for (final id in hidden) ['h', id],
],
content: '',
sig: '',
),
];
}
expect(filter.tags, {
'#d': [_dmId],
});
onRead?.call();
// Serve like a relay: newest first, one limit across every kind. A stale
// metadata revision from before the d_tag backfill still lingers.
final events = [
_event(39000, 3, [
['name', 'DM'],
['t', 'dm'],
['private'],
['hidden'],
['p', self],
['p', _peer],
]),
_event(39000, 2, [
['name', 'DM'],
['t', 'dm'],
['private'],
]),
_event(39002, 1, [
if (member) ['p', self, '', 'member'],
['p', _peer, '', 'member'],
]),
].where((e) => filter.kinds.contains(e.kind)).toList();
return events.take(filter.limit).toList();
}
}
NostrEvent _event(int kind, int createdAt, List<List<String>> tags) =>
NostrEvent(
id: '$kind-$createdAt',
pubkey: 'relay',
createdAt: createdAt,
kind: kind,
tags: [
['d', _dmId],
...tags,
],
content: '',
sig: '',
);