The personal finance app for everyone (by everyone)
Ruby
fix(mobile): load every page of the chat list, not just the first 20 (#4741)
alexcastgonzab7a902f92fb
diff --git a/mobile/lib/l10n/app_en.arb b/mobile/lib/l10n/app_en.arbindex 15a14a72ca..29cae5ca5e 100644--- a/mobile/lib/l10n/app_en.arb+++ b/mobile/lib/l10n/app_en.arb@@ -679,6 +679,8 @@"chatListDeleteFailed": "Failed to delete chats","@chatListDeleteFailed": { "description": "Snackbar shown when deleting multiple chats fails." },+ "chatListIncomplete": "Some chats may be missing. The list didn't finish loading.",+ "@chatListIncomplete": { "description": "Banner on the chat list screen when some pages of chats failed to load." },"chatListError": "Failed to load chats","@chatListError": { "description": "Error-state heading on the chat list screen." },diff --git a/mobile/lib/l10n/app_localizations.dart b/mobile/lib/l10n/app_localizations.dartindex 4ddad5a096..ca7453cf46 100644--- a/mobile/lib/l10n/app_localizations.dart+++ b/mobile/lib/l10n/app_localizations.dart@@ -1388,6 +1388,12 @@ abstract class AppLocalizations {/// **'Failed to delete chats'**String get chatListDeleteFailed;+ /// Banner on the chat list screen when some pages of chats failed to load.+ ///+ /// In en, this message translates to:+ /// **'Some chats may be missing. The list didn\'t finish loading.'**+ String get chatListIncomplete;+/// Error-state heading on the chat list screen.////// In en, this message translates to:diff --git a/mobile/lib/l10n/app_localizations_en.dart b/mobile/lib/l10n/app_localizations_en.dartindex fcfa4c938d..923e79d0c2 100644--- a/mobile/lib/l10n/app_localizations_en.dart+++ b/mobile/lib/l10n/app_localizations_en.dart@@ -724,6 +724,10 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get chatListDeleteFailed => 'Failed to delete chats';+ @override+ String get chatListIncomplete =>+ 'Some chats may be missing. The list didn\'t finish loading.';+@overrideString get chatListError => 'Failed to load chats';diff --git a/mobile/lib/l10n/app_localizations_sv.dart b/mobile/lib/l10n/app_localizations_sv.dartindex 5bd2667ee8..1c3942acbe 100644--- a/mobile/lib/l10n/app_localizations_sv.dart+++ b/mobile/lib/l10n/app_localizations_sv.dart@@ -735,6 +735,10 @@ class AppLocalizationsSv extends AppLocalizations {@overrideString get chatListDeleteFailed => 'Det gick inte att radera chattarna';+ @override+ String get chatListIncomplete =>+ 'Vissa chattar kan saknas. Listan lästes inte in helt.';+@overrideString get chatListError => 'Det gick inte att läsa in chattar';diff --git a/mobile/lib/l10n/app_sv.arb b/mobile/lib/l10n/app_sv.arbindex 28f7ea451b..6466d40555 100644--- a/mobile/lib/l10n/app_sv.arb+++ b/mobile/lib/l10n/app_sv.arb@@ -215,6 +215,7 @@"chatListDeleteMultiContent": "{count, plural, one{Radera {count} chatt? Det går inte att ångra.} other{Radera {count} chattar? Det går inte att ångra.}}","chatListDeletedSuccess": "Chattarna har raderats","chatListDeleteFailed": "Det gick inte att radera chattarna",+ "chatListIncomplete": "Vissa chattar kan saknas. Listan lästes inte in helt.","chatListError": "Det gick inte att läsa in chattar","chatListJustNow": "Nyss","chatListDeleteSingleContent": "Vill du verkligen radera \"{title}\"?",diff --git a/mobile/lib/providers/chat_provider.dart b/mobile/lib/providers/chat_provider.dartindex 097af799f7..2445576d52 100644--- a/mobile/lib/providers/chat_provider.dart+++ b/mobile/lib/providers/chat_provider.dart@@ -38,6 +38,11 @@ class ChatProvider with ChangeNotifier {/// to avoid prematurely stopping on a brief server-side generation pause.int _stablePollingCount = 0;+ /// Ids deleted while a chat-list fetch was awaiting later pages; null when+ /// no fetch is running. Lets the fetch drop chats the user removed meanwhile+ /// instead of restoring them from a stale page.+ final List<Set<String>> _deletedDuringChatListFetches = [];+List<Chat> get chats => _chats;Chat? get currentChat => _currentChat;bool get isLoading => _isLoading;@@ -52,6 +57,12 @@ class ChatProvider with ChangeNotifier {bool _hasIncompleteHistory = false;bool get hasIncompleteHistory => _hasIncompleteHistory;+ /// True when the chat list on screen may be missing chats: a later page+ /// failed to load, or the server reported more pages than we follow. The+ /// UI can offer a retry without treating it as a hard error.+ bool _hasIncompleteChatList = false;+ bool get hasIncompleteChatList => _hasIncompleteChatList;+/// Fetch list of chatsFuture<void> fetchChats({required String accessToken,@@ -61,6 +72,8 @@ class ChatProvider with ChangeNotifier {_isLoading = true;_errorMessage = null;notifyListeners();+ final deletedDuringFetch = <String>{};+ _deletedDuringChatListFetches.add(deletedDuringFetch);try {final result = await _chatService.getChats(@@ -70,7 +83,21 @@ class ChatProvider with ChangeNotifier {);if (result['success'] == true) {- _chats = result['chats'] as List<Chat>;+ final loaded = await _loadRemainingChatPages(+ accessToken: accessToken,+ perPage: perPage,+ page: page,+ firstPage: result,+ );+ _hasIncompleteChatList = !loaded.complete;+ // A failed later page returns null chats: keep the list already on+ // screen rather than replacing it with a truncated one.+ if (loaded.chats != null) {+ final deleted = deletedDuringFetch;+ _chats = deleted.isEmpty+ ? loaded.chats!+ : loaded.chats!.where((c) => !deleted.contains(c.id)).toList();+ }_errorMessage = null;} else {_errorMessage = result['error'] ?? 'Failed to fetch chats';@@ -79,11 +106,53 @@ class ChatProvider with ChangeNotifier {_log.warning('ChatProvider', 'fetchChats failed: ${e.runtimeType}');_errorMessage = 'Something went wrong. Please try again.';} finally {+ _deletedDuringChatListFetches.remove(deletedDuringFetch);_isLoading = false;notifyListeners();}}+ /// Upper bound on chat-list pages followed in one refresh, so a bogus+ /// `total_pages` from the server cannot trigger an unbounded request loop.+ static const _maxChatListPages = 100;++ /// Fetches the pages after [firstPage] (the response for [page]) of the chat+ /// list and returns all chats. The API paginates `/chats`, so without this+ /// only the first page would ever be shown. If a later page fails, returns+ /// the pages loaded so far when nothing is shown yet, and null chats otherwise+ /// so the caller keeps the list it already has. `complete` is false when a+ /// page failed or the page cap truncated the list.+ Future<({List<Chat>? chats, bool complete})> _loadRemainingChatPages({+ required String accessToken,+ required int perPage,+ required int page,+ required Map<String, dynamic> firstPage,+ }) async {+ final chats = <Chat>[...(firstPage['chats'] as List<Chat>)];+ final pagination = firstPage['pagination'] as Map<String, dynamic>?;+ final totalPages = (pagination?['total_pages'] as int?) ?? 1;+ final lastPage = totalPages < _maxChatListPages ? totalPages : _maxChatListPages;+ final seen = chats.map((c) => c.id).toSet();++ for (var next = page + 1; next <= lastPage; next++) {+ final pageResult = await _chatService.getChats(+ accessToken: accessToken,+ page: next,+ perPage: perPage,+ );++ if (pageResult['success'] != true) {+ _log.warning('ChatProvider', 'fetchChats page $next failed; stopping');+ return (chats: _chats.isEmpty ? chats : null, complete: false);+ }+ for (final chat in pageResult['chats'] as List<Chat>) {+ if (seen.add(chat.id)) chats.add(chat);+ }+ }++ return (chats: chats, complete: totalPages <= lastPage);+ }+/// Fetch a specific chat with messagesFuture<void> fetchChat({required String accessToken,@@ -379,6 +448,9 @@ class ChatProvider with ChangeNotifier {if (result['success'] == true) {_chats.removeWhere((c) => c.id == chatId);+ for (final s in _deletedDuringChatListFetches) {+ s.add(chatId);+ }if (_currentChat != null && _currentChat!.id == chatId) {_currentChat = null;@@ -416,6 +488,9 @@ class ChatProvider with ChangeNotifier {((result['failedIds'] as List?) ?? []).cast<String>().toSet();final deleted = chatIds.toSet().difference(failedIds);_chats.removeWhere((c) => deleted.contains(c.id));+ for (final s in _deletedDuringChatListFetches) {+ s.addAll(deleted);+ }if (_currentChat != null && deleted.contains(_currentChat!.id)) {_currentChat = null;diff --git a/mobile/lib/screens/chat_list_screen.dart b/mobile/lib/screens/chat_list_screen.dartindex 4262554b7a..9ea53687f0 100644--- a/mobile/lib/screens/chat_list_screen.dart+++ b/mobile/lib/screens/chat_list_screen.dart@@ -275,7 +275,7 @@ class _ChatListScreenState extends State<ChatListScreen> {);}- return RefreshIndicator(+ final chatListView = RefreshIndicator(onRefresh: _handleRefresh,child: ListView.builder(padding: const EdgeInsets.symmetric(vertical: 8),@@ -393,6 +393,22 @@ class _ChatListScreenState extends State<ChatListScreen> {},),);++ if (!chatProvider.hasIncompleteChatList) return chatListView;+ return Column(+ children: [+ MaterialBanner(+ content: Text(l.chatListIncomplete),+ actions: [+ TextButton(+ onPressed: _handleRefresh,+ child: Text(l.commonTryAgain),+ ),+ ],+ ),+ Expanded(child: chatListView),+ ],+ );},),floatingActionButton: FloatingActionButton(diff --git a/mobile/test/providers/chat_provider_test.dart b/mobile/test/providers/chat_provider_test.dartindex 41c24988f3..4e06a466ce 100644--- a/mobile/test/providers/chat_provider_test.dart+++ b/mobile/test/providers/chat_provider_test.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:convert';import 'package:flutter_test/flutter_test.dart';@@ -38,7 +39,224 @@ http.Response _chatPage({);}+http.Response _chatListPage({+ required int page,+ required int totalPages,+ required List<int> chatIds,+}) {+ return http.Response(+ jsonEncode({+ 'chats': chatIds+ .map((id) => {+ 'id': 'chat_$id',+ 'title': 'Chat $id',+ 'created_at': '2026-06-01T00:00:00Z',+ 'updated_at': '2026-06-01T00:00:00Z',+ })+ .toList(),+ 'pagination': {+ 'page': page,+ 'per_page': 20,+ 'total_count': 5,+ 'total_pages': totalPages,+ },+ }),+ 200,+ );+}+void main() {+ group('ChatProvider.fetchChats pagination', () {+ test('loads every page of the chat list', () async {+ final requestedPages = <String>[];+ final client = MockClient((request) async {+ expect(request.url.path, '/api/v1/chats');+ final page = request.url.queryParameters['page'] ?? '1';+ requestedPages.add(page);+ switch (page) {+ case '1':+ return _chatListPage(page: 1, totalPages: 3, chatIds: [1, 2]);+ case '2':+ return _chatListPage(page: 2, totalPages: 3, chatIds: [2, 3, 4]);+ case '3':+ return _chatListPage(page: 3, totalPages: 3, chatIds: [5]);+ default:+ return http.Response('{"error":"unexpected page"}', 500);+ }+ });++ final provider = ChatProvider(chatService: ChatService(client: client));+ await provider.fetchChats(accessToken: 'token');++ expect(requestedPages, ['1', '2', '3']);+ expect(provider.chats.map((c) => c.id).toList(),+ ['chat_1', 'chat_2', 'chat_3', 'chat_4', 'chat_5']);+ expect(provider.errorMessage, isNull);+ expect(provider.hasIncompleteChatList, isFalse);+ });++ test('flags the list as incomplete when a later page fails, and clears it on a full refresh', () async {+ var failPageTwo = true;+ final client = MockClient((request) async {+ final page = request.url.queryParameters['page'] ?? '1';+ if (page == '1') {+ return _chatListPage(page: 1, totalPages: 2, chatIds: [1, 2]);+ }+ if (failPageTwo) return http.Response('{"error":"boom"}', 500);+ return _chatListPage(page: 2, totalPages: 2, chatIds: [3]);+ });++ final provider = ChatProvider(chatService: ChatService(client: client));+ await provider.fetchChats(accessToken: 'token');+ expect(provider.hasIncompleteChatList, isTrue);++ failPageTwo = false;+ await provider.fetchChats(accessToken: 'token');+ expect(provider.hasIncompleteChatList, isFalse);+ expect(provider.chats.length, 3);+ });++ test('flags the list as incomplete when the page cap truncates it', () async {+ final requested = <String>[];+ final client = MockClient((request) async {+ final page = request.url.queryParameters['page'] ?? '1';+ requested.add(page);+ return _chatListPage(+ page: int.parse(page), totalPages: 150, chatIds: [int.parse(page)]);+ });++ final provider = ChatProvider(chatService: ChatService(client: client));+ await provider.fetchChats(accessToken: 'token');++ expect(requested.length, 100);+ expect(provider.hasIncompleteChatList, isTrue);+ });++ test('keeps the pages already loaded when a later page fails', () async {+ final client = MockClient((request) async {+ final page = request.url.queryParameters['page'] ?? '1';+ if (page == '1') {+ return _chatListPage(page: 1, totalPages: 2, chatIds: [1, 2]);+ }+ return http.Response('{"error":"not_found"}', 404);+ });++ final provider = ChatProvider(chatService: ChatService(client: client));+ await provider.fetchChats(accessToken: 'token');++ expect(provider.chats.map((c) => c.id).toList(), ['chat_1', 'chat_2']);+ });++ test('keeps the list already shown when a later page fails on refresh',+ () async {+ var failPageTwo = false;+ final client = MockClient((request) async {+ final page = request.url.queryParameters['page'] ?? '1';+ switch (page) {+ case '1':+ return _chatListPage(page: 1, totalPages: 2, chatIds: [1, 2]);+ case '2':+ if (failPageTwo) return http.Response('{"error":"boom"}', 500);+ return _chatListPage(page: 2, totalPages: 2, chatIds: [3]);+ default:+ return http.Response('{"error":"unexpected page"}', 500);+ }+ });++ final provider = ChatProvider(chatService: ChatService(client: client));+ await provider.fetchChats(accessToken: 'token');+ expect(provider.chats.map((c) => c.id).toList(),+ ['chat_1', 'chat_2', 'chat_3']);++ failPageTwo = true;+ await provider.fetchChats(accessToken: 'token');++ expect(provider.chats.map((c) => c.id).toList(),+ ['chat_1', 'chat_2', 'chat_3']);+ });++ test('continues after the requested page instead of restarting at page 2',+ () async {+ final requestedPages = <String>[];+ final client = MockClient((request) async {+ final page = request.url.queryParameters['page'] ?? '1';+ requestedPages.add(page);+ switch (page) {+ case '3':+ return _chatListPage(page: 3, totalPages: 4, chatIds: [5]);+ case '4':+ return _chatListPage(page: 4, totalPages: 4, chatIds: [6]);+ default:+ return http.Response('{"error":"unexpected page"}', 500);+ }+ });++ final provider = ChatProvider(chatService: ChatService(client: client));+ await provider.fetchChats(accessToken: 'token', page: 3);++ expect(requestedPages, ['3', '4']);+ expect(provider.chats.map((c) => c.id).toList(), ['chat_5', 'chat_6']);+ });++ test('does not restore a chat deleted while later pages were loading',+ () async {+ final pageTwo = Completer<http.Response>();+ final client = MockClient((request) async {+ if (request.method == 'DELETE') return http.Response('', 204);+ final page = request.url.queryParameters['page'] ?? '1';+ switch (page) {+ case '1':+ return _chatListPage(page: 1, totalPages: 2, chatIds: [1, 2]);+ case '2':+ return pageTwo.future;+ default:+ return http.Response('{"error":"unexpected page"}', 500);+ }+ });++ final provider = ChatProvider(chatService: ChatService(client: client));+ final fetch = provider.fetchChats(accessToken: 'token');+ await Future<void>.delayed(Duration.zero);+ await Future<void>.delayed(Duration.zero);++ await provider.deleteChat(accessToken: 'token', chatId: 'chat_2');+ pageTwo.complete(+ _chatListPage(page: 2, totalPages: 2, chatIds: [3]));+ await fetch;++ expect(provider.chats.map((c) => c.id).toList(), ['chat_1', 'chat_3']);+ });++ test('overlapping refreshes both finish without error', () async {+ final pageTwo = <Completer<http.Response>>[];+ final client = MockClient((request) async {+ final page = request.url.queryParameters['page'] ?? '1';+ if (page == '1') {+ return _chatListPage(page: 1, totalPages: 2, chatIds: [1]);+ }+ final c = Completer<http.Response>();+ pageTwo.add(c);+ return c.future;+ });++ final provider = ChatProvider(chatService: ChatService(client: client));+ final first = provider.fetchChats(accessToken: 'token');+ final second = provider.fetchChats(accessToken: 'token');+ for (var i = 0; i < 5; i++) {+ await Future<void>.delayed(Duration.zero);+ }+ expect(pageTwo.length, 2);++ pageTwo[0].complete(_chatListPage(page: 2, totalPages: 2, chatIds: [2]));+ await first;+ pageTwo[1].complete(_chatListPage(page: 2, totalPages: 2, chatIds: [2]));+ await second;++ expect(provider.errorMessage, isNull);+ expect(provider.chats.map((c) => c.id).toList(), ['chat_1', 'chat_2']);+ });+ });+group('ChatProvider.fetchChat pagination', () {test('merges every page so older and newer messages both surface', () async {final requestedPages = <String>[];