mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
## Summary Mobile read-state fixes within the current NIP-RS text. - **Stuck pending update.** When the relay refuses a pending update with `invalid: event timestamp too far from server time` and the update is older than the relay's 15-minute window by the device clock, the update is retired. The next pass reads a fresh snapshot and sends a strictly newer successor, journaled before it is sent, unless the relay already holds that update or an own-slot update covering every key in it. The marks come from the journaled local state, so nothing is lost. A refusal of an update that is not old by the device clock reports `ReadStateClockSkewError` and keeps the exact signed bytes. Unknown outcomes (timeouts, lost acknowledgements) still retry the exact bytes. - **Mark Read from the channel actions sheet.** The sheet is the only owner of the action, for custom-section channels too. It marks through the newest message known at the tap (the listed `lastMessageAt` or a newer observed unread event), not the `Channel` captured when the menu opened, so messages arriving after the tap stay unread. With no known message time it only releases forced-unread flags. - **Failed snapshot.** A failed snapshot, during startup or inside a publish, retries with backoff (5 s doubling to 5 min) while connected and on app resume; the retry re-syncs and sends journaled marks. When a publish's own snapshot read succeeds first, the pending retry is cancelled, the backoff resets to 5 s and the superseded snapshot error is cleared. A reconnect still re-syncs as before. The channels list shows a tappable "Unread status isn't syncing" notice while sync is failing. - **Marks in the manager gap.** A mark, seed or forced unread made after a dependency change retired the manager, but before the rebuild, now runs the pending rebuild and reaches the current manager instead of being dropped. The session-wide publishing switch-off after an unsupported-kind or missing-scope refusal is unchanged: marks stay journaled and the next manager (restart, re-authentication or community switch) publishes them. In that state the notice offers no retry and says to sign in again or restart Buzz. ## Tests - `read_state_manager_test.dart`: expired update with only partial coverage is renewed with a newer successor carrying every mark; expired update the relay already holds is retired with no new send; clock-skew refusal keeps the exact update and reports the skew error; failed snapshot retries on the backoff timer and stops after recovery; a snapshot failure inside a publish retries on its own and sends the marks; after an explicit flush whose snapshot read succeeds, no extra snapshot is read and the next failure retries after 5 s, whether the write succeeds or fails. - `channel_actions_sheet_test.dart`: Mark Read covers a message that arrived while the sheet was open; with no known message time it only releases forced unread. - `read_state_provider_test.dart`: a mark made between a community switch and the next manager's build is kept. Each new test fails without its fix. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz>
323 lines
11 KiB
Dart
323 lines
11 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:flutter/widgets.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
import '../relay/relay.dart';
|
|
import '../theme/theme_provider.dart';
|
|
import '../community/community_provider.dart';
|
|
import 'read_state_manager.dart';
|
|
import 'read_state_format.dart';
|
|
import 'read_state_time.dart';
|
|
|
|
class ReadStateState {
|
|
final bool isReady;
|
|
final String? pubkey;
|
|
final Map<String, int> contexts;
|
|
final int version;
|
|
final int retentionFloor;
|
|
|
|
/// Whether the last read-state sync failed: the snapshot did not load or
|
|
/// an update was not published. Retries continue in the background.
|
|
final bool syncFailed;
|
|
|
|
/// Whether the relay refused read state for the rest of this session.
|
|
/// Retrying cannot help; signing in again or restarting can.
|
|
final bool syncUnsupported;
|
|
|
|
/// Session-local forced-unread flags, keyed by the forced context id
|
|
/// (a channel id from the channel tile, or a `msg:` key from the message
|
|
/// actions sheet), each mapped to the channel it belongs to so channel
|
|
/// tiles and badges can surface message-level forces.
|
|
final Map<String, String> forcedUnreadContexts;
|
|
|
|
const ReadStateState({
|
|
required this.isReady,
|
|
required this.pubkey,
|
|
required this.contexts,
|
|
required this.version,
|
|
this.forcedUnreadContexts = const {},
|
|
this.retentionFloor = 0,
|
|
this.syncFailed = false,
|
|
this.syncUnsupported = false,
|
|
});
|
|
|
|
const ReadStateState.inert()
|
|
: isReady = false,
|
|
pubkey = null,
|
|
contexts = const {},
|
|
version = 0,
|
|
retentionFloor = 0,
|
|
syncFailed = false,
|
|
syncUnsupported = false,
|
|
forcedUnreadContexts = const {};
|
|
|
|
/// Channels that should surface as unread because of a forced-unread flag —
|
|
/// either forced directly, or containing a forced message.
|
|
Set<String> get locallyForcedChannelIds =>
|
|
forcedUnreadContexts.values.toSet();
|
|
|
|
/// Whether this exact context (channel id or `msg:` key) is forced unread.
|
|
bool isForcedUnread(String contextId) =>
|
|
forcedUnreadContexts.containsKey(contextId);
|
|
|
|
int? effectiveTimestamp(String contextId) {
|
|
if (pubkey == null || retentionFloor == 0 || isOverrideContext(contextId)) {
|
|
return contexts[contextId];
|
|
}
|
|
final floor = retentionFloor;
|
|
final stored = contexts[contextId];
|
|
return stored == null || stored < floor ? floor : stored;
|
|
}
|
|
|
|
ReadStateState copyWithContext(String contextId, int timestamp) {
|
|
final current = contexts[contextId] ?? 0;
|
|
if (timestamp <= current) {
|
|
return this;
|
|
}
|
|
|
|
return ReadStateState(
|
|
isReady: isReady,
|
|
pubkey: pubkey,
|
|
contexts: Map.unmodifiable({...contexts, contextId: timestamp}),
|
|
version: version + 1,
|
|
retentionFloor: retentionFloor,
|
|
forcedUnreadContexts: forcedUnreadContexts,
|
|
syncFailed: syncFailed,
|
|
syncUnsupported: syncUnsupported,
|
|
);
|
|
}
|
|
}
|
|
|
|
class ReadStateNotifier extends Notifier<ReadStateState> {
|
|
ReadStateManager? _manager;
|
|
bool _isInitialized = false;
|
|
final Map<String, String> _forcedUnreadContexts = {};
|
|
|
|
@override
|
|
ReadStateState build() {
|
|
_manager?.dispose(flushPending: false);
|
|
_manager = null;
|
|
_isInitialized = false;
|
|
_forcedUnreadContexts.clear();
|
|
|
|
final relayConfig = ref.watch(relayConfigProvider);
|
|
// Watch the session notifier, not its state: a status change (app resume,
|
|
// reconnect) must not rebuild the manager and drop session-local forced
|
|
// unread flags. The listener below re-syncs on reconnect instead.
|
|
ref.watch(relaySessionProvider.notifier);
|
|
ref.watch(activeCommunityProvider);
|
|
|
|
final nsec = relayConfig.nsec?.trim();
|
|
if (nsec == null || nsec.isEmpty) {
|
|
return const ReadStateState.inert();
|
|
}
|
|
|
|
final signedRelay = SignedEventRelay(
|
|
session: ref.read(relaySessionProvider.notifier),
|
|
nsec: nsec,
|
|
);
|
|
final pubkey = ref.watch(_readStatePubkeyProvider);
|
|
if (pubkey == null) return const ReadStateState.inert();
|
|
final crypto = ref.watch(readStateCryptoProvider);
|
|
if (crypto == null) {
|
|
return const ReadStateState.inert();
|
|
}
|
|
|
|
final prefs = ref.read(savedPrefsProvider);
|
|
late final ReadStateManager manager;
|
|
manager = ReadStateManager(
|
|
pubkey: pubkey,
|
|
relayUrl: relayConfig.baseUrl,
|
|
prefs: prefs,
|
|
crypto: crypto,
|
|
relaySession: ref.read(relaySessionProvider.notifier),
|
|
signedEventRelay: signedRelay,
|
|
remoteEnabled: true,
|
|
onChanged: () => _emitManagerState(manager),
|
|
isConnected: () =>
|
|
ref.read(relaySessionProvider).status == SessionStatus.connected,
|
|
);
|
|
_manager = manager;
|
|
// Expiry is semantic even on an idle screen with no incoming events.
|
|
final floorTimer = Timer.periodic(const Duration(minutes: 1), (_) {
|
|
if (_manager == manager) _emitManagerState(manager);
|
|
});
|
|
|
|
ref.onDispose(() {
|
|
floorTimer.cancel();
|
|
manager.dispose();
|
|
if (_manager == manager) {
|
|
_manager = null;
|
|
}
|
|
});
|
|
|
|
ref.listen(appLifecycleProvider, (_, next) {
|
|
if (next == AppLifecycleState.paused ||
|
|
next == AppLifecycleState.detached ||
|
|
next == AppLifecycleState.hidden) {
|
|
unawaited(manager.flush());
|
|
} else if (next == AppLifecycleState.resumed) {
|
|
unawaited(manager.retrySync());
|
|
}
|
|
});
|
|
|
|
ref.listen(relaySessionProvider, (prev, next) {
|
|
if (prev?.status != SessionStatus.connected &&
|
|
next.status == SessionStatus.connected) {
|
|
unawaited(manager.reinitializeRemote());
|
|
}
|
|
});
|
|
|
|
Future.microtask(() async {
|
|
await manager.initialize();
|
|
if (_manager != manager) return;
|
|
_isInitialized = true;
|
|
_emitManagerState(manager);
|
|
});
|
|
|
|
return _stateFromManager(manager, isReady: false);
|
|
}
|
|
|
|
/// Advance a context's read marker. Clears the forced-unread flag for
|
|
/// exactly this context, if any. An explicit channel-level "Mark read"
|
|
/// (channel tile/menu) should pass [clearForcedMessages] so message-level
|
|
/// forces inside the channel are released too; the automatic read on
|
|
/// channel open must not, so a message deliberately marked unread stays
|
|
/// unread until acted on.
|
|
void markContextRead(
|
|
String contextId,
|
|
int unixTimestamp, {
|
|
bool clearForcedMessages = false,
|
|
}) {
|
|
var removed = _forcedUnreadContexts.remove(contextId) != null;
|
|
if (clearForcedMessages) {
|
|
final before = _forcedUnreadContexts.length;
|
|
_forcedUnreadContexts.removeWhere(
|
|
(_, channelId) => channelId == contextId,
|
|
);
|
|
removed = removed || _forcedUnreadContexts.length != before;
|
|
}
|
|
_currentManager?.markContextRead(contextId, unixTimestamp);
|
|
if (removed) {
|
|
_refreshForcedState();
|
|
}
|
|
}
|
|
|
|
/// Force a context unread for the rest of the session. [contextId] is a
|
|
/// channel id (channel-tile action) or a `msg:` key (message actions
|
|
/// sheet); [channelId] is the channel the context belongs to, so tiles and
|
|
/// badges can surface message-level forces. Read markers are monotonic,
|
|
/// so this is the only way to move a context back to unread.
|
|
void markContextUnread(String contextId, {required String channelId}) {
|
|
if (_currentManager == null) return;
|
|
_forcedUnreadContexts[contextId] = channelId;
|
|
_refreshForcedState();
|
|
}
|
|
|
|
/// Clear a forced-unread flag without moving any read marker. Reading to
|
|
/// the bottom of a channel the reader marked unread uses this: it ends the
|
|
/// manual unread but must not read mentions or replies the reader has not
|
|
/// seen.
|
|
void clearForcedUnread(String contextId) {
|
|
if (_forcedUnreadContexts.remove(contextId) != null) {
|
|
_refreshForcedState();
|
|
}
|
|
}
|
|
|
|
void _refreshForcedState() {
|
|
final manager = _manager;
|
|
if (manager == null) return;
|
|
state = _stateFromManager(
|
|
manager,
|
|
isReady: _isInitialized,
|
|
previousVersion: state.version,
|
|
);
|
|
}
|
|
|
|
/// Publishes pending read markers now instead of after the usual delay.
|
|
Future<void> flush() async => _manager?.flush();
|
|
|
|
void seedContextRead(String contextId, int unixTimestamp) {
|
|
_currentManager?.seedContextRead(contextId, unixTimestamp);
|
|
}
|
|
|
|
/// Seed the first channel-list landing once, durably across restarts.
|
|
void seedContextsRead(Map<String, int> contexts) {
|
|
_currentManager?.seedInitialContextsRead(contexts);
|
|
}
|
|
|
|
/// Retry a failed read-state sync now.
|
|
Future<void> retrySync() async => _currentManager?.retrySync();
|
|
|
|
/// The manager for the current identity and community. A dependency change
|
|
/// retires the old manager before the rebuild that creates the next one, so
|
|
/// an action in that gap first runs the pending rebuild instead of being
|
|
/// dropped.
|
|
ReadStateManager? get _currentManager {
|
|
// Reading state runs a pending rebuild.
|
|
if (_manager == null) state.pubkey;
|
|
return _manager;
|
|
}
|
|
|
|
void _emitManagerState(ReadStateManager manager) {
|
|
if (_manager != manager) return;
|
|
final advances = manager.drainSyncedAdvances();
|
|
for (final contextId in advances) {
|
|
_forcedUnreadContexts.remove(contextId);
|
|
}
|
|
state = _stateFromManager(
|
|
manager,
|
|
isReady: _isInitialized,
|
|
previousVersion: state.version,
|
|
);
|
|
}
|
|
|
|
ReadStateState _stateFromManager(
|
|
ReadStateManager manager, {
|
|
required bool isReady,
|
|
int? previousVersion,
|
|
}) {
|
|
return ReadStateState(
|
|
isReady: isReady,
|
|
pubkey: manager.pubkey,
|
|
retentionFloor: readStateFloor(currentUnixSeconds()),
|
|
contexts: manager.effectiveContexts,
|
|
version: (previousVersion ?? 0) + 1,
|
|
syncFailed: manager.syncError != null,
|
|
syncUnsupported: manager.remoteUnsupported,
|
|
forcedUnreadContexts: Map.unmodifiable(
|
|
Map<String, String>.from(_forcedUnreadContexts),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
final readStateProvider = NotifierProvider<ReadStateNotifier, ReadStateState>(
|
|
ReadStateNotifier.new,
|
|
);
|
|
|
|
String? _normalizePubkey(String? value) {
|
|
final normalized = value?.trim().toLowerCase();
|
|
if (normalized == null || normalized.isEmpty) {
|
|
return null;
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
final _readStatePubkeyProvider = Provider<String?>((ref) {
|
|
final active = ref.watch(activeCommunityProvider).value;
|
|
final config = ref.watch(relayConfigProvider);
|
|
return _normalizePubkey(active?.pubkey) ??
|
|
_normalizePubkey(pubkeyFromNsec(config.nsec?.trim()));
|
|
});
|
|
|
|
/// Retains read-state encryption material across connection status changes.
|
|
final readStateCryptoProvider = Provider<ReadStateCrypto?>((ref) {
|
|
final config = ref.watch(relayConfigProvider);
|
|
final pubkey = ref.watch(_readStatePubkeyProvider);
|
|
final nsec = config.nsec?.trim();
|
|
if (nsec == null || nsec.isEmpty || pubkey == null) return null;
|
|
return ReadStateCrypto.tryCreate(nsec: nsec, pubkey: pubkey);
|
|
});
|