diff --git a/lib/features/search/email/domain/model/search_email_result.dart b/lib/features/search/email/domain/model/search_email_result.dart index 4aed36d4d..47028fbbf 100644 --- a/lib/features/search/email/domain/model/search_email_result.dart +++ b/lib/features/search/email/domain/model/search_email_result.dart @@ -9,20 +9,24 @@ enum LoadMoreState { idle, inProgress, failure } /// load-more lifecycle. Replaces the scattered `emailList` + `canLoadMore` /// booleans previously held separately in the controllers. See ADR-0093. class SearchEmailResult with EquatableMixin { - static const Object _keepLoadMoreException = Object(); + /// Sentinel letting `copyWith` tell "keep the current exception" apart from an + /// explicit `null` (clear it), since `null` is a valid value for the field. + static const Object _keepPendingException = Object(); final List emails; final bool canLoadMore; final LoadMoreState loadMore; - /// Transient load-more failure for urgent routing. - final Object? loadMoreException; + /// Transient failure from a background op (load-more or refresh) that preserves + /// the list, carried for the controller to route (ADR-0103) and cleared on the + /// next operation. + final Object? pendingUrgentException; const SearchEmailResult({ required this.emails, required this.canLoadMore, this.loadMore = LoadMoreState.idle, - this.loadMoreException, + this.pendingUrgentException, }); factory SearchEmailResult.empty() => @@ -32,15 +36,16 @@ class SearchEmailResult with EquatableMixin { List? emails, bool? canLoadMore, LoadMoreState? loadMore, - Object? loadMoreException = _keepLoadMoreException, + Object? pendingUrgentException = _keepPendingException, }) { return SearchEmailResult( emails: emails ?? this.emails, canLoadMore: canLoadMore ?? this.canLoadMore, loadMore: loadMore ?? this.loadMore, - loadMoreException: identical(loadMoreException, _keepLoadMoreException) - ? this.loadMoreException - : loadMoreException, + pendingUrgentException: + identical(pendingUrgentException, _keepPendingException) + ? this.pendingUrgentException + : pendingUrgentException, ); } diff --git a/lib/features/search/email/domain/notifier/search_email_notifier.dart b/lib/features/search/email/domain/notifier/search_email_notifier.dart index 23b1e7836..560ede3e0 100644 --- a/lib/features/search/email/domain/notifier/search_email_notifier.dart +++ b/lib/features/search/email/domain/notifier/search_email_notifier.dart @@ -120,7 +120,10 @@ class SearchEmailNotifier extends _$SearchEmailNotifier { /// (e.g. a socket-driven refresh arriving mid-load) is handled by [_latestRequestId] /// in [_runGuarded], which drops a superseded page — not by [LoadMoreState]. Future _runLoadMore(int requestId, SearchExecutionRequest request) { - state = AsyncData(_currentResult.copyWith(loadMore: LoadMoreState.inProgress)); + state = AsyncData(_currentResult.copyWith( + loadMore: LoadMoreState.inProgress, + pendingUrgentException: null, + )); return _runGuarded( requestId, () { @@ -140,16 +143,16 @@ class SearchEmailNotifier extends _$SearchEmailNotifier { .last; }, onPageLoaded: (page) => state = AsyncData(_currentResult.copyWith( - emails: [..._currentResult.emails, ...page], + emails: [..._currentResult.emails, ..._dropAlreadyLoaded(page)], canLoadMore: page.isNotEmpty, loadMore: LoadMoreState.idle, - loadMoreException: null, + pendingUrgentException: null, )), // Preserve the loaded page and surface urgent load-more failures. onFailure: (error, _) => state = AsyncData( _currentResult.copyWith( loadMore: LoadMoreState.failure, - loadMoreException: error, + pendingUrgentException: error, ), ), ); @@ -158,7 +161,10 @@ class SearchEmailNotifier extends _$SearchEmailNotifier { /// Refresh: replace the list on success; on failure keep the current list, never /// erroring the whole result. Future _runRefresh(int requestId, SearchExecutionRequest request) { - state = AsyncData(_currentResult.copyWith(loadMore: LoadMoreState.idle)); + state = AsyncData(_currentResult.copyWith( + loadMore: LoadMoreState.idle, + pendingUrgentException: null, + )); return _runGuarded( requestId, () { @@ -179,7 +185,12 @@ class SearchEmailNotifier extends _$SearchEmailNotifier { onPageLoaded: (page) => state = AsyncData( SearchEmailResult(emails: page, canLoadMore: page.isNotEmpty), ), - onFailure: (_, __) {}, // keep the current list + // Keep the current list on a background-refresh failure, but surface the + // exception so the controller routes urgent ones (ADR-0103) — same as + // load-more. + onFailure: (error, _) => state = AsyncData( + _currentResult.copyWith(pendingUrgentException: error), + ), ); } @@ -250,6 +261,14 @@ class SearchEmailNotifier extends _$SearchEmailNotifier { ); } + /// Drops emails already present in the current list so a load-more page whose + /// boundary overlaps the previous one (same-timestamp rows) never duplicates. + List _dropAlreadyLoaded(List page) { + final existingIds = + _currentResult.emails.map((email) => email.id).toSet(); + return page.where((email) => !existingIds.contains(email.id)).toList(); + } + /// Emails of a terminal success, else null (keep current on intermediate). List? _emailsOf(Success success) { return switch (success) { diff --git a/lib/features/search/email/presentation/search_email_controller.dart b/lib/features/search/email/presentation/search_email_controller.dart index 94edc71b9..57bde0721 100644 --- a/lib/features/search/email/presentation/search_email_controller.dart +++ b/lib/features/search/email/presentation/search_email_controller.dart @@ -122,6 +122,11 @@ class SearchEmailController extends BaseController StreamSubscription? shortcutActionEventSubscription; ProviderSubscription>? _searchEmailResultSubscription; + /// Emails reference last pushed to the presentation list. The executor reuses + /// the same list instance when only the load-more lifecycle changes (e.g. the + /// load-more spinner toggling), so an identity check skips the full rebuild. + List? _lastAppliedResultEmails; + PresentationMailbox? get currentMailbox => mailboxDashBoardController.selectedMailbox.value; AccountId? get accountId => mailboxDashBoardController.accountId.value; @@ -540,26 +545,16 @@ class SearchEmailController extends BaseController SearchEmailResult result, { required bool shouldScrollToTop, }) { - final resultEmailSearchList = result.emails - .map((email) => email.toSearchPresentationEmail(mailboxDashBoardController.mapMailboxById)) - .toList(); + // Rebuild the visible list only when the emails actually changed; a pure + // load-more/refresh lifecycle update keeps the same list instance. + if (!identical(result.emails, _lastAppliedResultEmails)) { + _lastAppliedResultEmails = result.emails; + _rebuildResultSearchList(result.emails); + } - final emailsBeforeChanges = listResultSearch; - final emailsAfterChanges = resultEmailSearchList; - final newListEmail = emailsAfterChanges.combine(emailsBeforeChanges); - - _searchEmailPresentationNotifier.setResultSearches(newListEmail.syncPresentationEmail( - mapMailboxById: mailboxDashBoardController.mapMailboxById, - searchQuery: searchEmailFilter.text, - isSearchEmailRunning: true - )); - - _searchEmailPresentationNotifier.setResultSearchViewState( - Right(SearchEmailSuccess(result.emails)), - ); _searchEmailPresentationNotifier.setCanSearchMore(result.canLoadMore); _updateSearchMoreState(result.loadMore); - _handleLoadMoreFailureIfNeeded(result); + _routePendingUrgentException(result); if (shouldScrollToTop && resultSearchScrollController.hasClients) { resultSearchScrollController.animateTo( @@ -573,6 +568,24 @@ class SearchEmailController extends BaseController } } + void _rebuildResultSearchList(List emails) { + final resultEmailSearchList = emails + .map((email) => email.toSearchPresentationEmail(mailboxDashBoardController.mapMailboxById)) + .toList(); + + final newListEmail = resultEmailSearchList.combine(listResultSearch); + + _searchEmailPresentationNotifier.setResultSearches(newListEmail.syncPresentationEmail( + mapMailboxById: mailboxDashBoardController.mapMailboxById, + searchQuery: searchEmailFilter.text, + isSearchEmailRunning: true + )); + + _searchEmailPresentationNotifier.setResultSearchViewState( + Right(SearchEmailSuccess(emails)), + ); + } + void _updateSearchMoreState(LoadMoreState loadMoreState) { switch (loadMoreState) { case LoadMoreState.inProgress: @@ -589,10 +602,10 @@ class SearchEmailController extends BaseController } } - /// Routes urgent load-more failures without clearing the list. - void _handleLoadMoreFailureIfNeeded(SearchEmailResult result) { - if (result.loadMore != LoadMoreState.failure) return; - _handleUrgentSearchException(result.loadMoreException); + /// Routes an urgent exception carried by a list-preserving failure (load-more + /// or refresh), the same path a full-search failure takes via [value.hasError]. + void _routePendingUrgentException(SearchEmailResult result) { + _handleUrgentSearchException(result.pendingUrgentException); } void _searchEmailsFailure(SearchEmailFailure failure) { diff --git a/test/features/search/email/domain/notifier/search_email_notifier_test.dart b/test/features/search/email/domain/notifier/search_email_notifier_test.dart index 2572da4c2..1b8637d10 100644 --- a/test/features/search/email/domain/notifier/search_email_notifier_test.dart +++ b/test/features/search/email/domain/notifier/search_email_notifier_test.dart @@ -29,6 +29,7 @@ import 'package:tmail_ui_user/features/thread/domain/state/search_email_state.da import 'package:tmail_ui_user/features/thread/domain/state/search_more_email_state.dart'; import 'package:tmail_ui_user/features/thread/domain/usecases/search_email_interactor.dart'; import 'package:tmail_ui_user/features/thread/domain/usecases/search_more_email_interactor.dart'; +import 'package:tmail_ui_user/main/exceptions/remote/authentication_exception.dart'; import '../../../../../fixtures/account_fixtures.dart'; import '../../../../../fixtures/session_fixtures.dart'; @@ -392,6 +393,30 @@ void main() { ); }); + test('load-more drops emails already present in the current list', () async { + final container = containerForSort(EmailSortOrderType.mostRecent); + + stubSearch([emailWith('e1'), emailWith('e2')]); + await runExecute(container, const NewSearchIntent()); + + // The next page overlaps the boundary (e2 repeats, same timestamp) and + // adds e3; only e3 must be appended. + stubSearchMore([emailWith('e2'), emailWith('e3')]); + await runExecute( + container, + LoadMoreIntent( + currentCount: 2, + lastEmailDate: cursorDate, + lastEmailId: EmailId(Id('e2')), + ), + ); + + expect( + container.read(searchEmailProvider).value!.emails.map((e) => e.id), + [EmailId(Id('e1')), EmailId(Id('e2')), EmailId(Id('e3'))], + ); + }); + test('empty load-more page sets canLoadMore false', () async { final container = containerForSort(EmailSortOrderType.relevance); @@ -474,8 +499,8 @@ void main() { [EmailId(Id('e1')), EmailId(Id('e2'))], ); expect(failed.value?.loadMore, LoadMoreState.failure); - // Surface the exception for urgent routing. - expect(failed.value?.loadMoreException, loadMoreFailure); + // Surface the exception for the controller to route. + expect(failed.value?.pendingUrgentException, loadMoreFailure); // Retry succeeds: the new page appends to the preserved pages, back to idle. stubSearchMore([emailWith('e3')]); @@ -517,6 +542,70 @@ void main() { expect(result.value?.emails.map((e) => e.id), [EmailId(Id('e1'))]); }); + test('refresh failure surfaces the exception for the controller to route', () async { + final container = containerForSort(EmailSortOrderType.relevance); + stubSearch([emailWith('e1')]); + await runExecute(container, const NewSearchIntent()); + + // Same shape as a load-more failure: keep the list and carry the exception + // so the controller routes urgent ones (ADR-0103). + final refreshFailure = SearchEmailFailure(const BadCredentialsException()); + when(refreshInteractor.execute( + any, + any, + limit: anyNamed('limit'), + position: anyNamed('position'), + sort: anyNamed('sort'), + filter: anyNamed('filter'), + collapseThreads: anyNamed('collapseThreads'), + properties: anyNamed('properties'), + )).thenAnswer((_) => Stream.value(Left(refreshFailure))); + await runExecute(container, const RefreshChangesIntent(currentCount: 1)); + + final result = container.read(searchEmailProvider); + expect(result.hasError, isFalse); + expect(result.value?.emails.map((e) => e.id), [EmailId(Id('e1'))]); + expect(result.value?.pendingUrgentException, refreshFailure); + }); + + test('the next operation clears a carried refresh exception', () async { + final container = containerForSort(EmailSortOrderType.relevance); + stubSearch([emailWith('e1')]); + await runExecute(container, const NewSearchIntent()); + + when(refreshInteractor.execute( + any, + any, + limit: anyNamed('limit'), + position: anyNamed('position'), + sort: anyNamed('sort'), + filter: anyNamed('filter'), + collapseThreads: anyNamed('collapseThreads'), + properties: anyNamed('properties'), + )).thenAnswer((_) => + Stream.value(Left(SearchEmailFailure(const BadCredentialsException())))); + await runExecute(container, const RefreshChangesIntent(currentCount: 1)); + expect( + container.read(searchEmailProvider).value?.pendingUrgentException, + isNotNull, + ); + + // A following load-more must not re-carry (and so re-route) the stale one. + stubSearchMore([emailWith('e2')]); + await runExecute( + container, + LoadMoreIntent( + currentCount: 1, + lastEmailDate: cursorDate, + lastEmailId: EmailId(Id('e1')), + ), + ); + expect( + container.read(searchEmailProvider).value?.pendingUrgentException, + isNull, + ); + }); + test('a refresh failure clears a load-more spinner it superseded', () async { final container = containerForSort(EmailSortOrderType.relevance); stubSearch([emailWith('e1')]);