Files
buzz/mobile/test/features/channels/sidebar_sync_fixture.dart
Wes 4079793f99 Match desktop unread cues on mobile channel rows (#9715)
## Summary

- Honor the synced `seen:<channel>` timestamp in mobile row styling and
the **Unreads** filter. Attention keeps its dot regardless of timestamp,
and the row's mark-read menu uses the underlying unread state.
- Hide the dot when the row shows a mute the relay has confirmed.
Confirmation survives reconnects within the same account and relay. The
row still exposes unread attention to screen readers. Unmuting on the
phone restores any dot supported by retained unread evidence as soon as
the bell disappears.
- Apply the same `seen:<channel>` timestamp to the app icon badge's
ordinary backlog count. Mentions and thread replies keep counting.
Includes #9721.

This reuses the existing read-state and mute sync. Pending mutes keep
the dot visible, and the patch adds no relay requests or read-state
writes.

### Related issue

No matching issue or open PR found. Earlier mobile sidebar unread parity
work is in #1303.

## Testing

- `just mobile-install mobile-check mobile-test`
- Widget coverage for backlog at and after the desktop cut, mentions on
either side of it, the **Unreads** filter, the mark-read menu, pending
and confirmed mute, and unmute while the relay still reports muted.
- Scripted relay coverage for mute confirmation across reconnects,
delayed and older responses, newer confirmations, and relay switches.
Read-state tests cover reading a peer's `seen:` context during an
ordinary mobile publish.
- Badge provider tests cover backlog at and after the cut, plus mentions
and thread replies older than the cut.

### Test on a phone with desktop alongside

1. Check out the PR. To install a local debug build, run
`./scripts/mobile-worktree-overrides.sh` from the repo root, then run
`flutter devices` and `flutter run -d <device-id>` from `mobile/` with
Hermit active. Use the device signing setup if needed for a physical
iPhone. Sign in to the same account and community on both clients. Use
an already initialized mobile account and leave the phone on the channel
list. [Device signing
setup](https://github.com/block/buzz/tree/main/mobile#ios-push-capability)
2. Have a second account post an ordinary message in a test channel.
Wait for its row to become bold on both clients. On desktop, open that
channel and switch away quickly, before the 300 ms reading dwell. After
sync, the phone row should lose bold. In the phone's section menu,
choose **Filter…**, select **Unreads**, and tap **Apply**. The row
should disappear. Use **Show hidden channels** and long-press the row to
verify that **Mark Read** is still available. Dismiss the menu, tap
**Hide filtered channels**, and have the second account send a newer
ordinary message. The row should appear bold again.
3. For a mention older than the cut, have the second account @mention
you in a different test channel before making the quick desktop visit.
After leaving the channel on desktop, the phone should still show its
attention dot. For a newer mention, do the quick desktop visit after an
ordinary post in a separate channel, wait for its phone row to quiet,
then send the @mention. Its phone row should gain a dot.
4. With the mention still unread, mute that channel on desktop. When the
phone shows the muted bell, verify that the attention dot disappears.
Turn off the phone's network connection, return to the channel list,
then reconnect. The dot should stay hidden throughout. On the phone,
long-press the row and choose **Unmute channel**. The dot should return
as soon as the bell disappears. Keep the phone on the channel list
throughout so it does not read the mention.
5. On a phone with app badges enabled, repeat the ordinary-message case
in step 2 with that message as the only unread item. After the phone
syncs the desktop visit, the app icon badge should clear. A newer
ordinary message should bring it back.

Device and desktop testing is pending.

### Before and after

Before and after captures from the Flutter channel list widget with
synthetic rows. The ordinary `desktop-seen` row loses bold, the
confirmed-muted mention loses its dot, and the unread control stays
bold.

| Theme | Before | After |
| --- | --- | --- |
| Light |
![before-light](https://raw.githubusercontent.com/block/buzz/fb3600cdb1017ef29df54305e598132c16acbf1e/pr-9715--before-light.png)
|
![after-light](https://raw.githubusercontent.com/block/buzz/fb3600cdb1017ef29df54305e598132c16acbf1e/pr-9715--after-light.png)
|
| Dark |
![before-dark](https://raw.githubusercontent.com/block/buzz/fb3600cdb1017ef29df54305e598132c16acbf1e/pr-9715--before-dark.png)
|
![after-dark](https://raw.githubusercontent.com/block/buzz/fb3600cdb1017ef29df54305e598132c16acbf1e/pr-9715--after-dark.png)
|

---------

Signed-off-by: Wes <wesb@block.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
2026-11-19 12:21:34 -07:00

290 lines
8.8 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:buzz/shared/crypto/nip44.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/relay/read_state_snapshot.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:shared_preferences/shared_preferences.dart';
/// A scripted relay behind the real [RelaySessionNotifier], so REQ/EOSE,
/// CLOSED classification, event batching and OK all run production code.
/// Retains replaceable heads the way the relay does: `created_at DESC, id ASC`.
class SidebarRelay {
SidebarRelay() {
session.debugAttachSocketForTest(_ScriptedSocket(_onSend));
}
final keys = nostr.Keys.generate();
late final session = ConnectedRelaySession(
httpClient: MockClient(_handleHttp),
);
late final signer = SignedEventRelay(session: session, nsec: keys.nsec);
final _storedByRelay = <String?, List<NostrEvent>>{};
/// Heads retained by the relay [session] currently serves, so a community
/// switch reaches a different relay's store.
List<NostrEvent> get stored =>
_storedByRelay.putIfAbsent(session.relayUrl, () => <NostrEvent>[]);
final published = <NostrEvent>[];
/// The relay [session] served when each [published] event was sent.
final publishedTo = <String?>[];
final reqs = <List<dynamic>>[];
final snapshotHosts = <String>[];
final _liveSubIds = <String?, String>{};
int historyFailures = 0;
Completer<void>? holdHistory;
Completer<void>? holdOk;
String? rejectLive;
bool withholdEose = false;
String get pubkey => keys.public;
NostrEvent event(
String dTag,
Object payload,
int createdAt, {
String? id,
List<List<String>> tags = const [],
}) {
// Snapshot transport verifies signatures; do not substitute a decoder.
if (id == null) {
return NostrEvent.fromJson(
nostr.Event.from(
kind: EventKind.readState,
tags: [
['d', dTag],
...tags,
],
content: nip44Encrypt(_key, jsonEncode(payload)),
createdAt: createdAt,
secretKey: keys.secret,
).toMap(),
);
}
return NostrEvent(
id: id,
pubkey: pubkey,
createdAt: createdAt,
kind: EventKind.readState,
tags: [
['d', dTag],
...tags,
],
content: nip44Encrypt(_key, jsonEncode(payload)),
sig: 'sig',
);
}
Object? decrypt(NostrEvent event) =>
jsonDecode(nip44Decrypt(_key, event.content));
late final _key = getConversationKey(
nostr.Nip19.decode(payload: keys.nsec).data,
keys.public,
);
List<List<dynamic>> reqsFor(String dTag, String prefix) => [
for (final req in reqs)
if ((req[1] as String).startsWith(prefix) && _dTagOf(req) == dTag) req,
];
/// Delivers [event] on the live subscription for its `d` tag, or else on
/// the one filtered by `#t` alone.
void emit(NostrEvent event) => session.debugHandleMessage([
'EVENT',
_liveSubIds[event.getTagValue('d')] ?? _liveSubIds[null],
event.toJson(),
]);
void closeLive(String dTag, String message) =>
session.debugHandleMessage(['CLOSED', _liveSubIds[dTag], message]);
void _onSend(List<dynamic> message) {
if (message.first == 'EVENT') {
final event = NostrEvent.fromJson(message[1] as Map<String, dynamic>);
published.add(event);
publishedTo.add(session.relayUrl);
stored.add(event);
final ok = ['OK', event.id, true, ''];
final hold = holdOk;
hold == null
? scheduleMicrotask(() => _reply(ok))
: hold.future.then((_) => _reply(ok));
}
if (message.first != 'REQ') return;
reqs.add(message);
final subId = message[1] as String;
if (subId.startsWith('h-')) {
unawaited(_answerHistory(subId, _dTagOf(message)));
return;
}
_liveSubIds[_dTagOf(message)] = subId;
final rejection = rejectLive;
if (rejection == null && withholdEose) return;
scheduleMicrotask(
() => _reply(
rejection == null ? ['EOSE', subId] : ['CLOSED', subId, rejection],
),
);
}
Future<void> _answerHistory(String subId, String? dTag) async {
await holdHistory?.future;
if (historyFailures > 0) {
historyFailures--;
return _reply(['CLOSED', subId, 'error: overloaded']);
}
// A `#t` filter reaches every slot it tags; a `#d` filter, one head.
if (dTag == null) {
for (final e in stored.where((e) => e.getTagValue('t') != null)) {
_reply(['EVENT', subId, e.toJson()]);
}
return _reply(['EOSE', subId]);
}
final heads = stored.where((e) => e.getTagValue('d') == dTag).toList()
..sort(
(a, b) => a.createdAt != b.createdAt
? b.createdAt.compareTo(a.createdAt)
: a.id.compareTo(b.id),
);
if (heads.isNotEmpty) _reply(['EVENT', subId, heads.first.toJson()]);
_reply(['EOSE', subId]);
}
Future<http.Response> _handleHttp(http.Request request) async {
// Bind discovery to the requested host, not whichever community is active
// when a held request completes.
final community = request.url.host == 'second.example'
? 'bbbbbbbb-eeee-abcd-abcd-abcdefabcdef'
: 'aaaaaaaa-eeee-abcd-abcd-abcdefabcdef';
if (request.method == 'GET' && request.url.path == '/') {
return http.Response(
jsonEncode({
'read_state_snapshot': {'version': 1, 'community_id': community},
}),
200,
);
}
expect(request.method, 'POST');
expect(request.url.path, '/query');
expect(request.headers['Authorization'], isNotNull);
expect(jsonDecode(request.body), [
{
'kinds': [30078],
'authors': [pubkey],
'read_state_snapshot': 1,
},
]);
snapshotHosts.add(request.url.host);
final source = _storedByRelay.putIfAbsent(
request.url.origin,
() => <NostrEvent>[],
);
await holdHistory?.future;
if (historyFailures > 0) {
historyFailures--;
return http.Response('error: overloaded', 503);
}
final heads = <String, NostrEvent>{};
final own =
source.where((e) => e.kind == 30078 && e.pubkey == pubkey).toList()
..sort(
(a, b) => a.createdAt != b.createdAt
? b.createdAt.compareTo(a.createdAt)
: a.id.compareTo(b.id),
);
for (final event in own) {
heads.putIfAbsent(event.getTagValue('d') ?? '', () => event);
}
return http.Response(
jsonEncode({
'read_state_snapshot': 1,
'complete': true,
'community_id': community,
'pubkey': pubkey,
'snapshot_id': 'a' * 64,
'events': [for (final e in heads.values) e.toJson()],
}),
200,
);
}
void _reply(List<dynamic> message) => session.debugHandleMessage(message);
/// Null for a filter by `#t` alone, such as read state's slot discovery.
static String? _dTagOf(List<dynamic> req) =>
((req[2] as Map<String, dynamic>)['#d'] as List?)?.single as String?;
}
class ConnectedRelaySession extends RelaySessionNotifier {
ConnectedRelaySession({super.httpClient})
: super(snapshotDecoder: (input) async => validateReadStateSnapshot(input));
void setStatus(SessionStatus status) => state = SessionState(status: status);
@override
SessionState build() {
// Follows the active community, as the production session does.
debugRelayUrl = ref.watch(relayConfigProvider).baseUrl;
return const SessionState(status: SessionStatus.connected);
}
}
class _ScriptedSocket extends RelaySocket {
_ScriptedSocket(this._send)
: super(
wsUrl: 'wss://relay.example',
nsec: null,
onMessage: (_) {},
onConnected: () {},
onDisconnected: (_) {},
);
final void Function(List<dynamic>) _send;
@override
void send(List<dynamic> payload) => _send(payload);
@override
void dispose() {}
}
/// Preferences whose next [failures] writes return false or throw [error].
class FlakyPrefs extends Fake implements SharedPreferences {
FlakyPrefs(this._inner);
final SharedPreferences _inner;
int failures = 0;
Object? error;
@override
String? getString(String key) => _inner.getString(key);
@override
Future<bool> remove(String key) => _inner.remove(key);
@override
Future<bool> setString(String key, String value) async {
if (failures == 0) return _inner.setString(key, value);
failures--;
if (error == null) return false;
throw error!;
}
}
Future<SharedPreferences> freshPrefs() async {
SharedPreferences.setMockInitialValues({});
return SharedPreferences.getInstance();
}
int nowSeconds() => DateTime.now().millisecondsSinceEpoch ~/ 1000;
void fakeAsyncTest(String name, void Function(FakeAsync clock) body) =>
test(name, () => fakeAsync(body));