mirror of
https://github.com/block/buzz.git
synced 2026-11-26 03:01:38 +00:00
Mobile Home now reads desktop's unified sidebar from block/buzz-app#3791 and shows the same workspaces, filings, icons and section order as the desktop sidebar. It is read-only while a unified record exists. ## What changed - **Reads desktop's records.** Mobile reads `channel-workspaces` and `channel-workspace-sort`. Until the unified record exists, it falls back to the legacy `channel-sections` and Solo groups, merging them the way desktop imports them (`expandWorkspaceRecord`, `importWorkspaceFallback`, `mergeLegacyWorkspaces`). Sort follows desktop's `meta.g` registers. - **Layout.** Sections are Starred, then the workspaces, Team, Solo and Direct messages, in desktop's `sectionOrder`. A workspace holds Team channels and Solo chats alike, and shows its icon: Unicode emoji as text, `:shortcode:` as the community's custom emoji, and nothing for an unknown shortcode. - **Read-only lock.** While a unified record exists, mobile hides rename, delete, move, New project and sort edits, and never publishes the legacy records desktop would ignore. That includes: - an edit queued before the lock; - a unified head arriving during a relay rate-limit wait (`mayPublish`); - a Team publish whose preflight read failed; - a New project or workspace pick opened before the lock (the chat is still created, without the filing). - **Recovery.** A foreground refresh with a pending legacy sort still applies a missed unified head. - **No All/Solo/Team filter.** Desktop removed its tabs in #3791, since workspaces now hold Solo and team chats together, so Home drops its chips too. The Messages header keeps its title and actions and no longer collapses on scroll. - **Filters.** The Unreads filter uses Solo's own unread state for Solo rows. - **NIP-44.** Decryption accepts the extended length prefix for payloads over 65535 bytes. A nostr-tools vector is included. ## Tests - `workspace_layout_interop_test.dart`: a table generated by running desktop's TypeScript from buzz-app `main` (11 layouts and 10 invalid records). It checks that mobile computes the same sections, assignments and order. - `sidebar_workspaces_journey_test.dart`: Home runs on the real sections and sort notifiers over the relay fixture. It starts on legacy sections, receives desktop's signed heads live, then checks the order, filings, icon, read-only sheet and Unreads. It also checks that only the filter choice is published. - `unified_sidebar_records_test.dart`: Team and sort publish nothing once a unified head is seen: before an edit, while one waits, or past a failed preflight. - `project_creation_test.dart`: the unified layout arrives while a workspace is being named. Nothing is written, and nothing is left to resume. - `solo_creation_tags_test.dart` and `me_sync_test.dart`: a project picked or a filing queued before the lock doesn't stop a new Solo chat from being created. Each new guard was mutation-checked: removing it fails its test. `flutter analyze` is clean and `flutter test` passes (5450). ## Not in this PR (open questions) - **Forums** stay hidden on Home, as before. Desktop shows them, so a forum filed into a workspace or starred on desktop doesn't appear on mobile. Should mobile add a Forums section? - **Filters** still use the legacy `channel-filter` record. Desktop prefers `channel-workspace-filter`. - **Solo creation without a unified record** still writes the legacy Solo groups, as before. - **Empty workspaces** are shown, as on desktop. Mobile rejects a unified record that carries `meta` without `filings`; desktop never writes that shape. - Built-in titles now match desktop: "Team" (was "Channels") and "Direct messages" (was "DMs"). ## How to test 1. On desktop (buzz-app with #3791), create two workspaces, give one an emoji icon, and file a Team channel and a Solo chat into it. Reorder the sections. 2. Open mobile Home in the same community. The sections, order, icon and filings should match desktop. 3. Open a workspace's options. You should see only Sort (disabled) and Show. Long-press a channel: there's no "Move to section…". 4. There is no All/Solo/Team filter row under the Messages title. 5. Change the order on desktop. Mobile should follow live, or after you foreground the app. Screenshots are in the comment below. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Wes <wesbillman@users.noreply.github.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@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: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
366 lines
11 KiB
Dart
366 lines
11 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:buzz/shared/relay/relay_query_response.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();
|
|
final rateLimitGate = RelayRateLimitGate();
|
|
late final session = ConnectedRelaySession(
|
|
httpClient: MockClient(_handleHttp),
|
|
rateLimitGate: rateLimitGate,
|
|
);
|
|
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;
|
|
int writerFailures = 0;
|
|
final writerQueries = <String>[];
|
|
NostrEvent Function(NostrEvent)? replaceNextPublish;
|
|
Completer<void>? holdHistory;
|
|
Completer<void>? holdWriter;
|
|
// Pause the response after the writer has selected its head.
|
|
Completer<void>? holdWriterResponse;
|
|
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) &&
|
|
(_dTagsOf(req)?.contains(dTag) ?? false))
|
|
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);
|
|
final replace = replaceNextPublish;
|
|
replaceNextPublish = null;
|
|
stored.add(replace == null ? event : replace(event));
|
|
final ok = [
|
|
'OK',
|
|
event.id,
|
|
true,
|
|
replace == null ? '' : 'duplicate: newer event already stored',
|
|
];
|
|
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, _dTagsOf(message)));
|
|
return;
|
|
}
|
|
final dTags = _dTagsOf(message);
|
|
if (dTags == null) _liveSubIds[null] = subId;
|
|
for (final dTag in dTags ?? const <String>[]) {
|
|
_liveSubIds[dTag] = subId;
|
|
}
|
|
final rejection = rejectLive;
|
|
if (rejection == null && withholdEose) return;
|
|
scheduleMicrotask(
|
|
() => _reply(
|
|
rejection == null ? ['EOSE', subId] : ['CLOSED', subId, rejection],
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> _answerHistory(String subId, List<String>? dTags) 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 per
|
|
// coordinate it names.
|
|
if (dTags == null) {
|
|
for (final e in stored.where((e) => e.getTagValue('t') != null)) {
|
|
_reply(['EVENT', subId, e.toJson()]);
|
|
}
|
|
return _reply(['EOSE', subId]);
|
|
}
|
|
for (final dTag in dTags) {
|
|
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);
|
|
final filter = (jsonDecode(request.body) as List).single as Map;
|
|
if (filter['#d'] case [final String coordinate]) {
|
|
expect(filter, {
|
|
'kinds': [30078],
|
|
'authors': [pubkey],
|
|
'#d': [coordinate],
|
|
'limit': 1,
|
|
'consistency': 'strong',
|
|
});
|
|
writerQueries.add(coordinate);
|
|
await holdWriter?.future;
|
|
if (writerFailures > 0) {
|
|
writerFailures--;
|
|
return http.Response('error: overloaded', 503);
|
|
}
|
|
final heads = _heads(_storedByRelay[request.url.origin] ?? const []);
|
|
final head = heads[coordinate];
|
|
final hold = holdWriterResponse;
|
|
if (hold != null) await hold.future;
|
|
return http.Response(jsonEncode([if (head != null) head.toJson()]), 200);
|
|
}
|
|
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);
|
|
}
|
|
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(source).values) e.toJson()],
|
|
}),
|
|
200,
|
|
);
|
|
}
|
|
|
|
Map<String, NostrEvent> _heads(List<NostrEvent> source) {
|
|
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 heads;
|
|
}
|
|
|
|
void _reply(List<dynamic> message) => session.debugHandleMessage(message);
|
|
|
|
/// Null for a filter by `#t` alone, such as read state's slot discovery.
|
|
static List<String>? _dTagsOf(List<dynamic> req) =>
|
|
((req[2] as Map<String, dynamic>)['#d'] as List?)?.cast<String>();
|
|
}
|
|
|
|
class ConnectedRelaySession extends RelaySessionNotifier {
|
|
ConnectedRelaySession({super.httpClient, super.rateLimitGate})
|
|
: super(
|
|
snapshotDecoder: (input) async => validateReadStateSnapshot(input),
|
|
queryDecoder: (response) async => parseRelayQueryEvents(
|
|
response.bodyBytes,
|
|
response.headers['content-type'],
|
|
),
|
|
);
|
|
|
|
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));
|
|
|
|
/// An independent preferences cache for a second device using the same relay.
|
|
class SidebarDevicePrefs extends Fake implements SharedPreferences {
|
|
final _strings = <String, String>{};
|
|
|
|
@override
|
|
String? getString(String key) => _strings[key];
|
|
|
|
@override
|
|
Future<bool> remove(String key) async {
|
|
_strings.remove(key);
|
|
return true;
|
|
}
|
|
|
|
@override
|
|
Future<bool> setString(String key, String value) async {
|
|
_strings[key] = value;
|
|
return true;
|
|
}
|
|
}
|