Notifications: agent notify reaches every device and clears everywhere

- Server: chat ntfy messages carry a sequence id derived from their app id;
  clearing a chat app notification also clears it in ntfy (PUT
  /<topic>/<seq>/clear, verified on ntfy v2.38.1).
- Server: a turn that sent an agent notify does not also send chat_reply.
- notify tool and MCP instructions: Pipelines already notifies at reply end
  and for questions/approvals; notify is for mid-turn or background news.
- Shown notify items carry channels (apps/phone); the transcript row says
  where it went.
- App: NotificationBridge.close(tag); web closes tracked Notifications and
  tells other tabs over a BroadcastChannel; native bridge cancels by tag and
  now supports macOS. AgentNotices closes on notifications_cleared and on
  resubscribe cleared ids, and a tap sends clear_notifications.
- Docs: skill, chat reference, ntfy/notifications docs, app note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 19:43:55 +00:00
parent c441400f36
commit b91ef04ab0
32 changed files with 743 additions and 73 deletions
@@ -31,6 +31,13 @@ class AgentToast {
/// ones within [agentNoticeReplayWindow] are shown once and every id is
/// recorded in the persisted notification ledger, so neither a reload nor a
/// reconnect repeats one.
///
/// It also keeps the system notifications in step with the server: a clear
/// (`notifications_cleared`, pushed when the operator opened the chat, tapped
/// or dismissed the notification on any device, or the reply to this client's
/// own clear) and the cleared ids a reconnect reports close the matching
/// notification here, and a tap clears it on the server, so it vanishes from
/// every other device too.
class AgentNotices {
AgentNotices({
required this.gateway,
@@ -96,6 +103,7 @@ class AgentNotices {
}
void _onSubscribed(JsonMap reply) {
_closeCleared(reply['ids']);
final raw = reply['notifications'];
if (_disposed || raw is! List) return;
final notices = [for (final value in raw) ?AgentNotice.parse(value)];
@@ -107,6 +115,10 @@ class AgentNotices {
_onSubscribed(frame);
return;
}
if (frame['type'] == 'notifications_cleared') {
_closeCleared(frame['ids']);
return;
}
if (frame['type'] != 'notification') return;
final notice = AgentNotice.parse(frame['notification']);
if (notice == null) return;
@@ -119,6 +131,42 @@ class AgentNotices {
});
}
/// Closes the system notifications for server ids cleared on any device.
void _closeCleared(Object? ids) {
if (_disposed || ids is! List) return;
for (final id in ids) {
if (id is! String || id.isEmpty) continue;
try {
notifications.bridge.close(id);
} catch (_) {
// Nothing shown for it here.
}
}
}
/// Clears [id] on the server: every other device then drops it, and the
/// equivalent acknowledgement marks the chat seen.
void _clearOnServer(String id) {
final send = sendOnly;
try {
if (send != null) {
send('clear_notifications', {
'ids': [id],
});
} else {
unawaited(
gateway
.call('clear_notifications', {
'ids': [id],
})
.then((_) {}, onError: (Object _) {}),
);
}
} catch (_) {
// Not connected: opening the chat marks it seen when it connects.
}
}
/// Runs deliveries one at a time, in arrival order.
void _enqueue(Future<void> Function() step) {
_queue = _queue.then((_) => step()).catchError((Object _) {});
@@ -164,7 +212,13 @@ class AgentNotices {
void open() => openChat(notice.sessionId);
var badge = delivery.badge;
// A system notification the OS refused is counted in the tab title.
if (delivery.system && !_showSystem(notice, headline, open)) badge = true;
if (delivery.system &&
!_showSystem(notice, headline, () {
_clearOnServer(notice.id);
open();
})) {
badge = true;
}
if (delivery.toast) {
showToast(
AgentToast(headline: headline, message: notice.message, open: open),
@@ -21,8 +21,13 @@ abstract interface class NotificationBridge {
Future<String> requestPermission();
/// Shows one notification, attaching [onTap] as its tap intent when given.
/// Returns whether the platform accepted it.
/// Returns whether the platform accepted it. A notification with the same
/// [NotificationMessage.tag] replaces the earlier one.
bool show(NotificationMessage message, {void Function()? onTap});
/// Removes the notification this device shows for [tag], if any: it was
/// read or cleared on this or another device. Unknown tags are ignored.
void close(String tag);
}
/// The bridge for the current platform: the browser `Notification` on the web,
@@ -5,8 +5,9 @@ import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'notification_bridge.dart';
import 'notification_models.dart';
/// System notifications on a phone: Android's notification shade (and iOS's
/// centre). The permission is cached so [environment] stays synchronous; it
/// System notifications from the native app: Android's notification shade (when
/// its background notification service is off), iOS's and macOS's
/// notification centre. [close] removes a delivered one by its tag. The permission is cached so [environment] stays synchronous; it
/// is refreshed when the bridge starts and after every request.
class NativeNotificationBridge implements NotificationBridge {
NativeNotificationBridge() {
@@ -15,6 +16,9 @@ class NativeNotificationBridge implements NotificationBridge {
final _plugin = FlutterLocalNotificationsPlugin();
final Map<int, void Function()> _taps = {};
/// The platform id each shown tag was posted with, so [close] can remove it.
final Map<String, int> _ids = {};
late final Future<void> _ready;
String _permission = 'default';
bool _started = false;
@@ -30,20 +34,25 @@ class NativeNotificationBridge implements NotificationBridge {
priority: Priority.high,
);
static const _darwin = DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
);
Future<void> _start() async {
try {
await _plugin.initialize(
settings: const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
iOS: DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
),
iOS: _darwin,
macOS: _darwin,
),
onDidReceiveNotificationResponse: (response) {
final id = response.id;
if (id != null) _taps.remove(id)?.call();
if (id == null) return;
_ids.removeWhere((_, posted) => posted == id);
_taps.remove(id)?.call();
},
);
_started = true;
@@ -61,12 +70,19 @@ class NativeNotificationBridge implements NotificationBridge {
>()
?.areNotificationsEnabled();
_permission = enabled == true ? 'granted' : 'default';
} else if (Platform.isMacOS) {
final options = await _plugin
.resolvePlatformSpecificImplementation<
MacOSFlutterLocalNotificationsPlugin
>()
?.checkPermissions();
_permission = options?.isEnabled == true ? 'granted' : 'default';
}
}
@override
NotificationEnvironment environment() => NotificationEnvironment(
supported: Platform.isAndroid || Platform.isIOS,
supported: Platform.isAndroid || Platform.isIOS || Platform.isMacOS,
// A native app needs no secure origin.
secureContext: true,
permission: _permission,
@@ -89,6 +105,12 @@ class NativeNotificationBridge implements NotificationBridge {
IOSFlutterLocalNotificationsPlugin
>()
?.requestPermissions(alert: true, badge: true, sound: true);
} else if (Platform.isMacOS) {
granted = await _plugin
.resolvePlatformSpecificImplementation<
MacOSFlutterLocalNotificationsPlugin
>()
?.requestPermissions(alert: true, badge: true, sound: true);
}
_permission = granted == true
? 'granted'
@@ -101,17 +123,35 @@ class NativeNotificationBridge implements NotificationBridge {
@override
bool show(NotificationMessage message, {void Function()? onTap}) {
if (!_started || _permission != 'granted') return false;
final id = _nextId++;
if (onTap != null) _taps[id] = onTap;
// The same tag reuses its platform id, so the new one replaces the old.
final id = _ids[message.tag] ??= _nextId++;
if (onTap != null) {
_taps[id] = onTap;
} else {
_taps.remove(id);
}
_plugin.show(
id: id,
title: message.title,
body: message.body,
notificationDetails: const NotificationDetails(android: _channel),
notificationDetails: const NotificationDetails(
android: _channel,
iOS: DarwinNotificationDetails(),
macOS: DarwinNotificationDetails(),
),
payload: message.tag,
);
return true;
}
@override
void close(String tag) {
final id = _ids.remove(tag);
if (id == null || !_started) return;
_taps.remove(id);
// Removes the delivered notification (Android shade, Darwin centre).
_plugin.cancel(id: id).catchError((Object _) {});
}
}
NotificationBridge createNotificationBridge() => NativeNotificationBridge();
@@ -21,6 +21,9 @@ class UnsupportedNotificationBridge implements NotificationBridge {
@override
bool show(NotificationMessage message, {void Function()? onTap}) => false;
@override
void close(String tag) {}
}
NotificationBridge createNotificationBridge() =>
@@ -1,6 +1,8 @@
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:web/web.dart' as web;
import 'notification_bridge.dart';
import 'notification_models.dart';
@@ -20,6 +22,8 @@ extension type _Notification._(JSObject _) implements JSObject {
external set onclick(JSFunction? handler);
external set onclose(JSFunction? handler);
external void close();
}
@@ -38,6 +42,40 @@ bool _secureContext() {
return value.isA<JSBoolean>() && (value as JSBoolean).toDart;
}
/// The notifications this tab posted and still shows, by tag, so a clear (from
/// the server, or from another tab) can close them. Shared by every bridge in
/// the tab.
final Map<String, _Notification> _open = {};
/// Tells the other tabs and installed-app windows of this origin to close a
/// tag too: each one closes only the `Notification` objects it created.
web.BroadcastChannel? _channel;
web.BroadcastChannel? _tabs() {
if (_channel != null) return _channel;
try {
final channel = web.BroadcastChannel('pipelines.notifications');
channel.onmessage = ((web.MessageEvent event) {
final data = event.data;
if (data.isA<JSString>()) _closeLocal((data as JSString).toDart);
}).toJS;
_channel = channel;
} catch (_) {
// No BroadcastChannel: every tab still receives the server's clear.
}
return _channel;
}
void _closeLocal(String tag) {
final notification = _open.remove(tag);
if (notification == null) return;
try {
notification.close();
} catch (_) {
// Already gone.
}
}
/// The browser bridge: the real `Notification` API, reached through
/// `dart:js_interop`.
///
@@ -79,17 +117,30 @@ class WebNotificationBridge implements NotificationBridge {
bool show(NotificationMessage message, {void Function()? onTap}) {
if (!_supported()) return false;
try {
final tag = message.tag;
// The new one replaces any earlier one with this tag; forget the old
// object first so its close event is not mistaken for this one's.
_open.remove(tag);
final notification = _Notification(
message.title.toJS,
_NotificationOptions(body: message.body.toJS, tag: message.tag.toJS),
_NotificationOptions(body: message.body.toJS, tag: tag.toJS),
);
_tabs();
_open[tag] = notification;
// A close event (the operator's dismissal, but also a notification
// daemon's timeout or another tab replacing it) only forgets it here: it
// is not reported to the server, so a timeout never clears it on the
// operator's other devices.
notification.onclose = (() {
if (identical(_open[tag], notification)) _open.remove(tag);
}).toJS;
final open = onTap;
if (open != null) {
notification.onclick = (() {
// Bring this tab forward first: a click on a notification does not
// focus the page that posted it on its own.
globalContext.callMethod<JSAny?>('focus'.toJS);
notification.close();
close(tag);
open();
}).toJS;
}
@@ -100,6 +151,16 @@ class WebNotificationBridge implements NotificationBridge {
return false;
}
}
@override
void close(String tag) {
_closeLocal(tag);
try {
_tabs()?.postMessage(tag.toJS);
} catch (_) {
// The other tabs still receive the server's clear.
}
}
}
NotificationBridge createNotificationBridge() => const WebNotificationBridge();
@@ -3,15 +3,28 @@ import 'package:flutter/material.dart';
import '../../../../../core/api_gateway.dart';
import 'chat_shown_surface.dart';
/// What a `notify` entry says: the phone notification was accepted for
/// delivery, or why it was not sent.
/// What a `notify` entry says: where the notification went (the server's
/// `channels`: the operator's signed-in Pipelines `apps` and/or their `phone`),
/// or why it was not sent.
String chatShownNotifyText(JsonMap item) {
final title = chatShownTitle(item, 'notification');
if (item['delivered'] == true) return 'Notified your phone: $title';
if (item['delivered'] == true) return '${_notifiedWhere(item)}: $title';
final detail = '${item['detail'] ?? ''}'.trim();
return detail.isEmpty
? 'Phone notification not sent: $title'
: 'Phone notification not sent: $title — $detail';
? 'Notification not sent: $title'
: 'Notification not sent: $title — $detail';
}
String _notifiedWhere(JsonMap item) {
final raw = item['channels'];
final channels = raw is List ? raw.map((c) => '$c').toSet() : <String>{};
final apps = channels.contains('apps');
final phone = channels.contains('phone');
if (apps && phone) return 'Notified your apps and phone';
if (apps) return 'Notified your apps';
if (phone) return 'Notified your phone';
// An entry recorded before the server said where it went.
return 'Notified you';
}
/// One secondary line in the agent's column for a `notify` entry, with the
+27
View File
@@ -29,3 +29,30 @@ view, insecure unfocused toast with `document.title == "(1) Pipelines"` and back
to `Pipelines` on focus, and the Settings hints for secure and insecure pages.
Browser system notifications themselves were not captured (headless Chrome,
permission not granted); unit tests cover that path.
## Clearing everywhere
`AgentNotices` closes the system notification for every id in a
`notifications_cleared` frame (a push after a clear on another device or the
chat being opened, or the reply to this client's own clear) and for the cleared
ids a resubscribe reports. A tap sends `clear_notifications` for the notice
before opening the chat. `NotificationBridge.close(tag)` does the platform work:
the web bridge keeps the `Notification` objects it posted by tag, closes the one
for the tag and posts the tag on the `pipelines.notifications`
`BroadcastChannel` so the origin's other tabs and installed-app windows close
theirs; the native bridge (Android without the background service, iOS, and now
macOS) cancels the platform id it used for the tag. A browser `close` event is
deliberately not sent to the server: Chrome raises it for a notification
daemon's timeout and for a same-tag replacement by another tab, which would
clear the notice on every device seconds after it appeared. The transcript row
says where a notify went from the item's `channels` ("Notified your apps and
phone", "Notified your apps", "Notified your phone").
Browser check (headless Chromium, `tool/capture`, fixture
`?ui-review=1&agentNotice=6000[&agentNoticeClear=9000]`, notification
permission granted through CDP, `window.Notification` wrapped to record): the
notice posted `show chat:ui-review:notify:shown_capture`; a pushed
`notifications_cleared` then recorded `close` for that tag; without the clear,
a message on the `pipelines.notifications` BroadcastChannel (as another tab
sends) closed it. The transcript row reads "Notified your apps and phone:
Release ready" (`?chats=1&timestamps=1&shown=1`, route `/chat/perf-chat-0`).
@@ -17,6 +17,7 @@ class _Gateway implements ApiGateway {
final controller = StreamController<JsonMap>.broadcast();
List<JsonMap> backlog = [];
final calls = <String>[];
final sent = <JsonMap>[];
@override
Stream<JsonMap> get frames => controller.stream;
@@ -24,6 +25,7 @@ class _Gateway implements ApiGateway {
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(type);
sent.add({'type': type, ...fields});
return {
'type': 'notifications_subscribed',
'notifications': backlog,
@@ -140,6 +142,50 @@ void main() {
expect(opened, ['ses_1']);
});
test(
'a tap clears the notice on the server so other devices drop it',
() async {
await setUpWith();
gateway.controller.add(_push(_notice('a')));
await pump();
bridge.taps.first!();
await pump();
expect(opened, ['ses_1']);
expect(gateway.sent.last, {
'type': 'clear_notifications',
'ids': ['chat:ses_1:notify:a'],
});
},
);
test('a clear from the server (another device, or the chat opened) closes '
'the system notification here', () async {
await setUpWith();
gateway.controller.add(_push(_notice('a')));
await pump();
expect(bridge.shown, hasLength(1));
gateway.controller.add({
'type': 'notifications_cleared',
'ids': ['chat:ses_1:notify:a'],
});
await pump();
expect(bridge.closed, ['chat:ses_1:notify:a']);
});
test(
'ids cleared while away close their notifications on resubscribe',
() async {
await setUpWith();
gateway.controller.add({
'type': 'notifications_subscribed',
'notifications': <JsonMap>[],
'ids': ['chat:ses_1:notify:old'],
});
await pump();
expect(bridge.closed, ['chat:ses_1:notify:old']);
},
);
test('nothing shows when the chat is already in view', () async {
await setUpWith();
active = 'ses_1';
@@ -276,4 +276,7 @@ class _ThrowingBridge implements NotificationBridge {
@override
bool show(NotificationMessage message, {void Function()? onTap}) =>
throw StateError('the browser refused to construct a notification');
@override
void close(String tag) {}
}
@@ -114,6 +114,7 @@ class FakeNotificationBridge implements NotificationBridge {
int requests = 0;
final List<NotificationMessage> shown = [];
final List<void Function()?> taps = [];
final List<String> closed = [];
@override
NotificationEnvironment environment() => NotificationEnvironment(
@@ -135,4 +136,7 @@ class FakeNotificationBridge implements NotificationBridge {
taps.add(onTap);
return accepts;
}
@override
void close(String tag) => closed.add(tag);
}
@@ -188,16 +188,34 @@ void main() {
expect(find.byKey(const Key('stub-html')), findsNothing);
});
testWidgets('notify rows say whether the phone was notified', (tester) async {
testWidgets('notify rows say where the notification went', (tester) async {
await pump(tester, {
'id': 'n',
'kind': 'notify',
'title': 'Build done',
'message': 'All green',
'delivered': true,
'channels': ['apps', 'phone'],
});
expect(find.text('Notified your phone: Build done'), findsOneWidget);
expect(
find.text('Notified your apps and phone: Build done'),
findsOneWidget,
);
expect(find.text('All green'), findsOneWidget);
for (final (channels, text) in [
(['apps'], 'Notified your apps: Build done'),
(['phone'], 'Notified your phone: Build done'),
(null, 'Notified you: Build done'),
]) {
await pump(tester, {
'id': 'n-$text',
'kind': 'notify',
'title': 'Build done',
'delivered': true,
'channels': ?channels,
});
expect(find.text(text), findsOneWidget);
}
await pump(tester, {
'id': 'n2',
'kind': 'notify',
@@ -207,7 +225,7 @@ void main() {
});
expect(
find.text(
'Phone notification not sent: Build done — notifications are not set up',
'Notification not sent: Build done — notifications are not set up',
),
findsOneWidget,
);
+12
View File
@@ -6,6 +6,9 @@
// for the `ui-review` chat (add `ui-review=1` so the
// chat has its title). `agentNoticePriority=2|3|4`
// sets its priority (default 3).
// `?agentNoticeClear=<ms>` then pushes `notifications_cleared` for it <ms>
// after the subscription, as when the operator opens
// the chat or taps the notification on another device.
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
@@ -40,6 +43,15 @@ JsonMap? agentNoticeReply(JsonMap request, void Function(JsonMap) emit) {
});
});
}
final clear = int.tryParse(_params['agentNoticeClear'] ?? '');
if (clear != null) {
Timer(Duration(milliseconds: clear), () {
emit({
'type': 'notifications_cleared',
'ids': ['chat:ui-review:notify:shown_capture'],
});
});
}
return {
'id': request['id'],
'type': 'notifications_subscribed',
+1
View File
@@ -69,6 +69,7 @@ JsonMap chatShownFixture(Object? sessionId) => {
'message': 'All three stages passed; the release is ready to publish.',
'priority': 'default',
'delivered': true,
'channels': ['apps', 'phone'],
},
{
'id': 'shown-diff',
+6 -2
View File
@@ -17,9 +17,13 @@ The same settings decide what is sent on both paths.
| Stage hook | a stage's own `notify` block fires ([ntfy reference](ntfy.md)) |
| Chat needs you | a chat asks a question or requests approval |
| Chat replied | an assistant turn ends (off by default) |
| Agent notification | a chat's agent calls its `notify` tool (always on; a turn that notified sends no separate "Chat replied") |
Each event notifies once. Opening or dismissing it on one device clears it on
the others.
Each event notifies once, on every device signed in (each web tab or installed
web app window, the Android app, the macOS app) and on ntfy. Opening the chat
or run, tapping the notification, or dismissing it in the app or the Android
notification shade clears it on every device, including the ntfy app for chat
notifications (see [Clearing notifications across devices](ntfy.md#clearing-notifications-across-devices)).
Chat events do not need the chat to be open. When the last app or browser
leaves a chat whose turn is still running, or which has an unanswered question
+26 -5
View File
@@ -210,9 +210,29 @@ once, and on a disconnected device when it next connects. The protocol is
`attention_acks_changed` frame with the change. Acknowledgements for deleted runs
or sessions, or older than 30 days, are pruned.
This does **not** reach notifications the ntfy app has already shown on a phone:
once ntfy delivered a message, the server cannot retract it, so those must still
be swiped away in the ntfy app (or the Android notification shade).
Every client removes its system notification when the clear reaches it:
- **Web** (every tab and installed web app window): the page closes the browser
`Notification` with that tag, and tells the origin's other tabs to close
theirs over a `BroadcastChannel`. A click on a browser notification sends
`clear_notifications` for it. A browser *close* event is not reported back:
browsers raise it for a notification daemon's timeout and for a same-tag
replacement too, so treating it as a dismissal would clear the notification on
every device seconds after it appeared.
- **Android with Receive notifications in Pipelines**: the background service
cancels it; a tap or a swipe (delete intent) sends `clear_notifications`.
- **Android without the service, iOS and macOS** (the in-app
`flutter_local_notifications` bridge while the app runs): it is cancelled /
removed from the notification centre by its tag; a tap clears it. The plugin
reports no dismissal, so a swipe there is not sent back.
- **ntfy**: chat notifications (questions, approvals, replies and agent
`notify`) are published with an ntfy sequence id derived from their app id
(`X-Sequence-ID: pl-<24 hex of sha256(id)>`), and clearing one sends
`PUT /<topic>/<sequence id>/clear`. ntfy (v2.15 or later; verified with
v2.38.1) emits `message_clear` and its Android and web apps dismiss the
notification. Run notifications carry no sequence id and stay in the ntfy app
until swiped away. An older ntfy does not support clearing; a failed clear is
only logged.
## App notification stream (no ntfy app needed)
@@ -248,8 +268,9 @@ N = {"id":"run:7:3:waiting","kind":"run_waiting","title":"Run needs your decisio
`chat:<id>`. `priority` is 3 and `tags` empty, matching what ntfy receives,
except `chat_notify`: an agent's `notify` tool call, whose priority is the
tool's (`low` 2, `default` 3, `high` 4). Every subscribed client receives it,
whichever chat it shows; the web app posts it as a browser notification or an
in-app alert, so an agent's notify reaches the operator without ntfy.
whichever chat it shows; each posts it as a system notification, so an
agent's notify reaches the operator without ntfy. A turn that sent one does
not also send its `chat_reply`.
- The subscribe reply holds the active (uncleared) notifications newer than the
`after` cursor (the last id the client holds), oldest first, at most 100;
an empty, unknown or pruned cursor replays them all. Its `ids` lists
+4 -1
View File
@@ -78,7 +78,10 @@ only when asked). Stage use: `references/format.md`.
A chat's agent has a `pipelines` MCP server: `show_file`, `show_image`,
`show_html`, `show_diff` (show the operator changes, e.g. before a pull request)
and `notify` (phone, only when the operator must look now). Show instead of
and `notify` (every Pipelines app the operator is signed in to plus their phone;
cleared everywhere once they read it or open the chat). Pipelines already
notifies when a reply ends or the agent asks something, so `notify` is only for
news mid-turn or after work the turn does not wait for. Show instead of
telling the operator a path. Details, limits, chat RPCs: `references/chat.md`.
## References
+1 -1
View File
@@ -15,7 +15,7 @@ operator's home (absolute, `~/...`, or relative to the chat's directory).
| `show_image` | `url_or_path`, `title?`, `alt?` | A home `image/*` file or an `https://` URL (no credentials, at most 2048 chars). |
| `show_html` | `html`, `title?`, `height_hint?` (120-600) | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `<details>`, `:hover`. Refused above 512 KiB. |
| `show_diff` | `path?`, `base?`, `committed_only?`, `title?` | A Git diff card when the operator asks to see the changes, or before submitting a pull request. No `base`: uncommitted work (staged, unstaged, untracked) against HEAD. `base` (e.g. `main`): everything since the merge base, which is what a PR contains, plus uncommitted work unless `committed_only`. Pipelines runs Git; do not paste the diff. |
| `notify` | `title`, `message`, `priority?` | A phone push that opens this chat. Only when the operator must look now (long task done, blocked on them). 5 per minute per chat; undelivered sends report why. |
| `notify` | `title`, `message`, `priority?` | A notification on every Pipelines app the operator is signed in to (web tabs, desktop, Android) and their phone (ntfy); a tap opens this chat. Opening the chat, or tapping or dismissing it on any device, clears it on all of them. Pipelines already notifies when the reply ends and for questions and approvals, so use it only for news mid-turn or after background work the turn does not wait for; a turn that notified sends no separate "replied" notification. 5 per minute per chat; the result says where it went, and undelivered sends report why. |
`show_diff` lists at most 300 files; a file patch over 256 KiB or a total over
1 MiB is shown partially and says so; binaries have no patch; renames show as
+8 -3
View File
@@ -26,7 +26,10 @@ func IsTool(name string) bool {
const Instructions = "These tools act on Pipelines, the app the operator reads this chat in, not on your workspace. " +
"Use show_file / show_image instead of telling the operator a path to open, show_html for diagrams, charts or small visual views, " +
"show_diff when the operator asks to see changes or a diff (for example before submitting a pull request), " +
"and notify only when the operator should look at Pipelines now (it reaches their open Pipelines apps and their phone). " +
"and notify only for something the operator should know mid-turn or after work the turn does not wait for: " +
"Pipelines already notifies them when your reply ends and when you ask a question or need an approval, so do not notify for those " +
"(a notify replaces this turn's end-of-reply notification). It reaches every Pipelines app they are signed in to and their phone, " +
"and clears everywhere once they open the chat. " +
"Your thinking is not shown to the operator: before asking them a question (for example with AskUserQuestion), " +
"write what you found and why you are asking as a normal message, because the question form shows only the question and its options."
@@ -109,8 +112,10 @@ func definitions() []toolDefinition {
{
Name: ToolNotify,
Title: "Notify the operator",
Description: "Send a notification to the operator's open Pipelines apps (web, desktop) and their phone; it opens this chat when tapped. " +
"Use it sparingly, for things they should know now (a long task finished, you are blocked on them). " +
Description: "Send a notification to every Pipelines app the operator is signed in to (web, desktop, Android) and their phone; it opens this chat when tapped " +
"and is cleared on every device once they read it or open the chat. " +
"Pipelines already notifies when your reply ends and when you ask a question or request an approval, so do not notify for those. " +
"Use it only for something they should know mid-turn, or for background work that finishes after the turn (one notify in a turn replaces that turn's end-of-reply notification). " +
"Limited to 5 per minute per chat. Returns whether delivery was accepted.",
InputSchema: objectSchema([]string{"title", "message"}, map[string]any{
"title": stringProperty("Short notification title (one line)."),
+4 -1
View File
@@ -55,8 +55,11 @@ type ChatShownItem struct {
Message string `json:"message,omitempty"`
Priority string `json:"priority,omitempty"`
Delivered bool `json:"delivered,omitempty"`
// Detail says why a notification was not delivered.
// Detail says why a notification was not delivered (or not to the phone).
Detail string `json:"detail,omitempty"`
// Channels says where a delivered notification went: "apps" (the
// operator's signed-in Pipelines apps) and/or "phone" (ntfy).
Channels []string `json:"channels,omitempty"`
}
// ChatShownDiffBody is one Git comparison a chat's model showed: the work tree
+2
View File
@@ -162,6 +162,7 @@ func (a *appNotifier) clear(ctx context.Context, ids []string, exclude string) (
}
if len(changed) > 0 {
a.enqueueLocked(protocol.Message{Type: protocol.NotificationsCleared, IDs: recordIDs(changed)}, exclude)
clearChatNtfy(recordIDs(changed))
}
return changed, nil
}
@@ -181,6 +182,7 @@ func (a *appNotifier) clearFor(ctx context.Context, filter pipeline.AppNotificat
}
if len(ids) > 0 {
a.enqueueLocked(protocol.Message{Type: protocol.NotificationsCleared, IDs: ids}, "")
clearChatNtfy(ids)
}
}
+1 -1
View File
@@ -192,7 +192,7 @@ func (h *chatHub) startChatAttention(a chatAttention) {
return
}
// ntfy takes a single-line message of at most 2048 bytes.
if _, err := chatAttentionPublish(ctx, "system", title, truncateUTF8(singleLine(body), 2000), "", nil, click, views...); err != nil {
if _, err := chatAttentionPublish(stage.WithNtfySequenceID(ctx, chatNtfySequence(a.id)), "system", title, truncateUTF8(singleLine(body), 2000), "", nil, click, views...); err != nil {
log.Printf("chat attention notification session=%s: %v", a.sessionID, err)
}
}()
+1 -1
View File
@@ -275,7 +275,7 @@ func (h *chatHub) foldEndedTurn(ctx context.Context, broker chatBroker, session
if key == "" {
key = replyID
}
if !h.claimChatAttentionLocked("reply\x00" + id + "\x00" + key) {
if !h.claimChatAttentionLocked("reply\x00"+id+"\x00"+key) || h.takeTurnNotifiedLocked(id) {
return
}
if body == "" {
+3
View File
@@ -51,6 +51,9 @@ type chatHub struct {
attentionSeen map[string]struct{}
attentionOrder []string
attentionWG sync.WaitGroup
// notifiedTurns holds the chats whose current turn already sent an agent
// notify, so that turn's end is not announced again (one turn, one ping).
notifiedTurns map[string]struct{}
// queueStore persists prompts queued behind a running turn; nil keeps the
// queue in memory only (tests and store-less servers).
queueStore chatPromptQueueStore
+132
View File
@@ -0,0 +1,132 @@
package server
import (
"context"
"sync"
"testing"
"time"
"github.com/coder/websocket"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// One turn, one ping: a turn that already sent an agent notify does not also
// announce its end, while a later turn without one does, and a notify sent
// after a turn ended (background work) does not silence the next turn.
func TestAgentNotifySuppressesThatTurnsReplyNotification(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
captured := newNtfyCapture(t)
store := newOperatorStore(t)
ctx := context.Background()
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_n")
h.settings = store
h.notes = newAppNotifier(store)
start := func(turn string) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
}
end := func(turn string) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
h.attentionWG.Wait()
}
start("turn_1")
if got := h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n1", Title: "Halfway", Message: "Tests pass"}); !got.App || !got.Phone {
t.Fatalf("delivery = %+v", got)
}
end("turn_1")
if got := captured(); len(got) != 1 || got[0].Title != "Halfway" {
t.Fatalf("turn with a notify published %+v", got)
}
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != 1 || active[0].Kind != protocol.NotificationChatNotify {
t.Fatalf("app notifications = %+v, %v", active, err)
}
// Background work notifies after the turn; the next turn still announces.
h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n2", Title: "Deploy done", Message: "Live"})
start("turn_2")
end("turn_2")
got := captured()
if len(got) != 3 || got[2].Title != "Chat replied" {
t.Fatalf("later deliveries = %+v", got)
}
}
// Every chat ntfy message carries a sequence id derived from its app id, and
// clearing the app notification (here: on another device) clears it in ntfy
// and pushes the clear to every other connected client.
func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var mu sync.Mutex
var published []string
originalPublish, originalClear := chatAttentionPublish, chatAttentionClear
chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
mu.Lock()
published = append(published, stage.NtfySequence(ctx))
mu.Unlock()
return stage.Values{"message_id": "m"}, nil
}
cleared := make(chan string, 8)
chatAttentionClear = func(_ context.Context, destination, sequence string) error {
if destination == "system" {
cleared <- sequence
}
return nil
}
defer func() { chatAttentionPublish, chatAttentionClear = originalPublish, originalClear }()
f := newAppNotificationFixture(t, ctx)
hub := f.handlerHub()
web, desktop, phone := dialAckClient(t, ctx, f.url), dialAckClient(t, ctx, f.url), dialAckClient(t, ctx, f.url)
subscribeNotifications(t, ctx, web, "")
subscribeNotifications(t, ctx, desktop, "")
subscribeNotifications(t, ctx, phone, "")
if got := hub.publishToolNotification(ctx, "ses_c", chatToolNotice{ID: "shown_c", Title: "Look", Message: "Now"}); !got.App || !got.Phone {
t.Fatalf("delivery = %+v", got)
}
id := "chat:ses_c:notify:shown_c"
for _, conn := range []*websocket.Conn{web, desktop, phone} {
if push := readFrame(t, ctx, conn, protocol.NotificationPush).Notification; push == nil || push.ID != id {
t.Fatalf("push = %+v", push)
}
}
mu.Lock()
if len(published) != 1 || published[0] != chatNtfySequence(id) {
t.Fatalf("published sequences = %v", published)
}
mu.Unlock()
// Tapped on the phone: the phone gets the reply, every other client a push.
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ClearNotifications, ID: "tap", IDs: []string{id}})
if reply := readFrame(t, ctx, phone, protocol.NotificationsCleared); reply.ID != "tap" || len(reply.IDs) != 1 || reply.IDs[0] != id {
t.Fatalf("phone reply = %+v", reply)
}
for name, conn := range map[string]*websocket.Conn{"web": web, "desktop": desktop} {
if push := readUntil(t, ctx, conn, protocol.NotificationsCleared); len(push.IDs) != 1 || push.IDs[0] != id {
t.Fatalf("%s cleared push = %+v", name, push)
}
}
select {
case sequence := <-cleared:
if sequence != chatNtfySequence(id) {
t.Fatalf("ntfy cleared %q", sequence)
}
case <-ctx.Done():
t.Fatal("ntfy was not cleared")
}
}
func TestChatNtfySequenceIsAValidStableNtfyID(t *testing.T) {
a, b := chatNtfySequence("chat:ses_x:notify:abc"), chatNtfySequence("chat:ses_x:notify:abd")
if a != chatNtfySequence("chat:ses_x:notify:abc") || a == b || len(a) != 27 {
t.Fatalf("sequences %q %q", a, b)
}
}
+54
View File
@@ -0,0 +1,54 @@
package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"log"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// chatAttentionClear dismisses one ntfy message by sequence id; tests may
// replace it.
var chatAttentionClear = stage.ClearNtfy
// chatNtfySequence is the ntfy sequence id a chat notification (app id
// "chat:<session>:<what>:<id>") is published with, so clearing the app
// notification can also clear it in the ntfy app. It is derived from the app
// id, so nothing extra is stored and a restart still clears it.
func chatNtfySequence(id string) string {
digest := sha256.Sum256([]byte(id))
return "pl-" + hex.EncodeToString(digest[:12])
}
// clearChatNtfy asks ntfy to clear the chat notifications among ids (every
// app notification id that was cleared), off the caller's goroutine. ntfy
// emits message_clear and its clients dismiss the notification. Run
// notifications are published without a sequence id and are left alone.
func clearChatNtfy(ids []string) {
if !chatAttentionConfigured() {
return
}
var sequences []string
for _, id := range ids {
if strings.HasPrefix(id, "chat:") {
sequences = append(sequences, chatNtfySequence(id))
}
}
if len(sequences) == 0 {
return
}
clear := chatAttentionClear
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
for _, sequence := range sequences {
if err := clear(ctx, "system", sequence); err != nil {
log.Printf("clear ntfy notification %s: %v", sequence, err)
}
}
}()
}
+33
View File
@@ -23,6 +23,10 @@ const chatReplyFallbackBody = "The agent finished its reply."
// (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.ChatStepStarted && !step.Intermediate {
// A new turn has not notified yet.
delete(h.notifiedTurns, frame.SessionID)
}
if frame.Kind != protocol.ChatEventStep || step == nil || step.Status != protocol.ChatStepEnded || step.Intermediate || frame.SessionID == "" {
return
}
@@ -35,6 +39,9 @@ func (h *chatHub) noteReplyAttentionLocked(prior *protocol.ChatStep, frame proto
if step.TurnID != "" && !h.claimChatAttentionLocked("reply\x00"+frame.SessionID+"\x00"+step.TurnID) {
return
}
if h.takeTurnNotifiedLocked(frame.SessionID) {
return
}
body := h.finalReplyTextLocked(frame.SessionID)
if body == "" {
body = chatReplyFallbackBody
@@ -46,6 +53,32 @@ func (h *chatHub) noteReplyAttentionLocked(prior *protocol.ChatStep, frame proto
h.startChatAttention(chatAttention{sessionID: frame.SessionID, reply: true, body: body, id: chatNotificationID(frame.SessionID, "reply", turnID)})
}
// markTurnNotified records that sessionID's turn in progress sent an agent
// notify, so its end is not announced as a reply too. A notify outside a turn
// the hub is following (background work after the turn) marks nothing.
func (h *chatHub) markTurnNotified(sessionID string) {
h.mu.Lock()
defer h.mu.Unlock()
turn := h.turns[sessionID]
if turn == nil || turn.step == nil || (turn.step.Status == protocol.ChatStepEnded && !turn.step.Intermediate) {
return
}
if h.notifiedTurns == nil {
h.notifiedTurns = map[string]struct{}{}
}
h.notifiedTurns[sessionID] = struct{}{}
}
// takeTurnNotifiedLocked reports and forgets whether sessionID's ending turn
// already sent an agent notify. Callers must hold h.mu.
func (h *chatHub) takeTurnNotifiedLocked(sessionID string) bool {
if _, ok := h.notifiedTurns[sessionID]; !ok {
return false
}
delete(h.notifiedTurns, sessionID)
return true
}
// finalReplyTextLocked returns a bounded excerpt, paragraph breaks kept, 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.
+8 -2
View File
@@ -16,6 +16,7 @@ import (
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// shownFile is a resolved file inside the operator's home.
@@ -172,10 +173,11 @@ func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string,
digest := sha256.Sum256([]byte(title + "\x00" + message))
id = hex.EncodeToString(digest[:8])
}
appID := chatNotificationID(sessionID, "notify", id)
var delivery chatToolDelivery
if h.notes != nil {
delivery.App = h.notes.record(ctx, pipeline.AppNotificationRecord{
AppNotification: protocol.AppNotification{ID: "chat:" + sessionID + ":notify:" + id, Kind: protocol.NotificationChatNotify, Title: title, Message: message, Click: click, Priority: chatNotifyPriority(notice.Priority), Tags: []string{}, Group: "chat:" + sessionID},
AppNotification: protocol.AppNotification{ID: appID, Kind: protocol.NotificationChatNotify, Title: title, Message: message, Click: click, Priority: chatNotifyPriority(notice.Priority), Tags: []string{}, Group: "chat:" + sessionID},
SessionID: sessionID,
})
}
@@ -185,12 +187,16 @@ func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string,
case !chatNotificationSettings(ctx, h.settings).NtfyEnabled:
delivery.Detail = "phone notifications (ntfy) are turned off"
default:
if _, err := chatAttentionPublish(ctx, "system", title, message, "", nil, click, views...); err != nil {
if _, err := chatAttentionPublish(stage.WithNtfySequenceID(ctx, chatNtfySequence(appID)), "system", title, message, "", nil, click, views...); err != nil {
log.Printf("chat tool notification session=%s: %v", sessionID, err)
delivery.Detail = "the phone notification service refused it: " + err.Error()
} else {
delivery.Phone = true
}
}
if delivery.App || delivery.Phone {
// This turn has pinged the operator; its end is not announced again.
h.markTurnNotified(sessionID)
}
return delivery
}
+6
View File
@@ -100,6 +100,12 @@ func (s *chatToolService) runNotify(ctx context.Context, sessionID, title, messa
id := newChatShownID()
delivery := s.notify(ctx, sessionID, chatToolNotice{ID: id, Title: title, Message: message, Priority: priority})
item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App || delivery.Phone, Detail: delivery.Detail}
if delivery.App {
item.Channels = append(item.Channels, "apps")
}
if delivery.Phone {
item.Channels = append(item.Channels, "phone")
}
switch {
case delivery.App && delivery.Phone:
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps and phone notifications."}
+2 -2
View File
@@ -251,7 +251,7 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
t.Fatalf("notified = %v", f.notified)
}
got := f.items(t, "ses_n1")
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" {
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" || strings.Join(got[0].Channels, ",") != "apps,phone" {
t.Fatalf("items = %+v", got)
}
@@ -277,7 +277,7 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
if r.IsError || r.Text != "Delivered to the operator's Pipelines apps; phone notifications (ntfy) are turned off." {
t.Fatalf("apps-only result: %v", r)
}
if last := f.items(t, "ses_n2"); len(last) != 3 || !last[2].Delivered || !strings.HasPrefix(last[2].ID, "shown_") {
if last := f.items(t, "ses_n2"); len(last) != 3 || !last[2].Delivered || !strings.HasPrefix(last[2].ID, "shown_") || strings.Join(last[2].Channels, ",") != "apps" {
t.Fatalf("the apps-only entry is recorded: %+v", last)
}
}
+6
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync"
"testing"
"time"
@@ -58,6 +59,11 @@ func newNtfyCapture(t *testing.T) func() []ntfyCapture {
var mu sync.Mutex
var got []ntfyCapture
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/clear") {
// A cleared chat notification's ntfy clear, not a delivery.
_ = json.NewEncoder(w).Encode(map[string]string{"id": "clr", "event": "message_clear"})
return
}
decoder := new(mime.WordDecoder)
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
+97 -30
View File
@@ -105,6 +105,60 @@ func NtfyPriority(ctx context.Context) int {
return priority
}
type ntfySequenceKey struct{}
// ntfySequenceID is the form of a sequence id this package sends: ntfy
// accepts the same characters as a topic name.
var ntfySequenceID = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
// WithNtfySequenceID makes PublishNtfy calls under ctx publish with ntfy
// sequence id sequence (X-Sequence-ID), so ClearNtfy can later dismiss the
// message on every subscribed client. An invalid id is ignored.
func WithNtfySequenceID(ctx context.Context, sequence string) context.Context {
return context.WithValue(ctx, ntfySequenceKey{}, sequence)
}
// NtfySequence is the sequence id WithNtfySequenceID set on ctx, "" when none.
func NtfySequence(ctx context.Context) string {
sequence, _ := ctx.Value(ntfySequenceKey{}).(string)
return sequence
}
// ClearNtfy marks the messages published with sequence id sequence on
// destination as read: ntfy (v2.15+) emits a message_clear event and its
// Android and web clients dismiss the notification. Clearing an unknown
// sequence id is harmless (ntfy still answers 200).
func ClearNtfy(ctx context.Context, destination, sequence string) error {
if !destinationName.MatchString(destination) || !ntfySequenceID.MatchString(sequence) {
return fmt.Errorf("invalid ntfy clear request")
}
endpoint, token, err := ntfyConnection(destination)
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPut, strings.TrimSuffix(endpoint, "/")+"/"+sequence+"/clear", nil)
if err != nil {
return fmt.Errorf("cannot create ntfy request")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(request)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("ntfy clear unconfirmed")
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64<<10))
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("ntfy clear returned HTTP %d", response.StatusCode)
}
return nil
}
// PublishNtfy is shared by native delivery stages and stage notification hooks.
// An empty filename publishes an event without an attachment. A non-empty click
// is an optional ntfy Click action (an absolute URL) so a tap on the notification
@@ -125,36 +179,9 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
if len(data) > 1<<20 || (filename != "" && (filename != filepath.Base(filename) || filename == "." || strings.ContainsAny(filename, "/\\\r\n\x00") || len(filename) > 200)) {
return nil, fmt.Errorf("invalid ntfy attachment")
}
prefix := "PIPELINES_NTFY_" + strings.ToUpper(destination)
if destination == "system" {
prefix = "PIPELINES_NTFY"
}
endpoint := os.Getenv(prefix + "_URL")
token := os.Getenv(prefix + "_TOKEN")
if path := os.Getenv(prefix + "_TOKEN_FILE"); path != "" {
if token != "" {
return nil, fmt.Errorf("configure only one ntfy token source")
}
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("cannot read ntfy token file")
}
contents, err := io.ReadAll(io.LimitReader(file, 4097))
file.Close()
if err != nil || len(contents) > 4096 {
return nil, fmt.Errorf("invalid ntfy token file")
}
token = strings.TrimSpace(string(contents))
if token == "" {
return nil, fmt.Errorf("ntfy token file is empty")
}
}
u, err := url.Parse(endpoint)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || !ntfyTopic.MatchString(strings.TrimPrefix(u.Path, "/")) || u.RawPath != "" {
return nil, fmt.Errorf("configure %s_URL with an HTTP(S) ntfy topic URL (no credentials or query)", prefix)
}
if token != "" && (len(token) > 4096 || !ntfyTokenValue.MatchString(token)) {
return nil, fmt.Errorf("invalid ntfy token configuration")
endpoint, token, err := ntfyConnection(destination)
if err != nil {
return nil, err
}
method := http.MethodPut
if filename == "" {
@@ -179,6 +206,9 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
if priority, ok := ctx.Value(ntfyPriorityKey{}).(int); ok && priority >= 1 && priority <= 5 {
request.Header.Set("Priority", strconv.Itoa(priority))
}
if sequence, ok := ctx.Value(ntfySequenceKey{}).(string); ok && ntfySequenceID.MatchString(sequence) {
request.Header.Set("X-Sequence-ID", sequence)
}
if actions != "" {
request.Header.Set("Actions", actions)
}
@@ -227,6 +257,43 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
return Values{"destination": destination, "message_id": ack.ID, "attachment_url": ack.Attachment.URL, "filename": filename}, nil
}
// ntfyConnection resolves destination's topic URL and token from the
// environment ("system" reads PIPELINES_NTFY_URL and its token).
func ntfyConnection(destination string) (string, string, error) {
prefix := "PIPELINES_NTFY_" + strings.ToUpper(destination)
if destination == "system" {
prefix = "PIPELINES_NTFY"
}
endpoint := os.Getenv(prefix + "_URL")
token := os.Getenv(prefix + "_TOKEN")
if path := os.Getenv(prefix + "_TOKEN_FILE"); path != "" {
if token != "" {
return "", "", fmt.Errorf("configure only one ntfy token source")
}
file, err := os.Open(path)
if err != nil {
return "", "", fmt.Errorf("cannot read ntfy token file")
}
contents, err := io.ReadAll(io.LimitReader(file, 4097))
file.Close()
if err != nil || len(contents) > 4096 {
return "", "", fmt.Errorf("invalid ntfy token file")
}
token = strings.TrimSpace(string(contents))
if token == "" {
return "", "", fmt.Errorf("ntfy token file is empty")
}
}
u, err := url.Parse(endpoint)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || !ntfyTopic.MatchString(strings.TrimPrefix(u.Path, "/")) || u.RawPath != "" {
return "", "", fmt.Errorf("configure %s_URL with an HTTP(S) ntfy topic URL (no credentials or query)", prefix)
}
if token != "" && (len(token) > 4096 || !ntfyTokenValue.MatchString(token)) {
return "", "", fmt.Errorf("invalid ntfy token configuration")
}
return endpoint, token, nil
}
// ValidNtfyClick accepts an empty click or an absolute URL the ntfy server will
// hand to the operating system on tap: a scheme, no credentials, no fragment,
// no control characters and a bounded length. The value is an operator-visible
+38
View File
@@ -234,3 +234,41 @@ func TestNtfyClickAndViewActions(t *testing.T) {
t.Fatalf("invalid actions still published: %d", len(click))
}
}
func TestNtfySequenceIDPublishAndClear(t *testing.T) {
var requests []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests = append(requests, r.Method+" "+r.URL.Path+" seq="+r.Header.Get("X-Sequence-ID")+" auth="+r.Header.Get("Authorization"))
if r.Method == http.MethodPost {
_, _ = w.Write([]byte(`{"id":"m1","event":"message","sequence_id":"pl-abc"}`))
return
}
_, _ = w.Write([]byte(`{"id":"m2","event":"message_clear","sequence_id":"pl-abc"}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "tok")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
ctx := WithNtfySequenceID(context.Background(), "pl-abc")
if _, err := PublishNtfy(ctx, "system", "Title", "Body", "", nil, ""); err != nil {
t.Fatal(err)
}
if err := ClearNtfy(context.Background(), "system", "pl-abc"); err != nil {
t.Fatal(err)
}
if err := ClearNtfy(context.Background(), "system", "bad/id"); err == nil {
t.Fatal("invalid sequence id accepted")
}
// An invalid sequence id on publish is dropped rather than sent.
if _, err := PublishNtfy(WithNtfySequenceID(context.Background(), "a:b"), "system", "Title", "Body", "", nil, ""); err != nil {
t.Fatal(err)
}
want := []string{
"POST /pipelines seq=pl-abc auth=Bearer tok",
"PUT /pipelines/pl-abc/clear seq= auth=Bearer tok",
"POST /pipelines seq= auth=Bearer tok",
}
if strings.Join(requests, "\n") != strings.Join(want, "\n") {
t.Fatalf("requests:\n%s", strings.Join(requests, "\n"))
}
}