diff --git a/mobile/lib/features/channels/channel_filter/channel_filter_activity.dart b/mobile/lib/features/channels/channel_filter/channel_filter_activity.dart index 534d0f3806a..7832401036c 100644 --- a/mobile/lib/features/channels/channel_filter/channel_filter_activity.dart +++ b/mobile/lib/features/channels/channel_filter/channel_filter_activity.dart @@ -9,6 +9,12 @@ import '../channels_provider.dart'; final channelFilterActivityProvider = Provider.autoDispose .family, String>((ref, channelId) { ref.watch(_activityWatchProvider(channelId)); + return ref.watch(cachedChannelFilterActivityProvider(channelId)); + }); + +/// Reads existing activity without adding channels to reconnect gap queries. +final cachedChannelFilterActivityProvider = Provider.autoDispose + .family, String>((ref, channelId) { final notifier = ref.watch(channelsProvider.notifier); final (:known, :at) = ref.watch( channelsProvider.select((_) => notifier.activityFor(channelId)), diff --git a/mobile/lib/features/channels/channel_filter/channel_filter_store.dart b/mobile/lib/features/channels/channel_filter/channel_filter_store.dart index f80e241d34d..9d4c4ede7f0 100644 --- a/mobile/lib/features/channels/channel_filter/channel_filter_store.dart +++ b/mobile/lib/features/channels/channel_filter/channel_filter_store.dart @@ -96,8 +96,13 @@ class ChannelFilterStore { static bool _key(Object? k) => k is String && k.trim().isNotEmpty && k.length <= 264 && k != '__proto__'; static bool _mode(Object? v) => v == 'all' || v == 'unreads' || v == 'active'; - ChannelFilterMode modeFor(String group) { + ChannelFilterMode modeFor( + String group, { + ChannelFilterMode fallback = ChannelFilterMode.all, + }) { final meta = _record['meta']; + final choices = (meta == null ? _record['groups'] : meta['g']) as Map; + if (!choices.containsKey(group)) return fallback; final value = meta == null ? (_record['groups'] as Map)[group] : ((meta['g'] as Map)[group] as List?)?[2]; @@ -118,9 +123,8 @@ class ChannelFilterStore { : count; } - int windowFor(String group) => - (_record['activeWindowSeconds'] as Map?)?[group] as int? ?? - defaultActiveWindowSeconds; + int windowFor(String group, {int fallback = defaultActiveWindowSeconds}) => + (_record['activeWindowSeconds'] as Map?)?[group] as int? ?? fallback; Map toJson() => jsonDecode(jsonEncode(_record)) as Map; @@ -146,12 +150,11 @@ class ChannelFilterStore { 'v': 1, 'g': { for (final entry in (data['groups'] as Map).entries) - if (entry.value != 'all') - entry.key as String: [ - remoteCreatedAt * 1000, - '0000000000000000', - entry.value, - ], + entry.key as String: [ + remoteCreatedAt * 1000, + '0000000000000000', + entry.value == 'all' ? null : entry.value, + ], }, }; final registers = (meta['g'] as Map).cast(); diff --git a/mobile/lib/features/channels/channel_sort/channel_sort_storage.dart b/mobile/lib/features/channels/channel_sort/channel_sort_storage.dart index 9e011aea25c..02ede4f138e 100644 --- a/mobile/lib/features/channels/channel_sort/channel_sort_storage.dart +++ b/mobile/lib/features/channels/channel_sort/channel_sort_storage.dart @@ -68,8 +68,8 @@ class ChannelSortStore { } /// Reads a `channel-workspace-sort` payload. Register metadata, when - /// present, is authoritative over the plain `groups` map; a null register - /// clears that section's choice. + /// present, takes precedence over the plain `groups` map. A null register + /// records an explicit return to alphabetical order. factory ChannelSortStore.fromWorkspaceJson(Map json) { final meta = json['meta']; if (meta is! Map) return ChannelSortStore.fromJson(json); @@ -82,7 +82,9 @@ class ChannelSortStore { for (final MapEntry(:key, :value) in (registers as Map? ?? const {}).entries) if (key is String && value is List && value.length == 3) - key: ?ChannelSortMode.fromWire(value[2]), + key: ?(value[2] == null + ? ChannelSortMode.alpha + : ChannelSortMode.fromWire(value[2])), }, ); } @@ -245,6 +247,11 @@ class ChannelSortStorage { } /// The last unified sort head, so a cold start sorts as desktop does. + /// + /// Builds before [_workspaceCacheVersion] wrote no version, and their + /// decoder dropped desktop's null (A–Z) registers. Such a cache keeps its + /// store, so legacy edits stay locked, but loses its cursor, so the startup + /// fetch decodes the same signed head again. ({ChannelSortStore store, int createdAt, String eventId})? readWorkspace( String pubkey, String relayUrl, @@ -252,15 +259,17 @@ class ChannelSortStorage { final raw = _prefs.getString(_workspaceKey(pubkey, relayUrl)); if (raw == null) return null; try { - if (jsonDecode(raw) case { + final cache = jsonDecode(raw); + if (cache case { 'store': final Map store, 'createdAt': final int createdAt, 'eventId': final String eventId, }) { + final current = cache['cacheVersion'] == _workspaceCacheVersion; return ( store: ChannelSortStore.fromJson(store), - createdAt: createdAt, - eventId: eventId, + createdAt: current ? createdAt : 0, + eventId: current ? eventId : '', ); } } on FormatException { @@ -279,6 +288,7 @@ class ChannelSortStorage { _prefs.setString( _workspaceKey(pubkey, relayUrl), jsonEncode({ + 'cacheVersion': _workspaceCacheVersion, 'store': store.toJson(), 'createdAt': createdAt, 'eventId': eventId, @@ -286,6 +296,10 @@ class ChannelSortStorage { ); } + /// Bump when the head decoder changes what it keeps, so caches written by + /// the old decoder are rebuilt from the relay head. + static const _workspaceCacheVersion = 2; + String _workspaceKey(String pubkey, String relayUrl) => '${channelSortKey(pubkey, relayUrl)}:workspace'; diff --git a/mobile/lib/features/channels/channels_page/body.dart b/mobile/lib/features/channels/channels_page/body.dart index a3668354fa4..41b448d8da6 100644 --- a/mobile/lib/features/channels/channels_page/body.dart +++ b/mobile/lib/features/channels/channels_page/body.dart @@ -245,7 +245,7 @@ class _SliverChannelsList extends HookConsumerWidget { final filters = ref.watch(channelFilterProvider); useListenable(filters); final display = optionsKey == null - ? const MessagesDisplay() + ? const MessagesDisplay(messages: false) : ref.watch(messagesDisplayProvider); final selectedChannel = useState(null); final clock = useState(0); @@ -258,7 +258,11 @@ class _SliverChannelsList extends HookConsumerWidget { if (display.modeFor(filters?.store, group) != ChannelFilterMode.active) { continue; } - final evidence = ref.watch(channelFilterActivityProvider(id)); + final evidence = ref.watch( + display.explicitlyActive(filters?.store, group) + ? channelFilterActivityProvider(id) + : cachedChannelFilterActivityProvider(id), + ); activity[id] = evidence; // Solo uses the same evidence and handles its own row expiry. if (key == 'solo') continue; @@ -519,7 +523,7 @@ class _SliverChannelsList extends HookConsumerWidget { Widget? sectionFor(String key) { final rows = buckets[key] ?? const []; final group = sidebarGroupKey(key); - ChannelSortMode mode() => display.sort ?? sortState.sortModeFor(group); + ChannelSortMode mode() => display.sortFor(sortState.store, group); if (key == 'solo') return soloSliver; final previewLimit = display.limitFor(filters?.store, group); if (key == 'starred' || key == 'channels' || key == 'dms') { diff --git a/mobile/lib/features/channels/channels_page/filters.dart b/mobile/lib/features/channels/channels_page/filters.dart index d750d15ce69..925a0bf143c 100644 --- a/mobile/lib/features/channels/channels_page/filters.dart +++ b/mobile/lib/features/channels/channels_page/filters.dart @@ -5,14 +5,20 @@ import '../channel_sort/channel_sort_provider.dart'; import '../channel_sections/section_reorder_sheet.dart'; import '../../../shared/widgets/app_list.dart'; import '../channel_sections/channel_sections_provider.dart'; + import 'package:flutter/material.dart'; import 'package:duo_kit/duo_kit.dart'; + import '../../../shared/widgets/duo_toolbar.dart'; + import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; + import '../../../shared/theme/theme.dart'; import '../../../shared/theme/buzz_icons.dart'; + import 'package:flutter/foundation.dart'; + import '../../../shared/widgets/buzz_setting_menu.dart'; import '../../../shared/widgets/ios_glass_navigation_button.dart'; import '../../../shared/widgets/app_list_card.dart'; @@ -76,6 +82,11 @@ Future showSectionViewSheet( ValueChanged? onSort, bool custom = false, }) async { + final centralized = group == null || context.widget is MessagesSectionOptions; + final messages = + group == null || + context.widget is MessagesSectionOptions || + MessagesSectionOptions.active(context); final orderScope = context .getElementForInheritedWidgetOfExactType(); final presentingRoute = defaultTargetPlatform == TargetPlatform.iOS @@ -107,8 +118,8 @@ Future showSectionViewSheet( builder: (sheetContext) { sheetRoute = ModalRoute.of(sheetContext); return _SectionViewSheet( - centralized: - group == null || context.widget is MessagesSectionOptions, + centralized: centralized, + messages: messages, canReorder: orderScope != null, title: title, group: group, @@ -166,11 +177,13 @@ class _SectionViewSheet extends HookConsumerWidget { final ChannelSortMode? initialSort; final ValueChanged? onSort; final bool custom; + final bool messages; final MessagesDisplay? draft; final ValueChanged onCustom; const _SectionViewSheet({ required this.centralized, + required this.messages, required this.canReorder, required this.title, required this.group, @@ -187,7 +200,7 @@ class _SectionViewSheet extends HookConsumerWidget { final global = group == null; final display = global ? ref.watch(messagesDisplayProvider) - : const MessagesDisplay(); + : MessagesDisplay(messages: messages); final scope = global ? ref.watch(mobileSectionOrderKeyProvider) : null; final initialScope = useRef(scope); final manager = global @@ -219,7 +232,7 @@ class _SectionViewSheet extends HookConsumerWidget { ? draft!.mode : global ? display.mode - : manager?.store.modeFor(group) ?? ChannelFilterMode.all, + : display.modeFor(manager?.store, group), ); final count = useState( draft != null @@ -233,8 +246,7 @@ class _SectionViewSheet extends HookConsumerWidget { ? draft!.days : global ? display.days - : (manager?.store.windowFor(group) ?? defaultActiveWindowSeconds) ~/ - 86400, + : display.windowFor(manager?.store, group) ~/ 86400, ); final filterDirty = useState(draft != null); final saving = useState(false); @@ -243,10 +255,8 @@ class _SectionViewSheet extends HookConsumerWidget { useEffect(() { if (!global && !filterDirty.value && !saving.value) { count.value = manager?.store.countFor(group) ?? sectionCounts.first; - mode.value = manager?.store.modeFor(group) ?? ChannelFilterMode.all; - days.value = - (manager?.store.windowFor(group) ?? defaultActiveWindowSeconds) ~/ - 86400; + mode.value = display.modeFor(manager?.store, group); + days.value = display.windowFor(manager?.store, group) ~/ 86400; } return null; }, [manager, manager?.ready, manager?.store]); @@ -280,12 +290,12 @@ class _SectionViewSheet extends HookConsumerWidget { bool filterChanged() => !global && filterDirty.value && - (mode.value != - (manager?.store.modeFor(group) ?? ChannelFilterMode.all) || + (mode.value != (display.modeFor(manager?.store, group)) || (mode.value != ChannelFilterMode.active && count.value != manager?.store.countFor(group)) || (mode.value == ChannelFilterMode.active && - days.value! * 86400 != manager?.store.windowFor(group))); + days.value! * 86400 != + display.windowFor(manager?.store, group))); Future apply([String? nextAction]) async { saving.value = true; diff --git a/mobile/lib/features/channels/channels_page/messages_display.dart b/mobile/lib/features/channels/channels_page/messages_display.dart index 92701eba808..92476b545a3 100644 --- a/mobile/lib/features/channels/channels_page/messages_display.dart +++ b/mobile/lib/features/channels/channels_page/messages_display.dart @@ -1,30 +1,57 @@ import 'dart:convert'; + import 'package:hooks_riverpod/hooks_riverpod.dart'; + import '../../../shared/theme/theme_provider.dart'; import '../channel_sections/section_reorder_sheet.dart'; import '../channel_filter/channel_filter_store.dart'; import '../channel_sort/channel_sort_storage.dart'; class MessagesDisplay { - const MessagesDisplay({this.mode, this.count, this.days, this.sort}); + const MessagesDisplay({ + this.mode, + this.count, + this.days, + this.sort, + this.messages = true, + }); + final bool messages; final ChannelSortMode? sort; + + ChannelSortMode sortFor(ChannelSortStore store, String group) => + sort ?? + store.groups[group] ?? + (messages ? ChannelSortMode.recent : defaultSortModeFor(group)); final ChannelFilterMode? mode; final int? count; final int? days; - ChannelFilterMode modeFor(ChannelFilterStore? store, String group) => - mode ?? store?.modeFor(group) ?? ChannelFilterMode.all; + ChannelFilterMode modeFor(ChannelFilterStore? store, String group) { + final fallback = messages + ? ChannelFilterMode.active + : ChannelFilterMode.all; + return mode ?? store?.modeFor(group, fallback: fallback) ?? fallback; + } + + bool explicitlyActive(ChannelFilterStore? store, String group) => + (mode ?? store?.modeFor(group)) == ChannelFilterMode.active; int? limitFor(ChannelFilterStore? store, String group) { final n = count ?? store?.countFor(group) ?? sectionCounts.first; - return modeFor(store, group) == ChannelFilterMode.active || n == 0 - ? null - : n; + return explicitlyActive(store, group) || n == 0 ? null : n; } - int windowFor(ChannelFilterStore? store, String group) => days == null - ? store?.windowFor(group) ?? defaultActiveWindowSeconds - : days! * 86400; + int windowFor(ChannelFilterStore? store, String group) { + final fallback = + messages && + modeFor(store, group) == ChannelFilterMode.active && + !explicitlyActive(store, group) + ? 7 * 86400 + : defaultActiveWindowSeconds; + return days == null + ? store?.windowFor(group, fallback: fallback) ?? fallback + : days! * 86400; + } } class _DisplayPreferences extends Notifier { diff --git a/mobile/lib/features/channels/channels_page/section_chats.dart b/mobile/lib/features/channels/channels_page/section_chats.dart index a5dbb67adcd..958f435c85f 100644 --- a/mobile/lib/features/channels/channels_page/section_chats.dart +++ b/mobile/lib/features/channels/channels_page/section_chats.dart @@ -28,9 +28,13 @@ SectionChatContent _watchSectionChats( ) == key; }).toList(); - final sort = - (messages ? ref.watch(messagesDisplayProvider).sort : null) ?? - ref.watch(channelSortProvider).sortModeFor(sidebarGroupKey(key)); + final display = messages + ? ref.watch(messagesDisplayProvider) + : const MessagesDisplay(messages: false); + final sort = display.sortFor( + ref.watch(channelSortProvider).store, + sidebarGroupKey(key), + ); final ordered = key == 'dms' && sort == ChannelSortMode.alpha ? sortDmChannelsByDisplayLabel( rows, diff --git a/mobile/lib/features/channels/me/me_page.dart b/mobile/lib/features/channels/me/me_page.dart index 6e03800bf58..c28a88eaa6a 100644 --- a/mobile/lib/features/channels/me/me_page.dart +++ b/mobile/lib/features/channels/me/me_page.dart @@ -1,8 +1,10 @@ import '../channel_sections/section_show_more.dart'; import '../channel_stars/channel_stars_provider.dart'; import '../../../shared/widgets/native_conversation_menu.dart'; + import 'dart:async'; import 'dart:convert'; + import '../channel_filter/channel_filter_activity.dart'; import '../channel_sort/channel_sort_provider.dart'; import '../channel_sort/channel_sort_storage.dart'; @@ -465,7 +467,7 @@ class _SoloFilterSection extends HookConsumerWidget { useListenable(manager); final display = MessagesSectionOptions.active(context) ? ref.watch(messagesDisplayProvider) - : const MessagesDisplay(); + : const MessagesDisplay(messages: false); final mode = display.modeFor(manager?.store, group); final window = display.windowFor(manager?.store, group); final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; @@ -488,7 +490,13 @@ class _SoloFilterSection extends HookConsumerWidget { : chats.toList(); for (final chat in orderedChats) { final activity = mode == ChannelFilterMode.active - ? ref.watch(channelFilterActivityProvider(chat.id)).asData + ? ref + .watch( + display.explicitlyActive(manager?.store, group) + ? channelFilterActivityProvider(chat.id) + : cachedChannelFilterActivityProvider(chat.id), + ) + .asData : null; final at = activity?.value; if (at != null) { diff --git a/mobile/test/features/channels/channel_sort/channel_sort_manager_test.dart b/mobile/test/features/channels/channel_sort/channel_sort_manager_test.dart index 7b51fbe65b4..99ffe03f6c1 100644 --- a/mobile/test/features/channels/channel_sort/channel_sort_manager_test.dart +++ b/mobile/test/features/channels/channel_sort/channel_sort_manager_test.dart @@ -39,6 +39,7 @@ void main() { ChannelSortManager manager( _FakeRelaySession relay, _RecordingSignedEventRelay signed, { + void Function()? onChanged, Duration retry = const Duration(milliseconds: 5), }) => ChannelSortManager( pubkey: keys.public, @@ -48,7 +49,7 @@ void main() { relaySession: relay, signedEventRelay: signed, remoteEnabled: true, - onChanged: () {}, + onChanged: onChanged ?? () {}, startupRetryBaseDelay: retry, publishDelay: const Duration(milliseconds: 5), ); @@ -270,15 +271,26 @@ void main() { test('retries failed startup and closes fetch-subscribe gap', () async { final relay = _FakeRelaySession()..fetchFailures = 1; - final subject = manager(relay, _RecordingSignedEventRelay()); + final applied = Completer(); + late final ChannelSortManager subject; + subject = manager( + relay, + _RecordingSignedEventRelay(), + onChanged: () { + if (!applied.isCompleted && + subject.sortModeFor('starred') == ChannelSortMode.recent) { + applied.complete(); + } + }, + ); + addTearDown(subject.dispose); await subject.initialize(); relay.historyEvents = [ event({'starred': 'recent'}, 300), ]; - await Future.delayed(const Duration(milliseconds: 40)); + await applied.future.timeout(const Duration(seconds: 5)); expect(subject.sortModeFor('starred'), ChannelSortMode.recent); expect(relay.fetchCount, greaterThanOrEqualTo(3)); - subject.dispose(); }); test('setSortModeFor prunes deleted custom section keys', () async { diff --git a/mobile/test/features/channels/channels_page_test.dart b/mobile/test/features/channels/channels_page_test.dart index a48a2e2b42d..ef4d5ad483f 100644 --- a/mobile/test/features/channels/channels_page_test.dart +++ b/mobile/test/features/channels/channels_page_test.dart @@ -472,6 +472,14 @@ void main() { buildTestable( realHome: true, overrides: [ + channelFilterProvider.overrideWithValue( + _filterTestManager( + cached: ChannelFilterStore.empty().edit( + 'channels', + ChannelFilterMode.all, + ), + ), + ), channelsProvider.overrideWith(() => _FakeNotifier(channels)), ], ), diff --git a/mobile/test/features/channels/messages_display_test.dart b/mobile/test/features/channels/messages_display_test.dart index 692d53dc0ad..def71ca3293 100644 --- a/mobile/test/features/channels/messages_display_test.dart +++ b/mobile/test/features/channels/messages_display_test.dart @@ -9,6 +9,41 @@ import 'package:shared_preferences/shared_preferences.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); + test('inherited Active caps previews without requesting gap recovery', () { + const display = MessagesDisplay(); + final saved = ChannelFilterStore.parse({ + 'version': 1, + 'groups': {'channels': 'active'}, + }); + expect(display.windowFor(saved, 'channels'), 30 * 86400); + expect(display.explicitlyActive(saved, 'channels'), isTrue); + expect(display.limitFor(saved, 'channels'), isNull); + expect(display.explicitlyActive(saved, 'dms'), isFalse); + expect(display.limitFor(saved, 'dms'), 5); + expect(const MessagesDisplay(count: 15).limitFor(saved, 'dms'), 15); + expect(display.windowFor(saved, 'dms'), 7 * 86400); + }); + + test('a desktop sort reset survives a local cache round trip', () { + final saved = ChannelSortStore.fromWorkspaceJson({ + 'meta': { + 'v': 1, + 'g': { + 'channels': [123, 'device', null], + }, + }, + }); + final cached = ChannelSortStore.fromJson(saved.toJson()); + expect( + const MessagesDisplay().sortFor(cached, 'channels'), + ChannelSortMode.alpha, + ); + expect( + const MessagesDisplay().sortFor(cached, 'dms'), + ChannelSortMode.recent, + ); + }); + test( 'section defaults survive upgrade and overrides reopen in their own scope', () async { @@ -35,6 +70,32 @@ void main() { expect(inherited.modeFor(store, 'channels'), ChannelFilterMode.unreads); expect(inherited.limitFor(store, 'channels'), 15); expect(inherited.sort, isNull); + expect(inherited.modeFor(store, 'dms'), ChannelFilterMode.active); + expect(inherited.windowFor(store, 'dms'), 7 * 86400); + expect( + inherited.sortFor(const ChannelSortStore(), 'dms'), + ChannelSortMode.recent, + ); + final saved = store.edit('dms', ChannelFilterMode.all); + expect(inherited.modeFor(saved, 'dms'), ChannelFilterMode.all); + expect( + inherited.sortFor( + const ChannelSortStore(groups: {'dms': ChannelSortMode.alpha}), + 'dms', + ), + ChannelSortMode.alpha, + ); + expect( + inherited.windowFor( + saved.edit( + 'dms', + ChannelFilterMode.active, + windowSeconds: 30 * 86400, + ), + 'dms', + ), + 30 * 86400, + ); await first .read(messagesDisplayProvider.notifier) .update( diff --git a/mobile/test/features/channels/unified_sidebar_records_test.dart b/mobile/test/features/channels/unified_sidebar_records_test.dart index 63c90a89c53..5c5ec622a19 100644 --- a/mobile/test/features/channels/unified_sidebar_records_test.dart +++ b/mobile/test/features/channels/unified_sidebar_records_test.dart @@ -1,6 +1,9 @@ +import 'dart:convert'; + import 'package:buzz/features/channels/channel_sections/channel_sections_manager.dart'; import 'package:buzz/features/channels/channel_sort/channel_sort_manager.dart'; import 'package:buzz/features/channels/channel_sort/channel_sort_storage.dart'; +import 'package:buzz/features/channels/channels_page/messages_display.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -246,4 +249,52 @@ void main() { expect(relay.published, isEmpty); }); } + + // Builds before the null-register fix cached desktop's A–Z reset as an + // empty store, next to that head's cursor. + fakeAsyncTest('an upgraded cache re-reads desktop A–Z from the same head', ( + clock, + ) { + final relay = SidebarRelay(); + final head = relay.event('channel-workspace-sort', { + 'version': 1, + 'groups': {}, + 'meta': { + 'v': 1, + 'g': { + 'channels': [123, 'device', null], + }, + }, + }, nowSeconds()); + relay.stored.add(head); + prefs.setString( + '${channelSortKey(relay.pubkey, 'wss://relay.example')}:workspace', + jsonEncode({ + 'store': const ChannelSortStore().toJson(), + 'createdAt': head.createdAt, + 'eventId': head.id, + }), + ); + final m = ChannelSortManager( + pubkey: relay.pubkey, + relayUrl: 'wss://relay.example', + prefs: prefs, + crypto: ChannelSortCrypto(relay.keys.nsec, relay.pubkey), + relaySession: relay.session, + signedEventRelay: relay.signer, + remoteEnabled: true, + onChanged: () {}, + ); + expect(m.editable, isFalse); + m.initialize(); + clock.flushMicrotasks(); + + expect( + const MessagesDisplay().sortFor(m.store, 'channels'), + ChannelSortMode.alpha, + ); + expect(relay.published, isEmpty); + m.dispose(); + clock.flushMicrotasks(); + }); }