Add server notification settings with app checkboxes

Persist three global ntfy switches in server_settings: run_finished
(default on: auto-mode runs notify on success, read inside the
transition transaction; on/off modes unchanged), chat_needs_you
(default on: gates chat question/approval alerts) and
chat_reply_finished (default off: one alert per finished assistant
turn). Expose notification_settings / set_notification_settings over
the websocket protocol, add a Phone notifications section with
Material and Cupertino checkboxes in Settings, document the settings,
and keep the cli, tui, stage and pipeline test packages from
inheriting a real ntfy configuration.
This commit is contained in:
2026-10-30 21:36:27 +00:00
parent 39d9150c3a
commit 498c6f17a6
26 changed files with 1381 additions and 28 deletions
@@ -0,0 +1,117 @@
import 'package:flutter/foundation.dart';
import '../../core/api_gateway.dart';
/// One server-side ntfy notification choice, in the server's wire key.
class NtfySetting {
const NtfySetting(this.key, this.label);
final String key;
final String label;
}
/// The server's global notification choices, in display order.
const ntfySettings = <NtfySetting>[
NtfySetting('run_finished', 'Run finished'),
NtfySetting('chat_needs_you', 'Chat needs your answer or approval'),
NtfySetting('chat_reply_finished', 'Chat reply finished'),
];
/// Loads and changes the server's ntfy notification settings through the
/// shared gateway (`notification_settings` / `set_notification_settings`).
///
/// A toggle shows the new value at once and is reverted, with the server's
/// refusal as [error], when the write fails. Every reply carries all keys, so
/// the stored result always replaces the local copy.
class NtfySettingsController extends ChangeNotifier {
NtfySettingsController(this.gateway);
final ApiGateway gateway;
Map<String, bool>? _values;
bool _loading = false;
String? _saving;
String _error = '';
bool _disposed = false;
/// The stored values, or null before the first successful load.
Map<String, bool>? get values => _values;
bool get loading => _loading;
/// The key whose change is being written, if any.
String? get saving => _saving;
String get error => _error;
/// Whether the checkboxes accept a change now.
bool get enabled => _values != null && !_loading && _saving == null;
Future<void> load() async {
if (_loading) return;
_loading = true;
_error = '';
_notify();
try {
final reply = await gateway.call('notification_settings');
_values = _decode(reply);
} catch (error) {
_error = 'Could not load notification settings: $error';
} finally {
_loading = false;
_notify();
}
}
Future<void> toggle(String key, bool value) async {
final current = _values;
if (current == null || !enabled) return;
final previous = current[key];
_values = {...current, key: value};
_saving = key;
_error = '';
_notify();
try {
final reply = await gateway.call('set_notification_settings', {
'notification_settings': {key: value},
});
_values = _decode(reply);
} catch (error) {
final reverted = {...?_values};
if (previous == null) {
reverted.remove(key);
} else {
reverted[key] = previous;
}
_values = reverted;
_error = 'Could not save: $error';
} finally {
_saving = null;
_notify();
}
}
static Map<String, bool> _decode(JsonMap reply) {
final raw = reply['notification_settings'];
if (raw is! Map) {
throw const FormatException('the reply carried no notification settings');
}
final result = <String, bool>{};
for (final setting in ntfySettings) {
final value = raw[setting.key];
if (value is! bool) {
throw FormatException('the reply is missing ${setting.key}');
}
result[setting.key] = value;
}
return result;
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
@@ -0,0 +1,169 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import 'ntfy_settings_controller.dart';
import 'settings_layout.dart';
import 'settings_theme.dart';
/// The section title for the server's ntfy notification choices.
const ntfySectionTitle = 'Phone notifications';
/// One line explaining where these notifications go.
const ntfySectionSubtitle =
'Sent through ntfy to the devices subscribed to this server.';
/// Shown instead of loading while the shared connection is down.
const ntfyOfflineText = 'Connect to a server to change these.';
ValueKey<String> ntfySettingKey(String key) => ValueKey<String>('ntfy-$key');
const ntfyErrorKey = ValueKey<String>('ntfy-settings-error');
/// The server-side notification checkboxes in Settings: run finished, chat
/// needs you and chat reply finished. Values load from the server whenever
/// [connected] becomes true and every toggle is written at once; a refusal is
/// shown inline and the checkbox reverts.
class SettingsNtfySection extends StatefulWidget {
const SettingsNtfySection({
super.key,
required this.gateway,
required this.connected,
});
final ApiGateway gateway;
final bool connected;
@override
State<SettingsNtfySection> createState() => _SettingsNtfySectionState();
}
class _SettingsNtfySectionState extends State<SettingsNtfySection> {
late NtfySettingsController _controller = NtfySettingsController(
widget.gateway,
);
@override
void initState() {
super.initState();
if (widget.connected) unawaited(_controller.load());
}
@override
void didUpdateWidget(SettingsNtfySection oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway != widget.gateway) {
_controller.dispose();
_controller = NtfySettingsController(widget.gateway);
}
if (widget.connected &&
(!oldWidget.connected || oldWidget.gateway != widget.gateway)) {
unawaited(_controller.load());
}
}
@override
void 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 values = _controller.values;
final enabled = widget.connected && _controller.enabled;
final status = !widget.connected
? ntfyOfflineText
: _controller.loading && values == null
? 'Loading…'
: '';
final tiles = <Widget>[
for (final setting in ntfySettings)
_tile(
cupertino,
setting,
values?[setting.key] ?? false,
enabled ? (value) => _controller.toggle(setting.key, value) : null,
),
];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
ntfySectionSubtitle,
style: settingsTextStyle(context, secondary: true),
),
if (status.isNotEmpty) ...<Widget>[
const SizedBox(height: settingsFieldGap),
Text(status, style: settingsTextStyle(context, secondary: true)),
],
const SizedBox(height: settingsFieldGap),
if (cupertino)
CupertinoListSection.insetGrouped(
margin: EdgeInsets.zero,
children: tiles,
)
else
...tiles,
if (_controller.error.isNotEmpty) ...<Widget>[
const SizedBox(height: settingsFieldGap),
Semantics(
liveRegion: true,
child: Text(
_controller.error,
key: ntfyErrorKey,
style: settingsTextStyle(context, error: true),
),
),
if (values == null && widget.connected && !_controller.loading)
Align(
alignment: AlignmentDirectional.centerStart,
child: cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _controller.load,
child: const Text('Retry'),
)
: TextButton(
onPressed: _controller.load,
child: const Text('Retry'),
),
),
],
],
);
}
Widget _tile(
bool cupertino,
NtfySetting setting,
bool value,
ValueChanged<bool>? onChanged,
) {
if (cupertino) {
return CupertinoListTile(
key: ntfySettingKey(setting.key),
title: Text(setting.label),
trailing: CupertinoCheckbox(
value: value,
onChanged: onChanged == null ? null : (next) => onChanged(next!),
),
onTap: onChanged == null ? null : () => onChanged(!value),
);
}
return CheckboxListTile(
key: ntfySettingKey(setting.key),
contentPadding: EdgeInsets.zero,
title: Text(setting.label),
value: value,
onChanged: onChanged == null ? null : (next) => onChanged(next!),
);
}
}
@@ -11,6 +11,7 @@ import 'settings_controller.dart';
import 'settings_controls.dart';
import 'settings_layout.dart';
import 'settings_notifications_section.dart';
import 'settings_ntfy_section.dart';
import 'settings_android_download_section.dart';
import 'settings_schedules_section.dart';
import 'settings_sections.dart';
@@ -228,6 +229,17 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
),
],
// The server's ntfy choices, beside the in-app permission.
const SizedBox(height: settingsSectionGap),
_SettingsSection(
title: ntfySectionTitle,
child: SettingsNtfySection(
gateway: widget.client,
connected:
widget.client.state.kind ==
transport.ConnectionKind.connected,
),
),
if (widget.onOpenSchedules != null) ...<Widget>[
const SizedBox(height: settingsSectionGap),
_SettingsSection(
+34
View File
@@ -0,0 +1,34 @@
# Notification settings (ntfy checkboxes)
Settings has a **Phone notifications** section beside the in-app
Notifications permission tile. It holds three checkboxes for the server's global
ntfy choices: **Run finished** (`run_finished`, default on), **Chat needs your
answer or approval** (`chat_needs_you`, default on) and **Chat reply finished**
(`chat_reply_finished`, default off), under one line saying they go through
ntfy to the subscribed devices. Material uses `CheckboxListTile`. Cupertino uses
`CupertinoListTile` with a `CupertinoCheckbox` in an inset grouped section.
Colours come from the theme only.
Files: `lib/features/settings/ntfy_settings_controller.dart` (gateway
load/toggle, revert on failure), `lib/features/settings/settings_ntfy_section.dart`
(widget), wired into `settings_screen.dart` with the shared client as the
`ApiGateway`.
Behaviour: the section loads `notification_settings` when the shared connection
is connected and reloads after reconnecting. While offline it shows "Connect to a
server to change these." Checkboxes are disabled while loading or saving. A
toggle sends `set_notification_settings` with only that key and shows the new
value at once. The stored reply then replaces every value. A refusal reverts the
checkbox and shows "Could not save: <reason>" inline. A load failure shows the
reason with a Retry button.
Verification: `test/features/settings/settings_ntfy_section_test.dart` covers
both styles. It checks loading, the exact set request, and revert plus error on
failure. It also covers the disabled state while loading, the offline state and
retry after a failed load. The existing Settings screen and Templates wiring
tests now answer the extra queued `notification_settings` read. Full
`flutter test` passed, `flutter analyze` reported only the pre-existing info in
`artifact_viewer_page_test.dart`, and `flutter build web` succeeded.
Not done: no browser capture or device run. Rendered behaviour is verified by
widget tests only, and phone delivery of the new notifications was not tested.
@@ -103,6 +103,15 @@ Future<void> openSettings(
'build': {'version': 'probe'},
'time': 'fixture',
});
// It then loads the server's ntfy notification settings.
await reply(tester, channel, 'notification_settings', 1, {
'type': 'notification_settings',
'notification_settings': {
'run_finished': true,
'chat_needs_you': true,
'chat_reply_finished': false,
},
});
}
Future<void> openTemplates(
@@ -0,0 +1,184 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/settings/settings_ntfy_section.dart';
/// A scripted gateway: records every request and answers from [respond].
class _Gateway implements ApiGateway {
_Gateway(this.respond);
final FutureOr<JsonMap> Function(String type, JsonMap fields) respond;
final calls = <(String, JsonMap)>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type, fields));
return respond(type, fields);
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
JsonMap _reply(bool run, bool needs, bool reply) => {
'type': 'notification_settings',
'notification_settings': {
'run_finished': run,
'chat_needs_you': needs,
'chat_reply_finished': reply,
},
};
Widget _host(ApiGateway gateway, {required bool cupertino}) => MaterialApp(
theme: ThemeData(
platform: cupertino ? TargetPlatform.iOS : TargetPlatform.android,
),
home: Scaffold(
body: SingleChildScrollView(
child: SettingsNtfySection(gateway: gateway, connected: true),
),
),
);
bool _checked(WidgetTester tester, String key, {required bool cupertino}) {
final tile = find.byKey(ntfySettingKey(key));
if (cupertino) {
return tester
.widget<CupertinoCheckbox>(
find.descendant(of: tile, matching: find.byType(CupertinoCheckbox)),
)
.value!;
}
return tester.widget<CheckboxListTile>(tile).value!;
}
void main() {
for (final cupertino in [false, true]) {
final style = cupertino ? 'Cupertino' : 'Material';
testWidgets('$style loads the stored values', (tester) async {
final gateway = _Gateway((_, _) => _reply(true, false, true));
await tester.pumpWidget(_host(gateway, cupertino: cupertino));
await tester.pumpAndSettle();
expect(gateway.calls.single.$1, 'notification_settings');
expect(find.text('Run finished'), findsOneWidget);
expect(find.text('Chat needs your answer or approval'), findsOneWidget);
expect(find.text('Chat reply finished'), findsOneWidget);
expect(find.text(ntfySectionSubtitle), findsOneWidget);
expect(_checked(tester, 'run_finished', cupertino: cupertino), isTrue);
expect(_checked(tester, 'chat_needs_you', cupertino: cupertino), isFalse);
expect(
_checked(tester, 'chat_reply_finished', cupertino: cupertino),
isTrue,
);
});
testWidgets('$style toggling writes only that setting', (tester) async {
final gateway = _Gateway((type, fields) {
if (type == 'set_notification_settings') {
return _reply(true, true, true);
}
return _reply(true, true, false);
});
await tester.pumpWidget(_host(gateway, cupertino: cupertino));
await tester.pumpAndSettle();
await tester.tap(find.byKey(ntfySettingKey('chat_reply_finished')));
await tester.pumpAndSettle();
expect(gateway.calls, hasLength(2));
expect(gateway.calls.last.$1, 'set_notification_settings');
expect(gateway.calls.last.$2, {
'notification_settings': {'chat_reply_finished': true},
});
expect(
_checked(tester, 'chat_reply_finished', cupertino: cupertino),
isTrue,
);
expect(find.byKey(ntfyErrorKey), findsNothing);
});
testWidgets('$style failure reverts and shows the refusal', (tester) async {
final pending = Completer<JsonMap>();
final gateway = _Gateway((type, _) {
if (type == 'set_notification_settings') return pending.future;
return _reply(true, true, false);
});
await tester.pumpWidget(_host(gateway, cupertino: cupertino));
await tester.pumpAndSettle();
await tester.tap(find.byKey(ntfySettingKey('run_finished')));
await tester.pump();
// The change shows at once and the group is disabled while it saves.
expect(_checked(tester, 'run_finished', cupertino: cupertino), isFalse);
await tester.tap(find.byKey(ntfySettingKey('chat_needs_you')));
await tester.pump();
expect(gateway.calls, hasLength(2));
pending.completeError(const ProtocolError('settings are read-only'));
await tester.pumpAndSettle();
expect(_checked(tester, 'run_finished', cupertino: cupertino), isTrue);
expect(_checked(tester, 'chat_needs_you', cupertino: cupertino), isTrue);
expect(
find.text('Could not save: settings are read-only'),
findsOneWidget,
);
});
}
testWidgets('disabled while loading and offline', (tester) async {
final pending = Completer<JsonMap>();
final gateway = _Gateway((_, _) => pending.future);
await tester.pumpWidget(_host(gateway, cupertino: false));
await tester.pump();
expect(find.text('Loading…'), findsOneWidget);
await tester.tap(find.byKey(ntfySettingKey('run_finished')));
await tester.pump();
expect(gateway.calls, hasLength(1));
expect(
tester
.widget<CheckboxListTile>(find.byKey(ntfySettingKey('run_finished')))
.onChanged,
isNull,
);
pending.complete(_reply(true, true, false));
await tester.pumpAndSettle();
expect(find.text('Loading…'), findsNothing);
final offline = _Gateway((_, _) => _reply(true, true, false));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SettingsNtfySection(gateway: offline, connected: false),
),
),
);
await tester.pumpAndSettle();
expect(offline.calls, isEmpty);
expect(find.text(ntfyOfflineText), findsOneWidget);
});
testWidgets('a load failure is shown with a retry', (tester) async {
var fail = true;
final gateway = _Gateway((_, _) {
if (fail) throw const ProtocolError('no store');
return _reply(false, true, false);
});
await tester.pumpWidget(_host(gateway, cupertino: false));
await tester.pumpAndSettle();
expect(
find.text('Could not load notification settings: no store'),
findsOneWidget,
);
fail = false;
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.byKey(ntfyErrorKey), findsNothing);
expect(
tester
.widget<CheckboxListTile>(find.byKey(ntfySettingKey('run_finished')))
.value,
isFalse,
);
});
}
@@ -153,7 +153,11 @@ void main() {
expect(find.text('Server time 2026-10-21T12:00:00Z'), findsOneWidget);
expect(find.byKey(SettingsKeys.disconnect), findsOneWidget);
expect(find.byKey(SettingsKeys.connect), findsOneWidget);
expect(factory.last.decodedOutgoing, hasLength(1));
// The only other request is the ntfy settings load, queued behind ping.
_answerNtfySettings(factory.last);
await tester.pump();
await tester.pump();
expect(factory.last.decodedOutgoing, hasLength(2));
});
testWidgets('connected without a ping reply names unavailable values', (
@@ -191,6 +195,8 @@ void main() {
expect(find.text(serverDetailsPending), findsNothing);
expect(find.text('Server build unavailable'), findsOneWidget);
expect(find.text('Server time unavailable'), findsOneWidget);
_answerNtfySettings(factory.last);
await tester.pump();
});
testWidgets(
@@ -361,3 +367,18 @@ Future<void> _pump(
await tester.pump();
await tester.pump();
}
/// Answers the Settings screen's queued ntfy-settings load on [channel].
void _answerNtfySettings(FakeChannel channel) {
final request = channel.decodedOutgoing.last;
expect(request['type'], 'notification_settings');
channel.reply(<String, dynamic>{
'id': request['id'],
'type': 'notification_settings',
'notification_settings': <String, dynamic>{
'run_finished': true,
'chat_needs_you': true,
'chat_reply_finished': false,
},
});
}