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,
},
});
}
+42 -5
View File
@@ -73,10 +73,15 @@ artifacts=markdown,files
Independently of any `notify` block, the server publishes one run-level
notification to the `system` destination when a run needs a person: when it enters
`waiting` (a human stage asked for a decision) and when it fails. Nothing else
notifies by default — queued, running, canceled and interrupted runs are silent.
Runs explicitly started with notifications **on** also notify on success.
The payload names the run and its pipeline. Run notifications and stage hooks
`waiting` (a human stage asked for a decision), when it fails, and — while the
**Run finished** setting (`run_finished`, on by default) is enabled — when it
succeeds (`Run succeeded`). Queued, running, canceled and interrupted runs are
silent. The run's own notify mode still wins: a run started with notifications
**on** always notifies on success, a run started with notifications **off**
never notifies anything, and the default **auto** mode follows `run_finished`
for success (waiting/failed always notify). The setting is read in the same
transaction that records the run's final state, so a change applies to runs
finishing after it. The payload names the run and its pipeline. Run notifications and stage hooks
use the configured web run link described below.
### Open notifications in the web app
@@ -132,7 +137,18 @@ permission (approval) request — the server publishes one notification to the
approval` for permissions; `Chat` when the session has no title), the question or
permission text as the body, `Click` `pipelines://chat/<session id>`, and the
**Open in browser** action to `<web>/chat/<session id>` when
`PIPELINES_WEB_PUBLIC_URL` is set. Ordinary finished replies do not notify.
`PIPELINES_WEB_PUBLIC_URL` is set. These are controlled by the **Chat needs your
answer or approval** setting (`chat_needs_you`, on by default).
Finished replies notify only when **Chat reply finished**
(`chat_reply_finished`) is turned on (off by default): when an assistant turn
ends (the authoritative, non-intermediate step end), the server publishes
`<chat title> replied` (`Chat replied` without a title) with the first ~200
characters of the turn's final assistant text as the body, or `The agent
finished its reply.` when no text was retained, plus the same click and browser
action. Each turn notifies once: a repeated or replayed end with no turn
observed in between, or a turn id already announced, publishes nothing, and
reading history never publishes.
- Each form/request id notifies at most once per server process: duplicate
events, reconnects and replays of a still-pending question are deduplicated in
@@ -145,6 +161,27 @@ permission text as the body, `Click` `pipelines://chat/<session id>`, and the
fails chat handling, and failures are only logged. Nothing is sent when
`PIPELINES_NTFY_URL` is not configured.
## Notification settings
Three global, server-side switches choose which of these events are published.
They are stored in the server database (`server_settings`), survive restarts and
apply to every device subscribed to the topic. Per-stage `notify` hooks and
explicit `type=ntfy` stages are not affected.
| Setting | Default | Effect |
| --- | --- | --- |
| `run_finished` — Run finished | on | an **auto**-mode run that succeeds notifies `Run succeeded` |
| `chat_needs_you` — Chat needs your answer or approval | on | chat question/form and approval requests notify |
| `chat_reply_finished` — Chat reply finished | off | each finished assistant turn in a chat notifies |
Change them in the app under **Settings → Phone notifications** (checkboxes; a
refused change reverts and shows the server's reason). Over the websocket
protocol, `{"type":"notification_settings"}` reads them and
`{"type":"set_notification_settings","notification_settings":{"chat_reply_finished":true}}`
changes any subset; both reply with type `notification_settings` carrying all
three keys. Unknown keys and non-boolean values are refused with an `error`
reply and nothing is written.
## Explicit delivery stage (optional)
The preceding stage must output three nonempty UTF-8 strings: `title`, `summary`,
+16
View File
@@ -0,0 +1,16 @@
package cli
import (
"os"
"testing"
)
// TestMain isolates the package from an operator's real notification setup:
// these tests run real servers and runs, a developer shell may export the
// installed server's ntfy configuration, and no test may publish to it.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
}
+16
View File
@@ -0,0 +1,16 @@
package pipeline
import (
"os"
"testing"
)
// TestMain isolates the package from an operator's real notification setup.
// The store only enqueues notifications, but a developer shell may export the
// installed server's ntfy configuration and no test may ever publish to it.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
}
@@ -0,0 +1,70 @@
package pipeline
import (
"context"
"database/sql"
"fmt"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// notificationSettingPrefix namespaces the global notification choices inside
// server_settings; each key stores "true" or "false". A missing row means the
// default from protocol.DefaultNotificationSettings.
const notificationSettingPrefix = "notify."
type settingsQuerier interface {
QueryContext(context.Context, string, ...any) (*sql.Rows, error)
}
// readNotificationSettings reads the stored choices through q, which may be the
// database or an open transaction (run-transition enqueue reads inside its tx).
func readNotificationSettings(ctx context.Context, q settingsQuerier) (protocol.NotificationSettings, error) {
settings := protocol.DefaultNotificationSettings()
rows, err := q.QueryContext(ctx, `SELECT key,value FROM server_settings WHERE key LIKE 'notify.%'`)
if err != nil {
return settings, err
}
defer rows.Close()
for rows.Next() {
var key, value string
if err := rows.Scan(&key, &value); err != nil {
return settings, err
}
if field := settings.Field(key[len(notificationSettingPrefix):]); field != nil {
*field = value == "true"
}
}
return settings, rows.Err()
}
// NotificationSettings returns the operator's global notification choices.
func (s *Store) NotificationSettings(ctx context.Context) (protocol.NotificationSettings, error) {
return readNotificationSettings(ctx, s.db)
}
// UpdateNotificationSettings applies a validated partial update atomically and
// returns the stored result. Unknown keys and non-boolean values are refused
// before anything is written.
func (s *Store) UpdateNotificationSettings(ctx context.Context, update map[string]any) (protocol.NotificationSettings, error) {
values, err := protocol.ValidateNotificationSettingsUpdate(update)
if err != nil {
return protocol.NotificationSettings{}, err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return protocol.NotificationSettings{}, err
}
defer tx.Rollback()
for key, value := range values {
if _, err := tx.ExecContext(ctx, `INSERT INTO server_settings(key,value) VALUES(?,?)
ON CONFLICT(key) DO UPDATE SET value=excluded.value`, notificationSettingPrefix+key, fmt.Sprint(value)); err != nil {
return protocol.NotificationSettings{}, err
}
}
settings, err := readNotificationSettings(ctx, tx)
if err != nil {
return protocol.NotificationSettings{}, err
}
return settings, tx.Commit()
}
@@ -0,0 +1,133 @@
package pipeline
import (
"context"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestNotificationSettingsDefaultPersistAndPartialUpdate(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "notify-settings.db")
s, err := Open(path)
if err != nil {
t.Fatal(err)
}
got, err := s.NotificationSettings(ctx)
if err != nil || got != protocol.DefaultNotificationSettings() {
t.Fatalf("defaults = %+v, %v", got, err)
}
if !got.RunFinished || !got.ChatNeedsYou || got.ChatReplyFinished {
t.Fatalf("default values changed: %+v", got)
}
got, err = s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true})
want := protocol.NotificationSettings{RunFinished: true, ChatNeedsYou: true, ChatReplyFinished: true}
if err != nil || got != want {
t.Fatalf("partial update = %+v, %v", got, err)
}
got, err = s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: false, protocol.NotifyChatNeedsYou: false})
want = protocol.NotificationSettings{RunFinished: false, ChatNeedsYou: false, ChatReplyFinished: true}
if err != nil || got != want {
t.Fatalf("second update = %+v, %v", got, err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
s, err = Open(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
if got, err := s.NotificationSettings(ctx); err != nil || got != want {
t.Fatalf("after reopen = %+v, %v", got, err)
}
// The OpenCode endpoint row shares the table and is unaffected.
if endpoint, err := s.OpenCodeEndpoint(ctx); err != nil || endpoint != "" {
t.Fatalf("endpoint = %q, %v", endpoint, err)
}
}
func TestNotificationSettingsRejectUnknownOrInvalid(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "reject.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
for name, update := range map[string]map[string]any{
"unknown": {protocol.NotifyRunFinished: false, "run_started": true},
"non-bool": {protocol.NotifyChatNeedsYou: "false"},
"empty": {},
"nil value": {protocol.NotifyChatReplyFinished: nil},
} {
if _, err := s.UpdateNotificationSettings(ctx, update); err == nil {
t.Fatalf("%s update accepted", name)
}
}
// A rejected update writes nothing, not even its valid keys.
if got, err := s.NotificationSettings(ctx); err != nil || got != protocol.DefaultNotificationSettings() {
t.Fatalf("rejected update changed settings: %+v, %v", got, err)
}
if _, err := s.UpdateNotificationSettings(ctx, map[string]any{"bogus": true}); err == nil || !strings.Contains(err.Error(), `"bogus"`) {
t.Fatalf("unknown key error = %v", err)
}
}
// A run reaching succeeded enqueues its generic alert according to its notify
// mode and, for auto, the run_finished setting read in the same transaction.
func TestSucceededRunEnqueueFollowsRunFinishedSetting(t *testing.T) {
for _, tc := range []struct {
mode string
runFinished bool
want int
}{
{"auto", true, 1}, {"auto", false, 0}, {"on", true, 1}, {"on", false, 1}, {"off", true, 0}, {"off", false, 0},
} {
t.Run(tc.mode+map[bool]string{true: "-enabled", false: "-disabled"}[tc.runFinished], func(t *testing.T) {
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "succeeded.db"), tc.mode)
defer s.Close()
if _, err := s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: tc.runFinished}); err != nil {
t.Fatal(err)
}
if err := notificationTransition(ctx, s, id, "succeeded"); err != nil {
t.Fatal(err)
}
got, err := s.RunNotifications(ctx, id)
if err != nil || len(got) != tc.want {
t.Fatalf("notifications = %+v, %v; want %d", got, err, tc.want)
}
if tc.want == 1 {
n, err := s.ClaimRunNotification(ctx, time.Now().Unix())
if err != nil || n == nil || n.Event != "succeeded" || n.Title != "Run succeeded" || n.Click != "pipelines://run/"+strconv.FormatInt(id, 10) {
t.Fatalf("claimed = %+v, %v", n, err)
}
}
})
}
}
// Waiting and failed alerts do not depend on run_finished.
func TestRunFinishedSettingLeavesAttentionAlone(t *testing.T) {
for _, status := range []string{"waiting", "failed"} {
t.Run(status, func(t *testing.T) {
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "attention.db"), "auto")
defer s.Close()
if _, err := s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: false}); err != nil {
t.Fatal(err)
}
if err := notificationTransition(ctx, s, id, status); err != nil {
t.Fatal(err)
}
if got, err := s.RunNotifications(ctx, id); err != nil || len(got) != 1 || got[0].Event != status {
t.Fatalf("notifications = %+v, %v", got, err)
}
})
}
}
@@ -144,8 +144,9 @@ func TestRunNotificationTransitionModesAndCoverage(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// run_finished defaults on, so an auto run announces success too.
want := 1
if mode == "off" || status == "succeeded" && mode != "on" {
if mode == "off" {
want = 0
}
if len(ns) != want {
@@ -154,21 +155,23 @@ func TestRunNotificationTransitionModesAndCoverage(t *testing.T) {
})
}
}
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "covered.db"), "on")
defer s.Close()
if err := s.CoverRunNotification(ctx, id, 1, "succeeded"); err != nil {
t.Fatal(err)
}
if err := notificationTransition(ctx, s, id, "succeeded"); err != nil {
t.Fatal(err)
}
ns, err := s.RunNotifications(ctx, id)
if err != nil || len(ns) != 1 || ns[0].Status != "covered" {
t.Fatalf("stage coverage lost: %+v %v", ns, err)
}
if n, err := s.ClaimRunNotification(ctx, 100); err != nil || n != nil {
t.Fatalf("covered stage duplicated: %+v %v", n, err)
for _, mode := range []string{"on", "auto"} {
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), mode+"-covered.db"), mode)
defer s.Close()
if err := s.CoverRunNotification(ctx, id, 1, "succeeded"); err != nil {
t.Fatal(err)
}
if err := notificationTransition(ctx, s, id, "succeeded"); err != nil {
t.Fatal(err)
}
ns, err := s.RunNotifications(ctx, id)
if err != nil || len(ns) != 1 || ns[0].Status != "covered" {
t.Fatalf("stage coverage lost: %+v %v", ns, err)
}
if n, err := s.ClaimRunNotification(ctx, 100); err != nil || n != nil {
t.Fatalf("covered stage duplicated: %+v %v", n, err)
}
}
}
+9 -1
View File
@@ -46,8 +46,16 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version
title = "Run failed"
body = "run failed"
case "succeeded":
// "on" always announces success; any other (auto/legacy) mode follows
// the operator's run_finished choice, read in this transaction.
if mode != "on" {
return nil
settings, err := readNotificationSettings(ctx, tx)
if err != nil {
return err
}
if !settings.RunFinished {
return nil
}
}
title = "Run succeeded"
body = "run succeeded"
+3
View File
@@ -238,4 +238,7 @@ type Message struct {
// displays. Both are optional so older peers ignore them.
RunEvent *RunEventFrame `json:"run_event,omitempty"`
RunIDs []int64 `json:"run_ids,omitempty"`
// NotificationSettings is the set_notification_settings partial update and
// the notification_settings reply (every key). See notification_settings.go.
NotificationSettings map[string]any `json:"notification_settings,omitempty"`
}
@@ -0,0 +1,93 @@
package protocol
import (
"fmt"
"sort"
)
// Notification settings are the operator's global choices about which events
// publish through the server's ntfy connection. A client reads them with
// {"type":"notification_settings"} and changes them with
// {"type":"set_notification_settings","notification_settings":{"<key>":bool}};
// a set may name any subset of keys, and unknown keys or non-boolean values
// are refused. Both replies have type "notification_settings" and carry every
// key with its stored value.
const (
GetNotificationSettings = "notification_settings"
SetNotificationSettings = "set_notification_settings"
NotificationSettingsReply = "notification_settings"
)
// Notification setting keys, as carried on the wire.
const (
NotifyRunFinished = "run_finished"
NotifyChatNeedsYou = "chat_needs_you"
NotifyChatReplyFinished = "chat_reply_finished"
)
// NotificationSettings is the typed form of the global notification choices.
type NotificationSettings struct {
// RunFinished notifies when a run with notify mode "auto" succeeds. Runs
// started with notifications "on" always notify and "off" never do.
RunFinished bool
// ChatNeedsYou notifies when a chat asks a question or requests approval.
ChatNeedsYou bool
// ChatReplyFinished notifies when an assistant turn in a chat ends.
ChatReplyFinished bool
}
// NotificationSettingKeys lists every setting key in a stable order.
var NotificationSettingKeys = []string{NotifyRunFinished, NotifyChatNeedsYou, NotifyChatReplyFinished}
// DefaultNotificationSettings are the values before the operator changes any.
func DefaultNotificationSettings() NotificationSettings {
return NotificationSettings{RunFinished: true, ChatNeedsYou: true, ChatReplyFinished: false}
}
// Map returns the wire form with every key present.
func (s NotificationSettings) Map() map[string]any {
return map[string]any{
NotifyRunFinished: s.RunFinished,
NotifyChatNeedsYou: s.ChatNeedsYou,
NotifyChatReplyFinished: s.ChatReplyFinished,
}
}
// Field returns a pointer to the setting named key, or nil for an unknown key.
func (s *NotificationSettings) Field(key string) *bool {
switch key {
case NotifyRunFinished:
return &s.RunFinished
case NotifyChatNeedsYou:
return &s.ChatNeedsYou
case NotifyChatReplyFinished:
return &s.ChatReplyFinished
}
return nil
}
// ValidateNotificationSettingsUpdate checks a partial update: at least one key,
// every key known and every value a boolean.
func ValidateNotificationSettingsUpdate(update map[string]any) (map[string]bool, error) {
if len(update) == 0 {
return nil, fmt.Errorf("notification_settings must name at least one setting")
}
keys := make([]string, 0, len(update))
for key := range update {
keys = append(keys, key)
}
sort.Strings(keys)
result := make(map[string]bool, len(update))
var probe NotificationSettings
for _, key := range keys {
if probe.Field(key) == nil {
return nil, fmt.Errorf("unknown notification setting %q", key)
}
value, ok := update[key].(bool)
if !ok {
return nil, fmt.Errorf("notification setting %q must be true or false", key)
}
result[key] = value
}
return result, nil
}
+13 -1
View File
@@ -23,7 +23,10 @@ var chatAttentionPublish = stage.PublishNtfy
type chatAttention struct {
sessionID string
approval bool
body string
// reply marks a finished assistant turn (gated by chat_reply_finished)
// rather than a question/approval (gated by chat_needs_you).
reply bool
body string
}
// claimChatAttentionLocked records key in the hub-wide dedupe set and reports
@@ -113,11 +116,17 @@ func (h *chatHub) startChatAttention(a chatAttention) {
base = context.Background()
}
registry := h.registry
settingsStore := h.settings
h.attentionWG.Add(1)
go func() {
defer h.attentionWG.Done()
ctx, cancel := context.WithTimeout(base, 30*time.Second)
defer cancel()
// The operator's choice is read here, off the hub mutex, at publish time.
settings := chatNotificationSettings(ctx, settingsStore)
if (a.reply && !settings.ChatReplyFinished) || (!a.reply && !settings.ChatNeedsYou) {
return
}
name := ""
if registry != nil {
if session, found, err := registry.OperatorSession(ctx, a.sessionID); err == nil && found {
@@ -125,6 +134,9 @@ func (h *chatHub) startChatAttention(a chatAttention) {
}
}
title, body := chatAttentionText(name, a.approval, a.body)
if a.reply {
title, body = chatReplyText(name, a.body)
}
click, views := chatAttentionLinks(a.sessionID)
if _, err := chatAttentionPublish(ctx, "system", title, body, "", nil, click, views...); err != nil {
log.Printf("chat attention notification session=%s: %v", a.sessionID, err)
+2
View File
@@ -37,6 +37,8 @@ type chatHub struct {
rooms map[string]*chatRoom
baseCtx context.Context
registry operatorRegistry
// settings holds the operator's notification choices; nil means defaults.
settings notificationSettingsStore
now func() time.Time
// userSeq is a monotonic source of ids for the user turns the server echoes
// to the other clients, so each retained user message has a stable id.
+98
View File
@@ -0,0 +1,98 @@
package server
import (
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatReplyBodyRunes bounds the reply excerpt carried in the notification body.
const chatReplyBodyRunes = 200
// chatReplyFallbackBody is used when the finished turn produced no text the
// hub retained (tool-only turns, or text beyond the retention cap).
const chatReplyFallbackBody = "The agent finished its reply."
// noteReplyAttentionLocked announces a finished assistant turn once. prior is
// the session's step state before frame was folded. Only an authoritative
// (non-intermediate) ended step that follows an observed, unfinished turn
// counts, so a repeated or replayed end with no turn in between never
// republishes; a native turn id is also claimed in the hub-wide dedupe set.
// Whether the operator wants these is decided at publish time
// (chat_reply_finished). Callers must hold h.mu.
func (h *chatHub) noteReplyAttentionLocked(prior *protocol.ChatStep, frame protocol.ChatEventFrame) {
step := frame.Step
if frame.Kind != protocol.ChatEventStep || step == nil || step.Status != protocol.ChatStepEnded || step.Intermediate || frame.SessionID == "" {
return
}
if prior == nil || (prior.Status == protocol.ChatStepEnded && !prior.Intermediate) {
return
}
if !chatAttentionConfigured() {
return
}
if step.TurnID != "" && !h.claimChatAttentionLocked("reply\x00"+frame.SessionID+"\x00"+step.TurnID) {
return
}
body := h.finalReplyTextLocked(frame.SessionID)
if body == "" {
body = chatReplyFallbackBody
}
h.startChatAttention(chatAttention{sessionID: frame.SessionID, reply: true, body: body})
}
// finalReplyTextLocked returns a bounded single-line excerpt of the latest
// assistant message's text in the current turn: messages after the last user
// message, scanned newest first. Callers must hold h.mu.
func (h *chatHub) finalReplyTextLocked(sessionID string) string {
turn := h.turns[sessionID]
if turn == nil {
return ""
}
for i := len(turn.order) - 1; i >= 0; i-- {
message := turn.messages[turn.order[i]]
if message == nil {
continue
}
if message.role == protocol.ChatRoleUser {
return ""
}
var text strings.Builder
for _, id := range message.order {
part := message.parts[id]
if part == nil || part.part.Type != protocol.ChatEventText || len(part.text) == 0 {
continue
}
if text.Len() > 0 {
text.WriteByte(' ')
}
text.Write(part.text)
if text.Len() > chatReplyBodyRunes*4 {
break
}
}
if excerpt := singleLine(text.String()); excerpt != "" {
return truncateRunes(excerpt, chatReplyBodyRunes)
}
}
return ""
}
// truncateRunes shortens text to at most limit runes, marking the cut.
func truncateRunes(text string, limit int) string {
runes := []rune(text)
if len(runes) <= limit {
return text
}
return strings.TrimSpace(string(runes[:limit])) + "…"
}
// chatReplyText builds the single-line ntfy title/body for a finished reply.
func chatReplyText(name, body string) (string, string) {
name = singleLine(name)
if name == "" {
name = "Chat"
}
const suffix = " replied"
return truncateUTF8(name, 256-len(suffix)) + suffix, truncateUTF8(singleLine(body), 2000)
}
+5
View File
@@ -407,8 +407,13 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) {
if room != nil && frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded && !frame.Step.Intermediate {
h.clearCompactionLocked(room)
}
var priorStep *protocol.ChatStep
if frame.Kind == protocol.ChatEventStep && frame.SessionID != "" {
priorStep = h.turnLocked(frame.SessionID).step
}
h.applyLocked(frame)
h.noteFormAttentionLocked(frame)
h.noteReplyAttentionLocked(priorStep, frame)
buffered := false
var targets []*chatSub
if room != nil {
+59
View File
@@ -0,0 +1,59 @@
package server
import (
"context"
"log"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// notificationSettingsStore persists the operator's global notification
// choices. *pipeline.Store implements it.
type notificationSettingsStore interface {
NotificationSettings(context.Context) (protocol.NotificationSettings, error)
UpdateNotificationSettings(context.Context, map[string]any) (protocol.NotificationSettings, error)
}
// handleNotificationSettings answers notification_settings and
// set_notification_settings. It reports whether request was one of them.
func handleNotificationSettings(ctx context.Context, request protocol.Message, store notificationSettingsStore, write func(protocol.Message) error) bool {
if request.Type != protocol.GetNotificationSettings && request.Type != protocol.SetNotificationSettings {
return false
}
response := protocol.Message{Type: protocol.NotificationSettingsReply, ID: request.ID}
var settings protocol.NotificationSettings
var err error
switch {
case store == nil:
response.Type = protocol.Error
response.Error = "notification settings are unavailable: no store"
case request.Type == protocol.GetNotificationSettings:
settings, err = store.NotificationSettings(ctx)
default:
settings, err = store.UpdateNotificationSettings(ctx, request.NotificationSettings)
}
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
} else if response.Type != protocol.Error {
response.NotificationSettings = settings.Map()
}
_ = write(response)
return true
}
// chatNotificationSettings reads the chat-related choices for a pending
// publication. Without a store the defaults apply; a read failure is logged and
// also falls back to the defaults so a transient database error neither
// silences the operator nor fails chat handling.
func chatNotificationSettings(ctx context.Context, store notificationSettingsStore) protocol.NotificationSettings {
if store == nil {
return protocol.DefaultNotificationSettings()
}
settings, err := store.NotificationSettings(ctx)
if err != nil {
log.Printf("read notification settings: %v", err)
return protocol.DefaultNotificationSettings()
}
return settings
}
@@ -0,0 +1,204 @@
package server
import (
"context"
"net/http/httptest"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
)
func notificationSettingsRoundTrip(t *testing.T, ctx context.Context, store *pipeline.Store, requests ...protocol.Message) []protocol.Message {
t.Helper()
handlerCtx, cancel := context.WithCancel(ctx)
handler := Handler(handlerCtx, store)
defer func() { cancel(); WaitRuns(handler) }()
srv := httptest.NewServer(handler)
defer srv.Close()
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
t.Fatal(err)
}
defer conn.CloseNow()
var welcome protocol.Message
if err := wsjson.Read(ctx, conn, &welcome); err != nil {
t.Fatal(err)
}
var replies []protocol.Message
for _, request := range requests {
if err := wsjson.Write(ctx, conn, request); err != nil {
t.Fatal(err)
}
var reply protocol.Message
if err := wsjson.Read(ctx, conn, &reply); err != nil {
t.Fatal(err)
}
replies = append(replies, reply)
}
return replies
}
func wantSettings(t *testing.T, reply protocol.Message, want protocol.NotificationSettings) {
t.Helper()
if reply.Type != protocol.NotificationSettingsReply || len(reply.NotificationSettings) != 3 {
t.Fatalf("reply = %+v", reply)
}
for key, value := range want.Map() {
if reply.NotificationSettings[key] != value {
t.Fatalf("%s = %v, want %v (reply %+v)", key, reply.NotificationSettings[key], value, reply.NotificationSettings)
}
}
}
func TestNotificationSettingsProtocol(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
store := newOperatorStore(t)
replies := notificationSettingsRoundTrip(t, ctx, store,
protocol.Message{Type: protocol.GetNotificationSettings, ID: "get"},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "set", NotificationSettings: map[string]any{protocol.NotifyChatReplyFinished: true}},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "unknown", NotificationSettings: map[string]any{protocol.NotifyRunFinished: false, "run_started": true}},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "string", NotificationSettings: map[string]any{protocol.NotifyRunFinished: "no"}},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "empty"},
protocol.Message{Type: protocol.GetNotificationSettings, ID: "again"},
)
defaults := protocol.DefaultNotificationSettings()
wantSettings(t, replies[0], defaults)
if replies[0].ID != "get" || replies[1].ID != "set" {
t.Fatalf("ids not echoed: %+v", replies)
}
updated := defaults
updated.ChatReplyFinished = true
wantSettings(t, replies[1], updated)
for _, reply := range replies[2:5] {
if reply.Type != protocol.Error || reply.Error == "" || reply.NotificationSettings != nil {
t.Fatalf("invalid update not refused: %+v", reply)
}
}
if !strings.Contains(replies[2].Error, "run_started") {
t.Fatalf("unknown key error = %q", replies[2].Error)
}
wantSettings(t, replies[5], updated)
// A new server on the same database (a restart) reads the stored choice.
replies = notificationSettingsRoundTrip(t, ctx, store, protocol.Message{Type: protocol.GetNotificationSettings, ID: "restart"})
wantSettings(t, replies[0], updated)
}
func TestChatNeedsYouSettingSuppressesQuestionsAndApprovals(t *testing.T) {
captured := newNtfyCapture(t)
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatNeedsYou: false}); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_quiet")
h.registry = store
h.settings = store
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_quiet", Kind: "question", Title: "Ship?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_quiet", Kind: protocol.ChatEventForm, Form: &form})
h.pushPermission("ses_quiet", protocol.ChatPermissionFrame{SessionID: "ses_quiet", RequestID: "per_1", Message: "Allow?"})
h.attentionWG.Wait()
if got := captured(); len(got) != 0 {
t.Fatalf("disabled chat_needs_you published %+v", got)
}
// Turning it back on announces new requests again.
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatNeedsYou: true}); err != nil {
t.Fatal(err)
}
h.pushPermission("ses_quiet", protocol.ChatPermissionFrame{SessionID: "ses_quiet", RequestID: "per_2", Message: "Allow now?"})
h.attentionWG.Wait()
if got := captured(); len(got) != 1 || got[0].Title != "Chat needs your approval" {
t.Fatalf("re-enabled chat_needs_you = %+v", got)
}
}
func replyTurn(h *chatHub, session, turnID, messageID, text string) {
h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turnID}})
if text != "" {
h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventText, MessageID: messageID, Part: &protocol.ChatPart{ID: messageID + "_p"}, Delta: text})
}
// A provider step boundary inside the turn is not the end of the reply.
h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turnID, Intermediate: true}})
h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turnID}})
}
func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
captured := newNtfyCapture(t)
store := newOperatorStore(t)
ctx := context.Background()
if err := store.RecordOperatorSession(ctx, "ses_done", t.TempDir(), "Release prep", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_done", "ses_bare")
h.registry = store
h.settings = store
// Off by default: a finished turn is silent.
replyTurn(h, "ses_done", "turn_0", "msg_0", "Quiet reply")
h.attentionWG.Wait()
if got := captured(); len(got) != 0 {
t.Fatalf("default published %+v", got)
}
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
t.Fatal(err)
}
long := "The build\nis green. " + strings.Repeat("x", 300)
replyTurn(h, "ses_done", "turn_1", "msg_1", long)
// Duplicate and replayed ends of the same turn, including after a
// reconnect builds a new room, publish nothing more.
ended := protocol.ChatEventFrame{SessionID: "ses_done", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}
h.emit(ended)
h.mu.Lock()
h.rooms["ses_done"] = newChatRoom(context.Background(), "ses_done")
h.mu.Unlock()
h.emit(ended)
h.emit(protocol.ChatEventFrame{SessionID: "ses_done", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}})
h.attentionWG.Wait()
got := captured()
if len(got) != 1 {
t.Fatalf("deliveries = %+v", got)
}
wantBody := truncateRunes("The build is green. "+strings.Repeat("x", 300), chatReplyBodyRunes)
want := ntfyCapture{Title: "Release prep replied", Message: wantBody, Click: "pipelines://chat/ses_done", Actions: "view, Open in browser, https://pipelines.example.com/chat/ses_done"}
if got[0] != want {
t.Fatalf("got %+v, want %+v", got[0], want)
}
// The next genuine turn notifies again; a turn without text (and a
// session without a title or native turn ids) uses the fallback text.
replyTurn(h, "ses_done", "turn_2", "msg_2", "Second answer")
h.emit(protocol.ChatEventFrame{SessionID: "ses_bare", Kind: protocol.ChatEventUser, MessageID: "usr_1", Part: &protocol.ChatPart{ID: "u1", Text: "do it"}})
replyTurn(h, "ses_bare", "", "", "")
h.attentionWG.Wait()
got = captured()
if len(got) != 3 {
t.Fatalf("deliveries = %+v", got)
}
bodies := map[string]string{}
for _, n := range got[1:] {
bodies[n.Title] = n.Message
}
if bodies["Release prep replied"] != "Second answer" || bodies["Chat replied"] != chatReplyFallbackBody {
t.Fatalf("later deliveries = %+v", got[1:])
}
}
func TestChatReplyFinishedNeedsNtfyConfiguration(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_off")
h.settings = store
replyTurn(h, "ses_off", "turn_1", "msg_1", "hello")
h.attentionWG.Wait()
h.mu.Lock()
defer h.mu.Unlock()
if len(h.attentionSeen) != 0 {
t.Fatalf("unconfigured ntfy still considered a publication: %v", h.attentionSeen)
}
}
@@ -250,11 +250,14 @@ func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
for _, tc := range []struct {
mode string
hook bool
want int32
// quiet turns the global run_finished setting off (it defaults on).
quiet bool
want int32
}{
{"on", false, 1}, {"auto", false, 0}, {"off", false, 0}, {"on", true, 1}, {"auto", true, 1}, {"off", true, 0},
{"on", false, false, 1}, {"auto", false, false, 1}, {"auto", false, true, 0}, {"on", false, true, 1}, {"off", false, false, 0},
{"on", true, false, 1}, {"auto", true, false, 1}, {"auto", true, true, 1}, {"off", true, false, 0},
} {
t.Run(tc.mode+map[bool]string{true: "-hook", false: "-no-hook"}[tc.hook], func(t *testing.T) {
t.Run(tc.mode+map[bool]string{true: "-hook", false: "-no-hook"}[tc.hook]+map[bool]string{true: "-quiet", false: ""}[tc.quiet], func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "modes.db"))
@@ -262,6 +265,11 @@ func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
if tc.quiet {
if _, err := s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: false}); err != nil {
t.Fatal(err)
}
}
source := pipeline.Template([]string{"one"}, true)
if tc.hook {
source = strings.Replace(source, "# stage one", "# stage one\n```notify\non=success\n```", 1)
@@ -287,7 +295,7 @@ func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
if err != nil || detail.Status != "succeeded" || detail.NotifyMode != tc.mode || calls.Load()-before != tc.want {
t.Fatalf("mode contract: %+v calls=%d %v", detail, calls.Load()-before, err)
}
if tc.mode == "on" && (len(detail.Notifications) != 1 || (detail.Notifications[0].Status != "sent" && detail.Notifications[0].Status != "covered")) {
if tc.want == 1 && !(tc.hook && tc.quiet) && (len(detail.Notifications) != 1 || (detail.Notifications[0].Status != "sent" && detail.Notifications[0].Status != "covered")) {
t.Fatalf("missing final audit: %+v", detail.Notifications)
}
cancel()
+8
View File
@@ -108,6 +108,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
}
hub.baseCtx = ctx
hub.registry = registry
var settingsStore notificationSettingsStore
if len(stores) > 0 {
settingsStore = stores[0]
}
hub.settings = settingsStore
mux.HandleFunc("GET /artifacts/{run}/{step}/{name...}", func(w http.ResponseWriter, r *http.Request) {
if runs == nil {
http.NotFound(w, r)
@@ -188,6 +193,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
if handleChat(connCtx, request, options.Chat, hub, registry, clientID, write) {
continue
}
if handleNotificationSettings(ctx, request, settingsStore, write) {
continue
}
if handleRunEvents(request, events, runs, clientID, write) {
continue
}
+16
View File
@@ -0,0 +1,16 @@
package stage
import (
"os"
"testing"
)
// TestMain isolates the package from an operator's real notification setup: a
// developer shell may export the installed server's ntfy configuration, and no
// test may publish to it. Tests that need ntfy point it at an httptest server.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
}
+16
View File
@@ -0,0 +1,16 @@
package tui
import (
"os"
"testing"
)
// TestMain isolates the package from an operator's real notification setup:
// these tests run real servers and runs, a developer shell may export the
// installed server's ntfy configuration, and no test may publish to it.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
}