Files
buzz/mobile/lib/shared/me/me_sync.dart
Wes 8827f986e4 mobile: follow desktop's unified sidebar workspaces (#9745)
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>
2026-11-19 18:49:12 -07:00

571 lines
18 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:shared_preferences/shared_preferences.dart';
import '../theme/theme_provider.dart';
import '../crypto/nip44.dart';
import '../relay/relay.dart';
import 'me_groups.dart';
import 'me_recovery.dart';
import 'me_journal.dart';
import 'package:buzz/shared/crypto/event_signing.dart';
/// A live, account/community-scoped reader for desktop's encrypted Solo record.
final meGroupsProvider = StreamProvider<MeGroups>((ref) {
final service = ref.watch(meSyncProvider);
if (service.connectionState != null) {
ref.listen(relaySessionProvider.select((state) => state.status), (
previous,
next,
) {
if (previous != next && next == SessionStatus.connected) {
ref.invalidateSelf();
}
});
}
final controller = StreamController<MeGroups>();
var disposed = false;
void Function()? unsubscribe;
NostrEvent? latest;
var hasSnapshot = false;
var subscriptionClosed = false;
var syncFailed = false;
Future<void> accept(NostrEvent event) async {
if (disposed ||
(latest != null &&
event.id != latest!.id &&
!meEventIsNewer(event, latest!))) {
return;
}
try {
final value = service.decode(event);
// Reserve the highest verified head before any awaited persistence.
latest = event;
hasSnapshot = true;
controller.add(value);
await service.cache(event);
} catch (error, stack) {
if (!disposed) {
syncFailed = true;
if (!hasSnapshot) controller.addError(error, stack);
}
}
}
Future<void> refresh() async {
try {
final remote = await service.head();
final candidate = service.latestCacheCandidate;
final event =
candidate != null &&
(remote == null || meEventIsNewer(candidate, remote))
? candidate
: remote;
if (disposed) return;
if (event != null) {
await accept(event);
} else if (latest == null) {
await service.cache(null);
if (disposed || latest != null) return;
hasSnapshot = true;
controller.add(const MeGroups());
}
} catch (error, stack) {
if (!disposed) {
syncFailed = true;
if (!hasSnapshot) controller.addError(error, stack);
}
}
}
Future<void> start() async {
try {
final candidate = service.latestCacheCandidate;
final cached = candidate == null
? service.cachedSnapshot()
: (event: candidate, groups: service.decode(candidate));
if (cached != null) {
latest = cached.event;
hasSnapshot = true;
controller.add(cached.groups);
}
} catch (_) {
// A corrupt cache must not prevent a fresh relay read.
}
try {
service.check();
unsubscribe = await service.session.subscribe(
service.filter,
accept,
onClosed: (_) {
if (disposed) return;
subscriptionClosed = true;
if (!hasSnapshot) {
controller.addError(
StateError('Couldn’t sync Solo. Reconnect and try again.'),
);
}
},
);
if (disposed) {
unsubscribe?.call();
return;
}
await refresh();
} catch (error, stack) {
if (!disposed) {
syncFailed = true;
if (!hasSnapshot) controller.addError(error, stack);
}
}
}
ref.listen(appForegroundProvider, (_, foreground) {
if (!foreground) return;
// Recover an interrupted reader by resubscribing instead of asking the user.
// Before reconnecting, leave recovery to the reconnect listener above.
if (subscriptionClosed || syncFailed) {
if (service.connected) ref.invalidateSelf();
} else {
unawaited(refresh());
}
});
ref.onDispose(() {
disposed = true;
unsubscribe?.call();
unawaited(controller.close());
});
unawaited(start());
return controller.stream;
}, retry: (_, _) => null);
/// Non-disruptive offline-save status, retained across reader retries.
final meOfflineSaveWarningProvider = StreamProvider<bool>((ref) {
final service = ref.watch(meSyncProvider);
final controller = StreamController<bool>();
void changed() => controller.add(service.cacheWriteFailed.value);
service.cacheWriteFailed.addListener(changed);
changed();
ref.onDispose(() {
service.cacheWriteFailed.removeListener(changed);
unawaited(controller.close());
});
return controller.stream;
});
/// NIP-01 replacement ordering: smallest ID wins an equal timestamp.
bool meEventIsNewer(NostrEvent a, NostrEvent b) =>
a.createdAt > b.createdAt ||
(a.createdAt == b.createdAt && a.id.compareTo(b.id) < 0);
final Provider<MeSync> meSyncProvider = Provider<MeSync>((ref) {
final config = ref.watch(relayConfigProvider);
final service = MeSync(
ref.read(relaySessionProvider.notifier),
config,
connectionState: () =>
ref.read(relaySessionProvider).status == SessionStatus.connected,
prefs: ref.read(savedPrefsProvider),
);
ref.onDispose(() => service.disposed = true);
return service;
});
/// Narrow private-recipe transport; never writes Messages organization.
class MeSync {
final RelaySessionNotifier session;
final RelayConfig config;
late final String community = Uri.parse(config.baseUrl).origin;
late final String privateHex = nostr.Nip19.decode(payload: config.nsec!).data;
late final String pubkey = derivePublicKeyHex(privateHex);
late final key = getConversationKey(privateHex, pubkey);
final bool _connected;
/// Live transport status without replacing account/community-scoped state.
final bool Function()? connectionState;
/// Whether relay operations can currently be attempted.
bool get connected => connectionState?.call() ?? _connected;
final SharedPreferences? prefs;
String get pendingKey => 'me-pending:$community:$pubkey';
bool disposed = false;
bool _saving = false;
MeSync(
this.session,
this.config, {
bool connected = true,
this.connectionState,
this.prefs,
}) : _connected = connected;
/// Encrypted last verified organization, isolated by account and community.
String get cacheKey => 'me-cache:$community:$pubkey';
/// Read while offline. A signed event preserves replacement ordering.
({NostrEvent? event, MeGroups groups})? cachedSnapshot() {
if (disposed || config.nsec == null) return null;
final saved = prefs?.getString(cacheKey);
if (saved == null) return null;
final value = jsonDecode(nip44Decrypt(key, saved)) as Map<String, dynamic>;
if (value['community'] != community) {
throw const FormatException('Invalid cached organization');
}
final json = value['event'] as Map<String, dynamic>?;
final event = json == null ? null : NostrEvent.fromJson(json);
return (
event: event,
groups: event == null ? const MeGroups() : decode(event),
);
}
Future<void> _cacheQueue = Future.value();
bool _cacheDirty = false;
NostrEvent? _latestCacheCandidate;
/// Highest verified candidate survives a reader retry after failed storage.
NostrEvent? get latestCacheCandidate => _latestCacheCandidate;
/// False only after the newest candidate is durably written.
final cacheWriteFailed = ValueNotifier(false);
/// Serialize writes and report failures so callers can expose a retry.
Future<void> cache(NostrEvent? event) {
if (event != null) decode(event);
var highest = _latestCacheCandidate;
try {
final persisted = cachedSnapshot()?.event;
if (persisted != null &&
(highest == null || meEventIsNewer(persisted, highest))) {
highest = persisted;
}
} catch (_) {
// Verified relay data can replace an unreadable cache.
}
if (highest != null &&
(event == null ||
(highest.id != event.id && !meEventIsNewer(event, highest)))) {
_latestCacheCandidate = highest;
return Future.value();
}
_latestCacheCandidate = event;
final operation = _cacheQueue.then((_) => _writeCache(event));
_cacheQueue = operation.catchError((Object _) {});
return operation;
}
Future<void> _writeCache(NostrEvent? event) async {
if (disposed || config.nsec == null || prefs == null) return;
final highest = _latestCacheCandidate;
if (highest != null && highest.id != event?.id) return;
if (event != null) decode(event);
try {
final previous = cachedSnapshot()?.event;
if (!_cacheDirty &&
previous != null &&
(event == null || !meEventIsNewer(event, previous))) {
return;
}
} catch (_) {
// Replace corrupt local storage with verified relay data.
}
try {
if (!await prefs!.setString(
cacheKey,
nip44Encrypt(
key,
jsonEncode({'community': community, 'event': event?.toJson()}),
),
)) {
throw const MeCacheException();
}
_cacheDirty = false;
if (_latestCacheCandidate?.id == event?.id) {
cacheWriteFailed.value = false;
}
} catch (_) {
// SharedPreferences updates its memory cache even if the disk write fails.
// Reload so Retry cannot mistake that optimistic value for durable data.
_cacheDirty = true;
if (_latestCacheCandidate?.id == event?.id) cacheWriteFailed.value = true;
try {
await prefs!.reload();
} finally {
throw const MeCacheException();
}
}
}
NostrFilter get filter => NostrFilter(
kinds: const [30078],
authors: [pubkey],
tags: {
'#d': [MeGroups.coordinate(community)],
},
limit: 1,
);
void check() {
if (disposed) throw StateError('Your community changed. Open Solo again.');
if (!connected || config.nsec == null) {
throw StateError('Connect to your community to load Solo.');
}
}
MeGroups decode(NostrEvent event) {
if (event.kind != 30078 ||
event.pubkey != pubkey ||
event.tags.where((t) => t.isNotEmpty && t[0] == 'd').length != 1 ||
!event.tags.any(
(t) =>
t.length == 2 &&
t[0] == 'd' &&
t[1] == MeGroups.coordinate(community),
) ||
!event.tags.any(
(t) => t.length == 2 && t[0] == 't' && t[1] == MeGroups.tag,
)) {
throw const FormatException('Invalid Solo record');
}
verifiedNostrEventFromJson(jsonEncode(event.toJson()));
return MeGroups.decode(nip44Decrypt(key, event.content), community);
}
Future<NostrEvent?> head() async {
check();
final events = await session.fetchHistory(filter);
check();
if (events.isEmpty) return null;
final event = events.reduce((a, b) => meEventIsNewer(a, b) ? a : b);
decode(event);
return event;
}
/// Discard only the pending snapshot the user explicitly reviewed.
Future<void> discardPending(String expected) async {
check();
if (_saving || prefs?.getString(pendingKey) != expected) {
throw StateError('The pending save changed. Review it again.');
}
await clearMeJournal(prefs!, pendingKey, expected, checkScope: check);
}
Future<void> _clearConfirmedPending(String expected) async {
final storage = prefs;
if (storage == null) return;
await storage.reload();
check();
final current = storage.getString(pendingKey);
if (current == null) return;
if (current != expected) {
throw StateError('The pending save changed. Review it again.');
}
try {
if (!await storage.remove(pendingKey)) {
throw StateError('Local cleanup failed.');
}
} catch (_) {
// remove() mutates the in-memory preferences even when disk removal fails.
await storage.reload();
throw StateError(
'Saved to your community, but cleanup on this phone failed. Retry to finish the pending save.',
);
}
}
/// Publishes [event], journaled as [record], unless [refused] says no at the
/// send boundary, after every relay wait. A refused event leaves no
/// replayable journal entry behind.
Future<void> _publishUnlessRefused(
NostrEvent event,
String record, {
required bool Function() refused,
}) async {
var wasRefused = false;
try {
await session.publish(
event,
mayPublish: () async => !(wasRefused = refused()),
);
} catch (_) {
if (!wasRefused) rethrow;
await _clearConfirmedPending(record);
throw const MeFilingClosed();
}
}
/// Refresh before applying an intent, then confirm the selected signed event.
///
/// [mayFile] says whether this client may still change projects or chat
/// filings. It is asked again at each relay send, including a pending
/// replay; a refused filing change is dropped from the journal and throws
/// [MeFilingClosed].
Future<void> update(
MeGroups Function(MeGroups) change, {
bool Function()? mayFile,
}) async {
check();
if (_saving) throw StateError('A Solo change is still being saved.');
_saving = true;
try {
MeGroups? recovered;
String? recoveredHead;
var unfiled = false;
final pending = prefs?.getString(pendingKey);
if (pending != null) {
final stored = jsonDecode(pending) as Map<String, dynamic>;
final event = NostrEvent.fromJson(
(stored['event'] as Map<String, dynamic>?) ?? stored,
);
final baseEvent = stored['base'] as Map<String, dynamic>?;
final base = baseEvent == null
? const MeGroups()
: decode(NostrEvent.fromJson(baseEvent));
var local = decode(event);
final remote = await head();
// A filing journaled before the lock can never be sent. Keep the
// chats it registered and rebase them like a superseded save, so the
// caller's own change can still go through.
unfiled =
mayFile?.call() == false &&
remote?.id != event.id &&
_filingsDiffer(base, local);
if (unfiled) {
local = MeGroups(
groups: base.groups,
assignments: base.assignments,
channels: local.channels,
);
}
if (unfiled ||
(remote != null &&
remote.id != event.id &&
meEventIsNewer(remote, event))) {
if (!stored.containsKey('event')) {
// Older clients did not persist a base, so a safe rebase is unknown.
throw MeRecoveryConflict();
}
recoveredHead = remote?.id;
recovered = rebaseMeGroups(
base,
local,
remote == null ? const MeGroups() : decode(remote),
);
} else {
if (remote?.id != event.id) {
check();
await _publishUnlessRefused(
event,
pending,
refused: () =>
mayFile?.call() == false && _filingsDiffer(base, local),
);
if ((await head())?.id != event.id) {
throw StateError(
'A previous Solo save is still unconfirmed. Try again.',
);
}
}
await _clearConfirmedPending(pending);
throw StateError(
'Your previous Solo save is confirmed. Review your projects before making another change.',
);
}
}
final before = await head();
if (recovered != null && before?.id != recoveredHead) {
throw StateError(
'Solo changed again. Your pending change is saved; try again.',
);
}
final baseGroups = before == null ? const MeGroups() : decode(before);
final value = recovered == null
? change(baseGroups)
: unfiled
? change(recovered)
: recovered;
bool refused() =>
mayFile?.call() == false && _filingsDiffer(baseGroups, value);
if (refused()) throw const MeFilingClosed();
final String encoded;
try {
encoded = value.encode(community);
} on FormatException {
if (recovered != null) throw MeRecoveryConflict();
rethrow;
}
final content = nip44Encrypt(key, encoded);
final current = await head();
if (before?.id != current?.id) {
throw StateError(
'Solo changed on another device. Refresh and try again.',
);
}
if (current != null &&
current.createdAt >= DateTime.now().millisecondsSinceEpoch ~/ 1000) {
throw StateError('Please wait a second before saving again.');
}
check();
final signed = NostrEvent.fromJson(
signNostrEvent(
kind: 30078,
content: content,
secretKey: privateHex,
tags: [
['d', MeGroups.coordinate(community)],
['t', MeGroups.tag],
],
).toMap(),
);
final pendingRecord = jsonEncode({
'event': signed.toJson(),
'base': before?.toJson(),
});
if (prefs != null && !await prefs!.setString(pendingKey, pendingRecord)) {
throw StateError('Couldn’t save this change on your phone. Try again.');
}
check();
await _publishUnlessRefused(signed, pendingRecord, refused: refused);
check();
if ((await head())?.id != signed.id) {
throw StateError(
'Another Solo change is selected. Refresh to see the latest projects.',
);
}
await _clearConfirmedPending(pendingRecord);
if (recovered != null && !unfiled) {
throw StateError(
'Your previous Solo save was recovered alongside the desktop changes. Review your projects before making another change.',
);
}
} finally {
_saving = false;
}
}
}
/// Another client now owns workspace filings, so this one must not write them.
class MeFilingClosed implements Exception {
/// Thrown before any filing reaches the relay.
const MeFilingClosed();
@override
String toString() =>
'Workspaces are now organized on desktop. Create this one there.';
}
bool _filingsDiffer(MeGroups a, MeGroups b) =>
jsonEncode(a.groups) != jsonEncode(b.groups) ||
!mapEquals(a.assignments, b.assignments);
/// A verified Solo snapshot could not be retained for offline use.
class MeCacheException implements Exception {
const MeCacheException();
@override
String toString() => 'Could not save Solo for offline use. Please retry.';
}