Merge: Android in-app notification service

This commit is contained in:
2026-11-01 02:22:03 +00:00
33 changed files with 2589 additions and 3 deletions
+15
View File
@@ -13,6 +13,8 @@ import '../shell/destination.dart';
import '../features/attention/notify/notification_controller.dart';
import '../features/attention/notify/chat_question_notices.dart';
import '../features/attention/notify/notification_store.dart';
import '../features/notification_service/notification_service_bridge.dart';
import '../features/notification_service/notification_service_handoff.dart';
import '../features/attention/runtime/attention_ack_queue.dart';
import '../features/attention/runtime/attention_ack_sync.dart';
import '../features/attention/runtime/attention_controller.dart';
@@ -147,6 +149,11 @@ class _PipelinesAppState extends State<PipelinesApp>
/// The count the shell's Runs tab shows; only a changed count rebuilds it.
final ValueNotifier<int> _attentionCount = ValueNotifier<int>(0);
/// Android background delivery (no service elsewhere).
final NotificationServiceBridge _deliveryService =
createNotificationServiceBridge();
NotificationServiceHandoff? _deliveryHandoff;
@override
void initState() {
super.initState();
@@ -157,6 +164,12 @@ class _PipelinesAppState extends State<PipelinesApp>
knownServer: widget.knownServer,
addresses: widget.serverAddresses,
);
// The service authenticates like the app: hand over each proven server.
_deliveryHandoff = NotificationServiceHandoff(
bridge: _deliveryService,
client: _session.client,
serverId: widget.serverId,
);
bindServerIdentity(_session.gateway, widget.serverId);
_ownsProvider = widget.routeInformationProvider == null;
_provider =
@@ -228,6 +241,7 @@ class _PipelinesAppState extends State<PipelinesApp>
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_deliveryHandoff?.dispose();
_session.removeListener(_attentionSessionChanged);
unawaited(_attentionFrames?.cancel());
_attention.removeListener(_attentionChanged);
@@ -552,6 +566,7 @@ class _PipelinesAppState extends State<PipelinesApp>
),
onOpenTemplates: _delegate.openTemplates,
notifications: _notifications,
deliveryService: _deliveryService,
),
},
);
@@ -0,0 +1,4 @@
import 'dart:io';
/// The real host OS, not the (test-overridable) target platform.
bool get runsOnAndroid => Platform.isAndroid;
@@ -0,0 +1,2 @@
/// Browsers have no background service.
bool get runsOnAndroid => false;
@@ -0,0 +1,139 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'host_platform_stub.dart' if (dart.library.io) 'host_platform_io.dart';
import 'notification_service_status.dart';
export 'notification_service_status.dart';
/// The app's handle on Android background delivery: a native foreground
/// service (android/…/notify/NotificationService.kt) that keeps its own
/// socket to the server and shows the server's notifications, so the ntfy app
/// is not needed. Other platforms have no service ([supported] is false).
abstract interface class NotificationServiceBridge {
bool get supported;
/// Status pushed by the service whenever its connection changes.
Stream<NotificationServiceStatus> get changes;
Future<NotificationServiceStatus> status();
/// Starts the service if delivery is enabled and a server was handed over.
Future<NotificationServiceStatus> start();
/// Hands over the server the app is connected to: its trusted addresses
/// (tried in order) and the web sign-in cookie, empty when none.
Future<NotificationServiceStatus> configure({
required String serverId,
required List<String> endpoints,
required String cookie,
});
Future<NotificationServiceStatus> setEnabled(bool enabled);
/// Opens Android's "ignore battery optimisations" prompt.
Future<bool> requestBatteryExemption();
}
/// The bridge for this platform. One instance owns the channel's handler.
NotificationServiceBridge createNotificationServiceBridge() => runsOnAndroid
? MethodChannelNotificationServiceBridge.instance
: const UnsupportedNotificationServiceBridge();
/// `pipelines/notification_service`, implemented by NotificationServiceChannel.kt.
class MethodChannelNotificationServiceBridge
implements NotificationServiceBridge {
@visibleForTesting
MethodChannelNotificationServiceBridge([
this._channel = const MethodChannel(channelName),
]) {
_channel.setMethodCallHandler(_onCall);
}
static const channelName = 'pipelines/notification_service';
static final instance = MethodChannelNotificationServiceBridge();
final MethodChannel _channel;
final _changes = StreamController<NotificationServiceStatus>.broadcast();
@override
bool get supported => true;
@override
Stream<NotificationServiceStatus> get changes => _changes.stream;
Future<void> _onCall(MethodCall call) async {
if (call.method == 'statusChanged') {
_changes.add(NotificationServiceStatus.fromMap(call.arguments));
}
}
Future<NotificationServiceStatus> _invoke(
String method, [
Map<String, Object?>? arguments,
]) async {
final reply = await _channel.invokeMethod<Object?>(method, arguments);
final status = NotificationServiceStatus.fromMap(reply);
_changes.add(status);
return status;
}
@override
Future<NotificationServiceStatus> status() => _invoke('status');
@override
Future<NotificationServiceStatus> start() => _invoke('start');
@override
Future<NotificationServiceStatus> configure({
required String serverId,
required List<String> endpoints,
required String cookie,
}) => _invoke('configure', {
'serverId': serverId,
'endpoints': endpoints,
'cookie': cookie,
});
@override
Future<NotificationServiceStatus> setEnabled(bool enabled) =>
_invoke('setEnabled', {'enabled': enabled});
@override
Future<bool> requestBatteryExemption() async =>
await _channel.invokeMethod<bool>('requestBatteryExemption') ?? false;
}
/// Web, iOS and desktop: no background service; nothing is pretended.
class UnsupportedNotificationServiceBridge
implements NotificationServiceBridge {
const UnsupportedNotificationServiceBridge();
@override
bool get supported => false;
@override
Stream<NotificationServiceStatus> get changes => const Stream.empty();
@override
Future<NotificationServiceStatus> status() async =>
NotificationServiceStatus.unsupported;
@override
Future<NotificationServiceStatus> start() => status();
@override
Future<NotificationServiceStatus> configure({
required String serverId,
required List<String> endpoints,
required String cookie,
}) => status();
@override
Future<NotificationServiceStatus> setEnabled(bool enabled) => status();
@override
Future<bool> requestBatteryExemption() async => false;
}
@@ -0,0 +1,84 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'notification_service_bridge.dart';
/// Settings' view of background delivery: the switch, the live status and the
/// battery exemption, all read from the native service (never guessed).
class NotificationServiceController extends ChangeNotifier {
NotificationServiceController(
this.bridge, {
this.requestNotificationPermission,
}) {
_changes = bridge.changes.listen(_apply);
}
final NotificationServiceBridge bridge;
/// Asks Android 13+ for POST_NOTIFICATIONS (the app's existing request).
final Future<void> Function()? requestNotificationPermission;
late final StreamSubscription<NotificationServiceStatus> _changes;
NotificationServiceStatus? _status;
bool _busy = false;
String _error = '';
bool _disposed = false;
NotificationServiceStatus? get status => _status;
bool get busy => _busy;
String get error => _error;
Future<void> load() => _run(bridge.status);
/// Re-reads after returning from a system screen (permission, battery).
Future<void> refresh() => load();
Future<void> setEnabled(bool enabled) => _run(() async {
if (enabled && _status?.notificationsAllowed == false) {
await requestNotificationPermission?.call();
}
return bridge.setEnabled(enabled);
});
Future<void> allowNotifications() => _run(() async {
await requestNotificationPermission?.call();
return bridge.status();
});
Future<void> allowBackgroundDelivery() => _run(() async {
await bridge.requestBatteryExemption();
return bridge.status();
});
Future<void> _run(Future<NotificationServiceStatus> Function() action) async {
if (_busy) return;
_busy = true;
_error = '';
_notify();
try {
_status = await action();
} catch (error) {
_error = 'Background delivery is unavailable: $error';
} finally {
_busy = false;
_notify();
}
}
void _apply(NotificationServiceStatus status) {
_status = status;
_notify();
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
unawaited(_changes.cancel());
super.dispose();
}
}
@@ -0,0 +1,74 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../core/session/server_session.dart';
import '../../core/transport/pipelines_client.dart';
import 'notification_service_bridge.dart';
/// Shares the app's proven connection with the background service.
///
/// Whenever the shared client connects, the server it reached (its trusted
/// addresses and the web sign-in cookie the socket used) is handed to the
/// service, so the service authenticates exactly like the app. On creation it
/// starts the service if delivery is enabled and a server was handed over
/// before, which covers app launches after the service was stopped.
class NotificationServiceHandoff {
NotificationServiceHandoff({
required this.bridge,
required this.client,
required this.serverId,
@visibleForTesting Map<String, String> Function(Uri endpoint)? headersFor,
}) : _headersFor = headersFor ?? ServerSession.headersFor {
if (!bridge.supported) return;
unawaited(_guard(bridge.start()));
_states = client.states.listen(_onState);
if (client.state.kind == ConnectionKind.connected) _handOver();
}
final NotificationServiceBridge bridge;
final PipelinesClient client;
/// The logical server; falls back to the connected address when absent.
final String? serverId;
final Map<String, String> Function(Uri endpoint) _headersFor;
StreamSubscription<ConnectionState>? _states;
void _onState(ConnectionState state) {
if (state.kind == ConnectionKind.connected) _handOver();
}
void _handOver() {
final endpoint = client.endpoint;
if (endpoint == null) return;
final addresses = client.endpoints.isEmpty ? [endpoint] : client.endpoints;
// Connected address first: it is the one known to work right now.
final ordered = <String>{
endpoint.toString(),
for (final address in addresses) address.toString(),
}.toList();
final id = serverId;
unawaited(
_guard(
bridge.configure(
serverId: id == null || id.isEmpty ? ordered.first : id,
endpoints: ordered,
cookie: _headersFor(endpoint)['Cookie'] ?? '',
),
),
);
}
/// A missing or failing platform side must never break the app.
Future<void> _guard(Future<Object?> call) async {
try {
await call;
} catch (error) {
debugPrint('Notification service: $error');
}
}
void dispose() {
unawaited(_states?.cancel());
}
}
@@ -0,0 +1,65 @@
/// The background connection's state, in the service's wire words.
enum DeliveryState {
off('off'),
unconfigured('unconfigured'),
connecting('connecting'),
connected('connected'),
reconnecting('reconnecting'),
waitingForNetwork('waiting_for_network');
const DeliveryState(this.wire);
final String wire;
static DeliveryState parse(Object? value) => DeliveryState.values.firstWhere(
(state) => state.wire == value,
orElse: () => DeliveryState.off,
);
}
/// What the native service reports: the switch, whether a server was handed
/// over, the connection, and the two Android permissions delivery relies on.
class NotificationServiceStatus {
const NotificationServiceStatus({
required this.enabled,
required this.configured,
required this.state,
required this.notificationsAllowed,
required this.batteryExempt,
});
static const unsupported = NotificationServiceStatus(
enabled: false,
configured: false,
state: DeliveryState.off,
notificationsAllowed: false,
batteryExempt: false,
);
final bool enabled;
final bool configured;
final DeliveryState state;
final bool notificationsAllowed;
final bool batteryExempt;
factory NotificationServiceStatus.fromMap(Object? raw) {
final map = raw is Map ? raw : const {};
return NotificationServiceStatus(
enabled: map['enabled'] == true,
configured: map['configured'] == true,
state: DeliveryState.parse(map['status']),
notificationsAllowed: map['notificationsAllowed'] == true,
batteryExempt: map['batteryExempt'] == true,
);
}
/// One short line for Settings.
String get label => switch (state) {
DeliveryState.connected => 'Connected',
DeliveryState.connecting => 'Connecting…',
DeliveryState.reconnecting => 'Reconnecting…',
DeliveryState.waitingForNetwork => 'Waiting for a network',
DeliveryState.unconfigured => 'Starts after the app connects to a server',
DeliveryState.off => enabled ? 'Not running' : 'Off',
};
}
@@ -27,6 +27,14 @@ const ntfySettings = <NtfySetting>[
NtfySetting('chat_reply_finished', 'Chat reply finished'),
];
/// The server's switch for also publishing to ntfy. Optional: older servers
/// do not send it, and Settings hides the switch then.
const ntfyEnabledSetting = NtfySetting(
'ntfy_enabled',
'Also send to ntfy',
subtitle: 'For devices that still use the ntfy app',
);
/// Loads and changes the server's ntfy notification settings through the
/// shared gateway (`notification_settings` / `set_notification_settings`).
///
@@ -112,6 +120,8 @@ class NtfySettingsController extends ChangeNotifier {
}
result[setting.key] = value;
}
final ntfy = raw[ntfyEnabledSetting.key];
if (ntfy is bool) result[ntfyEnabledSetting.key] = ntfy;
return result;
}
@@ -0,0 +1,148 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../notification_service/notification_service_bridge.dart';
import '../notification_service/notification_service_controller.dart';
import 'settings_group.dart';
import 'settings_row.dart';
import 'settings_theme.dart';
const deviceDeliveryTitle = 'Notifications in Pipelines';
const deviceDeliverySwitchLabel = 'Receive notifications in Pipelines';
const deviceDeliveryNote =
'Pipelines keeps its own connection to the server and shows its '
'notifications, so the ntfy app is no longer needed. Android shows a '
'quiet "Pipelines is connected" notification while it runs.';
const deviceDeliveryBatteryLabel = 'Allow background delivery';
const deviceDeliveryNotificationsLabel = 'Allow notifications';
abstract final class DeviceDeliveryKeys {
static const toggle = ValueKey<String>('settings.deviceDelivery.toggle');
static const status = ValueKey<String>('settings.deviceDelivery.status');
static const battery = ValueKey<String>('settings.deviceDelivery.battery');
static const permission = ValueKey<String>(
'settings.deviceDelivery.permission',
);
static const error = ValueKey<String>('settings.deviceDelivery.error');
}
/// Android background delivery in Settings: the switch, the service's live
/// status, and the two system grants it relies on (notification permission and
/// the battery-optimisation exemption). Absent where there is no service.
class SettingsDeviceDeliverySection extends StatefulWidget {
const SettingsDeviceDeliverySection({
super.key,
required this.bridge,
this.requestNotificationPermission,
});
final NotificationServiceBridge bridge;
final Future<void> Function()? requestNotificationPermission;
@override
State<SettingsDeviceDeliverySection> createState() =>
_SettingsDeviceDeliverySectionState();
}
class _SettingsDeviceDeliverySectionState
extends State<SettingsDeviceDeliverySection> {
late final NotificationServiceController _controller =
NotificationServiceController(
widget.bridge,
requestNotificationPermission: widget.requestNotificationPermission,
);
// System prompts (permission, battery) return by resuming the app.
late final AppLifecycleListener _lifecycle = AppLifecycleListener(
onResume: () => unawaited(_controller.refresh()),
);
@override
void initState() {
super.initState();
_lifecycle;
unawaited(_controller.load());
}
@override
void dispose() {
_lifecycle.dispose();
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: _controller,
builder: (context, _) => _body(context),
);
Widget _body(BuildContext context) {
final cupertino = usesCupertinoControls(context);
final status = _controller.status;
final enabled = status?.enabled ?? false;
final onChanged = status == null || _controller.busy
? null
: (bool value) => unawaited(_controller.setEnabled(value));
return SettingsGroup(
title: deviceDeliveryTitle,
footer: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
const Text(deviceDeliveryNote),
if (_controller.error.isNotEmpty)
Text(
_controller.error,
key: DeviceDeliveryKeys.error,
style: TextStyle(color: settingsErrorColor(context)),
),
],
),
children: <Widget>[
if (cupertino)
CupertinoListTile(
key: DeviceDeliveryKeys.toggle,
title: const Text(deviceDeliverySwitchLabel),
trailing: CupertinoSwitch(value: enabled, onChanged: onChanged),
onTap: onChanged == null ? null : () => onChanged(!enabled),
)
else
SwitchListTile(
key: DeviceDeliveryKeys.toggle,
title: const Text(deviceDeliverySwitchLabel),
value: enabled,
onChanged: onChanged,
),
SettingsRow(
key: DeviceDeliveryKeys.status,
title: const Text('Status'),
subtitle: Text(status == null ? 'Loading…' : status.label),
),
if (status != null && enabled && !status.notificationsAllowed)
SettingsRow(
key: DeviceDeliveryKeys.permission,
title: const Text(deviceDeliveryNotificationsLabel),
subtitle: const Text('Android is blocking Pipelines notifications'),
action: true,
enabled: !_controller.busy,
onTap: () => unawaited(_controller.allowNotifications()),
),
if (status != null && enabled)
SettingsRow(
key: DeviceDeliveryKeys.battery,
title: const Text(deviceDeliveryBatteryLabel),
subtitle: Text(
status.batteryExempt
? 'Allowed: battery optimisation will not pause delivery'
: 'Keeps notifications instant while the phone is idle',
),
action: !status.batteryExempt,
enabled: !status.batteryExempt && !_controller.busy,
onTap: () => unawaited(_controller.allowBackgroundDelivery()),
),
],
);
}
}
@@ -15,6 +15,12 @@ const ntfySectionTitle = 'Phone notifications';
const ntfySectionSubtitle =
'Sent through ntfy to the devices subscribed to this server.';
/// The subtitle once the server delivers to the app itself (it reports
/// `ntfy_enabled`).
const ntfySectionAppSubtitle =
'What the server notifies about: shown by the Pipelines app and, when '
'enabled, also sent through ntfy.';
/// Shown instead of loading while the shared connection is down.
const ntfyOfflineText = 'Connect to a server to change these.';
@@ -84,8 +90,12 @@ class _SettingsNtfySectionState extends State<SettingsNtfySection> {
: _controller.loading && values == null
? 'Loading…'
: '';
final hasNtfySwitch = values?.containsKey(ntfyEnabledSetting.key) ?? false;
final tiles = <Widget>[
for (final setting in ntfySettings)
for (final setting in [
...ntfySettings,
if (hasNtfySwitch) ntfyEnabledSetting,
])
_tile(
cupertino,
setting,
@@ -99,7 +109,7 @@ class _SettingsNtfySectionState extends State<SettingsNtfySection> {
footer: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
const Text(ntfySectionSubtitle),
Text(hasNtfySwitch ? ntfySectionAppSubtitle : ntfySectionSubtitle),
if (status.isNotEmpty) Text(status),
if (_controller.error.isNotEmpty)
Semantics(
@@ -14,6 +14,8 @@ import 'settings_group.dart';
import 'settings_page_body.dart';
import 'settings_notifications_section.dart';
import 'settings_ntfy_section.dart';
import 'settings_device_delivery_section.dart';
import '../notification_service/notification_service_bridge.dart';
import 'settings_android_download_section.dart';
import 'settings_schedules_section.dart';
import 'settings_sections.dart';
@@ -48,8 +50,12 @@ class SettingsScreen extends StatefulWidget {
this.showSignIn = false,
this.showAndroidDownload = false,
this.servers,
this.deliveryService,
});
/// Android background delivery; hidden when absent or unsupported.
final NotificationServiceBridge? deliveryService;
final transport.PipelinesClient client;
/// Whether to offer the web sign-in (the native app; a browser has its own).
@@ -183,6 +189,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
if (widget.notifications case final notifications?)
SettingsNotificationsSection(controller: notifications),
if (widget.deliveryService case final service? when service.supported)
SettingsDeviceDeliverySection(
bridge: service,
requestNotificationPermission: widget.notifications == null
? null
: () async {
await widget.notifications!.requestPermission();
},
),
// The server's ntfy choices, beside the in-app permission.
SettingsNtfySection(
gateway: widget.client,