diff --git a/docs/decisions.md b/docs/decisions.md index 6a40b8a74..fc7ddc18d 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -31,3 +31,10 @@ Categories: UX, UI, Product, Architecture, Infra, Tech. - Decided by: Dat H. Pham, in linagora/tmail-flutter#5163. - Why: the new tab keeps working without a second sign in, and a draft stays owned by the one tab that created it. - Scope: `app_route_tab_environment.dart`, `html_utils.dart`, `child_tab_session_cleaner.dart`, `mailbox_action_handler_mixin.dart`, `email_action_controller.dart`. + +## 2026-11-27, [Architecture] Settings › Delegation › With me re-reads the session when its list of owners differs from the session + +- Decision: when the With me list loads and names a different set of owners than the shown session's delegated accounts, the session is re-read once and handed to the dashboard, so the account switcher offers the same mailboxes as the list. A load that fails, or that a newer load replaced, triggers no re-read. Re-reading on resume and on `accountNotFound` stays with linagora/tmail-flutter#5162. +- Decided by: Dat Vu, in linagora/tmail-flutter#5188. +- Why: the session is read only at sign in, so a grant or a revoke made while the app runs reached the With me list but not the switcher, which then offered a mailbox the server refuses or hid one just granted. +- Scope: `delegated_to_me_notifier.dart`, `delegated_to_me_section.dart`. diff --git a/integration_test/robots/abstract/abstract_account_switcher_assertion_robot.dart b/integration_test/robots/abstract/abstract_account_switcher_assertion_robot.dart index 5c3b1def1..9a4fea8a4 100644 --- a/integration_test/robots/abstract/abstract_account_switcher_assertion_robot.dart +++ b/integration_test/robots/abstract/abstract_account_switcher_assertion_robot.dart @@ -10,6 +10,9 @@ abstract class AbstractAccountSwitcherAssertionRobot { /// The switcher's session no longer lists [ownerAddress]. Future expectNoLongerOffers(String ownerAddress); + /// The switcher's session lists [ownerAddress]. + Future expectOffers(String ownerAddress); + Future expectSwitchSettled(String ownerAddress); Future expectShownIdentitiesInclude(String email); diff --git a/integration_test/robots/account_switcher_assertion_robot.dart b/integration_test/robots/account_switcher_assertion_robot.dart index 7b268b7f8..36ac204ef 100644 --- a/integration_test/robots/account_switcher_assertion_robot.dart +++ b/integration_test/robots/account_switcher_assertion_robot.dart @@ -26,14 +26,21 @@ abstract class AccountSwitcherAssertionRobot extends CoreRobot } @override - Future expectNoLongerOffers(String ownerAddress) async { + Future expectNoLongerOffers(String ownerAddress) => + _waitSessionListing(ownerAddress, listed: false); + + @override + Future expectOffers(String ownerAddress) => + _waitSessionListing(ownerAddress, listed: true); + + Future _waitSessionListing(String ownerAddress, {required bool listed}) async { await waitForCondition( () { final session = appContainer().read(activeAccountProvider)?.session; return session != null && - session.delegatedAccounts.every((entry) => entry.value.name.value != ownerAddress); + session.delegatedAccounts.any((entry) => entry.value.name.value == ownerAddress) == listed; }, - reason: 'session no longer lists $ownerAddress', + reason: 'session ${listed ? 'lists' : 'no longer lists'} $ownerAddress', ); } diff --git a/integration_test/scenarios/delegation/refresh_delegated_to_me_scenario.dart b/integration_test/scenarios/delegation/refresh_delegated_to_me_scenario.dart new file mode 100644 index 000000000..04d2a7a93 --- /dev/null +++ b/integration_test/scenarios/delegation/refresh_delegated_to_me_scenario.dart @@ -0,0 +1,58 @@ +import 'package:tmail_ui_user/features/manage_account/presentation/model/account_menu_item.dart'; + +import '../../base/base_test_scenario.dart'; +import '../../mixin/delegation_standalone_scenario_mixin.dart'; +import '../../utils/jmap/jmap_delegate_provisioner.dart'; + +/// Bob has alice's mailbox delegated (reset-server seed). Alice changes her +/// delegates on the server while Bob's app runs. Stand-alone web and the +/// Android and iOS app. +class RefreshDelegatedToMeScenario extends BaseTestScenario + with DelegationStandaloneScenarioMixin { + const RefreshDelegatedToMeScenario(super.$, super.robots); + + static const _ownerPassword = 'alice'; + + @override + Future runTestLogic() async { + const ownerAddress = DelegationStandaloneScenarioMixin.ownerAddress; + final owner = JmapDelegateProvisioner.signedInAs( + ownerAddress, + _ownerPassword, + ); + final delegationRobot = robots.settingsRobot().delegationRobot; + + await enableDelegationAndReturnToMailbox(); + + await owner.removeAll(); + await _openDelegatedToMe(); + await delegationRobot.assertion.expectNothingDelegatedToMe(); + await _closeSettings(); + await accountSwitcher.assertion.expectNoLongerOffers(ownerAddress); + await accountSwitcher.assertion.expectSwitcherInactive(); + + await owner.add({DelegationStandaloneScenarioMixin.ownAddress}); + await _openDelegatedToMe(); + await delegationRobot.assertion.expectDelegatedToMeListed(ownerAddress); + await _closeSettings(); + // The re-read runs after the list shows, and the avatar opens the switcher only once the session lists the owner. + await accountSwitcher.assertion.expectOffers(ownerAddress); + await accountSwitcher.openMenu(); + await accountSwitcher.assertion.expectMenuShowsDelegated(ownerAddress); + await accountSwitcher.selectAddressWhenMenuOpen(ownerAddress); + await accountSwitcher.assertion.expectSwitchSettled(ownerAddress); + } + + Future _openDelegatedToMe() async { + await robots.mailboxMenuRobot().openSetting(); + await robots + .settingsRobot() + .openSettingsDetail(AccountMenuItem.delegation); + await robots.settingsRobot().delegationRobot.openDelegatedToMeTab(); + } + + Future _closeSettings() async { + await robots.settingsRobot().closeSettingsFromDetail(); + await robots.commonRobot().waitForMailboxReady(); + } +} diff --git a/integration_test/tests/delegation/refresh_delegated_to_me_test.dart b/integration_test/tests/delegation/refresh_delegated_to_me_test.dart new file mode 100644 index 000000000..0f387a8a4 --- /dev/null +++ b/integration_test/tests/delegation/refresh_delegated_to_me_test.dart @@ -0,0 +1,12 @@ +import '../../base/test_base.dart'; +import '../../models/test_tags.dart'; +import '../../scenarios/delegation/refresh_delegated_to_me_scenario.dart'; + +void main() { + TestBase().runPatrolTest( + description: + 'Should update the account switcher from Settings › With me when the owner revokes and grants access again', + scenarioBuilder: ($, robots) => RefreshDelegatedToMeScenario($, robots), + tags: [TestTags.android, TestTags.ios, TestTags.web], + ); +} diff --git a/integration_test/utils/jmap/jmap_delegate_provisioner.dart b/integration_test/utils/jmap/jmap_delegate_provisioner.dart index bb35f9e95..46f11d051 100644 --- a/integration_test/utils/jmap/jmap_delegate_provisioner.dart +++ b/integration_test/utils/jmap/jmap_delegate_provisioner.dart @@ -2,10 +2,20 @@ import 'package:tmail_ui_user/features/delegation/data/network/delegate_api.dart import 'jmap_test_client.dart'; +typedef JmapClientConnector = Future Function(); + /// Grants and revokes access to the signed-in mailbox straight through JMAP. class JmapDelegateProvisioner { + JmapDelegateProvisioner() : _connect = JmapTestClient.current; + + /// Acts on the mailbox of [email] instead of the signed-in one. + JmapDelegateProvisioner.signedInAs(String email, String password) + : _connect = (() => JmapTestClient.signedInAs(email, password)); + + final JmapClientConnector _connect; + Future add(Set delegateAddresses) async { - final client = await JmapTestClient.current(); + final client = await _connect(); final result = await DelegateApi(client.httpClient).addDelegates(client.accountId, delegateAddresses); if (result.rejectedUsernames.isNotEmpty) { throw StateError('Delegates rejected: ${result.rejectedUsernames.keys}'); @@ -13,7 +23,7 @@ class JmapDelegateProvisioner { } Future removeAll() async { - final client = await JmapTestClient.current(); + final client = await _connect(); final api = DelegateApi(client.httpClient); for (final delegate in await api.getDelegates(client.accountId)) { await api.removeDelegate(client.accountId, delegate); diff --git a/integration_test/utils/jmap/jmap_test_client.dart b/integration_test/utils/jmap/jmap_test_client.dart index c778f5b30..3468b8c9f 100644 --- a/integration_test/utils/jmap/jmap_test_client.dart +++ b/integration_test/utils/jmap/jmap_test_client.dart @@ -60,6 +60,10 @@ class JmapTestClient { return _connect(backendUrl, email, password); } + /// Signs in as another seeded user of the leased backend. + static Future signedInAs(String email, String password) => + _connect(TestBackend.current.url, email, password); + static Future _connect( String backendUrl, String email, diff --git a/lib/features/delegation/presentation/notifier/active_account_notifier.dart b/lib/features/delegation/presentation/notifier/active_account_notifier.dart index 6c06c7493..1180e46d1 100644 --- a/lib/features/delegation/presentation/notifier/active_account_notifier.dart +++ b/lib/features/delegation/presentation/notifier/active_account_notifier.dart @@ -15,6 +15,8 @@ class ActiveAccountNotifier extends _$ActiveAccountNotifier { @override ActiveAccount? build() => null; + Session? get currentSession => state?.session; + void applySession(Session session) { final shownAccount = state; final keepsShownDelegatedAccount = shownAccount != null && diff --git a/lib/features/delegation/presentation/notifier/delegated_to_me_notifier.dart b/lib/features/delegation/presentation/notifier/delegated_to_me_notifier.dart index e42e4b153..3e2d8e181 100644 --- a/lib/features/delegation/presentation/notifier/delegated_to_me_notifier.dart +++ b/lib/features/delegation/presentation/notifier/delegated_to_me_notifier.dart @@ -4,6 +4,7 @@ import 'package:jmap_dart_client/jmap/core/id.dart'; import 'package:jmap_dart_client/jmap/core/session/session.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:tmail_ui_user/features/base/interactor_consumer.dart'; +import 'package:tmail_ui_user/features/delegation/domain/extensions/session_delegation_extension.dart'; import 'package:tmail_ui_user/features/delegation/domain/state/get_delegated_accounts_state.dart'; import 'package:tmail_ui_user/features/delegation/presentation/notifier/active_account_notifier.dart'; import 'package:tmail_ui_user/features/delegation/presentation/providers/delegated_account_providers.dart'; @@ -26,20 +27,40 @@ class DelegatedToMeNotifier extends _$DelegatedToMeNotifier with InteractorConsu @override AsyncValue> build() => const AsyncLoading(); - Future load(Session session) async { + /// With [onSessionReloaded], a list that no longer matches the session re-reads it, so the switcher follows + /// a delegation granted or revoked while the app runs. + Future load(Session session, {OnSessionReloaded? onSessionReloaded}) async { final loadId = ++_latestLoadId; state = const AsyncLoading(); final interactor = ref.read(getDelegatedAccountsInteractorProvider); + final activeAccount = ref.read(activeAccountProvider.notifier); + List? loaded; await consumeInteractor(InteractorConsumeRequest( run: () => interactor.execute(session).last, isStale: () => !ref.mounted || loadId != _latestLoadId, onSuccess: (success) { if (success is GetDelegatedAccountsSuccess) { + loaded = success.delegatedAccounts; state = AsyncData(success.delegatedAccounts); } }, onFailure: (error, stackTrace) => state = AsyncError(error, stackTrace), )); + if (onSessionReloaded == null || _isLoadReplaced(loadId)) return; + if (_sessionMissesChange(activeAccount, loaded)) { + // A newer load compares the list with the session again, so this re-read must not overwrite its outcome. + await _reloadSession(activeAccount, onSessionReloaded, isOriginReplaced: () => _isLoadReplaced(loadId)); + } + } + + bool _isLoadReplaced(int loadId) => loadId != _latestLoadId; + + bool _sessionMissesChange(ActiveAccountNotifier activeAccount, List? accounts) { + final session = activeAccount.currentSession; + if (session == null || accounts == null) return false; + final sessionOwners = session.delegatedAccounts.map((entry) => entry.value.name.value).toSet(); + return sessionOwners.length != accounts.length || + accounts.any((account) => !sessionOwners.contains(account.username)); } /// Removes my access, then re-reads the session so the switcher drops that mailbox. @@ -84,12 +105,16 @@ class DelegatedToMeNotifier extends _$DelegatedToMeNotifier with InteractorConsu state = AsyncData(accounts.where((account) => account != delegatedAccount).toList()); } - Future _reloadSession(ActiveAccountNotifier activeAccount, OnSessionReloaded? onSessionReloaded) { + Future _reloadSession( + ActiveAccountNotifier activeAccount, + OnSessionReloaded? onSessionReloaded, { + StaleGuard? isOriginReplaced, + }) { final reloadId = ++_latestReloadId; return consumeInteractor(InteractorConsumeRequest( run: () => _getSessionInteractor.execute().last, // Only the latest re-read applies: it started after every removal that completed before it. - isStale: () => reloadId != _latestReloadId, + isStale: () => reloadId != _latestReloadId || (isOriginReplaced?.call() ?? false), onSuccess: (success) { // A cached session still lists the removed mailbox. if (success is GetSessionSuccess && diff --git a/lib/features/manage_account/presentation/delegation/delegated_to_me_section.dart b/lib/features/manage_account/presentation/delegation/delegated_to_me_section.dart index fee44f195..ca365fe94 100644 --- a/lib/features/manage_account/presentation/delegation/delegated_to_me_section.dart +++ b/lib/features/manage_account/presentation/delegation/delegated_to_me_section.dart @@ -40,7 +40,7 @@ class _DelegatedToMeSectionState extends ConsumerState { void _load() { if (!mounted) return; - ref.read(delegatedToMeProvider.notifier).load(widget.session); + ref.read(delegatedToMeProvider.notifier).load(widget.session, onSessionReloaded: widget.onSessionReloaded); } @override diff --git a/test/features/delegation/presentation/notifier/active_account_notifier_test.dart b/test/features/delegation/presentation/notifier/active_account_notifier_test.dart index 0c0d7c059..423b0e890 100644 --- a/test/features/delegation/presentation/notifier/active_account_notifier_test.dart +++ b/test/features/delegation/presentation/notifier/active_account_notifier_test.dart @@ -24,6 +24,20 @@ void main() { expect(stateOf(), isNull); }); + group('currentSession', () { + test('is null before a session is applied', () { + expect(notifierOf().currentSession, isNull); + }); + + test('is the signed-in session while a delegated account is shown', () { + final session = DelegationFixtures.session(); + notifierOf().applySession(session); + notifierOf().select(DelegationFixtures.bobAccountId); + + expect(notifierOf().currentSession, session); + }); + }); + group('applySession', () { test('starts on my own account', () { final session = DelegationFixtures.session(); diff --git a/test/features/delegation/presentation/notifier/delegated_to_me_notifier_test.dart b/test/features/delegation/presentation/notifier/delegated_to_me_notifier_test.dart index babd64bad..23b0394b3 100644 --- a/test/features/delegation/presentation/notifier/delegated_to_me_notifier_test.dart +++ b/test/features/delegation/presentation/notifier/delegated_to_me_notifier_test.dart @@ -83,6 +83,104 @@ void main() { }); }); + group('load refreshes the switcher', () { + Future> loadReporting(List accounts) async { + final reloadedSessions = []; + final load = notifier().load(session, onSessionReloaded: reloadedSessions.add); + await untilRepositoryCalled(); + repository.pendingLoads.last.complete(accounts); + await load; + return reloadedSessions; + } + + for (final (listState, listed) in [ + ('a mailbox the session does not list yet', [bobDelegation, carolDelegation]), + ('no longer a mailbox the session still lists', [bobDelegation]), + ]) { + test('should re-read the session when the list has $listState', () async { + session = DelegationFixtures.session(listsCarol: listed.length == 1); + container.read(activeAccountProvider.notifier).applySession(session); + final freshSession = DelegationFixtures.session(state: 'state-2', listsCarol: listed.length == 2); + getSessionInteractor.result = Right(GetSessionSuccess(freshSession)); + + final reloadedSessions = await loadReporting(listed); + + expect(getSessionInteractor.calls, 1); + expect(container.read(activeAccountProvider)?.session, freshSession); + expect(reloadedSessions, [freshSession]); + }); + } + + test('should re-read the session when the list names as many mailboxes but another owner', () async { + session = DelegationFixtures.session(listsCarol: false); + container.read(activeAccountProvider.notifier).applySession(session); + final freshSession = DelegationFixtures.session(state: 'state-2', listsBob: false); + getSessionInteractor.result = Right(GetSessionSuccess(freshSession)); + + final reloadedSessions = await loadReporting([carolDelegation]); + + expect(getSessionInteractor.calls, 1); + expect(reloadedSessions, [freshSession]); + }); + + test('should not re-read the session when the list matches it', () async { + final reloadedSessions = await loadReporting([bobDelegation, carolDelegation]); + + expect(getSessionInteractor.calls, 0); + expect(reloadedSessions, isEmpty); + }); + + test('should not re-read the session without a caller to report it to', () async { + await loadWith([bobDelegation]); + + expect(getSessionInteractor.calls, 0); + }); + + test('should not re-read the session when the list fails to load', () async { + final reloadedSessions = []; + final load = notifier().load(session, onSessionReloaded: reloadedSessions.add); + await untilRepositoryCalled(); + repository.pendingLoads.last.completeError(Exception('boom')); + await load; + + expect(getSessionInteractor.calls, 0); + expect(reloadedSessions, isEmpty); + }); + + test('should not re-read the session for a load a newer one replaced', () async { + final reloadedSessions = []; + final firstLoad = notifier().load(session, onSessionReloaded: reloadedSessions.add); + final secondLoad = notifier().load(session, onSessionReloaded: reloadedSessions.add); + await untilRepositoryCalled(); + repository.pendingLoads[1].complete([bobDelegation, carolDelegation]); + await secondLoad; + repository.pendingLoads[0].complete([bobDelegation]); + await firstLoad; + + expect(getSessionInteractor.calls, 0); + }); + + test('should not apply the re-read of a load a newer one replaced', () async { + getSessionInteractor.holdsReads = true; + final reloadedSessions = []; + final firstLoad = notifier().load(session, onSessionReloaded: reloadedSessions.add); + await untilRepositoryCalled(); + repository.pendingLoads[0].complete([bobDelegation]); + await untilRepositoryCalled(); + final secondLoad = notifier().load(session, onSessionReloaded: reloadedSessions.add); + await untilRepositoryCalled(); + repository.pendingLoads[1].complete([bobDelegation, carolDelegation]); + await secondLoad; + getSessionInteractor.pendingReads.single.complete( + Right(GetSessionSuccess(DelegationFixtures.session(state: 'state-2', listsCarol: false))), + ); + await firstLoad; + + expect(container.read(activeAccountProvider)?.session, session); + expect(reloadedSessions, isEmpty); + }); + }); + group('remove', () { test('should drop the account and apply the fresh session to the switcher', () async { await loadWith([bobDelegation, carolDelegation]); diff --git a/test/features/manage_account/presentation/delegation/delegated_to_me_section_test.dart b/test/features/manage_account/presentation/delegation/delegated_to_me_section_test.dart index cbd586634..efc9d647e 100644 --- a/test/features/manage_account/presentation/delegation/delegated_to_me_section_test.dart +++ b/test/features/manage_account/presentation/delegation/delegated_to_me_section_test.dart @@ -39,7 +39,8 @@ void main() { setUp(() { repository = FakeDelegatedAccountRepository(); - reReadSession = DelegationFixtures.session(listsBob: false); + // Lists only Bob, like the With me list most tests load. + reReadSession = DelegationFixtures.session(listsBob: false, listsCarol: false); reloadedSessions = []; getSessionInteractor = FakeGetSessionInteractor()..result = Right(GetSessionSuccess(reReadSession)); appToast = RecordingAppToast(); @@ -50,7 +51,7 @@ void main() { delegatedAccountRepositoryProvider.overrideWithValue(repository), appToastProvider.overrideWithValue(appToast.toast), ]); - container.read(activeAccountProvider.notifier).applySession(DelegationFixtures.session()); + container.read(activeAccountProvider.notifier).applySession(DelegationFixtures.session(listsCarol: false)); }); tearDown(() { @@ -72,7 +73,7 @@ void main() { locale: LocalizationService.defaultLocale, home: Scaffold( body: DelegatedToMeSection( - session: DelegationFixtures.session(), + session: DelegationFixtures.session(listsCarol: false), onSessionReloaded: reloadedSessions.add, ), ), @@ -97,6 +98,17 @@ void main() { await tester.pumpAndSettle(); } + testWidgets('should refresh the switcher when the list names a mailbox the session does not list', (tester) async { + final freshSession = DelegationFixtures.session(state: 'state-2'); + getSessionInteractor.result = Right(GetSessionSuccess(freshSession)); + await pumpSection(tester); + await completeLoad(tester, [bobDelegation, DelegatedAccount(id: Id('carol-delegation'), username: DelegationFixtures.carolAddress)]); + await tester.runAsync(() => Future.delayed(Duration.zero)); + await tester.pump(); + + expect(reloadedSessions, [freshSession]); + }); + testWidgets('should show a spinner while the list loads', (tester) async { await pumpSection(tester);