From 589b8a2936aba90c423462006f6e33de3fcbd1a1 Mon Sep 17 00:00:00 2001 From: Beast Date: Sat, 21 Nov 2026 00:47:41 +0800 Subject: [PATCH 1/9] Add the string for a desktop notification's Open action --- wallet_core/lib/l10n/app_en.arb | 4 ++++ wallet_core/lib/l10n/app_id.arb | 3 ++- wallet_core/lib/l10n/app_localizations.dart | 6 ++++++ wallet_core/lib/l10n/app_localizations_en.dart | 3 +++ wallet_core/lib/l10n/app_localizations_id.dart | 3 +++ 5 files changed, 18 insertions(+), 1 deletion(-) diff --git a/wallet_core/lib/l10n/app_en.arb b/wallet_core/lib/l10n/app_en.arb index 9139d68a2..a51244d85 100644 --- a/wallet_core/lib/l10n/app_en.arb +++ b/wallet_core/lib/l10n/app_en.arb @@ -4295,5 +4295,9 @@ "desktopActivityCreationFee": "Multisig fee", "@desktopActivityCreationFee": { "description": "Desktop transaction panel: the fee the chain charges for making a multisig" + }, + "desktopNotificationOpenAction": "Open", + "@desktopNotificationOpenAction": { + "description": "Desktop notification on Linux: the action that opens the wallet when the notification is clicked" } } diff --git a/wallet_core/lib/l10n/app_id.arb b/wallet_core/lib/l10n/app_id.arb index 3604aa342..05ee28172 100644 --- a/wallet_core/lib/l10n/app_id.arb +++ b/wallet_core/lib/l10n/app_id.arb @@ -798,5 +798,6 @@ "desktopActivityThreshold": "Ambang batas", "desktopActivitySigners": "Penanda tangan", "desktopActivityCreatedBy": "Dibuat oleh", - "desktopActivityCreationFee": "Biaya multisig" + "desktopActivityCreationFee": "Biaya multisig", + "desktopNotificationOpenAction": "Buka" } diff --git a/wallet_core/lib/l10n/app_localizations.dart b/wallet_core/lib/l10n/app_localizations.dart index fefe344d3..0c5466ac7 100644 --- a/wallet_core/lib/l10n/app_localizations.dart +++ b/wallet_core/lib/l10n/app_localizations.dart @@ -5371,6 +5371,12 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Multisig fee'** String get desktopActivityCreationFee; + + /// Desktop notification on Linux: the action that opens the wallet when the notification is clicked + /// + /// In en, this message translates to: + /// **'Open'** + String get desktopNotificationOpenAction; } class _AppLocalizationsDelegate extends LocalizationsDelegate { diff --git a/wallet_core/lib/l10n/app_localizations_en.dart b/wallet_core/lib/l10n/app_localizations_en.dart index 4bbf267ed..7ac93472c 100644 --- a/wallet_core/lib/l10n/app_localizations_en.dart +++ b/wallet_core/lib/l10n/app_localizations_en.dart @@ -2951,4 +2951,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get desktopActivityCreationFee => 'Multisig fee'; + + @override + String get desktopNotificationOpenAction => 'Open'; } diff --git a/wallet_core/lib/l10n/app_localizations_id.dart b/wallet_core/lib/l10n/app_localizations_id.dart index 442e3d423..0abcf7189 100644 --- a/wallet_core/lib/l10n/app_localizations_id.dart +++ b/wallet_core/lib/l10n/app_localizations_id.dart @@ -2954,4 +2954,7 @@ class AppLocalizationsId extends AppLocalizations { @override String get desktopActivityCreationFee => 'Biaya multisig'; + + @override + String get desktopNotificationOpenAction => 'Buka'; } From d3b8c6964d40114f7fb002d0f082e4a316cd3a06 Mon Sep 17 00:00:00 2001 From: Beast Date: Sat, 21 Nov 2026 00:54:22 +0800 Subject: [PATCH 2/9] Desktop: system notifications, asked for once a wallet is open DesktopLocalNotifications now shows wallet_core's notifications through flutter_local_notifications 21.0.0, the phone's version, on macOS, Windows and Linux. It starts with the app and asks macOS for permission once a wallet is open; Windows and Linux ask nothing. Notifications that cannot be shown never stop the app: the status says why (not asked, turned off, or unavailable with the reason), for Settings to tell the person. A scheduled notification fails loudly, as no desktop feature schedules one yet. --- desktop-app/lib/app.dart | 2 + desktop-app/lib/bootstrap/app_bootstrap.dart | 4 +- .../lib/models/notification_status.dart | 32 ++ .../lib/providers/notifications_provider.dart | 118 ++++++++ .../services/desktop_local_notifications.dart | 14 - .../lib/services/notification_plugin.dart | 54 ++++ desktop-app/pubspec.lock | 40 +++ desktop-app/pubspec.yaml | 2 + .../test/bootstrap/app_bootstrap_test.dart | 8 +- desktop-app/test/fakes.dart | 8 + .../notifications_provider_test.dart | 280 ++++++++++++++++++ .../desktop_local_notifications_test.dart | 30 -- .../services/fake_notification_plugin.dart | 48 +++ 13 files changed, 592 insertions(+), 48 deletions(-) create mode 100644 desktop-app/lib/models/notification_status.dart create mode 100644 desktop-app/lib/providers/notifications_provider.dart delete mode 100644 desktop-app/lib/services/desktop_local_notifications.dart create mode 100644 desktop-app/lib/services/notification_plugin.dart create mode 100644 desktop-app/test/providers/notifications_provider_test.dart delete mode 100644 desktop-app/test/services/desktop_local_notifications_test.dart create mode 100644 desktop-app/test/services/fake_notification_plugin.dart diff --git a/desktop-app/lib/app.dart b/desktop-app/lib/app.dart index 33187b1f3..0f8ccf6b1 100644 --- a/desktop-app/lib/app.dart +++ b/desktop-app/lib/app.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:quantus_desktop_wallet/constants.dart'; +import 'package:quantus_desktop_wallet/providers/notifications_provider.dart'; import 'package:quantus_desktop_wallet/ui/shell/desktop_shell.dart'; import 'package:quantus_sdk/quantus_sdk.dart'; import 'package:wallet_core/l10n/app_localizations.dart'; @@ -11,6 +12,7 @@ class QuantusDesktopApp extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { + ref.watch(notificationsStartupProvider); final theme = AppTheme.darkTheme(context, text: const AppTextThemeV3.desktop()); return MaterialApp( diff --git a/desktop-app/lib/bootstrap/app_bootstrap.dart b/desktop-app/lib/bootstrap/app_bootstrap.dart index 53c47db39..09aacb70d 100644 --- a/desktop-app/lib/bootstrap/app_bootstrap.dart +++ b/desktop-app/lib/bootstrap/app_bootstrap.dart @@ -2,8 +2,8 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/misc.dart'; import 'package:quantus_desktop_wallet/app.dart'; +import 'package:quantus_desktop_wallet/providers/notifications_provider.dart'; import 'package:quantus_desktop_wallet/providers/shell_providers.dart'; -import 'package:quantus_desktop_wallet/services/desktop_local_notifications.dart'; import 'package:quantus_desktop_wallet/services/desktop_push_registration.dart'; import 'package:quantus_desktop_wallet/services/desktop_telemetry.dart'; import 'package:quantus_desktop_wallet/services/user_approval.dart'; @@ -23,7 +23,7 @@ List desktopWalletCoreOverrides() => [ ...walletCoreOverrides( telemetry: (_) => const DesktopTelemetry(), pushRegistration: (_) => const DesktopPushRegistration(), - localNotifications: (_) => const DesktopLocalNotifications(), + localNotifications: (ref) => ref.watch(desktopLocalNotificationsProvider.notifier), userApproval: (ref) => ref.watch(systemApprovalProvider), ), // The sidebar shows every account's balance, so each refresh of the active diff --git a/desktop-app/lib/models/notification_status.dart b/desktop-app/lib/models/notification_status.dart new file mode 100644 index 000000000..ab3190b4e --- /dev/null +++ b/desktop-app/lib/models/notification_status.dart @@ -0,0 +1,32 @@ +/// What the system lets the app do with notifications. +sealed class NotificationStatus { + const NotificationStatus(); +} + +/// The system's notifications have not been started yet. +final class NotificationsStarting extends NotificationStatus { + const NotificationsStarting(); +} + +/// macOS: started, but the person has not been asked yet whether the app may +/// show notifications. +final class NotificationsNotAsked extends NotificationStatus { + const NotificationsNotAsked(); +} + +/// The app may show notifications. +final class NotificationsAllowed extends NotificationStatus { + const NotificationsAllowed(); +} + +/// macOS: the person said no, when asked or later in System Settings. +final class NotificationsDenied extends NotificationStatus { + const NotificationsDenied(); +} + +/// The system's notifications could not be used; [reason] says why. +final class NotificationsUnavailable extends NotificationStatus { + const NotificationsUnavailable(this.reason); + + final String reason; +} diff --git a/desktop-app/lib/providers/notifications_provider.dart b/desktop-app/lib/providers/notifications_provider.dart new file mode 100644 index 000000000..279a128dc --- /dev/null +++ b/desktop-app/lib/providers/notifications_provider.dart @@ -0,0 +1,118 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:quantus_desktop_wallet/constants.dart'; +import 'package:quantus_desktop_wallet/models/notification_status.dart'; +import 'package:quantus_desktop_wallet/models/wallet_presence.dart'; +import 'package:quantus_desktop_wallet/providers/wallet_presence_provider.dart'; +import 'package:quantus_desktop_wallet/services/notification_plugin.dart'; +import 'package:quantus_sdk/quantus_sdk.dart'; +import 'package:wallet_core/models/notification_models.dart'; +import 'package:wallet_core/providers/l10n_provider.dart'; +import 'package:wallet_core/services/local_notifications.dart'; +import 'package:wallet_core/services/telemetry.dart'; + +/// The desktop's system notifications: wallet_core's [LocalNotifications], +/// and what the system lets the app do with them. +/// +/// Notifications that cannot be shown never stop the app: the status says +/// why, for Settings to tell the person. +class DesktopLocalNotifications extends Notifier implements LocalNotifications { + /// Who the app is to Windows, which files its notifications under them. + static const windowsAppUserModelId = 'Quantus.DesktopWallet'; + + /// The app's notification activator on Windows. It must never change: the + /// system keeps it registered for the app. + static const windowsActivatorGuid = '745d2a45-cfdc-4f29-91c2-0c8a985a2e19'; + + Future? _started; + + @override + NotificationStatus build() => const NotificationsStarting(); + + /// Starts the system's notifications. Started once, however often called. + Future start() => _started ??= _start(); + + Future _start() async { + final settings = InitializationSettings( + macOS: const DarwinInitializationSettings( + requestAlertPermission: false, + requestSoundPermission: false, + requestBadgePermission: false, + ), + windows: const WindowsInitializationSettings( + appName: appTitle, + appUserModelId: windowsAppUserModelId, + guid: windowsActivatorGuid, + ), + linux: LinuxInitializationSettings(defaultActionName: ref.read(l10nProvider).desktopNotificationOpenAction), + ); + try { + await ref.read(notificationPluginProvider).initialize(settings, onClick: (_) {}); + } catch (e) { + _unavailable(e); + return; + } + state = defaultTargetPlatform == TargetPlatform.macOS + ? const NotificationsNotAsked() + : const NotificationsAllowed(); + } + + /// Asks macOS whether the app may show notifications. Windows and Linux do + /// not ask, and nothing can be asked of notifications that are unavailable. + Future requestPermission() async { + await start(); + if (defaultTargetPlatform != TargetPlatform.macOS || state is NotificationsUnavailable) return; + try { + final allowed = await ref.read(notificationPluginProvider).requestMacOSPermission(); + state = allowed ? const NotificationsAllowed() : const NotificationsDenied(); + } catch (e) { + _unavailable(e); + } + } + + void _unavailable(Object error) { + quantusPrint('Desktop notifications are unavailable: $error'); + ref.read(telemetryProvider).sendError('desktop_notifications_unavailable', error: error); + state = NotificationsUnavailable('$error'); + } + + /// Shows [notification] now. Callers check [state] first: showing one the + /// system does not allow fails. + @override + Future showOrScheduleNotification(NotificationData notification) async { + if (notification.hasValidScheduleTime) { + throw UnsupportedError('Desktop notifications cannot be scheduled: no desktop feature schedules one yet'); + } + final status = state; + if (status is! NotificationsAllowed) { + throw StateError('Desktop notifications are not allowed: ${status.runtimeType}'); + } + await ref + .read(notificationPluginProvider) + .show( + // The plugins take a 32-bit id. + id: notification.id.hashCode & 0x7fffffff, + title: notification.title, + body: notification.message, + payload: jsonEncode({'accountId': notification.accountId}), + ); + } +} + +final desktopLocalNotificationsProvider = NotifierProvider( + DesktopLocalNotifications.new, +); + +/// Starts the system's notifications with the app, and asks for permission +/// once there is a wallet to notify about. +final notificationsStartupProvider = Provider((ref) { + final notifications = ref.watch(desktopLocalNotificationsProvider.notifier); + unawaited(notifications.start()); + ref.listen(walletPresenceProvider, (_, presence) { + if (presence.value == WalletPresence.present) unawaited(notifications.requestPermission()); + }, fireImmediately: true); +}); diff --git a/desktop-app/lib/services/desktop_local_notifications.dart b/desktop-app/lib/services/desktop_local_notifications.dart deleted file mode 100644 index 118a918c6..000000000 --- a/desktop-app/lib/services/desktop_local_notifications.dart +++ /dev/null @@ -1,14 +0,0 @@ -import 'package:wallet_core/models/notification_models.dart'; -import 'package:wallet_core/services/local_notifications.dart'; - -/// Desktop notifications have not been built yet. -/// -/// Showing one fails, so the first desktop feature that notifies the user -/// forces the implementation instead of silently dropping the notification. -class DesktopLocalNotifications implements LocalNotifications { - const DesktopLocalNotifications(); - - @override - Future showOrScheduleNotification(NotificationData notification) async => - throw UnimplementedError('Desktop local notifications are not implemented.'); -} diff --git a/desktop-app/lib/services/notification_plugin.dart b/desktop-app/lib/services/notification_plugin.dart new file mode 100644 index 000000000..f566e6dce --- /dev/null +++ b/desktop-app/lib/services/notification_plugin.dart @@ -0,0 +1,54 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +/// The system's notifications, as the app uses them. The plugin sits behind +/// this so that tests can stand in for the system. +abstract interface class NotificationPlugin { + /// Starts the system's notifications with [settings], calling [onClick] + /// with a notification's payload when the person clicks it. Throws when the + /// system's notification service does not start. + Future initialize(InitializationSettings settings, {required void Function(String? payload) onClick}); + + /// Asks macOS whether the app may show notifications, with sounds and a + /// badge. Returns whether it may. macOS asks the person only the first + /// time; after that it answers with what they chose. + Future requestMacOSPermission(); + + /// Shows a notification now. One shown with the same [id] replaces it. + Future show({required int id, required String title, required String body, required String payload}); +} + +/// The system's notifications through flutter_local_notifications. +class SystemNotificationPlugin implements NotificationPlugin { + final _plugin = FlutterLocalNotificationsPlugin(); + + @override + Future initialize(InitializationSettings settings, {required void Function(String? payload) onClick}) async { + final started = await _plugin.initialize( + settings: settings, + onDidReceiveNotificationResponse: (response) => onClick(response.payload), + ); + // Null: the plugin has nothing for this platform. + if (started == null) throw StateError('There are no system notifications on $defaultTargetPlatform'); + // On macOS the answer is whether permission was granted, which starting + // does not ask for; Windows and Linux answer whether their service started. + if (!started && defaultTargetPlatform != TargetPlatform.macOS) { + throw StateError("The system's notification service did not start"); + } + } + + @override + Future requestMacOSPermission() async { + final macOS = _plugin.resolvePlatformSpecificImplementation(); + if (macOS == null) throw StateError('There are no macOS notifications on $defaultTargetPlatform'); + return await macOS.requestPermissions(alert: true, sound: true, badge: true) ?? false; + } + + @override + Future show({required int id, required String title, required String body, required String payload}) { + return _plugin.show(id: id, title: title, body: body, payload: payload); + } +} + +final notificationPluginProvider = Provider((ref) => SystemNotificationPlugin()); diff --git a/desktop-app/pubspec.lock b/desktop-app/pubspec.lock index 8afd27040..00ffab92d 100644 --- a/desktop-app/pubspec.lock +++ b/desktop-app/pubspec.lock @@ -286,6 +286,38 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + flutter_local_notifications: + dependency: "direct main" + description: + name: flutter_local_notifications + sha256: "0d9035862236fe38250fe1644d7ed3b8254e34a21b2c837c9f539fbb3bba5ef1" + url: "https://pub.dev" + source: hosted + version: "21.0.0" + flutter_local_notifications_linux: + dependency: transitive + description: + name: flutter_local_notifications_linux + sha256: e0f25e243c6c44c825bbbc6b2b2e76f7d9222362adcfe9fd780bf01923c840bd + url: "https://pub.dev" + source: hosted + version: "8.0.0" + flutter_local_notifications_platform_interface: + dependency: transitive + description: + name: flutter_local_notifications_platform_interface + sha256: e7db3d5b49c2b7ecc68deba4aaaa67a348f92ee0fef34c8e4b4459dbef0d7307 + url: "https://pub.dev" + source: hosted + version: "11.0.0" + flutter_local_notifications_windows: + dependency: transitive + description: + name: flutter_local_notifications_windows + sha256: "3a2654ba104fbb52c618ebed9def24ef270228470718c43b3a6afcd5c81bef0c" + url: "https://pub.dev" + source: hosted + version: "3.0.0" flutter_localizations: dependency: transitive description: flutter @@ -1121,6 +1153,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.6.18" + timezone: + dependency: transitive + description: + name: timezone + sha256: "784a5e34d2eb62e1326f24d6f600aaaee452eb8ca8ef2f384a59244e292d158b" + url: "https://pub.dev" + source: hosted + version: "0.11.0" typed_data: dependency: transitive description: diff --git a/desktop-app/pubspec.yaml b/desktop-app/pubspec.yaml index 80fb27269..82de70593 100644 --- a/desktop-app/pubspec.yaml +++ b/desktop-app/pubspec.yaml @@ -26,6 +26,8 @@ dependencies: # Platform ffi: ^2.2.0 + # The same version as the phone's. + flutter_local_notifications: ^21.0.0 local_auth: ^3.0.1 share_plus: ^13.1.0 url_launcher: ^6.3.2 diff --git a/desktop-app/test/bootstrap/app_bootstrap_test.dart b/desktop-app/test/bootstrap/app_bootstrap_test.dart index 0940852d9..70a5703c1 100644 --- a/desktop-app/test/bootstrap/app_bootstrap_test.dart +++ b/desktop-app/test/bootstrap/app_bootstrap_test.dart @@ -2,7 +2,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:quantus_desktop_wallet/bootstrap/app_bootstrap.dart'; -import 'package:quantus_desktop_wallet/services/desktop_local_notifications.dart'; +import 'package:quantus_desktop_wallet/providers/notifications_provider.dart'; import 'package:quantus_desktop_wallet/services/desktop_push_registration.dart'; import 'package:quantus_desktop_wallet/services/desktop_telemetry.dart'; import 'package:quantus_desktop_wallet/services/user_approval.dart'; @@ -19,7 +19,11 @@ void main() { expect(container.read(telemetryProvider), isA()); expect(container.read(pushRegistrationProvider), isA()); - expect(container.read(localNotificationsProvider), isA()); + // The very one whose status the app shows. + expect( + container.read(localNotificationsProvider), + same(container.read(desktopLocalNotificationsProvider.notifier)), + ); }); test('buildApp binds the approval that wallet_core asks for to the system\'s own', () { diff --git a/desktop-app/test/fakes.dart b/desktop-app/test/fakes.dart index 7a2d4bbd8..2bb0cb18b 100644 --- a/desktop-app/test/fakes.dart +++ b/desktop-app/test/fakes.dart @@ -9,6 +9,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:quantus_desktop_wallet/bootstrap/app_bootstrap.dart'; import 'package:quantus_desktop_wallet/providers/boot_intro_provider.dart'; import 'package:quantus_desktop_wallet/services/login_password.dart'; +import 'package:quantus_desktop_wallet/services/notification_plugin.dart'; import 'package:quantus_desktop_wallet/services/sensitive_clipboard.dart'; import 'package:quantus_desktop_wallet/services/user_approval.dart'; import 'package:quantus_desktop_wallet/services/window_chrome.dart'; @@ -27,6 +28,8 @@ import 'package:wallet_core/services/remote_config_service.dart'; import 'package:wallet_core/services/transaction_submission_service.dart'; import 'package:wallet_core/services/user_approval.dart'; +import 'services/fake_notification_plugin.dart'; + /// The stored settings the shell reads, without the device's storage. A /// wallet with its recovery phrase is there unless a test says otherwise. class FakeSettingsService extends Fake implements SettingsService { @@ -1095,6 +1098,9 @@ class FakeEncryptedSendController extends EncryptedSendController { /// /// The open wallet's polling is a fake one ([polling]) unless [realPolling] /// asks for the app's own. +/// +/// The system's notifications are always a fake one: [notifications] when a +/// test looks at them. Future pumpShell( WidgetTester tester, { required List overrides, @@ -1102,6 +1108,7 @@ Future pumpShell( FakeHistoryPollingManager? polling, bool realPolling = false, FakeNetwork? network, + FakeNotificationPlugin? notifications, bool settle = true, bool reduceMotion = true, }) async { @@ -1120,6 +1127,7 @@ Future pumpShell( // otherwise reach. loginPasswordProvider.overrideWithValue(loginPassword ?? FakeLoginPassword()), ...liveDataOverrides(polling: polling, network: network, realPolling: realPolling), + notificationPluginProvider.overrideWithValue(notifications ?? FakeNotificationPlugin()), ], ), ); diff --git a/desktop-app/test/providers/notifications_provider_test.dart b/desktop-app/test/providers/notifications_provider_test.dart new file mode 100644 index 000000000..1bb3e5a91 --- /dev/null +++ b/desktop-app/test/providers/notifications_provider_test.dart @@ -0,0 +1,280 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:quantus_desktop_wallet/models/notification_status.dart'; +import 'package:quantus_desktop_wallet/models/wallet_presence.dart'; +import 'package:quantus_desktop_wallet/providers/notifications_provider.dart'; +import 'package:quantus_desktop_wallet/providers/wallet_presence_provider.dart'; +import 'package:quantus_desktop_wallet/services/notification_plugin.dart'; +import 'package:wallet_core/l10n/app_localizations.dart'; +import 'package:wallet_core/models/notification_models.dart'; +import 'package:wallet_core/providers/l10n_provider.dart'; +import 'package:wallet_core/services/telemetry.dart'; + +import '../services/fake_notification_plugin.dart'; + +class _RecordingTelemetry implements Telemetry { + final errors = []; + + @override + void sendEvent(String eventName, {Map? parameters}) {} + + @override + void sendError(String errorName, {required Object error}) => errors.add(errorName); +} + +/// A wallet that is [initial] at first, and whatever [become] makes it later. +class _Presence extends WalletPresenceNotifier { + _Presence(this.initial); + + final WalletPresence initial; + + @override + Future build() async => initial; + + void become(WalletPresence presence) => state = AsyncData(presence); +} + +/// The app's notifications on [platform], the system's being [plugin]. +({ProviderContainer container, _RecordingTelemetry telemetry}) _open( + FakeNotificationPlugin plugin, { + required TargetPlatform platform, + List overrides = const [], +}) { + debugDefaultTargetPlatformOverride = platform; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final telemetry = _RecordingTelemetry(); + final container = ProviderContainer( + overrides: [ + notificationPluginProvider.overrideWithValue(plugin), + telemetryProvider.overrideWithValue(telemetry), + l10nProvider.overrideWithValue(lookupAppLocalizations(const Locale('en'))), + ...overrides, + ], + ); + addTearDown(container.dispose); + return (container: container, telemetry: telemetry); +} + +NotificationData _notification({String id = 'n-1', DateTime? scheduledTime}) => NotificationData( + id: id, + accountId: 'qzpyxSr48YN9EQe2ito734iCReTXjnungmNCSY4Yph1YznEda', + type: NotificationType.success, + source: NotificationSource.local, + title: 'Sent 1 QTC', + message: 'Main', + accountName: 'Main', + timestamp: DateTime(2026), + scheduledTime: scheduledTime, +); + +/// Lets what the providers started finish. +Future _settle() => Future.delayed(Duration.zero); + +void main() { + group('the binding', () { + test('starting sets up macOS, Windows and Linux without asking for permission', () async { + final plugin = FakeNotificationPlugin(); + final (:container, telemetry: _) = _open(plugin, platform: TargetPlatform.macOS); + final notifications = container.read(desktopLocalNotificationsProvider.notifier); + + await notifications.start(); + // Started once, however often asked. + await notifications.start(); + + expect(plugin.initializations, hasLength(1)); + final settings = plugin.initializations.single; + expect(settings.macOS?.requestAlertPermission, isFalse); + expect(settings.macOS?.requestSoundPermission, isFalse); + expect(settings.macOS?.requestBadgePermission, isFalse); + expect(settings.windows?.appName, 'Quantus Wallet'); + expect(settings.windows?.appUserModelId, 'Quantus.DesktopWallet'); + expect(settings.windows?.guid, '745d2a45-cfdc-4f29-91c2-0c8a985a2e19'); + expect(settings.linux?.defaultActionName, 'Open'); + expect(plugin.permissionRequests, 0); + expect(container.read(desktopLocalNotificationsProvider), isA()); + }); + + test('on macOS, asking for permission asks the system and reports allowed when it agrees', () async { + final plugin = FakeNotificationPlugin(grants: true); + final (:container, telemetry: _) = _open(plugin, platform: TargetPlatform.macOS); + final notifications = container.read(desktopLocalNotificationsProvider.notifier); + + await notifications.start(); + await notifications.requestPermission(); + + expect(plugin.permissionRequests, 1); + expect(container.read(desktopLocalNotificationsProvider), isA()); + }); + + test('on macOS, a refusal reports notifications as turned off', () async { + final plugin = FakeNotificationPlugin(grants: false); + final (:container, telemetry: _) = _open(plugin, platform: TargetPlatform.macOS); + final notifications = container.read(desktopLocalNotificationsProvider.notifier); + + await notifications.start(); + await notifications.requestPermission(); + + expect(container.read(desktopLocalNotificationsProvider), isA()); + }); + + for (final platform in [TargetPlatform.windows, TargetPlatform.linux]) { + test('on ${platform.name}, nothing is asked: once started, notifications are allowed', () async { + final plugin = FakeNotificationPlugin(); + final (:container, telemetry: _) = _open(plugin, platform: platform); + final notifications = container.read(desktopLocalNotificationsProvider.notifier); + + await notifications.start(); + + expect(container.read(desktopLocalNotificationsProvider), isA()); + + await notifications.requestPermission(); + + expect(plugin.permissionRequests, 0); + expect(container.read(desktopLocalNotificationsProvider), isA()); + }); + } + + test('a start that fails reports notifications unavailable with the reason, tells telemetry, and does not ' + 'throw', () async { + final plugin = FakeNotificationPlugin(startError: StateError('no session bus')); + final (:container, :telemetry) = _open(plugin, platform: TargetPlatform.linux); + final notifications = container.read(desktopLocalNotificationsProvider.notifier); + + await notifications.start(); + // Asking afterwards changes nothing: there is nothing to ask. + await notifications.requestPermission(); + + expect( + container.read(desktopLocalNotificationsProvider), + isA().having((s) => s.reason, 'reason', contains('no session bus')), + ); + expect(telemetry.errors, ['desktop_notifications_unavailable']); + }); + + test('a notification is shown with its title and body, each under its own id', () async { + final plugin = FakeNotificationPlugin(); + final (:container, telemetry: _) = _open(plugin, platform: TargetPlatform.windows); + final notifications = container.read(desktopLocalNotificationsProvider.notifier); + await notifications.start(); + + await notifications.showOrScheduleNotification(_notification(id: 'n-1')); + await notifications.showOrScheduleNotification(_notification(id: 'n-2')); + + expect(plugin.shown.map((n) => (n.title, n.body)), [('Sent 1 QTC', 'Main'), ('Sent 1 QTC', 'Main')]); + expect(plugin.shown.first.id, isNot(plugin.shown.last.id)); + }); + + test('a notification carries the account it is about', () async { + final plugin = FakeNotificationPlugin(); + final (:container, telemetry: _) = _open(plugin, platform: TargetPlatform.windows); + final notifications = container.read(desktopLocalNotificationsProvider.notifier); + await notifications.start(); + + await notifications.showOrScheduleNotification(_notification()); + + expect(jsonDecode(plugin.shown.single.payload), { + 'accountId': 'qzpyxSr48YN9EQe2ito734iCReTXjnungmNCSY4Yph1YznEda', + }); + }); + + test('a scheduled notification fails with UnsupportedError: nothing on desktop schedules one yet', () async { + final plugin = FakeNotificationPlugin(); + final (:container, telemetry: _) = _open(plugin, platform: TargetPlatform.windows); + final notifications = container.read(desktopLocalNotificationsProvider.notifier); + await notifications.start(); + + await expectLater( + notifications.showOrScheduleNotification(_notification(scheduledTime: DateTime(2026, 12))), + throwsUnsupportedError, + ); + expect(plugin.shown, isEmpty); + }); + + test('showing while notifications are not allowed fails with StateError', () async { + Future expectRefused(FakeNotificationPlugin plugin, TargetPlatform platform, {bool ask = false}) async { + final (:container, telemetry: _) = _open(plugin, platform: platform); + final notifications = container.read(desktopLocalNotificationsProvider.notifier); + await notifications.start(); + if (ask) await notifications.requestPermission(); + + await expectLater(notifications.showOrScheduleNotification(_notification()), throwsStateError); + expect(plugin.shown, isEmpty); + } + + // Not asked yet, refused, and no notification service. + await expectRefused(FakeNotificationPlugin(), TargetPlatform.macOS); + await expectRefused(FakeNotificationPlugin(grants: false), TargetPlatform.macOS, ask: true); + await expectRefused(FakeNotificationPlugin(startError: StateError('no session bus')), TargetPlatform.linux); + }); + + test('before it has started, showing fails with StateError', () async { + final plugin = FakeNotificationPlugin(); + final (:container, telemetry: _) = _open(plugin, platform: TargetPlatform.windows); + + await expectLater( + container.read(desktopLocalNotificationsProvider.notifier).showOrScheduleNotification(_notification()), + throwsStateError, + ); + }); + }); + + group('with the app', () { + test('the app starting starts the notifications; with no wallet yet, nothing is asked', () async { + final plugin = FakeNotificationPlugin(); + final presence = _Presence(WalletPresence.none); + final (:container, telemetry: _) = _open( + plugin, + platform: TargetPlatform.macOS, + overrides: [walletPresenceProvider.overrideWith(() => presence)], + ); + + container.read(notificationsStartupProvider); + await container.read(walletPresenceProvider.future); + await _settle(); + + expect(plugin.initializations, hasLength(1)); + expect(plugin.permissionRequests, 0); + expect(container.read(desktopLocalNotificationsProvider), isA()); + }); + + test('opening the wallet asks for permission', () async { + final plugin = FakeNotificationPlugin(); + final (:container, telemetry: _) = _open( + plugin, + platform: TargetPlatform.macOS, + overrides: [walletPresenceProvider.overrideWith(() => _Presence(WalletPresence.present))], + ); + + container.read(notificationsStartupProvider); + await container.read(walletPresenceProvider.future); + await _settle(); + + expect(plugin.permissionRequests, 1); + expect(container.read(desktopLocalNotificationsProvider), isA()); + }); + + test('a wallet made after the app started asks for permission once it is there', () async { + final plugin = FakeNotificationPlugin(); + final presence = _Presence(WalletPresence.none); + final (:container, telemetry: _) = _open( + plugin, + platform: TargetPlatform.macOS, + overrides: [walletPresenceProvider.overrideWith(() => presence)], + ); + container.read(notificationsStartupProvider); + await container.read(walletPresenceProvider.future); + await _settle(); + + presence.become(WalletPresence.present); + await _settle(); + + expect(plugin.permissionRequests, 1); + expect(container.read(desktopLocalNotificationsProvider), isA()); + }); + }); +} diff --git a/desktop-app/test/services/desktop_local_notifications_test.dart b/desktop-app/test/services/desktop_local_notifications_test.dart deleted file mode 100644 index 0ee6aa81d..000000000 --- a/desktop-app/test/services/desktop_local_notifications_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:quantus_desktop_wallet/services/desktop_local_notifications.dart'; -import 'package:wallet_core/models/notification_models.dart'; - -void main() { - test('desktop local notifications are not implemented: showing a notification fails', () async { - const localNotifications = DesktopLocalNotifications(); - final notification = NotificationData( - id: 'n-1', - accountId: 'qzpyxSr48YN9EQe2ito734iCReTXjnungmNCSY4Yph1YznEda', - type: NotificationType.info, - source: NotificationSource.push, - title: 'Received', - message: '1 QTC', - accountName: 'Account 1', - timestamp: DateTime(2026), - ); - - await expectLater( - localNotifications.showOrScheduleNotification(notification), - throwsA( - isA().having( - (e) => e.message, - 'message', - contains('Desktop local notifications are not implemented'), - ), - ), - ); - }); -} diff --git a/desktop-app/test/services/fake_notification_plugin.dart b/desktop-app/test/services/fake_notification_plugin.dart new file mode 100644 index 000000000..87f32682b --- /dev/null +++ b/desktop-app/test/services/fake_notification_plugin.dart @@ -0,0 +1,48 @@ +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:quantus_desktop_wallet/services/notification_plugin.dart'; + +/// A notification the app showed. +typedef ShownNotification = ({int id, String title, String body, String payload}); + +/// Stands in for the system's notifications: records what the app asks of +/// them, and answers as [startError] and [grants] say. +class FakeNotificationPlugin implements NotificationPlugin { + FakeNotificationPlugin({this.startError, this.grants = true}); + + /// What starting throws, as a system without a notification service would. + Object? startError; + + /// Whether macOS lets the app show notifications when asked. + bool grants; + + final initializations = []; + var permissionRequests = 0; + final shown = []; + void Function(String? payload)? _onClick; + + @override + Future initialize(InitializationSettings settings, {required void Function(String? payload) onClick}) async { + initializations.add(settings); + final error = startError; + if (error != null) throw error; + _onClick = onClick; + } + + @override + Future requestMacOSPermission() async { + permissionRequests++; + return grants; + } + + @override + Future show({required int id, required String title, required String body, required String payload}) async { + shown.add((id: id, title: title, body: body, payload: payload)); + } + + /// Clicks a notification with [payload], as the person would. + void click(String? payload) { + final onClick = _onClick; + if (onClick == null) throw StateError('Clicked a notification before the notifications were started'); + onClick(payload); + } +} From abecd6f93f5ed7eb15ef8e1572329e1e7b20df48 Mon Sep 17 00:00:00 2001 From: Beast Date: Sat, 21 Nov 2026 00:55:47 +0800 Subject: [PATCH 3/9] Desktop: keep polling while the window is minimized or hidden A send that never lands is only noticed by the history poll, which paused with a window no one could see, so it could not be notified then. The polling now pauses only without a network. What matters only on screen (prices, the swap's 1Click polling) still pauses with the window. --- desktop-app/lib/ui/shell/live_data_scope.dart | 23 ++++++++------- .../test/ui/shell/live_data_scope_test.dart | 28 +++++++++---------- 2 files changed, 24 insertions(+), 27 deletions(-) diff --git a/desktop-app/lib/ui/shell/live_data_scope.dart b/desktop-app/lib/ui/shell/live_data_scope.dart index 78e05b0d0..41c3a1305 100644 --- a/desktop-app/lib/ui/shell/live_data_scope.dart +++ b/desktop-app/lib/ui/shell/live_data_scope.dart @@ -9,13 +9,14 @@ import 'package:wallet_core/providers/connectivity_provider.dart'; import 'package:wallet_core/services/history_polling_manager.dart'; import 'package:wallet_core/services/telemetry.dart'; -/// Keeps what the open wallet shows current, as the phone does: the shared -/// polling ([HistoryPollingManager]) runs while the window is on screen and -/// the computer is online, and catches up at once when either comes back. +/// Keeps what the open wallet shows current: the shared polling +/// ([HistoryPollingManager]) runs while the computer is online, and catches +/// up at once when it comes back. /// -/// A window behind another app's is still on screen, and still being looked -/// at, so it keeps polling. Only a minimized or hidden window pauses, as a -/// phone's app does in the background. +/// Unlike the phone's, it keeps polling while the window is minimized or +/// hidden: what the wallet watches for, such as a send that never lands, is +/// noticed and notified then too. What only matters on screen still pauses +/// with a window no one can see ([appLifecycleStateProvider]). class LiveDataScope extends ConsumerStatefulWidget { const LiveDataScope({super.key, required this.child}); @@ -69,7 +70,6 @@ class _LiveDataScopeState extends ConsumerState { void _onWindowChanged(AppLifecycleState state) { _isOnScreen = _onScreen(state); _publish(state); - _update(); } /// Tells what else pauses in the background ([appLifecycleStateProvider]) @@ -78,12 +78,11 @@ class _LiveDataScopeState extends ConsumerState { ref.read(appLifecycleStateProvider.notifier).state = _isOnScreen ? AppLifecycleState.resumed : state; } - /// Pauses the polling when there is no one to show it to or no network to - /// poll, and resumes it, caught up, once there are both. + /// Pauses the polling when there is no network to poll, and resumes it, + /// caught up, once there is. void _update() { - final shouldRun = _isOnScreen && _isOnline; - if (shouldRun == !_isPaused) return; - _isPaused = !shouldRun; + if (_isOnline == !_isPaused) return; + _isPaused = !_isOnline; if (_isPaused) { _polling.pausePolling(); return; diff --git a/desktop-app/test/ui/shell/live_data_scope_test.dart b/desktop-app/test/ui/shell/live_data_scope_test.dart index 3886a6d54..e98c998bc 100644 --- a/desktop-app/test/ui/shell/live_data_scope_test.dart +++ b/desktop-app/test/ui/shell/live_data_scope_test.dart @@ -81,24 +81,19 @@ void main() { expect(polling.starts, 0); }); - testOnMac('a window that is minimized or hidden pauses the polling; shown again, it resumes and catches up at once', ( - tester, - ) async { + testOnMac('a window that is minimized or hidden keeps polling, so that what the wallet watches for is still ' + 'noticed', (tester) async { final polling = FakeHistoryPollingManager(); await _openWallet(tester, polling: polling); await _window(tester, AppLifecycleState.hidden); - expect(polling.calls, ['pause']); + expect(polling.calls, isEmpty); await _window(tester, AppLifecycleState.inactive); - - expect(polling.calls, ['pause', 'resume', 'silentRefresh']); - - // Taking the focus as well changes nothing more. await _window(tester, AppLifecycleState.resumed); - expect(polling.calls, ['pause', 'resume', 'silentRefresh']); + expect(polling.calls, isEmpty); }); testOnMac('a window that only loses the focus keeps polling', (tester) async { @@ -146,7 +141,7 @@ void main() { expect(polling.calls, ['pause', 'resume', 'silentRefresh']); }); - testOnMac('the network coming back while the window is hidden resumes nothing until it is shown', (tester) async { + testOnMac('the network coming back while the window is hidden resumes the polling at once', (tester) async { final polling = FakeHistoryPollingManager(); final network = FakeNetwork(); await _openWallet(tester, polling: polling, network: network); @@ -157,9 +152,9 @@ void main() { network.goOnline(); await tester.pumpAndSettle(); - // Paused once, however many reasons there are to be. - expect(polling.calls, ['pause']); + expect(polling.calls, ['pause', 'resume', 'silentRefresh']); + // Shown again, it is already caught up. await _window(tester, AppLifecycleState.inactive); expect(polling.calls, ['pause', 'resume', 'silentRefresh']); @@ -201,10 +196,13 @@ void main() { testOnMac('a catch-up that fails leaves the app running, the polling resumed', (tester) async { final polling = FakeHistoryPollingManager()..refreshError = StateError('the node did not answer'); - await _openWallet(tester, polling: polling); + final network = FakeNetwork(); + await _openWallet(tester, polling: polling, network: network); - await _window(tester, AppLifecycleState.hidden); - await _window(tester, AppLifecycleState.inactive); + network.goOffline(); + await tester.pumpAndSettle(); + network.goOnline(); + await tester.pumpAndSettle(); expect(tester.takeException(), isNull); expect(polling.calls, ['pause', 'resume', 'silentRefresh']); From fda036742fce954672d94e870c767c781703c02b Mon Sep 17 00:00:00 2001 From: Beast Date: Sat, 21 Nov 2026 01:01:31 +0800 Subject: [PATCH 4/9] Desktop: a clicked notification opens the account it was about The window comes to the front, restored if it was minimized or hidden, and the account the notification named is selected while it is still there. The window channel serves bringToFront on all three systems: macOS in MainFlutterWindow.swift, Windows in window_focus.cpp, Linux in my_application.cc. A click whose payload cannot be read still brings the window forward and is reported. --- .../lib/providers/notifications_provider.dart | 24 ++++++- desktop-app/lib/services/window_chrome.dart | 11 +++- desktop-app/linux/runner/my_application.cc | 34 ++++++++++ .../macos/Runner/MainFlutterWindow.swift | 18 ++++++ .../notifications_provider_test.dart | 24 +++++++ .../ui/shell/notification_click_test.dart | 64 +++++++++++++++++++ desktop-app/windows/runner/CMakeLists.txt | 1 + desktop-app/windows/runner/flutter_window.cpp | 3 + desktop-app/windows/runner/flutter_window.h | 4 ++ desktop-app/windows/runner/window_focus.cpp | 31 +++++++++ desktop-app/windows/runner/window_focus.h | 30 +++++++++ 11 files changed, 241 insertions(+), 3 deletions(-) create mode 100644 desktop-app/test/ui/shell/notification_click_test.dart create mode 100644 desktop-app/windows/runner/window_focus.cpp create mode 100644 desktop-app/windows/runner/window_focus.h diff --git a/desktop-app/lib/providers/notifications_provider.dart b/desktop-app/lib/providers/notifications_provider.dart index 279a128dc..d41a67e0d 100644 --- a/desktop-app/lib/providers/notifications_provider.dart +++ b/desktop-app/lib/providers/notifications_provider.dart @@ -7,8 +7,10 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:quantus_desktop_wallet/constants.dart'; import 'package:quantus_desktop_wallet/models/notification_status.dart'; import 'package:quantus_desktop_wallet/models/wallet_presence.dart'; +import 'package:quantus_desktop_wallet/providers/shell_providers.dart'; import 'package:quantus_desktop_wallet/providers/wallet_presence_provider.dart'; import 'package:quantus_desktop_wallet/services/notification_plugin.dart'; +import 'package:quantus_desktop_wallet/services/window_chrome.dart'; import 'package:quantus_sdk/quantus_sdk.dart'; import 'package:wallet_core/models/notification_models.dart'; import 'package:wallet_core/providers/l10n_provider.dart'; @@ -51,7 +53,7 @@ class DesktopLocalNotifications extends Notifier implements linux: LinuxInitializationSettings(defaultActionName: ref.read(l10nProvider).desktopNotificationOpenAction), ); try { - await ref.read(notificationPluginProvider).initialize(settings, onClick: (_) {}); + await ref.read(notificationPluginProvider).initialize(settings, onClick: _open); } catch (e) { _unavailable(e); return; @@ -74,6 +76,26 @@ class DesktopLocalNotifications extends Notifier implements } } + /// Opens what a clicked notification was about: the window comes to the + /// front, on the account the notification named when it is still there. + void _open(String? payload) { + unawaited(const WindowChrome().bringToFront()); + final String accountId; + try { + accountId = (jsonDecode(payload!) as Map)['accountId'] as String; + } catch (e) { + quantusPrint('A clicked notification could not be read: $e'); + ref.read(telemetryProvider).sendError('desktop_notification_click_unreadable', error: e); + return; + } + for (final account in ref.read(sidebarAccountsProvider)) { + if (account.account.accountId == accountId) { + unawaited(ref.read(sidebarSelectionProvider.notifier).showAccount(account)); + return; + } + } + } + void _unavailable(Object error) { quantusPrint('Desktop notifications are unavailable: $error'); ref.read(telemetryProvider).sendError('desktop_notifications_unavailable', error: error); diff --git a/desktop-app/lib/services/window_chrome.dart b/desktop-app/lib/services/window_chrome.dart index f035ff6d7..9e0435f79 100644 --- a/desktop-app/lib/services/window_chrome.dart +++ b/desktop-app/lib/services/window_chrome.dart @@ -15,8 +15,11 @@ const double trafficLightsInset = 84; /// lights in a strip of this height, so the two must change together. const double shellHeaderHeight = 52; -/// Asks the macOS window to do what its title bar would have done, now that -/// the app's header covers it. Served by `MainFlutterWindow.swift`. +/// Asks the window for what Flutter cannot do itself: on macOS, what its title +/// bar would have done, now that the app's header covers it; on every +/// platform, coming to the front. Served by `MainFlutterWindow.swift`, and on +/// Windows and Linux by the runner (`window_focus.cpp`, `my_application.cc`), +/// which serve [bringToFront] only. class WindowChrome { const WindowChrome(); @@ -28,4 +31,8 @@ class WindowChrome { /// Zooms or minimises the window, whichever the system is set to do for a /// double-click on a title bar. Future titleBarDoubleClick() => channel.invokeMethod('titleBarDoubleClick'); + + /// Shows the window, minimized or hidden as it may be, in front of the + /// other apps' windows. + Future bringToFront() => channel.invokeMethod('bringToFront'); } diff --git a/desktop-app/linux/runner/my_application.cc b/desktop-app/linux/runner/my_application.cc index cd94bd4bf..83603b29e 100644 --- a/desktop-app/linux/runner/my_application.cc +++ b/desktop-app/linux/runner/my_application.cc @@ -10,10 +10,35 @@ struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; + // Brings the window to the front for the app. + FlMethodChannel* window_channel; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) +// Answers the app's requests of its window, |user_data|, as when a +// notification is clicked. WindowChrome in lib/services/window_chrome.dart is +// the app's side; of its requests, Linux serves "bringToFront" only. +static void window_method_call_cb(FlMethodChannel* channel, + FlMethodCall* method_call, + gpointer user_data) { + GtkWindow* window = GTK_WINDOW(user_data); + g_autoptr(FlMethodResponse) response = nullptr; + if (g_strcmp0(fl_method_call_get_name(method_call), "bringToFront") == 0) { + // Restores a minimized window too. The window manager may only mark it + // as wanting attention instead of raising it. + gtk_window_present(window); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); + } else { + response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + } + g_autoptr(GError) error = nullptr; + if (!fl_method_call_respond(method_call, response, &error)) { + g_warning("Failed to answer %s: %s", fl_method_call_get_name(method_call), + error->message); + } +} + // Called when first Flutter frame received. static void first_frame_cb(MyApplication* self, FlView* view) { gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); @@ -81,6 +106,14 @@ static void my_application_activate(GApplication* application) { fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + self->window_channel = fl_method_channel_new( + fl_engine_get_binary_messenger(fl_view_get_engine(view)), + "com.quantus.desktop-wallet/window", FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler( + self->window_channel, window_method_call_cb, g_object_ref(window), + g_object_unref); + gtk_widget_grab_focus(GTK_WIDGET(view)); } @@ -127,6 +160,7 @@ static void my_application_shutdown(GApplication* application) { static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + g_clear_object(&self->window_channel); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } diff --git a/desktop-app/macos/Runner/MainFlutterWindow.swift b/desktop-app/macos/Runner/MainFlutterWindow.swift index 71675103e..b9e468bcf 100644 --- a/desktop-app/macos/Runner/MainFlutterWindow.swift +++ b/desktop-app/macos/Runner/MainFlutterWindow.swift @@ -53,6 +53,9 @@ class MainFlutterWindow: NSWindow { case "titleBarDoubleClick": self?.performTitleBarDoubleClick() result(nil) + case "bringToFront": + self?.bringToFront() + result(nil) default: result(FlutterMethodNotImplemented) } @@ -127,6 +130,21 @@ class MainFlutterWindow: NSWindow { } } + /// Shows the window in front of the other apps' windows, minimized or + /// hidden as it may be: a notification was clicked. + private func bringToFront() { + NSApp.unhide(nil) + if self.isMiniaturized { + self.deminiaturize(nil) + } + self.makeKeyAndOrderFront(nil) + if #available(macOS 14.0, *) { + NSApp.activate() + } else { + NSApp.activate(ignoringOtherApps: true) + } + } + /// Moves the window with the mouse press the app's header just received. private func startDrag() { // By the time the app's request arrives the button may be up again, and diff --git a/desktop-app/test/providers/notifications_provider_test.dart b/desktop-app/test/providers/notifications_provider_test.dart index 1bb3e5a91..4507d7fa9 100644 --- a/desktop-app/test/providers/notifications_provider_test.dart +++ b/desktop-app/test/providers/notifications_provider_test.dart @@ -10,6 +10,7 @@ import 'package:quantus_desktop_wallet/models/wallet_presence.dart'; import 'package:quantus_desktop_wallet/providers/notifications_provider.dart'; import 'package:quantus_desktop_wallet/providers/wallet_presence_provider.dart'; import 'package:quantus_desktop_wallet/services/notification_plugin.dart'; +import 'package:quantus_desktop_wallet/services/window_chrome.dart'; import 'package:wallet_core/l10n/app_localizations.dart'; import 'package:wallet_core/models/notification_models.dart'; import 'package:wallet_core/providers/l10n_provider.dart'; @@ -76,6 +77,8 @@ NotificationData _notification({String id = 'n-1', DateTime? scheduledTime}) => Future _settle() => Future.delayed(Duration.zero); void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + group('the binding', () { test('starting sets up macOS, Windows and Linux without asking for permission', () async { final plugin = FakeNotificationPlugin(); @@ -223,6 +226,27 @@ void main() { }); }); + group('a click', () { + test('whose payload cannot be read still brings the window forward, and is reported', () async { + final window = []; + final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(WindowChrome.channel, (call) async { + window.add(call.method); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(WindowChrome.channel, null)); + final plugin = FakeNotificationPlugin(); + final (:container, :telemetry) = _open(plugin, platform: TargetPlatform.macOS); + await container.read(desktopLocalNotificationsProvider.notifier).start(); + + plugin.click('not what the app shows'); + await _settle(); + + expect(window, ['bringToFront']); + expect(telemetry.errors, ['desktop_notification_click_unreadable']); + }); + }); + group('with the app', () { test('the app starting starts the notifications; with no wallet yet, nothing is asked', () async { final plugin = FakeNotificationPlugin(); diff --git a/desktop-app/test/ui/shell/notification_click_test.dart b/desktop-app/test/ui/shell/notification_click_test.dart new file mode 100644 index 000000000..a7f4f61c1 --- /dev/null +++ b/desktop-app/test/ui/shell/notification_click_test.dart @@ -0,0 +1,64 @@ +import 'dart:convert'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:quantus_desktop_wallet/ui/shell/desktop_shell.dart'; +import 'package:quantus_sdk/quantus_sdk.dart'; +import 'package:wallet_core/providers/account_providers.dart'; + +import '../../fakes.dart'; +import '../../services/fake_notification_plugin.dart'; + +/// Opens the window on a wallet whose active account is Main. +Future _openWallet(WidgetTester tester, FakeNotificationPlugin notifications) async { + await pumpShell( + tester, + notifications: notifications, + overrides: shellOverrides( + accounts: const [mainAccount, savingsAccount], + settings: FakeSettingsService(activeAccount: const RegularAccount(mainAccount)), + ), + ); + return ProviderScope.containerOf(tester.element(find.byType(DesktopShell))); +} + +/// What a notification about [accountId] carries. +String _about(String accountId) => jsonEncode({'accountId': accountId}); + +String? _activeAccountId(ProviderContainer container) => container.read(activeAccountProvider).value?.account.accountId; + +Future _clickSelectsTheAccount(WidgetTester tester) async { + final notifications = FakeNotificationPlugin(); + final window = recordWindowRequests(tester); + final container = await _openWallet(tester, notifications); + + notifications.click(_about(savingsAccount.accountId)); + await tester.pumpAndSettle(); + + expect(window, ['bringToFront']); + expect(_activeAccountId(container), savingsAccount.accountId); +} + +void main() { + testOnMac( + 'clicking a notification brings the window forward and selects the account it was about', + _clickSelectsTheAccount, + ); + + testOnWindowsAndLinux( + 'clicking a notification brings the window forward and selects the account it was about', + _clickSelectsTheAccount, + ); + + testOnMac('a click about an account that is gone since only brings the window forward', (tester) async { + final notifications = FakeNotificationPlugin(); + final window = recordWindowRequests(tester); + final container = await _openWallet(tester, notifications); + + notifications.click(_about('qzGone')); + await tester.pumpAndSettle(); + + expect(window, ['bringToFront']); + expect(_activeAccountId(container), mainAccount.accountId); + }); +} diff --git a/desktop-app/windows/runner/CMakeLists.txt b/desktop-app/windows/runner/CMakeLists.txt index 5f47b127f..3db5013a1 100644 --- a/desktop-app/windows/runner/CMakeLists.txt +++ b/desktop-app/windows/runner/CMakeLists.txt @@ -12,6 +12,7 @@ add_executable(${BINARY_NAME} WIN32 "sensitive_clipboard.cpp" "utils.cpp" "win32_window.cpp" + "window_focus.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" diff --git a/desktop-app/windows/runner/flutter_window.cpp b/desktop-app/windows/runner/flutter_window.cpp index 710b37a0f..b66610b98 100644 --- a/desktop-app/windows/runner/flutter_window.cpp +++ b/desktop-app/windows/runner/flutter_window.cpp @@ -29,6 +29,7 @@ bool FlutterWindow::OnCreate() { RegisterPlugins(flutter_controller_->engine()); sensitive_clipboard_ = std::make_unique(flutter_controller_->engine()->messenger(), GetHandle()); + window_focus_ = std::make_unique(flutter_controller_->engine()->messenger(), GetHandle()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); flutter_controller_->engine()->SetNextFrameCallback([&]() { @@ -54,6 +55,8 @@ void FlutterWindow::OnDestroy() { } sensitive_clipboard_ = nullptr; } + // Its channel answers on the engine's messenger, which goes with the engine. + window_focus_ = nullptr; if (flutter_controller_) { flutter_controller_ = nullptr; } diff --git a/desktop-app/windows/runner/flutter_window.h b/desktop-app/windows/runner/flutter_window.h index 8eee17863..5a9f08e12 100644 --- a/desktop-app/windows/runner/flutter_window.h +++ b/desktop-app/windows/runner/flutter_window.h @@ -8,6 +8,7 @@ #include "sensitive_clipboard.h" #include "win32_window.h" +#include "window_focus.h" // A window that does nothing but host a Flutter view. class FlutterWindow : public Win32Window { @@ -32,6 +33,9 @@ class FlutterWindow : public Win32Window { // Copies secrets for the app, kept out of clipboard history. std::unique_ptr sensitive_clipboard_; + + // Brings the window to the front for the app. + std::unique_ptr window_focus_; }; #endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/desktop-app/windows/runner/window_focus.cpp b/desktop-app/windows/runner/window_focus.cpp new file mode 100644 index 000000000..a78678df6 --- /dev/null +++ b/desktop-app/windows/runner/window_focus.cpp @@ -0,0 +1,31 @@ +#include "window_focus.h" + +#include + +namespace { + +constexpr char kChannelName[] = "com.quantus.desktop-wallet/window"; + +} // namespace + +WindowFocus::WindowFocus(flutter::BinaryMessenger* messenger, HWND window) : window_(window) { + channel_ = std::make_unique>( + messenger, kChannelName, &flutter::StandardMethodCodec::GetInstance()); + channel_->SetMethodCallHandler( + [this](const flutter::MethodCall& call, + std::unique_ptr> result) { + if (call.method_name() == "bringToFront") { + BringToFront(); + result->Success(); + } else { + result->NotImplemented(); + } + }); +} + +void WindowFocus::BringToFront() { + ShowWindow(window_, IsIconic(window_) ? SW_RESTORE : SW_SHOW); + // Windows keeps the foreground for the app in use, and when it refuses it + // flashes the window's taskbar button instead. + SetForegroundWindow(window_); +} diff --git a/desktop-app/windows/runner/window_focus.h b/desktop-app/windows/runner/window_focus.h new file mode 100644 index 000000000..ac73164ac --- /dev/null +++ b/desktop-app/windows/runner/window_focus.h @@ -0,0 +1,30 @@ +#ifndef RUNNER_WINDOW_FOCUS_H_ +#define RUNNER_WINDOW_FOCUS_H_ + +#include +#include +#include +#include + +#include + +// Brings the app's window to the front when the app asks, as it does when a +// notification is clicked. WindowChrome in lib/services/window_chrome.dart is +// the app's side; of its requests, Windows serves "bringToFront" only. +class WindowFocus { + public: + // Answers the app on |messenger| for the top-level |window|. + WindowFocus(flutter::BinaryMessenger* messenger, HWND window); + + WindowFocus(const WindowFocus&) = delete; + WindowFocus& operator=(const WindowFocus&) = delete; + + private: + // Shows the window, restored when it is minimized, in front of the others. + void BringToFront(); + + HWND window_; + std::unique_ptr> channel_; +}; + +#endif // RUNNER_WINDOW_FOCUS_H_ From d1065e81a09b38d405d51e420521e090b2ecd07b Mon Sep 17 00:00:00 2001 From: Beast Date: Sat, 21 Nov 2026 01:18:21 +0800 Subject: [PATCH 5/9] Add the strings for the desktop's notifications about its own sends and proposals --- wallet_core/lib/l10n/app_en.arb | 82 +++++++++++++++++++ wallet_core/lib/l10n/app_id.arb | 12 ++- wallet_core/lib/l10n/app_localizations.dart | 60 ++++++++++++++ .../lib/l10n/app_localizations_en.dart | 42 ++++++++++ .../lib/l10n/app_localizations_id.dart | 42 ++++++++++ 5 files changed, 237 insertions(+), 1 deletion(-) diff --git a/wallet_core/lib/l10n/app_en.arb b/wallet_core/lib/l10n/app_en.arb index a51244d85..9c9ea1209 100644 --- a/wallet_core/lib/l10n/app_en.arb +++ b/wallet_core/lib/l10n/app_en.arb @@ -4299,5 +4299,87 @@ "desktopNotificationOpenAction": "Open", "@desktopNotificationOpenAction": { "description": "Desktop notification on Linux: the action that opens the wallet when the notification is clicked" + }, + "desktopNotificationSentTitle": "Sent {amount}", + "@desktopNotificationSentTitle": { + "description": "Desktop notification title: a send from this computer was confirmed by the chain; amount includes the token symbol", + "placeholders": { + "amount": { + "type": "String" + } + } + }, + "desktopNotificationSentBody": "From {account}", + "@desktopNotificationSentBody": { + "description": "Desktop notification body: the account the confirmed send came from", + "placeholders": { + "account": { + "type": "String" + } + } + }, + "desktopNotificationSendNotConfirmedTitle": "Send not confirmed", + "@desktopNotificationSendNotConfirmedTitle": { + "description": "Desktop notification title: a send from this computer was not seen on the chain within the time the wallet watches for it" + }, + "desktopNotificationSendNotConfirmedBody": "{amount} from {account} wasn’t seen on the chain in time. It may have failed, or only be late.", + "@desktopNotificationSendNotConfirmedBody": { + "description": "Desktop notification body: a send not seen on the chain in time; amount includes the token symbol", + "placeholders": { + "amount": { + "type": "String" + }, + "account": { + "type": "String" + } + } + }, + "desktopNotificationSendFailedTitle": "Send failed", + "@desktopNotificationSendFailedTitle": { + "description": "Desktop notification title: a send from this computer failed" + }, + "desktopNotificationSendFailedBody": "{amount} from {account} was not sent.", + "@desktopNotificationSendFailedBody": { + "description": "Desktop notification body: a send that failed; amount includes the token symbol", + "placeholders": { + "amount": { + "type": "String" + }, + "account": { + "type": "String" + } + } + }, + "desktopNotificationProposalCreatedTitle": "Proposal created", + "@desktopNotificationProposalCreatedTitle": { + "description": "Desktop notification title: a multisig proposal made on this computer was created on the chain" + }, + "desktopNotificationProposalCreatedBody": "Send {amount} from {multisig}", + "@desktopNotificationProposalCreatedBody": { + "description": "Desktop notification body: what the created proposal sends, and from which multisig; amount includes the token symbol", + "placeholders": { + "amount": { + "type": "String" + }, + "multisig": { + "type": "String" + } + } + }, + "desktopNotificationProposalNotConfirmedTitle": "Proposal not confirmed", + "@desktopNotificationProposalNotConfirmedTitle": { + "description": "Desktop notification title: a multisig proposal made on this computer was not seen on the chain in time" + }, + "desktopNotificationProposalNotConfirmedBody": "The proposal to send {amount} from {multisig} wasn’t seen on the chain in time.", + "@desktopNotificationProposalNotConfirmedBody": { + "description": "Desktop notification body: a proposal not seen on the chain in time; amount includes the token symbol", + "placeholders": { + "amount": { + "type": "String" + }, + "multisig": { + "type": "String" + } + } } } diff --git a/wallet_core/lib/l10n/app_id.arb b/wallet_core/lib/l10n/app_id.arb index 05ee28172..c61dd76ba 100644 --- a/wallet_core/lib/l10n/app_id.arb +++ b/wallet_core/lib/l10n/app_id.arb @@ -799,5 +799,15 @@ "desktopActivitySigners": "Penanda tangan", "desktopActivityCreatedBy": "Dibuat oleh", "desktopActivityCreationFee": "Biaya multisig", - "desktopNotificationOpenAction": "Buka" + "desktopNotificationOpenAction": "Buka", + "desktopNotificationSentTitle": "{amount} terkirim", + "desktopNotificationSentBody": "Dari {account}", + "desktopNotificationSendNotConfirmedTitle": "Pengiriman belum terkonfirmasi", + "desktopNotificationSendNotConfirmedBody": "{amount} dari {account} tidak terlihat di rantai tepat waktu. Mungkin gagal, atau hanya terlambat.", + "desktopNotificationSendFailedTitle": "Pengiriman gagal", + "desktopNotificationSendFailedBody": "{amount} dari {account} tidak terkirim.", + "desktopNotificationProposalCreatedTitle": "Proposal dibuat", + "desktopNotificationProposalCreatedBody": "Kirim {amount} dari {multisig}", + "desktopNotificationProposalNotConfirmedTitle": "Proposal belum terkonfirmasi", + "desktopNotificationProposalNotConfirmedBody": "Proposal untuk mengirim {amount} dari {multisig} tidak terlihat di rantai tepat waktu." } diff --git a/wallet_core/lib/l10n/app_localizations.dart b/wallet_core/lib/l10n/app_localizations.dart index 0c5466ac7..934b5ca99 100644 --- a/wallet_core/lib/l10n/app_localizations.dart +++ b/wallet_core/lib/l10n/app_localizations.dart @@ -5377,6 +5377,66 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Open'** String get desktopNotificationOpenAction; + + /// Desktop notification title: a send from this computer was confirmed by the chain; amount includes the token symbol + /// + /// In en, this message translates to: + /// **'Sent {amount}'** + String desktopNotificationSentTitle(String amount); + + /// Desktop notification body: the account the confirmed send came from + /// + /// In en, this message translates to: + /// **'From {account}'** + String desktopNotificationSentBody(String account); + + /// Desktop notification title: a send from this computer was not seen on the chain within the time the wallet watches for it + /// + /// In en, this message translates to: + /// **'Send not confirmed'** + String get desktopNotificationSendNotConfirmedTitle; + + /// Desktop notification body: a send not seen on the chain in time; amount includes the token symbol + /// + /// In en, this message translates to: + /// **'{amount} from {account} wasn’t seen on the chain in time. It may have failed, or only be late.'** + String desktopNotificationSendNotConfirmedBody(String amount, String account); + + /// Desktop notification title: a send from this computer failed + /// + /// In en, this message translates to: + /// **'Send failed'** + String get desktopNotificationSendFailedTitle; + + /// Desktop notification body: a send that failed; amount includes the token symbol + /// + /// In en, this message translates to: + /// **'{amount} from {account} was not sent.'** + String desktopNotificationSendFailedBody(String amount, String account); + + /// Desktop notification title: a multisig proposal made on this computer was created on the chain + /// + /// In en, this message translates to: + /// **'Proposal created'** + String get desktopNotificationProposalCreatedTitle; + + /// Desktop notification body: what the created proposal sends, and from which multisig; amount includes the token symbol + /// + /// In en, this message translates to: + /// **'Send {amount} from {multisig}'** + String desktopNotificationProposalCreatedBody(String amount, String multisig); + + /// Desktop notification title: a multisig proposal made on this computer was not seen on the chain in time + /// + /// In en, this message translates to: + /// **'Proposal not confirmed'** + String get desktopNotificationProposalNotConfirmedTitle; + + /// Desktop notification body: a proposal not seen on the chain in time; amount includes the token symbol + /// + /// In en, this message translates to: + /// **'The proposal to send {amount} from {multisig} wasn’t seen on the chain in time.'** + String desktopNotificationProposalNotConfirmedBody(String amount, String multisig); } class _AppLocalizationsDelegate extends LocalizationsDelegate { diff --git a/wallet_core/lib/l10n/app_localizations_en.dart b/wallet_core/lib/l10n/app_localizations_en.dart index 7ac93472c..29449b23e 100644 --- a/wallet_core/lib/l10n/app_localizations_en.dart +++ b/wallet_core/lib/l10n/app_localizations_en.dart @@ -2954,4 +2954,46 @@ class AppLocalizationsEn extends AppLocalizations { @override String get desktopNotificationOpenAction => 'Open'; + + @override + String desktopNotificationSentTitle(String amount) { + return 'Sent $amount'; + } + + @override + String desktopNotificationSentBody(String account) { + return 'From $account'; + } + + @override + String get desktopNotificationSendNotConfirmedTitle => 'Send not confirmed'; + + @override + String desktopNotificationSendNotConfirmedBody(String amount, String account) { + return '$amount from $account wasn’t seen on the chain in time. It may have failed, or only be late.'; + } + + @override + String get desktopNotificationSendFailedTitle => 'Send failed'; + + @override + String desktopNotificationSendFailedBody(String amount, String account) { + return '$amount from $account was not sent.'; + } + + @override + String get desktopNotificationProposalCreatedTitle => 'Proposal created'; + + @override + String desktopNotificationProposalCreatedBody(String amount, String multisig) { + return 'Send $amount from $multisig'; + } + + @override + String get desktopNotificationProposalNotConfirmedTitle => 'Proposal not confirmed'; + + @override + String desktopNotificationProposalNotConfirmedBody(String amount, String multisig) { + return 'The proposal to send $amount from $multisig wasn’t seen on the chain in time.'; + } } diff --git a/wallet_core/lib/l10n/app_localizations_id.dart b/wallet_core/lib/l10n/app_localizations_id.dart index 0abcf7189..3ba03e1c6 100644 --- a/wallet_core/lib/l10n/app_localizations_id.dart +++ b/wallet_core/lib/l10n/app_localizations_id.dart @@ -2957,4 +2957,46 @@ class AppLocalizationsId extends AppLocalizations { @override String get desktopNotificationOpenAction => 'Buka'; + + @override + String desktopNotificationSentTitle(String amount) { + return '$amount terkirim'; + } + + @override + String desktopNotificationSentBody(String account) { + return 'Dari $account'; + } + + @override + String get desktopNotificationSendNotConfirmedTitle => 'Pengiriman belum terkonfirmasi'; + + @override + String desktopNotificationSendNotConfirmedBody(String amount, String account) { + return '$amount dari $account tidak terlihat di rantai tepat waktu. Mungkin gagal, atau hanya terlambat.'; + } + + @override + String get desktopNotificationSendFailedTitle => 'Pengiriman gagal'; + + @override + String desktopNotificationSendFailedBody(String amount, String account) { + return '$amount dari $account tidak terkirim.'; + } + + @override + String get desktopNotificationProposalCreatedTitle => 'Proposal dibuat'; + + @override + String desktopNotificationProposalCreatedBody(String amount, String multisig) { + return 'Kirim $amount dari $multisig'; + } + + @override + String get desktopNotificationProposalNotConfirmedTitle => 'Proposal belum terkonfirmasi'; + + @override + String desktopNotificationProposalNotConfirmedBody(String amount, String multisig) { + return 'Proposal untuk mengirim $amount dari $multisig tidak terlihat di rantai tepat waktu.'; + } } From f2ad9f71943bddb4618113b079485033c9f5094e Mon Sep 17 00:00:00 2001 From: Beast Date: Sat, 21 Nov 2026 01:26:32 +0800 Subject: [PATCH 6/9] Desktop: notify what this computer did, once the chain has had its say A Transparent send from here notifies once it is confirmed, failed, or not seen within the time the wallet watches for it; a proposal made here once it is created or not seen in time. Each notification names the account or multisig and the amount, never an address, and follows the Settings switch. A send the wallet stops watching for is removed from the pending sends unfound, as a wipe also removes it. Only one watched for the whole time is taken as given up on, so that wallet_core's PendingTransactionPollingService timeout is now public; nothing else in wallet_core changes. --- desktop-app/lib/app.dart | 2 + .../services/own_activity_notifications.dart | 206 ++++++++++++ desktop-app/pubspec.lock | 2 +- desktop-app/pubspec.yaml | 3 + .../own_activity_notifications_test.dart | 302 ++++++++++++++++++ .../pending_transaction_polling_service.dart | 7 +- 6 files changed, 519 insertions(+), 3 deletions(-) create mode 100644 desktop-app/lib/services/own_activity_notifications.dart create mode 100644 desktop-app/test/services/own_activity_notifications_test.dart diff --git a/desktop-app/lib/app.dart b/desktop-app/lib/app.dart index 0f8ccf6b1..92f74d1aa 100644 --- a/desktop-app/lib/app.dart +++ b/desktop-app/lib/app.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:quantus_desktop_wallet/constants.dart'; import 'package:quantus_desktop_wallet/providers/notifications_provider.dart'; +import 'package:quantus_desktop_wallet/services/own_activity_notifications.dart'; import 'package:quantus_desktop_wallet/ui/shell/desktop_shell.dart'; import 'package:quantus_sdk/quantus_sdk.dart'; import 'package:wallet_core/l10n/app_localizations.dart'; @@ -13,6 +14,7 @@ class QuantusDesktopApp extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { ref.watch(notificationsStartupProvider); + ref.watch(ownActivityNotificationsProvider); final theme = AppTheme.darkTheme(context, text: const AppTextThemeV3.desktop()); return MaterialApp( diff --git a/desktop-app/lib/services/own_activity_notifications.dart b/desktop-app/lib/services/own_activity_notifications.dart new file mode 100644 index 000000000..b9b6966e2 --- /dev/null +++ b/desktop-app/lib/services/own_activity_notifications.dart @@ -0,0 +1,206 @@ +import 'dart:async'; + +import 'package:clock/clock.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:quantus_desktop_wallet/models/notification_status.dart'; +import 'package:quantus_desktop_wallet/providers/notifications_provider.dart'; +import 'package:quantus_sdk/quantus_sdk.dart'; +import 'package:wallet_core/l10n/app_localizations.dart'; +import 'package:wallet_core/models/notification_models.dart'; +import 'package:wallet_core/providers/account_providers.dart'; +import 'package:wallet_core/providers/l10n_provider.dart'; +import 'package:wallet_core/providers/multisig_proposal_confirmations_provider.dart'; +import 'package:wallet_core/providers/multisig_providers.dart'; +import 'package:wallet_core/providers/notification_config_provider.dart'; +import 'package:wallet_core/providers/pending_multisig_proposals_provider.dart'; +import 'package:wallet_core/providers/pending_transactions_provider.dart'; +import 'package:wallet_core/providers/wallet_providers.dart'; +import 'package:wallet_core/send/send_strategy.dart'; +import 'package:wallet_core/services/pending_transaction_polling_service.dart'; +import 'package:wallet_core/services/telemetry.dart'; + +/// Notifies what this computer itself did, once the chain has had its say: a +/// Transparent send confirmed, failed or not seen in time, and a proposal +/// made here created or not seen in time. +/// +/// What happens elsewhere (funds received, what other signers do) is for +/// remote notifications. +class OwnActivityNotifications { + OwnActivityNotifications(this._ref) { + _ref.listen(pendingTransactionsProvider, (_, sends) => _onSends(sends)); + _ref.listen(pendingMultisigProposalsProvider, (_, proposals) => _onProposals(proposals)); + _ref.listen( + multisigProposalConfirmationsProvider, + (previous, settled) => _onSettled(previous ?? const {}, settled), + ); + } + + final Ref _ref; + + /// The broadcast sends being watched, by id, with when each was broadcast. + final _sends = {}; + + /// The proposals broadcast from here, by the hash of the transaction each + /// was sent in. Kept until their outcome is known: a created proposal + /// leaves the pending proposals before that. + final _proposals = {}; + + void _onSends(List sends) { + final now = clock.now(); + for (final send in sends) { + final watched = _sends[send.id]; + switch (send.transactionState) { + case TransactionState.pending when watched == null: + _sends[send.id] = (send: send, broadcastAt: now); + case TransactionState.inHistory when watched != null: + _sends.remove(send.id); + _notifySend( + send, + title: (l10n, amount) => l10n.desktopNotificationSentTitle(amount), + body: (l10n, _, account) => l10n.desktopNotificationSentBody(account), + ); + case TransactionState.failed when watched != null: + _sends.remove(send.id); + _notifySend( + send, + title: (l10n, _) => l10n.desktopNotificationSendFailedTitle, + body: (l10n, amount, account) => l10n.desktopNotificationSendFailedBody(amount, account), + ); + default: + break; + } + } + final present = {for (final send in sends) send.id}; + for (final id in _sends.keys.where((id) => !present.contains(id)).toList()) { + final (:send, :broadcastAt) = _sends.remove(id)!; + // Gone unfound: the wallet gave up on it, which it does only once it + // has watched for the whole time. A wipe empties the list at any time. + if (now.difference(broadcastAt) < PendingTransactionPollingService.timeout) continue; + _notifySend( + send, + title: (l10n, _) => l10n.desktopNotificationSendNotConfirmedTitle, + body: (l10n, amount, account) => l10n.desktopNotificationSendNotConfirmedBody(amount, account), + ); + } + } + + void _onProposals(List proposals) { + for (final proposal in proposals) { + final hash = proposal.extrinsicHash; + if (hash != null) _proposals[hash] = proposal; + } + } + + void _onSettled(Map previous, Map settled) { + for (final MapEntry(key: hash, value: outcome) in settled.entries) { + if (previous.containsKey(hash)) continue; + final proposal = _proposals.remove(hash); + if (proposal == null) { + quantusPrint('A proposal settled that was never seen broadcast: $hash'); + continue; + } + final multisig = _ref + .read(multisigAccountsProvider) + .value + ?.where((msig) => msig.accountId == proposal.multisigAddress) + .firstOrNull; + if (multisig == null) { + quantusPrint('Not notifying about a proposal in a multisig no longer in the wallet: $hash'); + continue; + } + final l10n = _ref.read(l10nProvider); + final amount = _amountText(proposal.amount); + switch (outcome) { + case SendConfirmation.confirmed: + _show( + id: 'proposal_created_$hash', + accountId: multisig.accountId, + accountName: multisig.name, + intent: NotificationIntent.others, + title: l10n.desktopNotificationProposalCreatedTitle, + body: l10n.desktopNotificationProposalCreatedBody(amount, multisig.name), + ); + case SendConfirmation.unconfirmed: + _show( + id: 'proposal_not_confirmed_$hash', + accountId: multisig.accountId, + accountName: multisig.name, + intent: NotificationIntent.others, + title: l10n.desktopNotificationProposalNotConfirmedTitle, + body: l10n.desktopNotificationProposalNotConfirmedBody(amount, multisig.name), + ); + case SendConfirmation.pending: + throw StateError('A proposal is settled as still pending: $hash'); + } + } + } + + void _notifySend( + PendingTransactionEvent send, { + required String Function(AppLocalizations l10n, String amount) title, + required String Function(AppLocalizations l10n, String amount, String account) body, + }) { + final account = _ref.read(accountsProvider).value?.where((a) => a.accountId == send.from).firstOrNull; + if (account == null) { + quantusPrint('Not notifying about a send from an account no longer in the wallet: ${send.id}'); + return; + } + final l10n = _ref.read(l10nProvider); + final amount = _amountText(send.amount); + _show( + id: 'send_${send.id}', + accountId: account.accountId, + accountName: account.name, + intent: NotificationIntent.sentTokens, + title: title(l10n, amount), + body: body(l10n, amount, account.name), + ); + } + + String _amountText(BigInt amount) { + final formatted = _ref.read(numberFormattingServiceProvider).formatBalance(amount, smartDecimals: 4); + return _ref.read(l10nProvider).commonAmountBalance(formatted, AppConstants.tokenSymbol); + } + + /// Shows a notification when the person wants it and the system allows it. + void _show({ + required String id, + required String accountId, + required String accountName, + required NotificationIntent intent, + required String title, + required String body, + }) { + final config = _ref.read(notificationConfigProvider); + if (!config.enabled || !config.isIntentEnabled(intent)) return; + final status = _ref.read(desktopLocalNotificationsProvider); + if (status is! NotificationsAllowed) { + quantusPrint('Not notifying "$title": notifications are ${status.runtimeType}'); + return; + } + final notification = NotificationData( + id: id, + accountId: accountId, + type: NotificationType.info, + intent: intent, + source: NotificationSource.local, + title: title, + message: body, + accountName: accountName, + timestamp: clock.now(), + persistent: false, + ); + unawaited(_showNow(notification)); + } + + Future _showNow(NotificationData notification) async { + try { + await _ref.read(desktopLocalNotificationsProvider.notifier).showOrScheduleNotification(notification); + } catch (e) { + quantusPrint('Showing a notification failed: $e'); + _ref.read(telemetryProvider).sendError('desktop_notification_show_failed', error: e); + } + } +} + +final ownActivityNotificationsProvider = Provider(OwnActivityNotifications.new); diff --git a/desktop-app/pubspec.lock b/desktop-app/pubspec.lock index 00ffab92d..5b1657442 100644 --- a/desktop-app/pubspec.lock +++ b/desktop-app/pubspec.lock @@ -90,7 +90,7 @@ packages: source: hosted version: "0.2.0" clock: - dependency: transitive + dependency: "direct main" description: name: clock sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b diff --git a/desktop-app/pubspec.yaml b/desktop-app/pubspec.yaml index 82de70593..f8cb1be10 100644 --- a/desktop-app/pubspec.yaml +++ b/desktop-app/pubspec.yaml @@ -24,6 +24,9 @@ dependencies: # UI cupertino_icons: ^1.0.9 + # Time, so that tests can set it. + clock: ^1.1.1 + # Platform ffi: ^2.2.0 # The same version as the phone's. diff --git a/desktop-app/test/services/own_activity_notifications_test.dart b/desktop-app/test/services/own_activity_notifications_test.dart new file mode 100644 index 000000000..a44b436db --- /dev/null +++ b/desktop-app/test/services/own_activity_notifications_test.dart @@ -0,0 +1,302 @@ +import 'dart:convert'; + +import 'package:clock/clock.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:quantus_desktop_wallet/providers/notifications_provider.dart'; +import 'package:quantus_desktop_wallet/services/notification_plugin.dart'; +import 'package:quantus_desktop_wallet/services/own_activity_notifications.dart'; +import 'package:quantus_sdk/quantus_sdk.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wallet_core/providers/account_providers.dart'; +import 'package:wallet_core/providers/multisig_proposal_confirmations_provider.dart'; +import 'package:wallet_core/providers/multisig_providers.dart'; +import 'package:wallet_core/providers/notification_config_provider.dart'; +import 'package:wallet_core/providers/pending_multisig_proposals_provider.dart'; +import 'package:wallet_core/providers/pending_transactions_provider.dart'; +import 'package:wallet_core/send/send_strategy.dart'; +import 'package:wallet_core/services/pending_transaction_polling_service.dart'; +import 'package:wallet_core/services/telemetry.dart'; + +import '../fakes.dart'; +import 'fake_notification_plugin.dart'; + +class _RecordingTelemetry implements Telemetry { + final errors = []; + + @override + void sendEvent(String eventName, {Map? parameters}) {} + + @override + void sendError(String errorName, {required Object error}) => errors.add(errorName); +} + +/// 12.5 tokens. +final _amount = oneToken * BigInt.from(25) ~/ BigInt.two; +final _broadcastAt = DateTime(2026, 11, 21, 12); +const _sendId = 'tx-1'; +const _proposalId = 'proposal-1'; +const _proposalHash = '0xproposal'; + +/// A wallet of Main and Savings, with the Team multisig, whose notifications +/// are started on [platform] in the language [locale]. +Future<({ProviderContainer container, FakeNotificationPlugin notifications})> _open({ + TargetPlatform platform = TargetPlatform.windows, + String locale = 'en', +}) async { + debugDefaultTargetPlatformOverride = platform; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final notifications = FakeNotificationPlugin(); + final settings = FakeSettingsService(activeAccount: const RegularAccount(mainAccount), multisigs: [teamMultisig]) + ..locale = locale; + final container = ProviderContainer( + overrides: [ + ...shellOverrides(accounts: const [mainAccount, savingsAccount], settings: settings), + notificationPluginProvider.overrideWithValue(notifications), + telemetryProvider.overrideWithValue(_RecordingTelemetry()), + ], + ); + addTearDown(container.dispose); + await container.read(desktopLocalNotificationsProvider.notifier).start(); + container.read(ownActivityNotificationsProvider); + for (var i = 0; i < 100; i++) { + if (container.read(accountsProvider).hasValue && container.read(multisigAccountsProvider).hasValue) break; + await Future.delayed(Duration.zero); + } + return (container: container, notifications: notifications); +} + +/// Main sends 12.5 to Bob and the send is broadcast, as the send sheet does. +void _broadcast(ProviderContainer container) => withClock(Clock.fixed(_broadcastAt), () { + final sends = container.read(pendingTransactionsProvider.notifier); + sends.add( + PendingTransactionEvent( + tempId: _sendId, + from: mainAccount.accountId, + to: 'qzBob', + amount: _amount, + fee: BigInt.zero, + timestamp: _broadcastAt, + ), + ); + sends.updateState(_sendId, TransactionState.pending, extrinsicHash: '0xsend'); +}); + +/// What the wallet does once it has found the send on the chain. +void _found(ProviderContainer container) { + final sends = container.read(pendingTransactionsProvider.notifier); + sends.updateState(_sendId, TransactionState.inHistory); + sends.remove(_sendId); +} + +/// What the wallet does when it stops watching for a send it never found. +void _givenUp(ProviderContainer container) => withClock( + Clock.fixed(_broadcastAt.add(PendingTransactionPollingService.timeout + const Duration(seconds: 5))), + () => container.read(pendingTransactionsProvider.notifier).remove(_sendId), +); + +/// Main proposes, in Team, to send 12.5 to Bob, and the proposal is broadcast. +void _propose(ProviderContainer container) { + final proposals = container.read(pendingMultisigProposalsProvider.notifier); + proposals.add( + PendingMultisigProposalEvent( + tempId: _proposalId, + multisigAddress: teamMultisig.accountId, + proposerId: mainAccount.accountId, + recipient: 'qzBob', + amount: _amount, + deposit: BigInt.zero, + expiryBlock: 100, + palletFee: BigInt.zero, + ), + ); + proposals.update(_proposalId, extrinsicHash: _proposalHash); +} + +/// What became of the proposal, as the wallet records it: a created one +/// leaves the pending proposals first, one never seen after. +void _settle(ProviderContainer container, SendConfirmation outcome) { + final proposals = container.read(pendingMultisigProposalsProvider.notifier); + final confirmations = container.read(multisigProposalConfirmationsProvider.notifier); + if (outcome == SendConfirmation.confirmed) { + proposals.remove(_proposalId); + confirmations.settle(_proposalHash, outcome); + } else { + confirmations.settle(_proposalHash, outcome); + proposals.remove(_proposalId); + } +} + +/// Lets what was started finish. +Future _settleDown() async { + for (var i = 0; i < 5; i++) { + await Future.delayed(Duration.zero); + } +} + +Iterable<(String, String)> _shown(FakeNotificationPlugin notifications) => + notifications.shown.map((n) => (n.title, n.body)); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() => SharedPreferences.setMockInitialValues({})); + + group('a Transparent send from this computer', () { + test('that the chain confirms notifies that it was sent, with the amount and the account it came from', () async { + final (:container, :notifications) = await _open(); + + _broadcast(container); + await _settleDown(); + + // Nothing yet: it is only on its way. + expect(notifications.shown, isEmpty); + + _found(container); + await _settleDown(); + + expect(_shown(notifications), [('Sent 12.5 QTC', 'From Main')]); + expect(jsonDecode(notifications.shown.single.payload), {'accountId': mainAccount.accountId}); + }); + + test('that the wallet stops watching for unfound notifies that it was not confirmed', () async { + final (:container, :notifications) = await _open(); + + _broadcast(container); + _givenUp(container); + await _settleDown(); + + expect(_shown(notifications), [ + ( + 'Send not confirmed', + '12.5 QTC from Main wasn’t seen on the chain in time. It may have failed, or only be late.', + ), + ]); + }); + + test('that is marked failed notifies that it failed', () async { + final (:container, :notifications) = await _open(); + + _broadcast(container); + container.read(pendingTransactionsProvider.notifier).updateState(_sendId, TransactionState.failed); + container.read(pendingTransactionsProvider.notifier).remove(_sendId); + await _settleDown(); + + expect(_shown(notifications), [('Send failed', '12.5 QTC from Main was not sent.')]); + }); + + test('whose broadcast failed notifies nothing: the send sheet says so', () async { + final (:container, :notifications) = await _open(); + final sends = container.read(pendingTransactionsProvider.notifier); + + sends.add( + PendingTransactionEvent( + tempId: _sendId, + from: mainAccount.accountId, + to: 'qzBob', + amount: _amount, + fee: BigInt.zero, + timestamp: _broadcastAt, + ), + ); + sends.remove(_sendId); + await _settleDown(); + + expect(notifications.shown, isEmpty); + }); + + test('still watched for when the wallet is wiped notifies nothing about it', () async { + final (:container, :notifications) = await _open(); + + _broadcast(container); + // The wipe empties the pending sends at once. + withClock( + Clock.fixed(_broadcastAt.add(const Duration(minutes: 1))), + () => container.read(pendingTransactionsProvider.notifier).clear(), + ); + await _settleDown(); + + expect(notifications.shown, isEmpty); + }); + }); + + group('a proposal made on this computer', () { + test('that the chain creates notifies that it was created, with what it sends and from which multisig', () async { + final (:container, :notifications) = await _open(); + + _propose(container); + _settle(container, SendConfirmation.confirmed); + await _settleDown(); + + expect(_shown(notifications), [('Proposal created', 'Send 12.5 QTC from Team')]); + expect(jsonDecode(notifications.shown.single.payload), {'accountId': teamMultisig.accountId}); + }); + + test('not seen in time notifies that it was not confirmed', () async { + final (:container, :notifications) = await _open(); + + _propose(container); + _settle(container, SendConfirmation.unconfirmed); + await _settleDown(); + + expect(_shown(notifications), [ + ('Proposal not confirmed', 'The proposal to send 12.5 QTC from Team wasn’t seen on the chain in time.'), + ]); + }); + }); + + test('with notifications turned off in Settings, nothing is shown', () async { + final (:container, :notifications) = await _open(); + final config = container.read(notificationConfigProvider.notifier); + await config.updateConfig(container.read(notificationConfigProvider).copyWith(enabled: false)); + + _broadcast(container); + _found(container); + _propose(container); + _settle(container, SendConfirmation.confirmed); + await _settleDown(); + + expect(notifications.shown, isEmpty); + }); + + test('while the system does not allow notifications, nothing is shown and nothing fails', () async { + // macOS, not asked yet. + final (:container, :notifications) = await _open(platform: TargetPlatform.macOS); + + _broadcast(container); + _found(container); + await _settleDown(); + + expect(notifications.shown, isEmpty); + }); + + testOnWindowsAndLinux('the app watches what it does from the start', (tester) async { + final notifications = FakeNotificationPlugin(); + await pumpShell( + tester, + notifications: notifications, + overrides: shellOverrides( + accounts: const [mainAccount, savingsAccount], + settings: FakeSettingsService(activeAccount: const RegularAccount(mainAccount)), + ), + ); + final container = ProviderScope.containerOf(tester.element(find.byType(MaterialApp))); + + _broadcast(container); + _found(container); + await tester.pumpAndSettle(); + + expect(_shown(notifications), [('Sent 12.5 QTC', 'From Main')]); + }); + + test('the text follows the app language', () async { + final (:container, :notifications) = await _open(locale: 'id'); + + _broadcast(container); + _found(container); + await _settleDown(); + + expect(_shown(notifications), [('12,5 QTC terkirim', 'Dari Main')]); + }); +} diff --git a/wallet_core/lib/services/pending_transaction_polling_service.dart b/wallet_core/lib/services/pending_transaction_polling_service.dart index fcf4c0887..31e1d0290 100644 --- a/wallet_core/lib/services/pending_transaction_polling_service.dart +++ b/wallet_core/lib/services/pending_transaction_polling_service.dart @@ -11,7 +11,10 @@ class PendingTransactionPollingService { final Ref _ref; final Map _timers = {}; static const _searchInterval = Duration(seconds: 5); - static const _timeout = Duration(minutes: 5); + + /// How long a send is watched for. Not found by then, it is removed + /// from the pending sends without being marked found or failed. + static const timeout = Duration(minutes: 5); PendingTransactionPollingService(this._ref); @@ -39,7 +42,7 @@ class PendingTransactionPollingService { final startTime = DateTime.now(); final timer = Timer.periodic(_searchInterval, (_) { - if (DateTime.now().difference(startTime) > _timeout) { + if (DateTime.now().difference(startTime) > timeout) { quantusPrint('[PendingTxPoller] Timeout for ${pendingTx.id}, deferring to reconciliation'); stopPolling(pendingTx.id); _ref.read(pendingTransactionsProvider.notifier).remove(pendingTx.id); From 531a9bdbf359e2753686bce0c2357e8c780d3ff3 Mon Sep 17 00:00:00 2001 From: Beast Date: Sat, 21 Nov 2026 09:37:10 +0800 Subject: [PATCH 7/9] Desktop: open what the notification that launched the app was about A click on a notification after the wallet was quit launches the app before it starts its notifications, so macOS keeps the click in its launch details instead of passing it on. The app now reads them once its notifications have started, and keeps the clicked account until the wallet's accounts and its saved active account have loaded, so restoring that account does not undo the selection. A click on the running app waits the same way. Only macOS is asked: Linux has no launch details, and the plugin registers the app's activator with Windows only while the app runs. Review finding 1 on #771. --- .../lib/providers/notifications_provider.dart | 49 +++++++++++-- .../lib/services/notification_plugin.dart | 16 ++++ .../services/fake_notification_plugin.dart | 12 ++- .../services/notification_plugin_test.dart | 73 +++++++++++++++++++ .../ui/shell/notification_click_test.dart | 34 ++++++++- 5 files changed, 176 insertions(+), 8 deletions(-) create mode 100644 desktop-app/test/services/notification_plugin_test.dart diff --git a/desktop-app/lib/providers/notifications_provider.dart b/desktop-app/lib/providers/notifications_provider.dart index d41a67e0d..d613968f5 100644 --- a/desktop-app/lib/providers/notifications_provider.dart +++ b/desktop-app/lib/providers/notifications_provider.dart @@ -13,6 +13,7 @@ import 'package:quantus_desktop_wallet/services/notification_plugin.dart'; import 'package:quantus_desktop_wallet/services/window_chrome.dart'; import 'package:quantus_sdk/quantus_sdk.dart'; import 'package:wallet_core/models/notification_models.dart'; +import 'package:wallet_core/providers/account_providers.dart'; import 'package:wallet_core/providers/l10n_provider.dart'; import 'package:wallet_core/services/local_notifications.dart'; import 'package:wallet_core/services/telemetry.dart'; @@ -61,6 +62,22 @@ class DesktopLocalNotifications extends Notifier implements state = defaultTargetPlatform == TargetPlatform.macOS ? const NotificationsNotAsked() : const NotificationsAllowed(); + await _openLaunchClick(); + } + + /// Opens what the click that launched the app was about, if one did: such + /// a click comes before the notifications were started, so not through + /// [_open] as a click on the running app does. + Future _openLaunchClick() async { + final String? payload; + try { + payload = await ref.read(notificationPluginProvider).launchPayload(); + } catch (e) { + quantusPrint('The click that launched the app could not be read: $e'); + ref.read(telemetryProvider).sendError('desktop_notification_launch_unreadable', error: e); + return; + } + if (payload != null) _open(payload); } /// Asks macOS whether the app may show notifications. Windows and Linux do @@ -76,6 +93,11 @@ class DesktopLocalNotifications extends Notifier implements } } + /// The account a click asked for, until the wallet's accounts and its + /// active account have loaded, as at launch. + String? _clickedAccountId; + final _untilLoaded = >[]; + /// Opens what a clicked notification was about: the window comes to the /// front, on the account the notification named when it is still there. void _open(String? payload) { @@ -88,12 +110,29 @@ class DesktopLocalNotifications extends Notifier implements ref.read(telemetryProvider).sendError('desktop_notification_click_unreadable', error: e); return; } - for (final account in ref.read(sidebarAccountsProvider)) { - if (account.account.accountId == accountId) { - unawaited(ref.read(sidebarSelectionProvider.notifier).showAccount(account)); - return; - } + _clickedAccountId = accountId; + if (_openClickedAccount() || _untilLoaded.isNotEmpty) return; + _untilLoaded + ..add(ref.listen(sidebarAccountsProvider, (_, _) => _openClickedAccount())) + ..add(ref.listen(activeAccountProvider, (_, _) => _openClickedAccount())); + } + + /// Selects the clicked account once the accounts and the active account + /// have loaded: before that, restoring the saved active account would undo + /// it. Returns whether the click is done with. + bool _openClickedAccount() { + final accountId = _clickedAccountId; + if (accountId == null) return true; + final accounts = ref.read(sidebarAccountsProvider); + if (accounts.isEmpty || !ref.read(activeAccountProvider).hasValue) return false; + _clickedAccountId = null; + for (final subscription in _untilLoaded) { + subscription.close(); } + _untilLoaded.clear(); + final account = accounts.where((display) => display.account.accountId == accountId).firstOrNull; + if (account != null) unawaited(ref.read(sidebarSelectionProvider.notifier).showAccount(account)); + return true; } void _unavailable(Object error) { diff --git a/desktop-app/lib/services/notification_plugin.dart b/desktop-app/lib/services/notification_plugin.dart index f566e6dce..57e4ad4fe 100644 --- a/desktop-app/lib/services/notification_plugin.dart +++ b/desktop-app/lib/services/notification_plugin.dart @@ -10,6 +10,11 @@ abstract interface class NotificationPlugin { /// system's notification service does not start. Future initialize(InitializationSettings settings, {required void Function(String? payload) onClick}); + /// The payload of the notification whose click launched the app, if one + /// did. Such a click comes before the app has started its notifications, + /// so it never reaches [initialize]'s `onClick`. + Future launchPayload(); + /// Asks macOS whether the app may show notifications, with sounds and a /// badge. Returns whether it may. macOS asks the person only the first /// time; after that it answers with what they chose. @@ -38,6 +43,17 @@ class SystemNotificationPlugin implements NotificationPlugin { } } + /// Asked of macOS only. Linux has no launch details, and Windows cannot + /// launch this app for a click: the plugin registers the app's activator + /// with Windows only while the app is running. + @override + Future launchPayload() async { + if (defaultTargetPlatform != TargetPlatform.macOS) return null; + final details = await _plugin.getNotificationAppLaunchDetails(); + if (details == null || !details.didNotificationLaunchApp) return null; + return details.notificationResponse?.payload; + } + @override Future requestMacOSPermission() async { final macOS = _plugin.resolvePlatformSpecificImplementation(); diff --git a/desktop-app/test/services/fake_notification_plugin.dart b/desktop-app/test/services/fake_notification_plugin.dart index 87f32682b..dc1d9193f 100644 --- a/desktop-app/test/services/fake_notification_plugin.dart +++ b/desktop-app/test/services/fake_notification_plugin.dart @@ -7,7 +7,7 @@ typedef ShownNotification = ({int id, String title, String body, String payload} /// Stands in for the system's notifications: records what the app asks of /// them, and answers as [startError] and [grants] say. class FakeNotificationPlugin implements NotificationPlugin { - FakeNotificationPlugin({this.startError, this.grants = true}); + FakeNotificationPlugin({this.startError, this.grants = true, this.launchedBy}); /// What starting throws, as a system without a notification service would. Object? startError; @@ -15,6 +15,10 @@ class FakeNotificationPlugin implements NotificationPlugin { /// Whether macOS lets the app show notifications when asked. bool grants; + /// The payload of the notification whose click launched the app, if one did. + final String? launchedBy; + var launchPayloadReads = 0; + final initializations = []; var permissionRequests = 0; final shown = []; @@ -28,6 +32,12 @@ class FakeNotificationPlugin implements NotificationPlugin { _onClick = onClick; } + @override + Future launchPayload() async { + launchPayloadReads++; + return launchedBy; + } + @override Future requestMacOSPermission() async { permissionRequests++; diff --git a/desktop-app/test/services/notification_plugin_test.dart b/desktop-app/test/services/notification_plugin_test.dart new file mode 100644 index 000000000..48c21ee8f --- /dev/null +++ b/desktop-app/test/services/notification_plugin_test.dart @@ -0,0 +1,73 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:quantus_desktop_wallet/services/notification_plugin.dart'; + +/// The plugin's own channel to its native side. +const _channel = MethodChannel('dexterous.com/flutter/local_notifications'); + +/// Answers the plugin's native calls on macOS with [launchDetails] for the +/// launch, and records which calls were made. +List _nativeMacOS({required Map launchDetails}) { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + MacOSFlutterLocalNotificationsPlugin.registerWith(); + final calls = []; + final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(_channel, (call) async { + calls.add(call.method); + return switch (call.method) { + // The answer to whether permission was granted, which was not asked. + 'initialize' => false, + 'getNotificationAppLaunchDetails' => launchDetails, + _ => null, + }; + }); + addTearDown(() => messenger.setMockMethodCallHandler(_channel, null)); + return calls; +} + +const _settings = InitializationSettings(macOS: DarwinInitializationSettings()); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test("on macOS, the click that launched the app is read from the system's launch details", () async { + _nativeMacOS( + launchDetails: { + 'notificationLaunchedApp': true, + 'notificationResponse': { + 'notificationId': 7, + 'notificationResponseType': 0, + 'payload': '{"accountId":"qzSavings"}', + }, + }, + ); + final clicks = []; + final plugin = SystemNotificationPlugin(); + await plugin.initialize(_settings, onClick: clicks.add); + + expect(await plugin.launchPayload(), '{"accountId":"qzSavings"}'); + // Such a click never comes through the running app's callback. + expect(clicks, isEmpty); + }); + + test('on macOS, an app not launched by a notification has no launch payload', () async { + _nativeMacOS(launchDetails: {'notificationLaunchedApp': false}); + final plugin = SystemNotificationPlugin(); + await plugin.initialize(_settings, onClick: (_) {}); + + expect(await plugin.launchPayload(), isNull); + }); + + for (final platform in [TargetPlatform.windows, TargetPlatform.linux]) { + test('on ${platform.name}, which a click does not launch the app on, no launch details are asked for', () async { + final calls = _nativeMacOS(launchDetails: {'notificationLaunchedApp': true}); + debugDefaultTargetPlatformOverride = platform; + + expect(await SystemNotificationPlugin().launchPayload(), isNull); + expect(calls, isNot(contains('getNotificationAppLaunchDetails'))); + }); + } +} diff --git a/desktop-app/test/ui/shell/notification_click_test.dart b/desktop-app/test/ui/shell/notification_click_test.dart index a7f4f61c1..5448f49f5 100644 --- a/desktop-app/test/ui/shell/notification_click_test.dart +++ b/desktop-app/test/ui/shell/notification_click_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -9,13 +10,21 @@ import 'package:wallet_core/providers/account_providers.dart'; import '../../fakes.dart'; import '../../services/fake_notification_plugin.dart'; -/// Opens the window on a wallet whose active account is Main. -Future _openWallet(WidgetTester tester, FakeNotificationPlugin notifications) async { +/// Opens the window on a wallet whose active account is Main, its accounts +/// loaded by [loadAccounts] when given. +Future _openWallet( + WidgetTester tester, + FakeNotificationPlugin notifications, { + Future> Function()? loadAccounts, + bool settle = true, +}) async { await pumpShell( tester, notifications: notifications, + settle: settle, overrides: shellOverrides( accounts: const [mainAccount, savingsAccount], + loadAccounts: loadAccounts, settings: FakeSettingsService(activeAccount: const RegularAccount(mainAccount)), ), ); @@ -61,4 +70,25 @@ void main() { expect(window, ['bringToFront']); expect(_activeAccountId(container), mainAccount.accountId); }); + + testOnMac('a click that launched the app opens the account it was about', (tester) async { + final notifications = FakeNotificationPlugin(launchedBy: _about(savingsAccount.accountId)); + final window = recordWindowRequests(tester); + final container = await _openWallet(tester, notifications); + + expect(window, ['bringToFront']); + expect(_activeAccountId(container), savingsAccount.accountId); + }); + + testOnMac("a click that launched the app waits for the wallet's accounts to load", (tester) async { + final accounts = Completer>(); + final notifications = FakeNotificationPlugin(launchedBy: _about(savingsAccount.accountId)); + final container = await _openWallet(tester, notifications, loadAccounts: () => accounts.future, settle: false); + await tester.pump(const Duration(milliseconds: 100)); + + accounts.complete(const [mainAccount, savingsAccount]); + await tester.pumpAndSettle(); + + expect(_activeAccountId(container), savingsAccount.accountId); + }); } From 8cec1e80dee0fa84483ac7c0f24a2035ae8405b7 Mon Sep 17 00:00:00 2001 From: Beast Date: Sat, 21 Nov 2026 09:41:38 +0800 Subject: [PATCH 8/9] Desktop: say the amount the chain moved when a send is confirmed A Max send is recorded with the send sheet's estimate, as the chain sizes a transfer_all at inclusion, and finding it on the chain does not correct the record. The Sent notification now reads the transfer the indexer holds for the send's transaction hash, as the poller does, and says its amount. That covers a send found by the poller and one found by reconciliation. Without that amount there is nothing true to say, so a send the indexer cannot be read for is reported and not notified. Failed and unconfirmed sends keep the recorded amount: what they set out to send. The wallet_core fix (carry the found amount onto the pending record) would change what the phone's pending rows hold, so it waits for its own PR. Review finding 2 on #771. --- .../services/own_activity_notifications.dart | 43 +++++++-- desktop-app/test/fakes.dart | 8 ++ .../own_activity_notifications_test.dart | 93 +++++++++++++++---- 3 files changed, 117 insertions(+), 27 deletions(-) diff --git a/desktop-app/lib/services/own_activity_notifications.dart b/desktop-app/lib/services/own_activity_notifications.dart index b9b6966e2..838ad83ea 100644 --- a/desktop-app/lib/services/own_activity_notifications.dart +++ b/desktop-app/lib/services/own_activity_notifications.dart @@ -54,15 +54,13 @@ class OwnActivityNotifications { _sends[send.id] = (send: send, broadcastAt: now); case TransactionState.inHistory when watched != null: _sends.remove(send.id); - _notifySend( - send, - title: (l10n, amount) => l10n.desktopNotificationSentTitle(amount), - body: (l10n, _, account) => l10n.desktopNotificationSentBody(account), - ); + unawaited(_notifySent(send)); case TransactionState.failed when watched != null: _sends.remove(send.id); + // The amount it was recorded with: what it set out to send. _notifySend( send, + amount: send.amount, title: (l10n, _) => l10n.desktopNotificationSendFailedTitle, body: (l10n, amount, account) => l10n.desktopNotificationSendFailedBody(amount, account), ); @@ -78,12 +76,39 @@ class OwnActivityNotifications { if (now.difference(broadcastAt) < PendingTransactionPollingService.timeout) continue; _notifySend( send, + amount: send.amount, title: (l10n, _) => l10n.desktopNotificationSendNotConfirmedTitle, body: (l10n, amount, account) => l10n.desktopNotificationSendNotConfirmedBody(amount, account), ); } } + /// Notifies [send] as sent, with the amount the chain moved: a Max send + /// is recorded with an estimate, as the chain sizes it at inclusion, and + /// its record is not corrected when it is found. + Future _notifySent(PendingTransactionEvent send) async { + final TransactionEvent? indexed; + try { + final hash = send.extrinsicHash; + if (hash == null) throw StateError('A broadcast send has no transaction hash: ${send.id}'); + indexed = await _ref + .read(chainHistoryServiceProvider) + .searchByExtrinsicHash(extrinsicHash: hash, isReversible: send.isReversible); + if (indexed == null) throw StateError('The indexer does not hold the send it was found in: ${send.id}'); + } catch (e) { + // Without the amount the chain moved there is nothing true to say. + quantusPrint('Not notifying a confirmed send whose amount could not be read: $e'); + _ref.read(telemetryProvider).sendError('desktop_notification_sent_amount_unread', error: e); + return; + } + _notifySend( + send, + amount: indexed.amount, + title: (l10n, amount) => l10n.desktopNotificationSentTitle(amount), + body: (l10n, _, account) => l10n.desktopNotificationSentBody(account), + ); + } + void _onProposals(List proposals) { for (final proposal in proposals) { final hash = proposal.extrinsicHash; @@ -135,8 +160,10 @@ class OwnActivityNotifications { } } + /// Notifies about [send], of [amount]. void _notifySend( PendingTransactionEvent send, { + required BigInt amount, required String Function(AppLocalizations l10n, String amount) title, required String Function(AppLocalizations l10n, String amount, String account) body, }) { @@ -146,14 +173,14 @@ class OwnActivityNotifications { return; } final l10n = _ref.read(l10nProvider); - final amount = _amountText(send.amount); + final amountText = _amountText(amount); _show( id: 'send_${send.id}', accountId: account.accountId, accountName: account.name, intent: NotificationIntent.sentTokens, - title: title(l10n, amount), - body: body(l10n, amount, account.name), + title: title(l10n, amountText), + body: body(l10n, amountText, account.name), ); } diff --git a/desktop-app/test/fakes.dart b/desktop-app/test/fakes.dart index 2bb0cb18b..c02c2ba4e 100644 --- a/desktop-app/test/fakes.dart +++ b/desktop-app/test/fakes.dart @@ -364,6 +364,10 @@ class FakeSendChain { /// amount and fee it was recorded with. final transfers = <({String from, SendCall call, BigInt amount, BigInt fee})>[]; + /// The transfers the indexer holds, by the hash of the transaction each was + /// sent in. + final indexedTransfers = {}; + /// What proposing a transfer costs the member who proposes, as the mocks /// drew it: the usual fee, half a token of deposit and a tenth for the /// proposal, expiring at block 1284220. @@ -503,6 +507,10 @@ class _FakeChainHistoryService extends Fake implements ChainHistoryService { final FakeSendChain chain; + @override + Future searchByExtrinsicHash({required String extrinsicHash, required bool isReversible}) async => + chain.indexedTransfers[extrinsicHash]; + @override Future fetchAllTransactionTypes({ required List accountIds, diff --git a/desktop-app/test/services/own_activity_notifications_test.dart b/desktop-app/test/services/own_activity_notifications_test.dart index a44b436db..9ede59a13 100644 --- a/desktop-app/test/services/own_activity_notifications_test.dart +++ b/desktop-app/test/services/own_activity_notifications_test.dart @@ -37,25 +37,55 @@ class _RecordingTelemetry implements Telemetry { final _amount = oneToken * BigInt.from(25) ~/ BigInt.two; final _broadcastAt = DateTime(2026, 11, 21, 12); const _sendId = 'tx-1'; +const _sendHash = '0xsend'; const _proposalId = 'proposal-1'; const _proposalHash = '0xproposal'; +/// The transfer the indexer holds for Main's send to Bob, of [amount]. +TransferEvent _indexedSend(BigInt amount) => TransferEvent( + id: 'indexed-send', + from: mainAccount.accountId, + to: 'qzBob', + amount: amount, + timestamp: _broadcastAt, + fee: BigInt.zero, + extrinsicHash: _sendHash, + blockNumber: 10, + blockHash: '0xblock', +); + +/// The chain, its indexer holding Main's send to Bob as having moved +/// [sentAmount], or not holding it when that is null. +FakeSendChain _chain({required BigInt? sentAmount}) { + final chain = FakeSendChain(); + if (sentAmount != null) chain.indexedTransfers[_sendHash] = _indexedSend(sentAmount); + return chain; +} + /// A wallet of Main and Savings, with the Team multisig, whose notifications -/// are started on [platform] in the language [locale]. -Future<({ProviderContainer container, FakeNotificationPlugin notifications})> _open({ +/// are started on [platform] in the language [locale]. The indexer holds +/// Main's send to Bob as having moved [sentAmount], 12.5 unless said. +Future<({ProviderContainer container, FakeNotificationPlugin notifications, _RecordingTelemetry telemetry})> _open({ TargetPlatform platform = TargetPlatform.windows, String locale = 'en', + BigInt? sentAmount, + bool indexed = true, }) async { debugDefaultTargetPlatformOverride = platform; addTearDown(() => debugDefaultTargetPlatformOverride = null); final notifications = FakeNotificationPlugin(); + final telemetry = _RecordingTelemetry(); final settings = FakeSettingsService(activeAccount: const RegularAccount(mainAccount), multisigs: [teamMultisig]) ..locale = locale; final container = ProviderContainer( overrides: [ - ...shellOverrides(accounts: const [mainAccount, savingsAccount], settings: settings), + ...shellOverrides( + accounts: const [mainAccount, savingsAccount], + settings: settings, + chain: _chain(sentAmount: indexed ? sentAmount ?? _amount : null), + ), notificationPluginProvider.overrideWithValue(notifications), - telemetryProvider.overrideWithValue(_RecordingTelemetry()), + telemetryProvider.overrideWithValue(telemetry), ], ); addTearDown(container.dispose); @@ -65,23 +95,24 @@ Future<({ProviderContainer container, FakeNotificationPlugin notifications})> _o if (container.read(accountsProvider).hasValue && container.read(multisigAccountsProvider).hasValue) break; await Future.delayed(Duration.zero); } - return (container: container, notifications: notifications); + return (container: container, notifications: notifications, telemetry: telemetry); } -/// Main sends 12.5 to Bob and the send is broadcast, as the send sheet does. -void _broadcast(ProviderContainer container) => withClock(Clock.fixed(_broadcastAt), () { +/// Main sends [amount], 12.5 unless said, to Bob and the send is broadcast, +/// as the send sheet does. +void _broadcast(ProviderContainer container, {BigInt? amount}) => withClock(Clock.fixed(_broadcastAt), () { final sends = container.read(pendingTransactionsProvider.notifier); sends.add( PendingTransactionEvent( tempId: _sendId, from: mainAccount.accountId, to: 'qzBob', - amount: _amount, + amount: amount ?? _amount, fee: BigInt.zero, timestamp: _broadcastAt, ), ); - sends.updateState(_sendId, TransactionState.pending, extrinsicHash: '0xsend'); + sends.updateState(_sendId, TransactionState.pending, extrinsicHash: _sendHash); }); /// What the wallet does once it has found the send on the chain. @@ -145,7 +176,7 @@ void main() { group('a Transparent send from this computer', () { test('that the chain confirms notifies that it was sent, with the amount and the account it came from', () async { - final (:container, :notifications) = await _open(); + final (:container, :notifications, telemetry: _) = await _open(); _broadcast(container); await _settleDown(); @@ -160,8 +191,31 @@ void main() { expect(jsonDecode(notifications.shown.single.payload), {'accountId': mainAccount.accountId}); }); + test('sent as Max notifies the amount the chain moved, not the estimate it was recorded with', () async { + // Max sends everything there is at inclusion, which can be less than + // what the send sheet estimated. + final (:container, :notifications, telemetry: _) = await _open(sentAmount: oneToken * BigInt.from(9)); + + _broadcast(container, amount: oneToken * BigInt.from(10)); + _found(container); + await _settleDown(); + + expect(_shown(notifications), [('Sent 9 QTC', 'From Main')]); + }); + + test('found, but not in the indexer when its amount is read, notifies nothing and is reported', () async { + final (:container, :notifications, :telemetry) = await _open(indexed: false); + + _broadcast(container); + _found(container); + await _settleDown(); + + expect(notifications.shown, isEmpty); + expect(telemetry.errors, ['desktop_notification_sent_amount_unread']); + }); + test('that the wallet stops watching for unfound notifies that it was not confirmed', () async { - final (:container, :notifications) = await _open(); + final (:container, :notifications, telemetry: _) = await _open(); _broadcast(container); _givenUp(container); @@ -176,7 +230,7 @@ void main() { }); test('that is marked failed notifies that it failed', () async { - final (:container, :notifications) = await _open(); + final (:container, :notifications, telemetry: _) = await _open(); _broadcast(container); container.read(pendingTransactionsProvider.notifier).updateState(_sendId, TransactionState.failed); @@ -187,7 +241,7 @@ void main() { }); test('whose broadcast failed notifies nothing: the send sheet says so', () async { - final (:container, :notifications) = await _open(); + final (:container, :notifications, telemetry: _) = await _open(); final sends = container.read(pendingTransactionsProvider.notifier); sends.add( @@ -207,7 +261,7 @@ void main() { }); test('still watched for when the wallet is wiped notifies nothing about it', () async { - final (:container, :notifications) = await _open(); + final (:container, :notifications, telemetry: _) = await _open(); _broadcast(container); // The wipe empties the pending sends at once. @@ -223,7 +277,7 @@ void main() { group('a proposal made on this computer', () { test('that the chain creates notifies that it was created, with what it sends and from which multisig', () async { - final (:container, :notifications) = await _open(); + final (:container, :notifications, telemetry: _) = await _open(); _propose(container); _settle(container, SendConfirmation.confirmed); @@ -234,7 +288,7 @@ void main() { }); test('not seen in time notifies that it was not confirmed', () async { - final (:container, :notifications) = await _open(); + final (:container, :notifications, telemetry: _) = await _open(); _propose(container); _settle(container, SendConfirmation.unconfirmed); @@ -247,7 +301,7 @@ void main() { }); test('with notifications turned off in Settings, nothing is shown', () async { - final (:container, :notifications) = await _open(); + final (:container, :notifications, telemetry: _) = await _open(); final config = container.read(notificationConfigProvider.notifier); await config.updateConfig(container.read(notificationConfigProvider).copyWith(enabled: false)); @@ -262,7 +316,7 @@ void main() { test('while the system does not allow notifications, nothing is shown and nothing fails', () async { // macOS, not asked yet. - final (:container, :notifications) = await _open(platform: TargetPlatform.macOS); + final (:container, :notifications, telemetry: _) = await _open(platform: TargetPlatform.macOS); _broadcast(container); _found(container); @@ -279,6 +333,7 @@ void main() { overrides: shellOverrides( accounts: const [mainAccount, savingsAccount], settings: FakeSettingsService(activeAccount: const RegularAccount(mainAccount)), + chain: _chain(sentAmount: _amount), ), ); final container = ProviderScope.containerOf(tester.element(find.byType(MaterialApp))); @@ -291,7 +346,7 @@ void main() { }); test('the text follows the app language', () async { - final (:container, :notifications) = await _open(locale: 'id'); + final (:container, :notifications, telemetry: _) = await _open(locale: 'id'); _broadcast(container); _found(container); From ce151412c662ea677c85eccd71573d86b8daee23 Mon Sep 17 00:00:00 2001 From: Beast Date: Sat, 21 Nov 2026 10:00:30 +0800 Subject: [PATCH 9/9] Desktop: build the notification plugin with Visual Studio 2026 flutter_local_notifications_windows 3.0.0 builds as C++17, where the C++/WinRT headers pull in , which MSVC 14.52 rejects with STL1011. It gets the same macro local_auth_windows already builds with, and the same guard that fails the build once the target is gone, so the app stays on the phone's plugin version. --- desktop-app/windows/CMakeLists.txt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/desktop-app/windows/CMakeLists.txt b/desktop-app/windows/CMakeLists.txt index 176d800a5..7612b5134 100644 --- a/desktop-app/windows/CMakeLists.txt +++ b/desktop-app/windows/CMakeLists.txt @@ -70,6 +70,16 @@ endif() target_compile_definitions(local_auth_windows_plugin PRIVATE _SILENCE_EXPERIMENTAL_COROUTINE_DEPRECATION_WARNINGS) +# flutter_local_notifications_windows 3.0.0, the phone's plugin version, builds +# as C++17, where the C++/WinRT headers it includes pull in the same header. +# Remove this once the app is on its 4.x, which builds as C++20. +if(NOT TARGET flutter_local_notifications_windows) + message(FATAL_ERROR "flutter_local_notifications_windows is no longer built; " + "delete its STL1011 workaround in windows/CMakeLists.txt.") +endif() +target_compile_definitions(flutter_local_notifications_windows PRIVATE + _SILENCE_EXPERIMENTAL_COROUTINE_DEPRECATION_WARNINGS) + # === Installation === # Support files are copied into place next to the executable, so that it can