Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(mobile): load full chat history across all pages (#4421)

Tristan the Katana9b0ba900d4ac
diff --git a/mobile/lib/providers/chat_provider.dart b/mobile/lib/providers/chat_provider.dart
index 6fc02e715f..097af799f7 100644
--- a/mobile/lib/providers/chat_provider.dart
+++ b/mobile/lib/providers/chat_provider.dart
@@ -6,7 +6,15 @@ import '../services/chat_service.dart';
import '../services/log_service.dart';
class ChatProvider with ChangeNotifier {
- final ChatService _chatService = ChatService();
+ ChatProvider({ChatService? chatService})
+ : _chatService = chatService ?? ChatService(),
+ _ownsChatService = chatService == null;
+
+ final ChatService _chatService;
+
+ /// Whether this provider created [_chatService] itself. An injected service
+ /// is owned by the caller and must not be closed on dispose.
+ final bool _ownsChatService;
final LogService _log = LogService.instance;
List<Chat> _chats = [];
@@ -38,6 +46,12 @@ class ChatProvider with ChangeNotifier {
bool get isPolling => _pollingTimer != null;
String? get errorMessage => _errorMessage;
+ /// True when the current chat could not load all of its message pages, so the
+ /// rendered history is a partial, older slice. The UI can surface a
+ /// "load more"/retry affordance without treating it as a hard error.
+ bool _hasIncompleteHistory = false;
+ bool get hasIncompleteHistory => _hasIncompleteHistory;
+
/// Fetch list of chats
Future<void> fetchChats({
required String accessToken,
@@ -90,7 +104,13 @@ class ChatProvider with ChangeNotifier {
);
if (result['success'] == true) {
- _currentChat = result['chat'] as Chat;
+ final loaded = await _loadRemainingPages(
+ accessToken: accessToken,
+ chatId: chatId,
+ firstPage: result,
+ );
+ _currentChat = loaded.chat;
+ _hasIncompleteHistory = !loaded.complete;
_errorMessage = null;
} else {
_errorMessage = result['error'] ?? 'Failed to fetch chat';
@@ -104,6 +124,63 @@ class ChatProvider with ChangeNotifier {
}
}
+ /// Fetches every remaining page of a chat's messages and merges them into a
+ /// single Chat. The API orders messages oldest-first and paginates them, so
+ /// [firstPage] only holds the oldest slice — without this, newer messages are
+ /// silently dropped once a conversation exceeds one page.
+ ///
+ /// Pages are appended in ascending order to preserve chronology, and messages
+ /// are de-duped by id so an overlapping or locally-injected message can't
+ /// render twice.
+ ///
+ /// Returns the merged chat along with [complete], which is false when one or
+ /// more later pages failed to load so callers can flag a partial history.
+ Future<({Chat chat, bool complete})> _loadRemainingPages({
+ required String accessToken,
+ required String chatId,
+ required Map<String, dynamic> firstPage,
+ }) async {
+ final chat = firstPage['chat'] as Chat;
+ final pagination = firstPage['pagination'] as Map<String, dynamic>?;
+ final totalPages = (pagination?['total_pages'] as int?) ?? 1;
+
+ if (totalPages <= 1) return (chat: chat, complete: true);
+
+ final allMessages = <Message>[...chat.messages];
+ var complete = true;
+
+ for (var page = 2; page <= totalPages; page++) {
+ final pageResult = await _chatService.getChat(
+ accessToken: accessToken,
+ chatId: chatId,
+ page: page,
+ );
+
+ if (pageResult['success'] == true) {
+ allMessages.addAll((pageResult['chat'] as Chat).messages);
+ } else {
+ // Partial failure: keep the pages we have rather than losing the chat
+ // entirely. The user sees a truncated-but-chronological history, and
+ // [complete] lets callers surface that it's incomplete.
+ _log.warning('ChatProvider', 'fetchChat page $page failed; stopping');
+ complete = false;
+ break;
+ }
+ }
+
+ return (chat: chat.copyWith(messages: _dedupeById(allMessages)), complete: complete);
+ }
+
+ /// Returns the messages with duplicate ids removed, preserving first-seen order.
+ List<Message> _dedupeById(List<Message> messages) {
+ final seen = <String>{};
+ final deduped = <Message>[];
+ for (final message in messages) {
+ if (seen.add(message.id)) deduped.add(message);
+ }
+ return deduped;
+ }
+
/// Create a new chat
Future<Chat?> createChat({
required String accessToken,
@@ -402,7 +479,17 @@ class ChatProvider with ChangeNotifier {
);
if (result['success'] == true) {
- final updatedChat = result['chat'] as Chat;
+ // Load every page before comparing. A long chat spans multiple server
+ // pages, and the newest assistant reply lands on the last page — so a
+ // page-1-only poll would never see it and its count/stability checks
+ // would compare against a stale slice of the full history.
+ final loaded = await _loadRemainingPages(
+ accessToken: accessToken,
+ chatId: chatId,
+ firstPage: result,
+ );
+ final updatedChat = loaded.chat;
+ _hasIncompleteHistory = !loaded.complete;
if (_currentChat == null || _currentChat!.id != chatId) return;
@@ -505,6 +592,7 @@ class ChatProvider with ChangeNotifier {
@override
void dispose() {
_stopPolling();
+ if (_ownsChatService) _chatService.close();
super.dispose();
}
}
diff --git a/mobile/lib/services/chat_service.dart b/mobile/lib/services/chat_service.dart
index 37b927f4ca..c13f89212b 100644
--- a/mobile/lib/services/chat_service.dart
+++ b/mobile/lib/services/chat_service.dart
@@ -5,6 +5,21 @@ import '../models/message.dart';
import 'api_config.dart';
class ChatService {
+ ChatService({http.Client? client})
+ : _client = client ?? http.Client(),
+ _ownsClient = client == null;
+
+ final http.Client _client;
+
+ /// Whether this service created [_client] itself. Injected clients stay the
+ /// caller's responsibility and must not be closed here.
+ final bool _ownsClient;
+
+ /// Closes the underlying HTTP client, but only when this service created it.
+ void close() {
+ if (_ownsClient) _client.close();
+ }
+
/// Get list of chats with pagination
Future<Map<String, dynamic>> getChats({
required String accessToken,
@@ -16,7 +31,7 @@ class ChatService {
'${ApiConfig.baseUrl}/api/v1/chats?page=$page&per_page=$perPage',
);
- final response = await http.get(
+ final response = await _client.get(
url,
headers: ApiConfig.getAuthHeaders(accessToken),
).timeout(const Duration(seconds: 30));
@@ -73,7 +88,7 @@ class ChatService {
'${ApiConfig.baseUrl}/api/v1/chats/$chatId?page=$page&per_page=$perPage',
);
- final response = await http.get(
+ final response = await _client.get(
url,
headers: ApiConfig.getAuthHeaders(accessToken),
).timeout(const Duration(seconds: 30));
@@ -85,6 +100,10 @@ class ChatService {
return {
'success': true,
'chat': chat,
+ // Expose pagination so callers can fetch the remaining pages.
+ // The API orders messages oldest-first and paginates them, so a
+ // single request only returns one page of a long conversation.
+ 'pagination': responseData['pagination'],
};
} else if (response.statusCode == 401) {
return {
@@ -132,7 +151,7 @@ class ChatService {
body['message'] = initialMessage;
}
- final response = await http.post(
+ final response = await _client.post(
url,
headers: {
...ApiConfig.getAuthHeaders(accessToken),
@@ -186,7 +205,7 @@ class ChatService {
try {
final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/chats/$chatId/messages');
- final response = await http.post(
+ final response = await _client.post(
url,
headers: {
...ApiConfig.getAuthHeaders(accessToken),
@@ -241,7 +260,7 @@ class ChatService {
try {
final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/chats/$chatId');
- final response = await http.patch(
+ final response = await _client.patch(
url,
headers: {
...ApiConfig.getAuthHeaders(accessToken),
@@ -295,7 +314,7 @@ class ChatService {
try {
final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/chats/$chatId');
- final response = await http.delete(
+ final response = await _client.delete(
url,
headers: ApiConfig.getAuthHeaders(accessToken),
).timeout(const Duration(seconds: 30));
@@ -367,7 +386,7 @@ class ChatService {
try {
final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/chats/$chatId/messages/retry');
- final response = await http.post(
+ final response = await _client.post(
url,
headers: ApiConfig.getAuthHeaders(accessToken),
).timeout(const Duration(seconds: 30));
diff --git a/mobile/test/providers/chat_provider_test.dart b/mobile/test/providers/chat_provider_test.dart
new file mode 100644
index 0000000000..41c24988f3
--- /dev/null
+++ b/mobile/test/providers/chat_provider_test.dart
@@ -0,0 +1,119 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as http;
+import 'package:http/testing.dart';
+import 'package:sure_mobile/providers/chat_provider.dart';
+import 'package:sure_mobile/services/chat_service.dart';
+
+String _message(int id) => jsonEncode({
+ 'id': '$id',
+ 'type': 'UserMessage',
+ 'role': 'user',
+ 'content': 'message $id',
+ 'created_at': '2026-06-01T00:00:0$id' 'Z',
+ 'updated_at': '2026-06-01T00:00:0$id' 'Z',
+ });
+
+http.Response _chatPage({
+ required int page,
+ required int totalPages,
+ required List<int> messageIds,
+}) {
+ return http.Response(
+ jsonEncode({
+ 'id': 'chat_1',
+ 'title': 'Test chat',
+ 'created_at': '2026-06-01T00:00:00Z',
+ 'updated_at': '2026-06-01T00:00:00Z',
+ 'messages': messageIds.map((id) => jsonDecode(_message(id))).toList(),
+ 'pagination': {
+ 'page': page,
+ 'per_page': 50,
+ 'total_count': 4,
+ 'total_pages': totalPages,
+ },
+ }),
+ 200,
+ );
+}
+
+void main() {
+ group('ChatProvider.fetchChat pagination', () {
+ test('merges every page so older and newer messages both surface', () async {
+ final requestedPages = <String>[];
+
+ final client = MockClient((request) async {
+ expect(request.url.path, '/api/v1/chats/chat_1');
+ final page = request.url.queryParameters['page'] ?? '1';
+ requestedPages.add(page);
+
+ switch (page) {
+ case '1':
+ // Oldest slice — all the app used to render.
+ return _chatPage(page: 1, totalPages: 2, messageIds: [1, 2]);
+ case '2':
+ // Newest slice — previously dropped on mobile.
+ return _chatPage(page: 2, totalPages: 2, messageIds: [3, 4]);
+ default:
+ return http.Response('{"error":"unexpected page"}', 500);
+ }
+ });
+
+ final provider = ChatProvider(chatService: ChatService(client: client));
+
+ await provider.fetchChat(accessToken: 'token', chatId: 'chat_1');
+
+ final messages = provider.currentChat!.messages;
+ expect(requestedPages, ['1', '2']);
+ expect(messages.map((m) => m.id).toList(), ['1', '2', '3', '4']);
+ expect(provider.hasIncompleteHistory, isFalse);
+ });
+
+ test('de-dupes messages that overlap across pages', () async {
+ final client = MockClient((request) async {
+ final page = request.url.queryParameters['page'] ?? '1';
+ switch (page) {
+ case '1':
+ return _chatPage(page: 1, totalPages: 2, messageIds: [1, 2]);
+ case '2':
+ // id 2 overlaps with page 1 and must not render twice.
+ return _chatPage(page: 2, totalPages: 2, messageIds: [2, 3]);
+ default:
+ return http.Response('{"error":"unexpected page"}', 500);
+ }
+ });
+
+ final provider = ChatProvider(chatService: ChatService(client: client));
+
+ await provider.fetchChat(accessToken: 'token', chatId: 'chat_1');
+
+ expect(
+ provider.currentChat!.messages.map((m) => m.id).toList(),
+ ['1', '2', '3'],
+ );
+ });
+
+ test('keeps partial history when a later page fails', () async {
+ final client = MockClient((request) async {
+ final page = request.url.queryParameters['page'] ?? '1';
+ if (page == '1') {
+ return _chatPage(page: 1, totalPages: 2, messageIds: [1, 2]);
+ }
+ return http.Response('{"error":"not_found"}', 404);
+ });
+
+ final provider = ChatProvider(chatService: ChatService(client: client));
+
+ await provider.fetchChat(accessToken: 'token', chatId: 'chat_1');
+
+ // Page 2 failed, but the chat is still usable with page 1's messages.
+ expect(
+ provider.currentChat!.messages.map((m) => m.id).toList(),
+ ['1', '2'],
+ );
+ // ...and the provider flags that the history is incomplete.
+ expect(provider.hasIncompleteHistory, isTrue);
+ });
+ });
+}