Fix notification auto-reconnection on page reload

- Add auto-resubscribe logic to web push notification service
  - Automatically restore push subscription if notifications were previously enabled
  - Sync subscription state with saved preferences on initialization
  - Handle failed resubscription by updating preferences accordingly

- Fix Mac app notification service startup check
  - Only establish SSE connection if notifications are enabled in config
  - Prevents unnecessary connection attempts when notifications are disabled
  - Ensures consistent behavior between web and native components

This fixes the issue where notification settings appeared enabled but the
SSE connection indicator was red and test button was disabled until the
user manually toggled notifications off and on.
This commit is contained in:
Peter Steinberger 2025-07-28 20:15:28 +02:00
parent 5aabd862e7
commit dcd65b5db4
2 changed files with 42 additions and 0 deletions

View file

@ -67,6 +67,13 @@ final class NotificationService: NSObject {
/// Start monitoring server events
func start() async {
logger.info("🚀 NotificationService.start() called")
// Check if notifications are enabled in config
guard configManager.notificationsEnabled else {
logger.info("📴 Notifications are disabled in config, skipping SSE connection")
return
}
guard serverManager.isRunning else {
logger.warning("🔴 Server not running, cannot start notification service")
return

View file

@ -94,6 +94,9 @@ export class PushNotificationService {
// Monitor permission changes
this.monitorPermissionChanges();
// Auto-resubscribe if notifications were previously enabled
await this.autoResubscribe();
this.initialized = true;
logger.log('push notification service initialized');
} catch (error) {
@ -159,6 +162,38 @@ export class PushNotificationService {
});
}
/**
* Auto-resubscribe if notifications were previously enabled
*/
private async autoResubscribe(): Promise<void> {
try {
// Load saved preferences
const preferences = await this.loadPreferences();
// Check if notifications were previously enabled
if (preferences.enabled) {
// Check if we have permission but no subscription
const permission = this.getPermission();
if (permission === 'granted' && !this.pushSubscription) {
logger.log('Auto-resubscribing to push notifications based on saved preferences');
// Attempt to resubscribe
const subscription = await this.subscribe();
if (subscription) {
logger.log('Successfully auto-resubscribed to push notifications');
} else {
logger.warn('Failed to auto-resubscribe, user will need to manually enable');
// Update preferences to reflect the failed state
preferences.enabled = false;
await this.savePreferences(preferences);
}
}
}
} catch (error) {
logger.error('Error during auto-resubscribe:', error);
}
}
/**
* Request notification permission from user
*/