Merge branch 'worktree-agent-abec427641b9e4fa8'

This commit is contained in:
2026-12-03 23:41:55 +00:00
138 changed files with 1958 additions and 4651 deletions
-4
View File
@@ -1,8 +1,4 @@
# Prefer scripts/configure-compose.py to detect the host timezone automatically.
TZ=Europe/London
# Replace this with your machine's LAN/VPN address, not localhost on the phone.
NTFY_BASE_URL=http://192.168.1.20:8090
# Explicitly expose ntfy on your trusted LAN/VPN; use HTTPS on public networks.
NTFY_BIND_ADDRESS=0.0.0.0
# Avoid collision while an existing host pipeline server still owns port 8080.
PIPELINES_PORT=8081
+1 -1
View File
@@ -63,7 +63,7 @@
<data android:scheme="pipelines" android:host="chat" />
</intent-filter>
</activity>
<!-- Instant delivery of server notifications without the ntfy app.
<!-- Instant delivery of server notifications while the app is closed.
specialUse: a persistent push connection to a self-hosted server
has no dedicated type, and dataSync is time-limited on Android 15. -->
<service
@@ -10,7 +10,7 @@ data class ServerNotification(
val title: String,
val message: String,
val click: String,
/** ntfy-style priority, clamped to 1..5 (3 is the default). */
/** Priority, clamped to 1..5 (3 is the default). */
val priority: Int,
val tags: List<String>,
val createdAt: String,
@@ -20,7 +20,7 @@ import java.util.concurrent.TimeUnit
/**
* Keeps one authenticated websocket to the configured Pipelines server while
* the app is in the background, like ntfy's instant delivery: no Flutter
* the app is in the background, for instant delivery: no Flutter
* engine runs here. It subscribes with the replay cursor, posts each pushed
* notification, mirrors cross-device clears and sends the user's own clears.
*
@@ -1,6 +1,6 @@
/// An agent's own notification: the `chat_notify` app notification the server
/// records when a chat's model calls the `notify` tool, as the notification
/// stream carries it (see docs/ntfy.md).
/// stream carries it (see docs/notifications.md).
library;
/// The stream kind of an agent's notify call.
@@ -30,7 +30,7 @@ class AgentNotice {
final String title;
final String message;
/// The ntfy-style priority: 2 low, 3 default, 4 high.
/// The priority, 1-5: 2 low, 3 default, 4 high.
final int priority;
final DateTime? createdAt;
@@ -4,8 +4,9 @@ import '../../../../../core/api_gateway.dart';
import 'chat_shown_surface.dart';
/// 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.
/// `channels`: the operator's signed-in Pipelines `apps`; `phone` appears only
/// in entries recorded before the server stopped publishing to a phone push
/// service), or why it was not sent.
String chatShownNotifyText(JsonMap item) {
final title = chatShownTitle(item, 'notification');
if (item['delivered'] == true) return '${_notifiedWhere(item)}: $title';
@@ -12,8 +12,8 @@ export 'notification_service_status.dart';
/// The app's handle on Android background delivery: a native foreground
/// service (android/…/notify/NotificationService.kt) that keeps its own
/// socket to the server and shows the server's notifications, so the ntfy app
/// is not needed. Other platforms have no service ([supported] is false).
/// socket to the server and shows the server's notifications while the app
/// is closed. Other platforms have no service ([supported] is false).
abstract interface class NotificationServiceBridge {
bool get supported;
@@ -2,9 +2,9 @@ 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, {this.subtitle});
/// One server-side notification choice, in the server's wire key.
class NotificationSetting {
const NotificationSetting(this.key, this.label, {this.subtitle});
final String key;
final String label;
@@ -13,36 +13,30 @@ class NtfySetting {
final String? subtitle;
}
/// The server's global notification choices, in display order.
/// The server's global notification choices, in display order. They are
/// stored on the server, so they apply to every signed-in device.
///
/// `run_finished` (server default off) makes every run end notify; without it
/// only runs started with "Notify me" announce their success or failure.
const ntfySettings = <NtfySetting>[
NtfySetting(
const notificationSettings = <NotificationSetting>[
NotificationSetting(
'run_finished',
'Notify when any run ends',
subtitle: 'Otherwise only runs started with Notify me',
),
NtfySetting('chat_needs_you', 'Chat needs your answer or approval'),
NtfySetting('chat_reply_finished', 'Chat reply finished'),
NotificationSetting('chat_needs_you', 'Chat needs your answer or approval'),
NotificationSetting('chat_reply_finished', 'Chat reply finished'),
];
/// The server's switch for also publishing to ntfy. Optional: older servers
/// do not send it, and Settings hides the switch then.
const ntfyEnabledSetting = NtfySetting(
'ntfy_enabled',
'Also send to ntfy',
subtitle: 'For devices that still use the ntfy app',
);
/// Loads and changes the server's ntfy notification settings through the
/// shared gateway (`notification_settings` / `set_notification_settings`).
/// Loads and changes the server's 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);
/// the stored result always replaces the local copy. Keys the app does not
/// show (such as a retired one an older server still sends) are ignored.
class NotificationSettingsController extends ChangeNotifier {
NotificationSettingsController(this.gateway);
final ApiGateway gateway;
@@ -119,15 +113,13 @@ class NtfySettingsController extends ChangeNotifier {
throw const FormatException('the reply carried no notification settings');
}
final result = <String, bool>{};
for (final setting in ntfySettings) {
for (final setting in notificationSettings) {
final value = raw[setting.key];
if (value is! bool) {
throw FormatException('the reply is missing ${setting.key}');
}
result[setting.key] = value;
}
final ntfy = raw[ntfyEnabledSetting.key];
if (ntfy is bool) result[ntfyEnabledSetting.key] = ntfy;
return result;
}
@@ -12,8 +12,8 @@ const deviceDeliveryTitle = 'Notifications in Pipelines';
const deviceDeliverySwitchLabel = 'Receive notifications in Pipelines';
const deviceDeliveryNote =
'Pipelines keeps its own connection to the server and shows its '
'notifications, so the ntfy app is no longer needed. Android shows a '
'quiet "Pipelines is connected" notification while it runs.';
'notifications even while the app is closed. Android shows a quiet '
'"Pipelines is connected" notification while it runs.';
const deviceDeliveryBatteryLabel = 'Allow background delivery';
const deviceDeliveryNotificationsLabel = 'Allow notifications';
const deviceDeliveryWarningTitle = 'Delivery can pause while idle';
@@ -3,35 +3,33 @@ import 'dart:async';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import 'ntfy_settings_controller.dart';
import 'notification_settings_controller.dart';
import 'settings_group.dart';
import 'settings_theme.dart';
/// The section title for the server's ntfy notification choices.
const ntfySectionTitle = 'Phone notifications';
/// The section title for the server's notification choices.
const notificationEventsTitle = 'Notification events';
/// One line explaining where these notifications go.
const ntfySectionSubtitle =
'Sent through ntfy to the devices subscribed to this server.';
/// The subtitle once the server delivers to the app itself (it reports
/// `ntfy_enabled`).
const ntfySectionAppSubtitle =
'What the server notifies about: shown by the Pipelines app and, when '
'enabled, also sent through ntfy.';
/// One line explaining that these choices are shared.
const notificationEventsSubtitle =
'What the server notifies about. Stored on the server, so these apply to '
'every device signed in to it.';
/// Shown instead of loading while the shared connection is down.
const ntfyOfflineText = 'Connect to a server to change these.';
const notificationEventsOfflineText = 'Connect to a server to change these.';
ValueKey<String> ntfySettingKey(String key) => ValueKey<String>('ntfy-$key');
const ntfyErrorKey = ValueKey<String>('ntfy-settings-error');
ValueKey<String> notificationSettingKey(String key) =>
ValueKey<String>('notification-setting-$key');
const notificationSettingsErrorKey = ValueKey<String>(
'notification-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({
class SettingsNotificationSettingsSection extends StatefulWidget {
const SettingsNotificationSettingsSection({
super.key,
required this.gateway,
required this.connected,
@@ -41,13 +39,14 @@ class SettingsNtfySection extends StatefulWidget {
final bool connected;
@override
State<SettingsNtfySection> createState() => _SettingsNtfySectionState();
State<SettingsNotificationSettingsSection> createState() =>
_SettingsNotificationSettingsSectionState();
}
class _SettingsNtfySectionState extends State<SettingsNtfySection> {
late NtfySettingsController _controller = NtfySettingsController(
widget.gateway,
);
class _SettingsNotificationSettingsSectionState
extends State<SettingsNotificationSettingsSection> {
late NotificationSettingsController _controller =
NotificationSettingsController(widget.gateway);
@override
void initState() {
@@ -56,11 +55,11 @@ class _SettingsNtfySectionState extends State<SettingsNtfySection> {
}
@override
void didUpdateWidget(SettingsNtfySection oldWidget) {
void didUpdateWidget(SettingsNotificationSettingsSection oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway != widget.gateway) {
_controller.dispose();
_controller = NtfySettingsController(widget.gateway);
_controller = NotificationSettingsController(widget.gateway);
}
if (widget.connected &&
(!oldWidget.connected || oldWidget.gateway != widget.gateway)) {
@@ -84,16 +83,12 @@ class _SettingsNtfySectionState extends State<SettingsNtfySection> {
final values = _controller.values;
final enabled = widget.connected && _controller.enabled;
final status = !widget.connected
? ntfyOfflineText
? notificationEventsOfflineText
: _controller.loading && values == null
? 'Loading…'
: '';
final hasNtfySwitch = values?.containsKey(ntfyEnabledSetting.key) ?? false;
final tiles = <Widget>[
for (final setting in [
...ntfySettings,
if (hasNtfySwitch) ntfyEnabledSetting,
])
for (final setting in notificationSettings)
_tile(
setting,
values?[setting.key] ?? false,
@@ -106,18 +101,18 @@ class _SettingsNtfySectionState extends State<SettingsNtfySection> {
!_controller.loading &&
(values == null || _controller.loadFailed);
return SettingsGroup(
title: ntfySectionTitle,
title: notificationEventsTitle,
footer: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(hasNtfySwitch ? ntfySectionAppSubtitle : ntfySectionSubtitle),
const Text(notificationEventsSubtitle),
if (status.isNotEmpty) Text(status),
if (_controller.error.isNotEmpty)
Semantics(
liveRegion: true,
child: Text(
_controller.error,
key: ntfyErrorKey,
key: notificationSettingsErrorKey,
style: TextStyle(color: settingsErrorColor(context)),
),
),
@@ -135,9 +130,13 @@ class _SettingsNtfySectionState extends State<SettingsNtfySection> {
);
}
Widget _tile(NtfySetting setting, bool value, ValueChanged<bool>? onChanged) {
Widget _tile(
NotificationSetting setting,
bool value,
ValueChanged<bool>? onChanged,
) {
return CheckboxListTile(
key: ntfySettingKey(setting.key),
key: notificationSettingKey(setting.key),
title: Text(setting.label),
subtitle: setting.subtitle == null ? null : Text(setting.subtitle!),
value: value,
@@ -151,11 +151,13 @@ extension _SettingsPageSections on _SettingsScreenState {
),
),
SettingsSection(
id: 'phone-notifications',
title: ntfySectionTitle,
keywords: 'ntfy push phone run finished chat needs you',
id: 'notification-events',
title: notificationEventsTitle,
keywords:
'notifications push phone events all devices run finished '
'chat needs you reply finished',
lazy: true,
builder: (_) => SettingsNtfySection(
builder: (_) => SettingsNotificationSettingsSection(
gateway: widget.client,
connected:
widget.client.state.kind == transport.ConnectionKind.connected,
@@ -12,7 +12,7 @@ const settingsPhoneFirstIds = [
'sign-in',
'notifications',
'device-delivery',
'phone-notifications',
'notification-events',
];
/// [sections] reordered for a phone: [settingsPhoneFirstIds] first.
@@ -25,7 +25,7 @@ import 'health/settings_health_section.dart';
import 'settings_search_page.dart';
import 'settings_section.dart';
import 'settings_notifications_section.dart';
import 'settings_ntfy_section.dart';
import 'settings_notification_settings_section.dart';
import 'settings_device_delivery_section.dart';
import '../notification_service/notification_service_bridge.dart';
import '../notification_service/notification_service_controller.dart';
+1 -1
View File
@@ -5,7 +5,7 @@
- `android/.../notify/NotificationThreads.kt` (new): `ThreadEntry`, `ThreadHistory`
(bounded per-thread entries, bounded thread count, persisted through the
ledger's `LedgerStore` under `threads.history`), and naming helpers. Threads are
keyed by the server `group` (`chat:<id>` or `run:<id>`, per `docs/ntfy.md`).
keyed by the server `group` (`chat:<id>` or `run:<id>`, per `docs/notifications.md`).
- `NotificationPresenter.kt`: a grouped notification posts one conversation
notification per thread with a stable id (`thread:<group>`), the latest 5 lines
(sender = chat title, run title for runs), the unread count (`setNumber`), and a
+32
View File
@@ -0,0 +1,32 @@
# ntfy removal (app side)
Operator decision: ntfy is removed from Pipelines. Every client gets
notifications from the server's own app notification stream: browser
Notification on web, the "Receive notifications in Pipelines" background
service or the in-app bridge on Android, the in-app bridge on iOS/macOS.
## Change
- Settings "Phone notifications" (ntfy) section replaced by **Notification
events** (`lib/features/settings/settings_notification_settings_section.dart`,
controller `notification_settings_controller.dart`; section id
`notification-events`, still in the phone-first order). It shows the three
server-stored switches `run_finished`, `chat_needs_you`,
`chat_reply_finished` with the subtitle "What the server notifies about.
Stored on the server, so these apply to every device signed in to it."
- The `ntfy_enabled` switch is gone; a reply that still carries it is ignored
(only the three known keys are decoded) and writes send only the toggled key.
- Search keywords no longer mention ntfy.
- "Notifications in Pipelines" note no longer mentions the ntfy app.
- Comments in `agent_notice.dart` (docs/notifications.md, priority 1-5),
`notification_service_bridge.dart`, `AndroidManifest.xml`,
`NotificationService.kt`, `NotificationProtocol.kt` drop ntfy.
- `chat_shown_notify_row.dart` still renders a `phone` channel for transcript
entries recorded before the change; new entries only carry `apps`.
## Checks
- `tool/analyze.sh`: clean.
- memwatch `test/features/settings`: 216 passed; `test/features/attention`:
159 passed; `test/features/notification_service`: 11 passed.
- No browser capture taken for the renamed section.
+1 -1
View File
@@ -11,7 +11,7 @@ not only on the web and then I have to clear again on mobile."
device has open, records a per-session `chat_seen` watermark in epoch ms.
ntfy notifications already shown on a phone cannot be retracted (see
`docs/ntfy.md`, "Clearing notifications across devices").
`docs/notifications.md`, "Clearing notifications across devices").
## Protocol (server, `internal/protocol/attention_acks.go`)
@@ -27,7 +27,7 @@ bool _switchValue(WidgetTester tester) {
}
void main() {
testWidgets('shows the switch, status and ntfy note', (tester) async {
testWidgets('shows the switch, status and delivery note', (tester) async {
final service = FakeNotificationService();
await tester.pumpWidget(_host(service));
await tester.pumpAndSettle();
@@ -4,7 +4,7 @@ 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';
import 'package:pipelines_app/features/settings/settings_notification_settings_section.dart';
/// A scripted gateway: records every request and answers from [respond].
class _Gateway implements ApiGateway {
@@ -32,24 +32,31 @@ JsonMap _reply(bool run, bool needs, bool reply) => {
},
};
Widget _host(ApiGateway gateway) {
Widget _host(ApiGateway gateway, {bool connected = true}) {
final body = SingleChildScrollView(
child: SettingsNtfySection(gateway: gateway, connected: true),
child: SettingsNotificationSettingsSection(
gateway: gateway,
connected: connected,
),
);
return MaterialApp(home: Scaffold(body: body));
}
bool _checked(WidgetTester tester, String key) {
final tile = find.byKey(ntfySettingKey(key));
return tester.widget<CheckboxListTile>(tile).value!;
}
Finder _tile(String key) => find.byKey(notificationSettingKey(key));
bool _checked(WidgetTester tester, String key) =>
tester.widget<CheckboxListTile>(_tile(key)).value!;
void main() {
testWidgets('loads the stored values', (tester) async {
testWidgets('shows the three shared switches with stored values', (
tester,
) async {
final gateway = _Gateway((_, _) => _reply(true, false, true));
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(gateway.calls.single.$1, 'notification_settings');
expect(find.text(notificationEventsTitle), findsOneWidget);
expect(find.text(notificationEventsSubtitle), findsOneWidget);
expect(find.text('Notify when any run ends'), findsOneWidget);
expect(
find.text('Otherwise only runs started with Notify me'),
@@ -57,14 +64,13 @@ void main() {
);
expect(find.text('Chat needs your answer or approval'), findsOneWidget);
expect(find.text('Chat reply finished'), findsOneWidget);
expect(find.text(ntfySectionSubtitle), findsOneWidget);
expect(find.byType(CheckboxListTile), findsNWidgets(3));
expect(_checked(tester, 'run_finished'), isTrue);
expect(_checked(tester, 'chat_needs_you'), isFalse);
expect(_checked(tester, 'chat_reply_finished'), isTrue);
});
testWidgets('shows the server default: only marked runs', (tester) async {
// The server's defaults: run ends notify only for "Notify me" runs.
final gateway = _Gateway((_, _) => _reply(false, true, false));
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
@@ -73,24 +79,53 @@ void main() {
expect(_checked(tester, 'chat_reply_finished'), isFalse);
});
testWidgets('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);
for (final key in ['run_finished', 'chat_needs_you', 'chat_reply_finished']) {
testWidgets('toggling $key writes only that setting', (tester) async {
final gateway = _Gateway((type, fields) {
if (type == 'set_notification_settings') {
return _reply(true, true, true);
}
return _reply(false, false, false);
});
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
await tester.tap(_tile(key));
await tester.pumpAndSettle();
expect(gateway.calls, hasLength(2));
expect(gateway.calls.last.$1, 'set_notification_settings');
expect(gateway.calls.last.$2, {
'notification_settings': {key: true},
});
expect(_checked(tester, key), isTrue);
expect(find.byKey(notificationSettingsErrorKey), findsNothing);
});
}
testWidgets('a legacy ntfy_enabled key in the reply is ignored', (
tester,
) async {
JsonMap legacy() => {
'type': 'notification_settings',
'notification_settings': {
...(_reply(true, true, false)['notification_settings'] as Map),
'ntfy_enabled': true,
},
};
final gateway = _Gateway((_, _) => legacy());
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
await tester.tap(find.byKey(ntfySettingKey('chat_reply_finished')));
expect(find.byType(CheckboxListTile), findsNWidgets(3));
expect(_tile('ntfy_enabled'), findsNothing);
expect(find.textContaining('ntfy'), findsNothing);
expect(find.byKey(notificationSettingsErrorKey), findsNothing);
// A write after such a reply still sends only the toggled key.
await tester.tap(_tile('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'), isTrue);
expect(find.byKey(ntfyErrorKey), findsNothing);
expect(find.byType(CheckboxListTile), findsNWidgets(3));
});
testWidgets('failure reverts and shows the refusal', (tester) async {
@@ -101,53 +136,50 @@ void main() {
});
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
await tester.tap(find.byKey(ntfySettingKey('run_finished')));
await tester.tap(_tile('run_finished'));
await tester.pump();
// The change shows at once and the group is disabled while it saves.
expect(_checked(tester, 'run_finished'), isFalse);
await tester.tap(find.byKey(ntfySettingKey('chat_needs_you')));
await tester.tap(_tile('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'), isTrue);
expect(_checked(tester, 'chat_needs_you'), isTrue);
expect(
find.text('Could not save: settings are read-only'),
findsOneWidget,
);
expect(find.text('Could not save: settings are read-only'), findsOneWidget);
});
testWidgets('disabled while loading and offline', (tester) async {
testWidgets('disabled while loading', (tester) async {
final pending = Completer<JsonMap>();
final gateway = _Gateway((_, _) => pending.future);
await tester.pumpWidget(_host(gateway));
await tester.pump();
expect(find.text('Loading…'), findsOneWidget);
await tester.tap(find.byKey(ntfySettingKey('run_finished')));
await tester.tap(_tile('run_finished'));
await tester.pump();
expect(gateway.calls, hasLength(1));
expect(
tester
.widget<CheckboxListTile>(find.byKey(ntfySettingKey('run_finished')))
.onChanged,
tester.widget<CheckboxListTile>(_tile('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),
),
),
);
testWidgets('offline: no request, the offline text, switches disabled', (
tester,
) async {
final gateway = _Gateway((_, _) => _reply(true, true, false));
await tester.pumpWidget(_host(gateway, connected: false));
await tester.pumpAndSettle();
expect(offline.calls, isEmpty);
expect(find.text(ntfyOfflineText), findsOneWidget);
expect(gateway.calls, isEmpty);
expect(find.text(notificationEventsOfflineText), findsOneWidget);
expect(
tester.widget<CheckboxListTile>(_tile('chat_needs_you')).onChanged,
isNull,
);
});
testWidgets('a load failure is shown with a retry', (tester) async {
@@ -165,47 +197,7 @@ void main() {
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,
);
});
group('ntfy_enabled', () {
JsonMap withNtfy(bool ntfy) => {
'type': 'notification_settings',
'notification_settings': {
...(_reply(true, true, false)['notification_settings'] as Map),
'ntfy_enabled': ntfy,
},
};
testWidgets('hidden when the server does not send it', (tester) async {
final gateway = _Gateway((_, _) => _reply(true, true, false));
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(find.byKey(ntfySettingKey('ntfy_enabled')), findsNothing);
expect(find.text(ntfySectionSubtitle), findsOneWidget);
});
testWidgets('shows and writes it', (tester) async {
final gateway = _Gateway(
(type, _) => withNtfy(type == 'set_notification_settings'),
);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(find.text('Also send to ntfy'), findsOneWidget);
expect(find.text(ntfySectionAppSubtitle), findsOneWidget);
expect(_checked(tester, 'ntfy_enabled'), isFalse);
await tester.tap(find.byKey(ntfySettingKey('ntfy_enabled')));
await tester.pumpAndSettle();
expect(gateway.calls.last.$2, {
'notification_settings': {'ntfy_enabled': true},
});
expect(_checked(tester, 'ntfy_enabled'), isTrue);
});
expect(find.byKey(notificationSettingsErrorKey), findsNothing);
expect(_checked(tester, 'run_finished'), isFalse);
});
}
@@ -164,8 +164,8 @@ void main() {
'ping',
'notification_settings',
]);
await openSettingsSection(tester, 'Phone notifications');
_answerNtfySettings(factory.last);
await openSettingsSection(tester, 'Notification events');
_answerNotificationSettings(factory.last);
await tester.pump();
await tester.pump();
expect(factory.last.decodedOutgoing, hasLength(2));
@@ -203,8 +203,8 @@ void main() {
expect(find.text(serverDetailsPending), findsNothing);
expect(find.text('Server build unavailable'), findsOneWidget);
expect(find.text('Server time unavailable'), findsOneWidget);
await openSettingsSection(tester, 'Phone notifications');
_answerNtfySettings(factory.last);
await openSettingsSection(tester, 'Notification events');
_answerNotificationSettings(factory.last);
await tester.pump();
});
@@ -521,8 +521,8 @@ Future<void> _pump(
await openSettingsSection(tester, 'Connection');
}
/// Answers the Settings screen's queued ntfy-settings load on [channel].
void _answerNtfySettings(FakeChannel channel) {
/// Answers the Settings screen's queued notification-settings load on [channel].
void _answerNotificationSettings(FakeChannel channel) {
final request = channel.decodedOutgoing.last;
expect(request['type'], 'notification_settings');
channel.reply(<String, dynamic>{
@@ -48,7 +48,7 @@ void main() {
..._filler(6),
SettingsSection(
id: 'server',
title: 'Phone notifications',
title: 'Notification events',
lazy: true,
builder: (_) => ServerSettingsView<int>(
load: load,
@@ -60,11 +60,11 @@ void main() {
// The local sections are built and the server section is only a skeleton:
// no request runs until the list reaches it.
expect(find.text('filler body'), findsWidgets);
expect(find.text('Phone notifications'), findsOneWidget);
expect(find.text('Notification events'), findsOneWidget);
expect(fetches, 0);
expect(tester.takeException(), isNull);
await tester.ensureVisible(find.text('Phone notifications'));
await tester.ensureVisible(find.text('Notification events'));
await tester.pump();
await tester.pump();
expect(fetches, 1);
@@ -131,8 +131,8 @@ void main() {
..._filler(6),
SettingsSection(
id: 'server',
title: 'Phone notifications',
keywords: 'ntfy push',
title: 'Notification events',
keywords: 'push devices',
lazy: true,
builder: (_) => ServerSettingsView<int>(
load: load,
@@ -144,7 +144,7 @@ void main() {
await tester.enterText(
find.byKey(const ValueKey('settings.search')),
'ntfy',
'devices',
);
await tester.pump();
await tester.pump();
-39
View File
@@ -5,23 +5,14 @@ services:
init: true
restart: unless-stopped
stop_grace_period: 60s
depends_on:
ntfy:
condition: service_healthy
environment:
TZ: ${TZ:?Set TZ to your host timezone; scripts/configure-compose.py detects it}
PIPELINES_NTFY_URL: http://ntfy/pipelines
PIPELINES_NTFY_PUBLIC_URL: ${NTFY_BASE_URL:?Set the address your Android phone can reach}
PIPELINES_WEB_PUBLIC_URL: ${PIPELINES_WEB_PUBLIC_URL:-}
PIPELINES_NTFY_TOKEN_FILE: /run/secrets/ntfy_token
PIPELINES_DEFAULT_MODEL: ${PIPELINES_DEFAULT_MODEL:-}
PIPELINES_HOST_IP: ${PIPELINES_HOST_IP:-}
PIPELINES_PUBLIC_PORT: ${PIPELINES_PORT:-8080}
PIPELINES_NTFY_READER: phone-reader
PIPELINES_UID: ${PIPELINES_UID:-10001}
PIPELINES_GID: ${PIPELINES_GID:-10001}
secrets:
- ntfy_token
ports:
- "${PIPELINES_BIND_ADDRESS:-0.0.0.0}:${PIPELINES_PORT:-8080}:8080"
volumes:
@@ -52,37 +43,7 @@ services:
timeout: 5s
retries: 12
start_period: 10s
ntfy:
image: binwiederhier/ntfy:latest
command: serve
restart: unless-stopped
environment:
TZ: ${TZ:?Set TZ to your host timezone}
NTFY_BASE_URL: ${NTFY_BASE_URL:?Set the address your Android phone can reach}
NTFY_LISTEN_HTTP: :80
NTFY_CACHE_FILE: /var/lib/ntfy/cache.db
NTFY_CACHE_DURATION: 168h
NTFY_AUTH_FILE: /var/lib/ntfy/auth.db
NTFY_AUTH_DEFAULT_ACCESS: deny-all
NTFY_ENABLE_LOGIN: "true"
NTFY_ATTACHMENT_CACHE_DIR: /var/lib/ntfy/attachments
NTFY_ATTACHMENT_EXPIRY_DURATION: 168h
NTFY_ATTACHMENT_TOTAL_SIZE_LIMIT: 1G
NTFY_ATTACHMENT_FILE_SIZE_LIMIT: 1M
ports:
- "${NTFY_BIND_ADDRESS:-0.0.0.0}:8090:80"
volumes:
- ntfy-data:/var/lib/ntfy
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/v1/health"]
interval: 5s
timeout: 3s
retries: 12
secrets:
ntfy_token:
file: ./secrets/ntfy-token.txt
volumes:
pipelines-data:
opencode-home:
pipelines-workspace:
ntfy-data:
+10 -18
View File
@@ -78,20 +78,15 @@ the sum of the per-run totals `inspect` shows. Only usage rows whose recorded
step still exists are counted, so rows orphaned by an old history wipe are ignored
(not deleted). `pipelines stats --json` exposes these aggregates.
Use `:status` on any TUI page to open server and ntfy information. Scroll with
Use `:status` on any TUI page to open server information. Scroll with
arrows or `j/k`, PgUp/PgDn; `r` refreshes and Esc closes without changing the page.
`pipelines status [--json]` returns the same server data, including hostname,
start/uptime, the connected server endpoint/port, active interface IPs, ntfy
publishing health, public phone URL/topic/port and candidate URLs. It does not
start services or send a notification. The ntfy health probe has a two-second
deadline; it checks the publishing server, not phone reachability.
start/uptime, the connected server endpoint/port, active interface IPs and
candidate URLs. It does not start services or send a notification.
IPs belong to the **server computer or container**, not necessarily the client.
Candidate IP/port combinations are not reachability checks: loopback bindings,
firewalls, container port mapping and TLS can prevent access. ntfy candidates
are only derived when a configured endpoint identifies this computer; remote
ntfy hosts are not misrepresented as local. Publishing URLs and credentials are
never returned. Missing public phone configuration is labeled explicitly.
firewalls, container port mapping and TLS can prevent access.
`pipelines service status` remains the separate OS autostart status command.
## Search
@@ -334,7 +329,7 @@ Submitting activates included schedules, so review them before publishing.
| Resume a run parked for a usage limit | `resume ID --yes --json` |
| Default whole-run budget | `run-budget [USD\|off] --json` |
| Connection and phone settings | `connection --json`, `ping --json` |
| Server/ntfy status popup | `status --json` |
| Server status popup | `status --json` |
| Usage statistics/charts | `stats --json` |
| Run-history retention | `retention report --keep N --json`, `retention apply --keep N --yes` |
| Retire an unused pipeline | `archive NAME --yes`, `unarchive NAME`, `list --archived` |
@@ -359,13 +354,12 @@ optional `kind` and `limit`) and returns a `search_results` response whose ranke
and matched field. `list_runs` also returns all-history `usage`
aggregates. `attention_acks` reads and `ack_attention` adds to the operator's
shared in-app acknowledgements (dismissed Needs-you entries and chat read
watermarks; see [ntfy.md](ntfy.md#clearing-notifications-across-devices)); other
watermarks; see [notifications.md](notifications.md#clearing-notifications-across-devices)); other
connections receive an `attention_acks_changed` push. `subscribe_notifications`
(optional `after` cursor) streams the same notifications the server publishes to
ntfy as `notification` pushes, `clear_notifications` (`ids`) clears them on every
device, and `notifications_cleared` reports clears; `ntfy_enabled` in the
notification settings turns the ntfy publish off without stopping the stream (see
[ntfy.md](ntfy.md#app-notification-stream-no-ntfy-app-needed)).
(optional `after` cursor) streams the operator's notifications as `notification`
pushes, `clear_notifications` (`ids`) clears them on every device, and
`notifications_cleared` reports clears (see
[notifications.md](notifications.md#app-notification-stream-protocol)).
Every run summary (`list_runs` rows, `get_run`, subscribe snapshots and terminal
`run_event` frames) carries `size_bytes`: bytes on disk for the run (artifact tree
@@ -1176,8 +1170,6 @@ or that has no tools block never replays admitted tool work or invalid results.
Budget failures always stop. Cleanup must be confirmed before another attempt.
Existing explicit `retries=0` settings remain unchanged. The old 30-minute run deadline no longer truncates
stage timeouts; the 30-step and five-visits-per-stage limits still apply.
Native ntfy stages also accept `timeout` (default `1h`), but never automatically
retry potentially delivered notifications and do not accept model budgets.
Pinned definitions contain the configured limits. Run transcripts retain limits,
attempt counts and reported budget usage, also shown in the TUI's Evidence pane.
+50 -91
View File
@@ -1,84 +1,72 @@
# Pipeline server + ntfy in one Compose project (Android)
# Pipeline server in a Compose project
## Complete installer (recommended for both services in Docker)
## Complete installer (recommended for Docker)
Run `./install --docker` from an interactive terminal (Docker is the explicit
`--docker`/`docker` mode; `./install.sh` remains a compatibility alias, and a bare
`./install` now performs the native host installation). It handles Compose
configuration, ntfy users/permissions/token, image build, container skill install,
first-time container harness provider login (OpenCode by default; `./install
--docker --harness pi` configures Pi and skips OpenCode login), startup, and an
authenticated test notification. Choose your own provider in the configured
configuration, image build, container skill install, first-time container
harness provider login (OpenCode by default; `./install --docker --harness pi`
configures Pi and skips OpenCode login), startup and a status check. Choose your
own provider in the configured
harness; signup/login credentials stay in the Docker volume, not your host
account. Re-run to update while
preserving `.env`, tokens, histories and volumes. Use `--relogin` to connect another
provider. No fixed OpenCode Go login is required. Health/publishing checks do not
prove model inference or phone reception.
The phone-facing ntfy URL uses the detected LAN IP; both services bind `0.0.0.0` by default.
There are no networking questions. Advanced URL/bind/timezone flags remain optional.
preserving `.env`, histories and volumes. Use `--relogin` to connect another
provider. No fixed OpenCode Go login is required. Health checks do not prove
model inference. The server binds `0.0.0.0` by default. There are no networking
questions; `--timezone` and `--port` remain optional.
The steps below are for manual setup or a developer/legacy local Pipelines server
with Docker ntfy; they are **not** the supported installation and are not needed when
you use `./install`.
Notifications reach the Pipelines apps through the server itself (browser
notifications in the web app, the **Receive notifications in Pipelines**
background service or the open app on Android, the app on iOS and macOS); see
[Notifications](notifications.md). There is no ntfy service any more.
## Manual developer/legacy: local pipeline server, Docker ntfy
Re-running `./install --docker` over an installation from before this change
retires its ntfy: it removes the Compose project's `ntfy` container and
`<project>_ntfy-data` volume (ntfy's caches and accounts, which nothing reads any
more), `secrets/ntfy-token.txt` and the `NTFY_BASE_URL`/`NTFY_BIND_ADDRESS` lines
in `.env`, and recreates the server with `--remove-orphans`. Running it again
finds nothing left to remove. `./uninstall` removes any leftover ntfy container
and volume too.
The steps below are for manual setup or a developer/legacy local Pipelines
server; they are **not** the supported installation and are not needed when you
use `./install`.
## Manual developer/legacy: local pipeline server
To reuse your host OpenCode login without container authentication (manual,
developer/legacy use—not a supported installation):
developer/legacy use, not a supported installation):
```sh
docker compose up -d ntfy
# Bootstrap ntfy users/token as described below, then:
sh scripts/run-local-server.sh
go run ./cmd/pipelines-tui -url ws://127.0.0.1:8080/connect
```
Do not run `docker compose up -d` for this mode: that starts the pipeline container
too. The local launcher uses the existing host database and OpenCode account,
publishes via localhost:8090, and advertises `.env`'s `NTFY_BASE_URL` to the TUI.
The top bar shows **ntfy**, the external server URL, and topic beside the pipeline
server address on every page.
No credentials are included in the public setup data. Stop any existing local
pipeline server before launching another against the same database/port.
The local launcher uses the existing host database and OpenCode account. Stop
any existing local pipeline server before launching another against the same
database/port.
`compose.yaml` runs two services: `pipelines` (Go server + OpenCode V2) and `ntfy`.
The pipeline server publishes internally to `http://ntfy/pipelines`; Android connects
to your host's LAN/VPN URL. No host OpenCode service or credential database is
mounted. Separate volumes persist pipeline history, workspace files, OpenCode
credentials/sessions, and ntfy data. Do not use `docker compose down -v` unless
you intend to delete those volumes.
**Verification:** `docker compose build pipelines` completed, and
`docker compose up -d ntfy` started ntfy. A local authenticated Markdown upload
was accepted with a phone-facing attachment URL. The local server's WebSocket
advertised the public URL/topic and accepted the notification test pipeline.
Go race tests and vet passed. Pipeline-container startup/model authentication
and Android delivery are still **not tested**. Existing host history is preserved;
the local server was restarted with notification configuration. The image now
also includes python3 so the installer regression suite can run inside the
container; a real 40x16/80x24/120x36 terminal UI review remains an independent
step.
`compose.yaml` runs one service, `pipelines` (Go server + OpenCode V2). No host
OpenCode service or credential database is mounted. Separate volumes persist
pipeline history, workspace files and OpenCode credentials/sessions. Do not use
`docker compose down -v` unless you intend to delete those volumes.
## 1. Local settings
Start Docker Desktop/Colima/your Docker daemon first. Choose the host address your
phone can reach. Example (replace the LAN IP):
Start Docker Desktop/Colima/your Docker daemon first.
```sh
python3 scripts/configure-compose.py \
--ntfy-url http://192.168.1.20:8090 \
--bind-address 0.0.0.0
python3 scripts/configure-compose.py
docker compose config --quiet
```
The helper detects the **host's timezone** and writes it to `.env`, so the Linux
containers do not silently schedule in UTC. It refuses to overwrite `.env` or an
existing token. If detection is unavailable, use `--timezone Europe/London` (or
your actual IANA timezone). Rerun/edit settings if you move/change timezones.
containers do not silently schedule in UTC. It refuses to overwrite `.env`. If
detection is unavailable, use `--timezone Europe/London` (or your actual IANA
timezone). Rerun/edit settings if you move/change timezones.
The helper creates an empty, protected token file for bootstrap; no notifications
are sent until it is filled. `.env`, `secrets/`, and `data/` are git-ignored and
excluded from image builds. The container publishes port **8080**; the default
`.env`, `secrets/`, and `data/` are git-ignored and excluded from image builds. The container publishes port **8080**; the default
host mapping is **8081**, bound to host `0.0.0.0`, avoiding the existing native
server on 8080. Query the actual mapped port with
`docker compose port pipelines 8080`. The unauthenticated pipeline WebSocket API
@@ -86,32 +74,11 @@ shares that port, so expose it only on a trusted LAN/VPN and never to the public
internet.
Use HTTP only on a trusted LAN or encrypted VPN. For public access, use HTTPS
with a reverse proxy/VPN; configure the external URL in `NTFY_BASE_URL`. The
container's attachment URLs use that external URL, not the internal service name.
Both host port mappings default to `0.0.0.0`; firewall them appropriately. The
Pipelines API has no authentication and must not be exposed to untrusted networks.
with a reverse proxy/VPN. The host port mapping defaults to `0.0.0.0`; firewall
it appropriately. The Pipelines API has no authentication and must not be
exposed to untrusted networks.
## 2. Bootstrap ntfy users and token
```sh
docker compose up -d ntfy
docker compose exec ntfy ntfy user add pipeline-publisher
docker compose exec ntfy ntfy access pipeline-publisher pipelines write-only
docker compose exec ntfy ntfy user add phone-reader
docker compose exec ntfy ntfy access phone-reader pipelines read-only
docker compose exec -T ntfy ntfy token add pipeline-publisher | python3 scripts/save-ntfy-token.py
```
User creation prompts for passwords. Keep `secrets/` mode **0700** on the host.
The helper extracts only the raw token (the ntfy CLI includes prose in its response)
and makes the final file readable inside the non-root pipeline container: local Compose
file secrets are bind mounts and do not reliably remap uid/mode. Its private parent
directory protects the source file from other host users. Do not commit tokens
or paste them into a chat. Recreating/replacing the secret file requires restarting
the pipeline container. The application accepts `_TOKEN_FILE` or `_TOKEN`, not
both, and never puts the token in model prompts, outputs, or diagnostics.
## 3. Authenticate the harness, then start the server
## 2. Authenticate the harness, then start the server
```sh
python3 scripts/build_metadata.py # resolve releases and stamp revision/dirty identity
@@ -151,18 +118,11 @@ bundled example pipelines, seeded once; an existing database is never changed.
Open `:templates` and use **Submit template** to name/review/publish another copy,
or **Customize** to edit it first. All bundled examples are manual-only.
## 4. Android
## 3. Notifications
Install ntfy, add the custom server `http://192.168.1.20:8090` (or your HTTPS/VPN
URL), sign in as `phone-reader`, and subscribe to **pipelines**. This is the single
system-wide notification topic, shared by every pipeline. Grant notifications
and background operation as required by your Android app/device. Outside your
LAN, enable the VPN or use your HTTPS address. `localhost` on Android is the
phone, not your server. No iOS/APNS upstream is needed for this Android setup.
Use the app to confirm a test notification and download an attachment before
relying on unattended schedules. This phone/background-delivery check has **not
been performed**. Attachments/messages expire after seven days in this config.
Notifications come through the Pipelines apps, connected to this server; see
[Notifications](notifications.md). If you subscribed to the old `pipelines`
topic in the ntfy app, remove that subscription.
## Existing data and rebuilds
@@ -179,8 +139,7 @@ resolves the current releases, use `python3 scripts/build_metadata.py`. A plain
The workspace volume does not automatically replace its existing source tree
on image rebuild; back it up and update it explicitly if you need new source for
Go verification. Do not delete it casually: it may contain user-created artifacts.
`compose.yaml` still uses ntfy's `latest` tag; pin a tested version/digest before
production. OpenCode and Pi are not fixed version pins: `./install` resolves the
OpenCode and Pi are not fixed version pins: `./install` resolves the
current supported OpenCode V2 release from the single documented complete
`GET /repos/{owner}/{repo}/git/matching-refs/tags/v2` response — a complete bounded
array with no page/per_page query and no `Link` pagination (never the moving
+2 -4
View File
@@ -11,7 +11,7 @@ service or a guarantee that a model's answer is correct.
Docker is optional with `./install --docker`.
3. Open the web address reported by setup. For terminal use, put the installation's
`bin` directory on PATH and run `pipelines` from your project directory.
4. Setup also starts the authenticated web proxy, server, and ntfy and enables
4. Setup also starts the authenticated web proxy and server and enables
login startup. See [installation](install.md) for the private web credential
location. The installed CLI's `pipelines service enable` / `service status`
manage that same service; do not start another server manually.
@@ -59,9 +59,7 @@ a new execution can repeat side effects. Never delete data/volumes to fix a run.
Browser alerts require the page to be open; closed-app web push is not supported.
The Android app delivers notifications in the background over its own
connection. ntfy is an optional fallback channel that works without the
Pipelines Android app. Installation verifies publishing, not reception. Check
device reception before relying on it. See [Notifications](notifications.md).
connection. Check device reception before relying on it. See [Notifications](notifications.md).
## Known limits
+69 -28
View File
@@ -17,11 +17,10 @@ them, and it stops naming whatever is missing.
| Tool | Why |
| --- | --- |
| Go (version in `go.mod`, currently 1.27) | builds `pipelines-server`, `pipelines` and ntfy |
| Go (version in `go.mod`, currently 1.27) | builds `pipelines-server` and `pipelines` |
| Node.js 18+ | runs the authenticated web proxy (`web/serve.mjs`) |
| Python 3.9+ | installer and the lifecycle manager (`manage.py`) |
| git, curl | source checkout, updates, release lookup |
| C compiler (`cc`, `clang` or `gcc`) | ntfy's SQLite driver is cgo (Xcode Command Line Tools on macOS) |
| **Docker, running** | builds the Flutter web app and the APK |
| OpenCode on `PATH` | required; default stage and chat harness (`curl -fsSL https://opencode.ai/install \| bash`) |
| Pi, Claude Code, Codex | optional; set up after install with `pipelines harness setup <name>` |
@@ -52,18 +51,69 @@ Linux needs `systemctl --user`. Other platforms are refused.
6. Writes host harness profiles to `~/.config/pipelines/harnesses.json`. If no
usable OpenCode default model is found, it opens the model picker in the
terminal (or fails without a terminal; pass `--model`).
7. Builds ntfy from its pinned Go module, writes its config and creates the
`pipeline-publisher` and `phone-reader` accounts.
8. Migrates data from an earlier Docker installation, if its volumes exist.
7. Migrates data from an earlier Docker installation, if its volumes exist.
8. Retires the ntfy server an older installation ran, if any (see
[Reinstalling over an ntfy installation](#reinstalling-over-an-ntfy-installation)).
9. Registers the login service, writes the manifest
`<prefix>/pipelines-install.json`, saves `ws://127.0.0.1:<port>/connect` as
the CLI default in `~/.config/pipelines/client.json`, and starts everything.
the CLI default in `~/.config/pipelines/client.json`, and starts everything
that is not already running. A running service keeps the previous build
until `pipelines restart`.
10. Retires the legacy standalone web agent `net.awan.pipelines.web` on macOS
(stopped, plist renamed to `.disabled`), so only one web app is served.
11. If `PIPELINES_WEB_PUBLIC_URL` is an `https://…ts.net` address, runs
`tailscale serve --bg --https=<port> http://127.0.0.1:<web-port>`.
12. Prints the browser URLs and the next step, setting up harnesses.
## Notifications
Pipelines sends notifications through its own server to the Pipelines apps;
there is nothing to install or subscribe to:
- **Web app**: browser notifications, once allowed in the browser.
- **Android**: the **Receive notifications in Pipelines** background service,
or in the app while it is open.
- **iOS and macOS**: in the app.
See [Notifications](notifications.md).
### Reinstalling over an ntfy installation
Installations from before this change ran an ntfy server beside Pipelines.
`./install` retires it, once, after the new build is in place and before the
new manifest is written (`Setup.retire_ntfy` in `scripts/setup-native.py`,
using `retire_ntfy` in `scripts/manage.py`):
1. It records the paths it removes and the old ntfy version, from the old
manifest, in `<prefix>/logs/install.log`. No credentials are written there.
2. It stops the old ntfy process from `<prefix>/ntfy.pid`, but only while that
PID's command line is still `<prefix>/bin/ntfy serve …`; any other PID is
left alone and the stale PID file is removed.
3. It deletes `<prefix>/bin/ntfy`, `<prefix>/ntfy.pid`, `<prefix>/logs/ntfy.log`,
`<prefix>/secrets/publisher-token` and the whole `<prefix>/data/ntfy/`
directory.
`<prefix>/data/ntfy/` is deleted rather than kept: it held only ntfy's
configuration, its message and attachment caches, and its account database
(`phone-reader`, `pipeline-publisher`), which nothing reads any more. Pipelines
history lives in `<prefix>/data/pipelines.db` and is untouched.
The new manifest has a top-level `"mode": "native"` and no `ntfy`, `ntfy_port`,
`topic`, `username` or `public_url` entries. Until that reinstall, a manifest
with the older `ntfy.mode: "native"` marker is still treated as native.
`./install` does not restart a service that is already running, so the old
server keeps running (without ntfy) until `pipelines restart`. The restart stops
the old supervisor; the new one starts only the server and web proxy, and stops
an ntfy that is somehow still running from the PID file under the same check.
Running `./install` again finds nothing left to retire. On a phone, remove the
old Pipelines subscription from the ntfy app.
Docker installations (`./install --docker`) retire ntfy the same way: the
installer removes the old `ntfy` container and its `<project>_ntfy-data` volume,
`secrets/ntfy-token.txt` and the `NTFY_*` lines in `.env`, and recreates the
server with `--remove-orphans`.
## Set up harnesses
One command per harness, the same on native and Docker installations:
@@ -90,7 +140,6 @@ one; it does not touch that binary.
| --- | --- | --- |
| Web proxy (sign-in, web app, `/updates/`) | port 8082, loopback + tailnet only | `--web-port`, `--web-host`, `--web-lan` |
| Server API (no auth) | `127.0.0.1:8080` | `--port`, `--bind-address` |
| ntfy | `:8090` | `--ntfy-port`, `--ntfy-url` |
Expose only the web proxy. It listens on loopback and this machine's Tailscale
addresses unless you opt into the LAN; see
@@ -131,8 +180,6 @@ From `arguments()` in `scripts/setup-native.py`:
| `--web-host tailnet\|IP` | web proxy access: `tailnet` (default for new installs: loopback and Tailscale addresses only) or a literal IPv4 bind such as `0.0.0.0`; existing installs keep theirs and get a warning |
| `--web-lan` | also accept plain-HTTP LAN connections; sign-in over them stays refused |
| `--web-lan-plain-login` | allow sign-in over plain-HTTP LAN (unencrypted password and cookie; trusted networks only) |
| `--ntfy-port N` | ntfy port (default 8090) |
| `--ntfy-url URL` | ntfy address given to phones (default `http://<LAN IP>:<ntfy-port>`) |
| `--timezone TZ` | override the detected timezone (fallback UTC) |
| `--model PROVIDER/MODEL` | default model for new starters and missing OpenCode profile fields |
| `--allow-authoring` | allow creating and publishing pipelines (fresh installs default to this) |
@@ -166,7 +213,7 @@ This reset has no confirmation prompt. Do not use it merely to update the app.
```sh
./install --web # rebuild and install only the web app (Docker), then reload the page
./install --apk # build the Android APK (Docker, slower) and offer it to phones
./install --docker # server and ntfy in Docker Compose instead of native
./install --docker # server in Docker Compose instead of native
```
`./install --apk` builds a release APK for this installation's web address,
@@ -252,11 +299,11 @@ another installation.
| Command | Effect |
| --- | --- |
| `pipelines start` | start server, web proxy and ntfy; print the startup report |
| `pipelines stop` | stop all three; harness sessions keep running and the next start reattaches them (see below) |
| `pipelines start` | start server and web proxy; print the startup report |
| `pipelines stop` | stop both; harness sessions keep running and the next start reattaches them (see below) |
| `pipelines restart` | stop then start, keeping data; chat turns and stage sessions continue |
| `pipelines doctor` | startup report, health of server and ntfy, OpenCode API check (no inference) |
| `pipelines status` | server, host and ntfy publishing health, from the running server |
| `pipelines doctor` | startup report, server health, OpenCode API check (no inference) |
| `pipelines status` | server and host health, from the running server |
| `pipelines logs` | follow `logs/server.log` |
| `pipelines update` | pull and reinstall the same way, then restart (see below) |
| `pipelines uninstall [--purge] [--yes]` | remove the service and binaries; `--purge` also deletes data |
@@ -310,7 +357,7 @@ endpoint and the Codex App Server are separate processes anyway.
The login service is `~/Library/LaunchAgents/net.a-wan.pipelines.plist` on
macOS and `~/.config/systemd/user/net.a-wan.pipelines.service` on Linux. It
runs `manage.py supervise`, which owns all three processes. This is login
runs `manage.py supervise`, which owns the server and web proxy processes. This is login
autostart, not boot-without-login.
## Where things live
@@ -318,12 +365,10 @@ autostart, not boot-without-login.
| Path | Contents |
| --- | --- |
| `<prefix>/pipelines-install.json` | manifest (ports, paths, install args, environment) |
| `<prefix>/bin/` | `pipelines`, `pipelines-server`, `pipelines-claude-host`, `pipelines-codex-host`, `ntfy` |
| `<prefix>/bin/` | `pipelines`, `pipelines-server`, `pipelines-claude-host`, `pipelines-codex-host` |
| `<prefix>/data/pipelines.db` | SQLite database (definitions, runs, chats, settings) |
| `<prefix>/data/artifacts/` | run artifacts and session exports |
| `<prefix>/data/ntfy/` | ntfy config, cache and accounts |
| `<prefix>/secrets/publisher-token` | ntfy publishing token |
| `<prefix>/logs/` | `server.log`, `web.log`, `ntfy.log`, `supervisor.log` |
| `<prefix>/logs/` | `server.log`, `web.log`, `supervisor.log`, `install.log` |
| `~/.config/pipelines/web-auth.json` | web password and cookie secret (`PIPELINES_WEB_AUTH_FILE`) |
| `~/.config/pipelines/harnesses.json` | harness profiles (`PIPELINES_HARNESS_CONFIG`) |
| `~/.config/pipelines/client.json` | default server URL for the CLI/TUI |
@@ -342,9 +387,6 @@ twice). Without a terminal, set `PIPELINES_WEB_PASSWORD`. It is stored in
and reused unchanged on every reinstall. An invalid or non-private file stops
the installer rather than being reset.
The same password is given to the ntfy `phone-reader` account when that account
is first created; existing ntfy accounts keep their passwords.
After updating the installation, change the web sign-in password from the
checkout with:
@@ -356,8 +398,7 @@ It prompts twice without echoing the password, requires at least eight
characters, and writes the private password file atomically. The updated web
proxy picks it up on the next request; no service restart is needed, and existing
sessions and running tasks remain connected. SSH is supported with an interactive
TTY. This changes the web/app sign-in password; the ntfy notification account's
password is unchanged. `--prefix PATH` selects another installation, and
TTY. This changes the web/app sign-in password. `--prefix PATH` selects another installation, and
`PIPELINES_WEB_AUTH_FILE` selects an explicitly configured password file.
## Upgrading
@@ -369,8 +410,8 @@ pipelines update
`update` refuses while runs are executing (finish or cancel them first). It
then runs `git pull --ff-only` in the checkout it was installed from (skipped
when the branch has no upstream), re-runs `./install` with the recorded
arguments, restarts, and prints the startup report. Data, passwords, ntfy
accounts and the signing key are kept. If the installer fails, the previous
arguments, restarts, and prints the startup report. Data, passwords and the signing key
are kept. If the installer fails, the previous
version keeps running.
Running `./install` again from the checkout does the same without the pull.
@@ -403,8 +444,8 @@ per-user data directory (`XDG_DATA_HOME`, or Application Support on macOS).
## Troubleshooting
- **"Docker is not running"**: start Docker Desktop (or the daemon) and rerun.
- **Ports busy**: a Docker installation or an old server may hold 8080, 8082 or
8090. Stop it, or choose other ports with the flags above.
- **Ports busy**: a Docker installation or an old server may hold 8080 or 8082.
Stop it, or choose other ports with the flags above.
- **"No usable configured harness model"**: rerun `./install` in a terminal to
pick models, or pass `--model PROVIDER/MODEL`.
- **CLI talks to the wrong server**: `PIPELINES_URL` overrides the saved
+173 -43
View File
@@ -1,29 +1,37 @@
# Notifications
The server records every notification once and delivers it two ways:
The server records every notification once, in its `app_notifications` table,
and streams it over the app's own connection (`/connect`) to every signed-in
Pipelines client, which posts it as a system notification:
1. **In the Pipelines app** (Android, and the web page while it is open), over
the app's own connection. No ntfy app is needed.
2. **ntfy** (optional fallback), for devices that still use the ntfy app.
- **Web** (each tab and installed web app window): a browser `Notification`,
while the page is open and the browser allows it. Closed-browser web push is
not implemented.
- **Android**: the **Receive notifications in Pipelines** background service
(keeps its own connection, also with the app closed), or the in-app bridge
while the app runs.
- **iOS and macOS**: the in-app bridge while the app runs.
The same settings decide what is sent on both paths.
No other app, server or account is involved. (Earlier versions also published
to a self-hosted ntfy server; that was removed. See
[Upgrading from ntfy](#upgrading-from-ntfy).)
## What notifies
| Event | When |
| --- | --- |
| Run needs your decision | a run reaches a human decision stage (runs not set to Silent) |
| Run failed / succeeded | runs started with **Notify me** (`--notify on`), or every run when **Notify when any run ends** is on |
| Stage hook | a stage's own `notify` block fires ([ntfy reference](ntfy.md)) |
| Run failed / succeeded | runs started with **Notify me** (`--notify on`), or every run when **Notify when any run ends** is on; unexpected failures always |
| Stage hook | a stage's own `notify` block fires ([below](#stage-notify-hooks)) |
| 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") |
| Schedule delayed / skipped | a scheduled run could not start on time (low priority) |
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)).
Each event notifies once, on every signed-in device. Opening the chat or run,
tapping the notification, or dismissing it in the app or the Android
notification shade clears it on every device (see
[Clearing notifications across devices](#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
@@ -61,48 +69,170 @@ In the app, **Settings**:
- **Allow background delivery**: asks Android to exempt Pipelines from battery
optimisation so delivery stays instant while the phone is idle. Grant it.
**Phone notifications** (stored on the server, shared by every device):
**Notification events** (stored on the server, shared by every device):
| Setting | Default |
| --- | --- |
| Notify when any run ends (otherwise only runs started with **Notify me**) | off |
| Chat needs your answer or approval | on |
| Chat reply finished | off |
| Also send to ntfy (for devices that still use the ntfy app) | on |
| Setting | Key | Default | Effect |
| --- | --- | --- | --- |
| Notify when any run ends | `run_finished` | off | every **auto**-mode run that fails or succeeds notifies; otherwise only runs started with **Notify me** announce their end |
| Chat needs your answer or approval | `chat_needs_you` | on | chat questions/forms and approval requests notify |
| Chat reply finished | `chat_reply_finished` | off | each finished assistant turn notifies |
Turning **Also send to ntfy** off stops publishing to ntfy; the app still
receives everything.
They are stored in the server database (`server_settings`, keys `notify.*`) and
survive restarts. Per-stage `notify` hooks are not affected by them. 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 every
key. Unknown keys and non-boolean values are refused with an `error` reply and
nothing is written. The removed `ntfy_enabled` key is accepted and ignored, so an
older app's switch does not fail; a stored `notify.ntfy_enabled` row is never
read.
`run_finished` changed meaning once: it meant "auto runs announce success" and
defaulted on. It is stored under `notify.any_run_ended`, so a value saved under
the old meaning (`notify.run_finished`) is ignored.
Per run, choose **Notify me**, the default (auto), or **Silent** when starting
it. From the CLI: `pipelines run … --notify on|auto|off`.
## The web app
## Run notifications
The web page shows notifications only while it is open and the browser allows
them. Closed-browser web push is not implemented.
Independently of any `notify` block, the server records one run-level
notification when a run needs a person or ends and was marked to notify:
## ntfy (optional)
| Run notify mode | Enters `waiting` | Fails / succeeds |
| --- | --- | --- |
| **on** ("Notify me", `--notify on`) | `Run needs your decision` | `Run failed` / `Run succeeded` |
| **auto** (default) | `Run needs your decision` | unexpected failure or interruption; success only when **Notify when any run ends** is on |
| **off** ("Silent") | silent | silent |
`./install` builds and runs ntfy on port 8090 with a private `pipelines` topic.
The installer prints the subscription details at the end, and
`pipelines doctor` repeats them (`Phone server … · topic: pipelines ·
username: phone-reader`).
A deliberate route to `#failure` with its reason is an expected failure: it does
not notify in auto mode. Queued, running and canceled runs are silent. The
setting is read in the same transaction that records the run's final state.
To subscribe from the ntfy app:
Run events go through a durable outbox (`run_notifications`): the event is
queued with the run's state change and recorded on the app stream at once; a
crash before it is recorded is recovered after a restart. A run that stays
`waiting` is not announced again on a read or restart, and a stage `notify` hook
that already covered the same event (`on=waiting`, or a failure hook)
suppresses the run-level one, so one event means one notification. A
notification problem is logged and never changes the run.
1. Add a server: the ntfy address (default `http://<LAN IP>:8090`, or the
`--ntfy-url` you installed with). Off your home network, use a VPN such as
Tailscale.
2. Sign in as `phone-reader`. A freshly created account uses the web sign-in
password; an account kept from an earlier install keeps its old password.
3. Subscribe to the topic `pipelines`.
A tap opens `pipelines://run/<id>` in the app (the web app opens the same run).
A tap opens `pipelines://run/<id>` or `pipelines://chat/<id>` in the Android
app; the **Open in browser** action opens the same page on
`PIPELINES_WEB_PUBLIC_URL`.
## Stage notify hooks
Notifications already shown by the ntfy app cannot be retracted by the server;
swipe them away there.
Every stage can have an optional `notify` block:
See [ntfy reference](ntfy.md) for stage `notify` hooks, explicit ntfy stages,
the app notification protocol and network troubleshooting.
````markdown
# stage compose
```notify
on=success,failure
open=*.md
link=standup-link.txt
```
````
- `on` is `success`, `failure`, `waiting`, or a comma list. A failure is an
execution error, the `error` outcome, or a route to `#failure`; any other
completed stage is a success. It reports the stage's result, not the run's.
- For a sequential workflow whose error routes go to `#failure`, add
`on=failure` to intermediate stages and `on=success,failure` to the final
stage: one notification on every normal terminal path, without progress
alerts.
- `open=<pattern>` attaches one file from the run's shared `public/` directory
to the notification (with a short text preview) and makes a tap open it. The
pattern is a relative glob without absolute paths, `..` or hidden segments;
the most recently modified match wins. Without `open=`, exactly one regular
file in `public/` is attached automatically; zero or several attach nothing.
- `link=<pattern>` makes a tap open a URL the stage produced (for example a
published doc): the matched `public/` file's first non-empty line must be an
absolute http(s) URL without credentials or fragment. The run stays reachable
from the notification's run action. A missing file or invalid URL keeps the
usual tap target and is noted on the stage's notification receipt.
- `artifacts=` and `destination=` lines from older definitions still parse but
do nothing: they configured ntfy attachments and connections.
Hooks run after the stage completes and before the run's final status is saved.
They are not a finalizer for cancellation, crashes or runtime limits, and loops
can notify more than once. The receipt (recorded or not) appears in the stage's
**Metadata**; it never changes routing.
The former `type=ntfy` delivery stage was removed. A definition that still uses
it is refused by validation with: "ntfy stages were removed; notifications go
to the Pipelines apps — use the stage notify hook".
## Clearing notifications across devices
The app's attention state is shared through the server: dismissing an entry or
using **Clear all** in the Needs-you sheet, and opening a chat (which clears its
**New** badge), clears it on every connected browser and phone at once, and on a
disconnected device when it next connects. The protocol is
`{"type":"attention_acks"}` (read the whole set) and
`{"type":"ack_attention","attention_acks":{"dismissed":["42:Failed"],"chat_seen":{"ses_x":1730000000000}}}`
(add to it). Both reply `attention_acks`, and every other connection receives an
`attention_acks_changed` frame. Acknowledgements for deleted runs or sessions,
or older than 30 days, are pruned.
Every client removes its system notification when the clear reaches it:
- **Web**: the page closes the browser `Notification` with that tag and tells
the origin's other tabs to close theirs over a `BroadcastChannel`. A click
sends `clear_notifications`. A browser *close* event is not reported back
(browsers raise it for timeouts and same-tag replacements too).
- **Android with Receive notifications in Pipelines**: the background service
cancels it; a tap or a swipe sends `clear_notifications`.
- **Android without the service, iOS and macOS** (the in-app bridge while the
app runs): it is removed by its tag; a tap clears it. A swipe is not reported.
## App notification stream (protocol)
```text
→ {"type":"subscribe_notifications","id":"1","after":"run:7:3:waiting"}
← {"type":"notifications_subscribed","id":"1","notifications":[N...],"ids":["<cleared id>",...]}
← {"type":"notification","notification":N} (push)
← {"type":"notifications_cleared","ids":["run:7:3:waiting"]} (push)
→ {"type":"clear_notifications","id":"2","ids":["run:7:3:waiting"]}
← {"type":"notifications_cleared","id":"2","ids":[<ids it cleared>]}
N = {"id":"run:7:3:waiting","kind":"run_waiting","title":"Run needs your decision",
"message":"Run #7 · release · waiting for a human decision at stage approve",
"click":"pipelines://run/7","priority":3,"tags":[],
"created_at":"2026-11-01T10:00:00Z","group":"run:7"}
```
- `id` is stable: `run:<run>:<step>:<event>` (event `waiting`, `failed`,
`succeeded`, or `success` for a mid-run stage hook),
`chat:<session>:<form|permission|reply|notify|auto-switch>:<id>` or
`schedule:<id>:<due>:<event>`. `kind` is one of `run_waiting`, `run_failed`,
`run_succeeded`, `stage_failed`, `stage_succeeded`, `chat_question`,
`chat_approval`, `chat_reply`, `chat_notify`, `schedule`. `group` is
`run:<id>`, `chat:<id>` or `schedule:<id>`.
- `priority` is 1–5 (3 default). Schedule notices and the Claude account
auto-switch notice are 2; an agent's `notify` uses the tool's priority (`low`
2, `default` 3, `high` 4).
- A stage hook notification may carry `artifact` (the `open=` file) and
`preview`; with a `link=` its `click` is the link and `run_click` the run.
- The subscribe reply holds the active (uncleared) notifications newer than the
`after` cursor, oldest first, at most 100; an empty, unknown or pruned cursor
replays them all. Its `ids` lists notifications cleared within the 7-day
retention (newest first, at most 500) so a reconnecting device can dismiss
ones it still shows. Pushes follow in order; subscribing again replaces the
subscription.
- `clear_notifications` has the same effect as the matching `ack_attention`:
`run_waiting` dismisses `<run>:Decision`, `run_failed`/`stage_failed`
`<run>:Failed`, and a chat notification marks the chat seen (clearing its
other notifications too).
- Notifications are also cleared, with a push, by `ack_attention` from any
client, by a run leaving `waiting`, by deleting a run, and by an answered or
cancelled chat question or approval.
## Upgrading from ntfy
Installs made before the removal ran a bundled ntfy server on port 8090. The
installer retires it on reinstall and `./uninstall` removes any leftover (see
[Install](install.md)). Phones that subscribed in the ntfy app keep the old
subscription but receive nothing further: remove the Pipelines server from the
ntfy app, and turn on **Receive notifications in Pipelines** in the Android app
instead. Old stored settings keep their meaning; the `ntfy_enabled` choice and
the old chat push outbox (`chat_notifications`, dropped at startup) are ignored.
-415
View File
@@ -1,415 +0,0 @@
# Self-hosted ntfy delivery
For the user-facing overview (in-app Android delivery, settings, subscribing)
see [Notifications](notifications.md). This page is the reference for stage
hooks, the app notification protocol and ntfy itself.
Every stage can have an optional `notify` property block. Notifications go to
your own ntfy instance and can attach Markdown and output files. It does not ask
an LLM to handle credentials or run curl. The full Markdown remains in the run
audit as well as the ntfy attachment. A separate HTML report viewer is not included.
## Per-stage notifications (recommended)
### One terminal-path alert without adding stages
For a sequential workflow such as `research → report`, where intermediate
blocked/error routes go straight to `#failure`, add `on=failure` notification
hooks to intermediate stages and `on=success,failure` to the final stage.
Keep the graph and output contracts unchanged; omit `artifacts` for event-only
alerts. This avoids intermediate success alerts while covering early stage
errors and the final success/error result. Putting a hook only on the last stage
misses earlier failures; putting success hooks on every stage sends progress alerts.
These are stage hooks, not a universal run-finalizer: they run before the final
status is saved, and do not guarantee notifications for cancellation, crashes,
persistence failures or runtime step/visit limits. Recovery routes and loops can
notify before termination or more than once. An explicit native publisher stage
is not necessary for ordinary completion alerts and cannot reliably consume the
required `title`/`summary`/`markdown` after an upstream execution error.
The installed authoring skill includes this recipe and native-delivery details in
`references/notifications.md`; authoring does not require a checkout of this project.
````markdown
# stage compose
```notify
on=success,failure
artifacts=markdown,files
```
...stage output, prompt, tools, edges, and configs...
````
- `on` is `success`, `failure`, or `success,failure`. A failure is an execution
error, the `error` outcome, or a route to `#failure`; any other completed stage
is a success. This reports the stage's result, not the final run's result.
- All notification hooks use one system-wide server-to-phone connection. Stages
do not choose topics or addresses. Configure `PIPELINES_NTFY_URL` (publishing
topic URL), `PIPELINES_NTFY_PUBLIC_URL` (phone-facing server base URL), and
`PIPELINES_NTFY_TOKEN` or `PIPELINES_NTFY_TOKEN_FILE` once on the server.
The topic is `pipelines` in the provided setup. No block means no per-stage
notifications; a run that needs a person is still announced automatically (see
below). Legacy `destination` lines remain parseable for immutable-history compatibility
but no longer select a connection for notification hooks. Explicit native
`type=ntfy` stages retain their separate destination configuration.
- `artifacts=markdown` sends the string in `output.markdown` as `digest.md`.
- `artifacts=files` sends paths listed in `output.artifacts`, e.g.
`["reports/result.txt", "screenshots/chart.png"]`. Model stages with this policy
are instructed to list files they actually created/modified. No workspace scan
or file discovery occurs; an invalid model response may leave no artifact list.
- Both artifact kinds can be selected. Each file gets a separate notification
(ntfy supports one attachment per notification). If none were produced, an
event-only notification is still sent, including on failure.
- Files must be workspace-relative regular files, at most 1 MiB each and 10 files
per stage. Traversal, absolute paths, symlinks, hidden paths, known database/key
paths, `secrets/`, and `node_modules/` are rejected. These guards are not a
content scanner/DLP system: only list files you intend to share.
- Notifications have a 30-second total budget, with no automatic retries. Their
receipts/failures appear in the selected run stage's **Metadata**, separately
from output. They do not change routing or convert a successful stage into a
failed run. A crash can leave a `sending` receipt with uncertain delivery;
notifications are not replayed during recovery. Tool access follows the stage's
declared tools; notification settings do not grant additional tools.
## Automatic run-attention notifications
Independently of any `notify` block, the server publishes one run-level
notification to the `system` destination when a run needs a person or ends and
was marked to notify. The run's notify mode decides:
| Run notify mode | Enters `waiting` | Fails / succeeds |
| --- | --- | --- |
| **on** ("Notify me" in the app, `--notify on` in the CLI) | `Run needs your decision` | `Run failed` / `Run succeeded` |
| **auto** (default) | `Run needs your decision` | silent, unless **Notify when any run ends** is on |
| **off** ("Silent") | silent | silent |
Queued, running, canceled and interrupted runs are always silent. The **Notify
when any run ends** setting (`run_finished`, off by default) makes every auto
run's end notify too; it is read in the same transaction that records the run's
final state, so a change applies to runs finishing after it. A stage `notify`
block is the pipeline's own opt-in and still publishes for an auto run; when it
covers the same event the run-level alert is not sent again.
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
Set `PIPELINES_WEB_PUBLIC_URL` on the **Pipelines server** to the authenticated web
proxy's phone-reachable origin, for example `https://pipelines.example.com` or
`http://192.168.1.20:8082` on a trusted LAN. Notifications then carry
`https://pipelines.example.com/runs/<id>`, opening that exact run in the browser
(or installed web app). The existing sign-in gate remains; after login the web
proxy returns to the requested run.
Use the address you actually open on the phone, not localhost, the API port, or
the ntfy address. No credentials, query, fragment or subpath are allowed. This
does not expose a port or add authentication to the underlying control API.
An invalid configured origin omits the click action and logs a configuration
warning rather than leaking credentials. Without this setting, existing
Android-only installations retain `pipelines://run/<id>` for compatibility.
Native installs save a default from the web proxy's advertised LAN address/port.
Override it with `PIPELINES_WEB_PUBLIC_URL=https://pipelines.example.com ./install`;
reinstalls preserve that saved choice unless overridden. Custom services set the
environment variable in their service definition; `pipelines service enable`
preserves it. Docker Compose accepts the same variable, pointing to a separately
reachable authenticated web proxy. Apply service changes only after active work
is finished. Already-delivered notifications keep their original click target;
verify a new notification after configuration is installed.
A genuine event notifies once: a run that stays `waiting` is not republished on a
read or restart, and a stage `notify` policy that already covers the same event
(`on=waiting`, or a failure hook) suppresses the run-level default, so one event
means one notification. A failed delivery is logged, never fails the run, and is
not retried. The Android app shows the same information in one attention surface
ordered by importance — a run waiting for a decision, then a failed run, then a
run that finished since the operator last looked — derived from the run events the
server already pushes, so it needs no refresh and starts nothing.
## Tapping a notification
Run notifications (stage hooks and run-level waiting/failed/succeeded alerts)
set the ntfy `Click` to the app deep link `pipelines://run/<id>`, so a tap on the
phone opens the native Pipelines app at that run. When `PIPELINES_WEB_PUBLIC_URL`
is set to a valid HTTP(S) origin (no credentials, path, query or fragment), each
notification also gets one ntfy `view` action, **Open in browser**, pointing at
`<web>/runs/<id>`. Without it, or with an invalid value, only the app link is
sent. Queued run notifications derive both links from the run id at delivery,
so rows queued by older servers (which stored a web URL) also open the app.
## Chats that need you
When a chat asks the operator something — an unresolved question/form or a
permission (approval) request — the server publishes one notification to the
`system` destination: title `<chat title> needs your answer` (or `... needs your
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. 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
memory, and a form first seen already resolved or cancelled never notifies.
The record is not persisted, so a request still pending across a server
restart can notify once more.
- The server only observes a chat while at least one client is subscribed to
it, so questions raised while no client watches the session are not seen.
- Publishing is asynchronous within the same 30-second budget, never blocks or
fails chat handling, and failures are only logged. Nothing is sent when
`PIPELINES_NTFY_URL` is not configured.
## Notification settings
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` — Notify when any run ends | off | every **auto**-mode run that fails or succeeds notifies; otherwise only runs started with **Notify me** (`on`) announce their end |
| `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 |
| `ntfy_enabled` — Also send to ntfy | on | when off, nothing is published to ntfy; the app notification stream (below) still delivers every notification |
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 every
key. Unknown keys and non-boolean values are refused with an `error`
reply and nothing is written.
`run_finished` changed meaning: it once meant "auto runs announce success" and
defaulted on. It is now stored under `notify.any_run_ended`, so a value saved
under the old meaning (`notify.run_finished`) is ignored and every server starts
from the new default (off).
## Clearing notifications across devices
The app's in-app attention state is shared through the server: dismissing an
entry or using **Clear all** in the Needs-you sheet, and opening a chat (which
clears its **New** badge), clears it on every connected browser and phone at
once, and on a disconnected device when it next connects. The protocol is
`{"type":"attention_acks"}` (read the whole set) and
`{"type":"ack_attention","attention_acks":{"dismissed":["42:Failed"],"chat_seen":{"ses_x":1730000000000}}}`
(add to it). Both reply `attention_acks`, and every other connection receives an
`attention_acks_changed` frame with the change. Acknowledgements for deleted runs
or sessions, or older than 30 days, are pruned.
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)
Every notification the server publishes to ntfy — run waiting/failed/succeeded
alerts from the run outbox, stage `notify` hook events, and chat
question/approval/reply alerts — is first recorded in the `app_notifications`
table (kept 7 days) and streamed over `/connect` to clients that subscribe, so
the Pipelines app can post them itself. The same settings decide what is
recorded, so the stream carries exactly the set ntfy gets, with the same title,
message and `click` deep link. A stage hook with several attachments is one
stream notification per step event; explicit `type=ntfy` stages are not
streamed.
```text
→ {"type":"subscribe_notifications","id":"1","after":"run:7:3:waiting"}
← {"type":"notifications_subscribed","id":"1","notifications":[N...],"ids":["<cleared id>",...]}
← {"type":"notification","notification":N} (push)
← {"type":"notifications_cleared","ids":["run:7:3:waiting"]} (push)
→ {"type":"clear_notifications","id":"2","ids":["run:7:3:waiting"]}
← {"type":"notifications_cleared","id":"2","ids":[<ids it cleared>]}
N = {"id":"run:7:3:waiting","kind":"run_waiting","title":"Run needs your decision",
"message":"Run #7 · release · waiting for a human decision at stage approve",
"click":"pipelines://run/7","priority":3,"tags":[],
"created_at":"2026-11-01T10:00:00Z","group":"run:7"}
```
- `id` is stable: `run:<run>:<step>:<event>` (event `waiting`, `failed`,
`succeeded`, or `success` for a mid-run stage hook) or
`chat:<session>:<form|permission|reply|notify>:<id>`. `kind` is one of `run_waiting`,
`run_failed`, `run_succeeded`, `stage_failed`, `stage_succeeded`,
`chat_question`, `chat_approval`, `chat_reply`, `chat_notify`. `group` is `run:<id>` or
`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; 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
notifications cleared within the 7 days (newest first, at most 500) so a
reconnecting device can dismiss ones it still shows. Pushes follow in order;
subscribing again replaces the subscription.
- `clear_notifications` (the app's dismiss or tap) has the same effect as the
matching `ack_attention`: `run_waiting` dismisses `<run>:Decision`,
`run_failed`/`stage_failed` `<run>:Failed`, and a chat notification marks the
chat seen (clearing its other notifications too). Other subscribers receive
`notifications_cleared`; connections receive `attention_acks_changed`.
- Notifications are also cleared, with a push, by `ack_attention` from any
client, by a run leaving `waiting` (its waiting notifications), by deleting a
run, and by an answered or cancelled chat question or approval.
## Explicit delivery stage (optional)
The preceding stage must output three nonempty UTF-8 strings: `title`, `summary`,
and `markdown`. Title/summary must be single-line (256/2048 byte limits); Markdown
is limited to 1 MiB. Native delivery stages do not accept model prompts/tools or
inline credentials. They require `destination` and a `success` edge:
````markdown
# stage notify
```configs
type=ntfy
destination=system
```
```edges
success -> #success
error -> #failure
```
````
Configure the **pipeline server process** outside the pipeline file:
```sh
export PIPELINES_NTFY_URL='https://ntfy.your-domain.example/pipelines'
# Set PIPELINES_NTFY_TOKEN_FILE to the existing publishing token file.
go run ./cmd/pipelines-server
```
The URL includes one topic, without credentials, query parameters, or a fragment.
`destination=system` uses the same connection as hooks. Other destinations use
the named pattern: `destination=reports` reads
`PIPELINES_NTFY_REPORTS_URL` and `PIPELINES_NTFY_REPORTS_TOKEN` (or `_TOKEN_FILE`
pointing to a secret file). Set only one token source. Destination names
use lowercase letters, digits, and underscores. A token is optional only when
the configured server permits anonymous publishing; private deployments need it.
Never put tokens in a prompt, committed file, or chat. Environment credentials
are inherited by subprocesses: do not grant untrusted stages shell/code-execution
access. Prefer a dedicated publishing user with write-only access to this topic.
## Local server
The root `compose.yaml` runs **both the pipeline server and ntfy** with persistent
volumes, internal service networking, and a private topic. See the
[Docker + Android setup](docker.md) for bootstrap, credentials, and timezone
detection. The previous ntfy-only Compose file has been replaced. Isolated real
Docker health and publishing checks have passed; phone reception and the user's
remote Tailscale connectivity remain **not tested** locally.
Use a TLS reverse proxy or a private VPN (e.g. Tailscale). A phone cannot reach
your computer's `127.0.0.1`; that address is only for local publishing/proxying.
To bind the container to a particular LAN/VPN interface, explicitly set
`NTFY_BIND_ADDRESS` to that interface IP. Do not expose an unauthenticated server,
or send access tokens over public plain HTTP. Set `NTFY_BASE_URL` to the same
address your phone uses so attachment URLs resolve correctly. If the pipeline
server is another container, localhost is that container, not the ntfy host.
## Phone
### Tailscale address times out while LAN works
Use `http://<server-Tailscale-IP>:8090`, not port 80; enable Tailscale on both the
server and phone. The default Compose mapping binds ntfy to `0.0.0.0:8090`.
Binding to all interfaces does not bypass tailnet grants/ACLs, host firewalls,
or Docker forwarding rules. A timeout alone cannot identify which is blocking.
Do not disable firewalls or publicly forward this port as a workaround.
On the server, these are read-only diagnostics (the remote checks are not tested
from this development machine):
```sh
tailscale status
docker compose port ntfy 80
curl --connect-timeout 5 http://127.0.0.1:8090/v1/health
curl --connect-timeout 5 "http://$(tailscale ip -4):8090/v1/health"
```
If the host health checks succeed but the phone times out, check that the phone
is in the intended tailnet and that tailnet access rules/firewalls allow this
phone to reach server TCP 8090. Once reachable, log in as `phone-reader` for the
Tailscale server entry, separately from the LAN entry. Set `NTFY_BASE_URL` to a
phone-reachable address if attachment URLs currently point to a LAN-only address;
that setting is not a substitute for fixing a TCP timeout.
Install the ntfy app, add your own server, authenticate with the reader account,
and subscribe to `pipelines`. Ensure notifications and required background operation
are allowed. Outside your home network, both topic subscriptions and attachment
downloads need access to your server through VPN or public HTTPS.
For **iOS instant notifications**, ntfy's current documentation requires
`NTFY_UPSTREAM_BASE_URL=https://ntfy.sh` (or an APNS-connected upstream with a
custom app). The upstream sends wake-up requests; message content is fetched
from your instance. This is not completely independent of third-party push
infrastructure. Without upstream forwarding, delivery can be substantially
delayed. Phone delivery/background behavior has **not been tested** here.
## Execution and failure behavior
- Publishing is bounded to 20 seconds and does not follow redirects.
- No automatic publish retry: timeouts or malformed acknowledgments may mean the
notification was delivered but its acknowledgment was lost. Inspect ntfy
before retrying an ambiguous failure.
- For the optional native `type=ntfy` stage, a confirmed response adds `delivery` metadata (destination name, message ID,
attachment URL, filename) to the existing output. Failures take the error route
and are recorded in normal run/step audits, without remote response bodies or
credentials in diagnostics.
- Repeating the same run request key does not publish again. A new run or a graph
loop visiting delivery again can send another notification; content-level
"only new items" deduplication is not yet implemented. For the initial digest,
keep notification last with no feedback edge.
- Markdown reports remain available in pipeline run history even after ntfy expires its
attachment. Configure ntfy retention for your needs; its attachment directory
must be dedicated to ntfy, not shared with other files.
File-attachment bytes are stored by ntfy, not permanently archived in SQLite;
run metadata stores the delivered filename/URL, and workspace files may later
change. Download attachments before your ntfy retention expires.
Bundled starters need no schedule setup. **Research and report** shows a
`notify` hook on research failure; it only delivers once the system phone
connection is configured. Add a
`notify` block to the stages of your own workflow the same way. Adding a schedule activates it on publication,
so review it explicitly rather than copying a scheduled niche example.
References: [publishing](https://docs.ntfy.sh/publish/),
[server configuration](https://docs.ntfy.sh/config/),
[iOS self-hosting](https://docs.ntfy.sh/config/#ios-instant-notifications).
+1 -1
View File
@@ -245,7 +245,7 @@ so a Docker-era profile is not left Docker-linked. It never installs, upgrades o
downloads a harness. Container and host credentials and accounts remain independent and
are reused on reinstall/reconfigure. `./install` installs natively by default
(`--native` is equivalent); explicit `./install --docker` selects the Docker
server + ntfy installation.
server installation.
Fresh setup accepts `./install --docker --harness pi` to skip OpenCode
login. Existing setup can configure either harness independently. Pi setup does
not run a generation check; `provider-check --harness pi --model PROVIDER/MODEL`
+24 -19
View File
@@ -39,14 +39,10 @@ crafted link to a file the attacker has placed in the user's home directory.
> issue can contain instructions that an agent follows ("prompt injection").
> Agents with shell access can then leak your secrets or change files. Prefer
> the "ask" permission modes, and give pipeline stages only the tools they need.
> - **The notification server (ntfy) is on your local network.** It listens on
> every network interface over plain HTTP on port 8090, and the phone account
> uses your web password by default. Only subscribe over a network you trust or
> over Tailscale.
> - **Agents can spend money.** Runs have step and time limits but no spending
> cap unless you set one.
> - **Install and update pull code from the internet.** The installer builds the
> newest ntfy and OpenCode releases. `pipelines update` pulls this repository
> newest OpenCode releases. `pipelines update` pulls this repository
> and reinstalls without a signature check.
>
> What is protected by default: the server API is on loopback only and needs a
@@ -64,13 +60,13 @@ crafted link to a file the attacker has placed in the user's home directory.
| H2 | High | Web password = arbitrary code execution; step-up elevation is bypassed by agent permission modes | Depends on the password; reachable only from loopback/tailnet |
| H3 | High | Agents run unsandboxed as the user with the server's environment and can read every Pipelines secret (cookie HMAC key, server token, update-signing key) | High once prompt injection reaches a shell-capable agent |
| H4 | High | Pipeline stages get unrestricted shell by default (no `tools` block, or `shell` without a policy) | High for any pipeline that omits a shell policy |
| M1 | Medium | ntfy listens on all interfaces over HTTP; the phone account reuses the web password (sniffable, and guessable outside the proxy's limiter) | High that the port is LAN-reachable |
| M2 | Medium | Supply chain floats: newest OpenCode, Pi and ntfy resolved at install time; unpinned base images; unchecked SDK zip; `pipelines update` has no signature check | Low per event, wide impact |
| M1 | Medium | **Resolved (ntfy removed).** ntfy listened on all interfaces over HTTP; the phone account reused the web password (sniffable, and guessable outside the proxy's limiter) | None: no ntfy port is installed |
| M2 | Medium | Supply chain floats: newest OpenCode and Pi resolved at install time (ntfy no longer installed); unpinned base images; unchecked SDK zip; `pipelines update` has no signature check | Low per event, wide impact |
| M3 | Medium | Docker mode (opt-in) exposes the unauthenticated API on 0.0.0.0 | Only with `--docker` |
| M4 | Medium | `show_html` previews load remote images/CSS (exfil beacons) and allow links that escape the sandbox, including to the app's own origin | Medium |
| M5 | Medium | No spending cap by default and no global concurrency cap | Medium |
| M6 | Medium | Chat transcripts and notifications are not redacted | Medium |
| L* | Low | Links open without confirmation; OSC 52 clipboard writes; ntfy click-link to any URL; `ws://` peers; TOCTOU in `/files`; debug-keystore APK signing; and more | |
| L* | Low | Links open without confirmation; OSC 52 clipboard writes; notification `link=` to any URL; `ws://` peers; TOCTOU in `/files`; debug-keystore APK signing; and more | |
---
@@ -83,7 +79,7 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
```
127.0.0.1:8080 # Go server API
*:8090 # ntfy
*:8090 # ntfy (removed since; see M1)
*:8082 # web proxy (wildcard bind, filtered per connection)
```
@@ -133,7 +129,15 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
can reach the sign-in page.
- **Mitigation:** restrict it with Tailscale ACLs. Mention this in the README.
#### M1. ntfy `:8090` on every interface, phone account = web password (Medium)
#### M1. ntfy `:8090` on every interface, phone account = web password (Medium) — resolved
- **Resolution (2026-12-03):** ntfy was removed from Pipelines. Notifications
reach every client through the server's own app notification stream over the
authenticated `/connect` connection (see `docs/notifications.md`). The
installer no longer builds, configures or starts ntfy, and creates no phone
account; a reinstall stops and deletes an existing ntfy and its data, and
`./uninstall` removes any leftover. Port 8090 is no longer opened. The
original finding is kept below for the record.
- **Evidence:**
- `scripts/setup-native.py:672`
@@ -486,11 +490,12 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
- **Mitigation:** confirm OSC 52 writes or put them behind a setting, and show
the link target on hover.
#### P3. ntfy click links to arbitrary URLs (Low)
#### P3. Notification `link=` targets to arbitrary URLs (Low)
- **Evidence:** `internal/server/notify_link.go:87-103` accepts any absolute
http(s) `link=` written by the agent into the run's `public/` directory.
- **Risk:** a phishing link delivered as a trusted notification.
- **Risk:** a phishing link delivered as a trusted notification. (ntfy is gone;
the same `link=` is now the app notification's tap target.)
- **Mitigation:** restrict to the configured web origin, or route through an
interstitial page.
@@ -498,6 +503,9 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
#### M2a. Harness and ntfy versions resolve to "newest" at install time (Medium)
- **Update:** ntfy is no longer installed, so its part of this finding is
resolved; the harness part stands.
- **Evidence:**
- `scripts/resolve-releases.py:1-27` picks the newest OpenCode v2 tag (GitHub
API), then its GHCR digest, and the newest Pi version from npm.
@@ -595,8 +603,7 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
- No secrets on command lines or in service unit files: the launchd plist
carries only `HOME` and `PATH`.
- Inline `PIPELINES_NTFY_TOKEN` is refused (`internal/installation/service.go:224-225`).
- **Docker ntfy token (Low):** world-readable inside a 0700 directory
(`scripts/save-ntfy-token.py:16`, `mode=0o444`). Docker mode only.
- ~~**Docker ntfy token (Low)**~~: resolved; ntfy and its token were removed.
- **M6. No redaction of transcripts or notifications (Medium):**
- Redaction exists only for failure evidence (`internal/stage/diagnostics.go:55-70`)
and turn-diff snapshots, which skip `.env*`, `*.pem`, `.ssh`, `.aws` and
@@ -732,9 +739,7 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
3. **Scrub the agent environment** (H3): drop `PIPELINES_*_FILE`,
`PIPELINES_WEB_AUTH_FILE` and token variables from every harness and `!`
child environment. *Small.*
4. **ntfy off the LAN by default** (M1): bind loopback + tailnet (or serve it
through `tailscale serve`), give the phone a random reader password or token,
and make LAN ntfy an opt-in. *Small to medium.*
4. ~~**ntfy off the LAN by default** (M1)~~: done by removing ntfy.
5. **Docker safe defaults** (M3): bind 127.0.0.1, generate a token, and refuse a
non-loopback bind without a token. *Small.*
6. **Deny-list secret paths** in `/files`, `show_file` and listings (F2).
@@ -744,7 +749,7 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
8. **Block remote loads in HTML previews** (M4): inject a strict meta CSP and
refuse same-origin links. *Small.*
9. **Default a run budget and a global run cap** (M5). *Small to medium.*
10. **Pin the supply chain** (M2): commit reviewed OpenCode, Pi and ntfy
10. **Pin the supply chain** (M2): commit reviewed OpenCode and Pi
versions and digests, pin base images by digest, verify the SDK zip's
sha256, and verify signed tags in `pipelines update`. *Medium.*
11. **Make elevation a real second factor** (H2): OS password via
@@ -757,7 +762,7 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
13. **Smaller items:**
- Default "Remember me" off.
- Disable mDNS when the LAN route is off.
- Confirm external links, OSC 52 writes and ntfy click links.
- Confirm external links, OSC 52 writes and notification `link=` targets.
- Redact known secrets from transcripts.
- Refuse `ws://` peers off the tailnet.
- Use a real APK keystore.
+1 -1
View File
@@ -140,7 +140,7 @@ func TestSkillUpgradeAddsSelfContainedNotificationReference(t *testing.T) {
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"on=failure", "on=success,failure", "destination=system", "cancellation", "output.markdown"} {
for _, want := range []string{"on=failure", "on=success,failure", "cancellation", "link=", "type=ntfy"} {
if !strings.Contains(string(data), want) {
t.Fatal("missing local recipe", want)
}
+1 -1
View File
@@ -26,7 +26,7 @@ regenerate, or a file you rewrote.
| `show_run` | `run_id`, `title?`, `replace?` | A live card for a run: pipeline, title, status, current stage, duration; it updates as the run progresses and opens the run when tapped. |
| `schedule_followup` | `message`, and `at?` or `after_minutes?`, or `run_id?` with `on?` | Queue a prompt to yourself in this chat: 1 minute to 7 days ahead (`at` is RFC 3339), or when run `run_id` reaches `on`: `finished` (default; it ended) or `attention` (it waits on a human decision, or ended), delivered after 7 days at the latest with the run's state appended. A run that already meets `on` is refused (act on it now). It is a scheduled message from "Agent follow-up" the operator can remove; it does not hold the operator's own messages back, and is delivered when the chat is free. At most 3 pending per chat. The result names the follow-up id and lists the pending ones. Do not wait for it in the current turn. |
| `cancel_followup` | `id` | Remove one of this chat's undelivered follow-ups by the id `schedule_followup` returned; the result lists those still pending. |
| `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. |
| `notify` | `title`, `message`, `priority?` | A notification on every Pipelines app the operator is signed in to (web tabs, desktop, Android, iOS); 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
+2 -1
View File
@@ -233,7 +233,8 @@ library (`pipelines skills list`), one per line: `name` loads the latest version
at run start, `name@N` pins version N. An empty or missing block loads none.
Drafts and publications are rejected for an unknown skill, a missing version,
`@0`/non-numeric versions, a skill listed twice (pinned or not) and a `skills`
block on a human or ntfy stage.
block on a human stage. `type=ntfy` stages were removed and are rejected; use
a stage `notify` hook instead.
```skills
review-checklist
@@ -1,7 +1,8 @@
# Notification authoring
Use the server's existing system phone connection. Never read, copy or request
tokens/passwords, edit server settings, or call curl to publish while authoring.
Notifications go to the operator's signed-in Pipelines apps (web, Android,
iOS, macOS) through the server's own notification stream; there is nothing to
configure. Never edit server settings or call curl to publish while authoring.
Validation is not delivery. Do not send a test notification or run the workflow
without explicit approval.
@@ -11,8 +12,8 @@ A fenced `notify` block belongs inside an existing stage. `on` accepts `success`
`failure`, or `success,failure` — not `error`. A failure means an execution error,
the `error` outcome, or a route to `#failure`; other completed outcomes are success.
Hooks send stage events, not a separate run-finished event. They leave the graph,
handoffs, tools, model and run verdict unchanged. Delivery failures are audited
separately and do not turn a successful stage into failure.
handoffs, tools, model and run verdict unchanged. A notification problem is
audited separately and does not turn a successful stage into failure.
For the common sequential workflow whose failure/blocked edges terminate:
@@ -45,35 +46,25 @@ can send repeated events. Inspect routing; explain these limits rather than prom
exactly one final notification for every possible termination. Do not reroute
failures through a successful publisher and accidentally turn failure into success.
## Attachments only when requested
## Opening an artifact or a link
Omit `artifacts` for an event-only alert. `artifacts=markdown` attaches a nonempty
string in `output.markdown`; a field named `report` is not automatically attached.
Only add/rename output fields and corresponding prompts if a report attachment is
requested, preserving downstream handoffs. If no attachment is produced (including
on execution error), an event-only notification is still attempted.
`artifacts=files` attaches the workspace-relative paths in `output.artifacts`;
`artifacts=markdown,files` selects both. Each file gets its own notification, so
attachments may mean more than one message. Files must be regular, nonsymlinked,
at most 1 MiB, with at most 10 listed. Absolute/traversal/hidden paths, `secrets/`,
database/key paths and `node_modules/` are rejected. This is not content scanning.
Do not promise phone reception from structural validation.
`artifacts=` (and `destination=`) lines in older definitions still parse but
do nothing: they configured ntfy attachments, and ntfy was removed. Do not add
them.
`open=<pattern>` attaches one artifact from the run's shared `public/` directory
to the app notification and makes its tap open that artifact. The pattern is a
relative glob with no absolute path, `..`, or hidden path segment; if several
files match, the most recently modified file wins. Without `open=`, exactly one
regular file in `public/` is attached automatically. Zero or multiple files
produce no attached artifact. This is separate from ntfy's `artifacts=` keys.
produce no attached artifact.
`link=<pattern>` makes a tap on the phone notification (ntfy and app) open a
URL the stage produced, such as a published doc. The pattern follows the `open=`
rules; the matched file's first non-empty line must be an absolute http(s) URL
without credentials or fragment. The run stays reachable from the notification's
run action (ntfy uses the link only when `PIPELINES_WEB_PUBLIC_URL` gives it a
browser run view), and `open=` still attaches its artifact; the link file itself
is never attached. A missing file or invalid URL keeps the usual tap target and
`link=<pattern>` makes a tap on the notification open a URL the stage
produced, such as a published doc. The pattern follows the `open=` rules; the
matched file's first non-empty line must be an absolute http(s) URL without
credentials or fragment. The run stays reachable from the notification's run
action, and `open=` still attaches its artifact; the link file itself is never
attached. A missing file or invalid URL keeps the usual tap target and
is noted on the notification receipt:
```notify
@@ -81,40 +72,16 @@ on=success
link=standup-link.txt
```
## Optional explicit delivery stage
## No delivery stage
Use native delivery only when the user needs delivery as an explicit routed stage
(e.g. delivery failure must fail the run), not for an ordinary completion alert.
The preceding stage must output nonempty UTF-8 strings `title`, `summary`, and
`markdown`. Title/summary are single-line, at most 256/2048 bytes; Markdown is at
most 1 MiB. The native stage does not accept model prompts or tools and does not
need an output block:
````markdown
# stage publish
```configs
type=ntfy
destination=system
```
```edges
success -> #success
error -> #failure
```
````
`destination=system` uses the server's existing system connection. Native delivery
adds retained delivery metadata on success and follows its error edge on failure.
Neither hooks nor native delivery automatically retry ambiguous publishes; a new
run or repeated visit can send again. An upstream execution error does not reliably
produce the required three strings, so adding this stage alone cannot cover it.
The former `type=ntfy` delivery stage was removed. Validation rejects it with
"ntfy stages were removed; notifications go to the Pipelines apps — use the
stage notify hook". Use a `notify` hook on the stage whose result matters.
## Automatic run-attention notifications
Independently of any `notify` block, the server publishes one run-level attention
notification to the same already-configured `system` destination when a run needs a
person: when it enters `waiting` (a human stage asked for a decision), or when it
Independently of any `notify` block, the server records one run-level attention
notification when a run needs a person: when it enters `waiting` (a human stage asked for a decision), or when it
has an unexpected failure or interruption. A deliberate route to `#failure` with
its reason is recorded as an expected failure: it remains in Runs but does not
notify or appear in Needs you. Explicit `run_finished`/`on` completion notifications
@@ -124,19 +91,13 @@ Runs marked `on` notify at completion, while `off` disables these notifications.
Queued and running runs send nothing. You do not author these; they are the operator
default, so a run you never wired still reaches the operator.
The payload names the run and its pipeline. When the operator configures
`PIPELINES_WEB_PUBLIC_URL` on the server, run notifications and stage hooks carry
the authenticated web link `<origin>/runs/<id>`. Native installs default this to
their advertised web address; custom/VPN domains require the operator's actual
phone-reachable URL. Never use the API listener or ntfy URL, nor put credentials
in the click link. Existing Android-only installations without that setting keep
`pipelines://run/<id>`. Invalid origins omit the link and log a warning. Existing
delivered alerts are not rewritten. Do not change service settings or send a test
notification merely to author a workflow. A run that stays waiting is not
The payload names the run and its pipeline; a tap opens the run in the app.
Do not change service settings or send a test notification merely to author a
workflow. A run that stays waiting is not
republished on a read or restart, and a
stage `notify` policy that already covers the same event (`on=waiting`, or a failure
hook) suppresses the run-level default, so one genuine event means one notification.
A delivery failure is logged, never fails the run, and is not retried.
A notification problem is logged and never fails the run.
The app shows the same information in one attention surface ordered by importance:
a run waiting for a decision, then a failed run, then a run that finished since the
@@ -4,7 +4,7 @@ Pipelines turns a reusable process into sequential stages with explicit handoffs
outcome routing and retained evidence. A Go CLI/TUI and the Pipelines app connect
to an execution server; the server owns execution and SQLite history, the stage's
harness (OpenCode, Claude Code or Pi) owns model/tool sessions, operator chats
run on OpenCode, Claude Code or Codex, and optional ntfy delivers notifications. It is technology-neutral, not a
run on OpenCode, Claude Code or Codex, and the server delivers notifications to the Pipelines apps. It is technology-neutral, not a
parallel/distributed task engine or a guarantee that model reports are correct.
## Lifecycle and location
@@ -54,8 +54,7 @@ inputs/outputs, status/errors, audit transcripts, session ownership/references,
reported per-stage model usage (tokens/cost), retry links, schedules/state,
notification receipts and file changes. Not everything
is in that database: drafts/settings are client files; complete OpenCode sessions
and credentials use OpenCode storage; repository artifacts are files; ntfy has its
own storage. A pipeline ZIP is not a full backup of these components.
and credentials use OpenCode storage; repository artifacts are files. A pipeline ZIP is not a full backup of these components.
Never merge or sync live SQLite files using generic file synchronization. Do not
delete databases, sessions, volumes or credentials to repair a workflow.
@@ -162,7 +161,7 @@ source-built test binaries, draft/publication/transfer and restart persistence w
inference, notifications or deployment. It is not a live-provider or phone test.
That is a developer test fixture, not the native installer. End-user installation
runs natively through `./install` by default (`scripts/setup-native.py`, with
`--native` equivalent); the Docker server + ntfy installation is explicit with
`--native` equivalent); the Docker server installation is explicit with
`./install --docker`.
## Retained stage file changes
+2 -2
View File
@@ -19,8 +19,8 @@ overwritten. A ZIP includes versioned manifest/checksums, names and pinned Markd
definitions. Exported version numbers are provenance, not portable database IDs.
**Definition transfer is not full backup or database synchronization.** No older
versions, run history/diffs, drafts, repository files, provider credentials or ntfy
storage/settings are included. Archives are private files, not encrypted; prompts
versions, run history/diffs, drafts, repository files, provider credentials or
notification settings are included. Archives are private files, not encrypted; prompts
can contain secrets. Limits are 1,000 definitions, 1 MiB each, 32 MiB total source.
## Import and existing-name conflicts
-3
View File
@@ -913,9 +913,6 @@ func (a App) Run(ctx context.Context, args []string) error {
}
case "connection":
fmt.Fprintln(a.Out, "Server:", o.url)
for _, n := range r.NotificationEndpoints {
fmt.Fprintf(a.Out, "ntfy: %s · topic %s\n", n.ServerURL, n.Topic)
}
if note := identityNote(r); note != "" {
fmt.Fprintln(a.Out, "Note:", note)
}
+4 -2
View File
@@ -62,17 +62,19 @@ func TestCLIHelpDoesNotNeedServer(t *testing.T) {
}
func TestCLIStatusAndStatistics(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
run, _, _ := setup(t)
output, err := run("status")
if err != nil {
t.Fatal(err)
}
for _, text := range []string{"Pipelines server", "ntfy", "not configured", "Port:"} {
for _, text := range []string{"Pipelines server", "Port:"} {
if !strings.Contains(output, text) {
t.Fatal("missing CLI status", text, output)
}
}
if strings.Contains(output, "ntfy") {
t.Fatal("CLI status still reports ntfy", output)
}
output, err = run("status", "--json")
if err != nil {
t.Fatal(err)
+2 -2
View File
@@ -32,7 +32,7 @@ func TestInstalledDockerDefaultAvoidsUnconfiguredServerAndHonorsOverrides(t *tes
if err := wsjson.Read(ctx, conn, &request); err != nil {
return
}
wsjson.Write(ctx, conn, protocol.Message{Type: protocol.Status, ID: request.ID, Status: &protocol.SystemStatus{Ntfy: protocol.ServiceStatus{Health: health}}})
wsjson.Write(ctx, conn, protocol.Message{Type: protocol.Status, ID: request.ID, Status: &protocol.SystemStatus{Hostname: health}})
}))
t.Cleanup(srv.Close)
return "ws" + strings.TrimPrefix(srv.URL, "http") + "/connect"
@@ -56,7 +56,7 @@ func TestInstalledDockerDefaultAvoidsUnconfiguredServerAndHonorsOverrides(t *tes
t.Fatal(err, stderr.String())
}
var status protocol.SystemStatus
if json.Unmarshal(out.Bytes(), &status) != nil || status.Ntfy.Health != want {
if json.Unmarshal(out.Bytes(), &status) != nil || status.Hostname != want {
t.Fatal("wrong server selected", out.String())
}
}
+3 -3
View File
@@ -48,8 +48,8 @@ var notes = map[string]string{
"repair-session-export": "Read-only native session readback for a settled run visit, using its exact recorded session/backend. Writes a versioned repair file and appends repair evidence, preserving originals and the run outcome. Empty/failed/partial repairs remain warnings; upstream session availability cannot be guaranteed.",
"version": "Identify the local CLI binary without connecting to a server. --version is an alias. Use ping --json to identify the running server separately.",
"ping": "Pong includes the running server's compiled build.version, build.commit and build.dirty (null when unknown). This identifies the server, not the client or runtime workspace. Older servers omit build. The client compares its own build/protocol against the server: a same-protocol build mismatch prints one warning to stderr, a server speaking a newer protocol fails the command, and a response carrying a field this client does not model prints a one-time unrecognized-field notice instead of dropping it silently.",
"connection": "Prints the server endpoint and phone notification endpoints. Like ping, it reports the client/server build relationship and warns or fails rather than silently proceeding against a mismatched server.",
"status": "Reports server, host and ntfy publishing health. The client compares its build/protocol against the server and warns once (or fails on a newer protocol) rather than proceeding silently.",
"connection": "Prints the server endpoint. Like ping, it reports the client/server build relationship and warns or fails rather than silently proceeding against a mismatched server.",
"status": "Reports server health, ports and the server computer's addresses. The client compares its build/protocol against the server and warns once (or fails on a newer protocol) rather than proceeding silently.",
"export": "Without a name, select pipelines with Space and save a ZIP in the current directory. --output writes a portable definition bundle; --all skips selection. One name without --output prints Markdown as before. No runs, credentials or old versions are exported.",
"import": "Select definitions from a ZIP. Identical existing definitions are skipped. For differing names, choose keep existing, keep both under a new name, or use imported as a new version (history retained). --on-conflict supplies an explicit automation policy; --yes only approves final publication. Schedules may activate; no run history is imported.",
"new": "Create an optional template copy or a single-stage starter. Opens the configured default harness; --harness opencode|pi|nvim overrides it. No submission is performed.",
@@ -80,7 +80,7 @@ var serviceHelp = map[string]string{
"skill": "pipelines skill install installs/updates the bundled workflow skill in OpenCode and detected Claude Code and Codex skill roots without changing login/config or user-modified skills. ./install includes this step.",
"service": "Configure per-user OS autostart: pipelines service enable. Runs use the directory you invoke pipelines run from. Use --print to preview, service status to inspect, and service disable before uninstalling. Linux uses systemd; macOS uses launchd. No sudo.",
"serve": "Run the native server in the foreground. Its flags are documented by pipelines serve --help. Installation never starts it automatically.",
"start": "Start the per-user native pipeline server and this installation's Docker ntfy together.",
"start": "Start the per-user native pipeline server and its authenticated web proxy.",
"stop": "Stop both services. Active execution is interrupted; file changes are not rolled back.",
"restart": "Stop, then start both services, retaining definitions, run history, and credentials.",
"doctor": "Check both health endpoints and host OpenCode API discovery; does not execute a model.",
+1 -1
View File
@@ -20,7 +20,7 @@ EXECUTE
chat-adopt <session-id> Adopt an existing OpenCode, Claude Code or Codex chat
draft-delete <draft.md> Delete a selected retained draft and its metadata
connection Server and public phone connection (no secrets)
status Server/ntfy health, ports and server computer IPs
status Server health, ports and server computer IPs
stats All-history usage, pipeline counts and daily activity
ping Check connection and identify the running server build
version Identify this CLI build without connecting (--version)
+4 -4
View File
@@ -5,11 +5,11 @@ import (
"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.
// TestMain isolates the package from the operator's environment: a developer
// shell may export the installed server's web origin, which tests must not
// pick up.
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"} {
for _, name := range []string{"PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
+13 -2
View File
@@ -17,7 +17,12 @@ type Config struct {
OpenCode string `json:"opencode"`
OpenCodeEnv map[string]string `json:"opencode_env"`
Path string `json:"path"`
Ntfy struct {
// Mode is "native" for a native installation (the per-user supervisor)
// and "docker" or empty for Compose.
Mode string `json:"mode"`
// LegacyNtfy is read only for its mode: manifests written before ntfy was
// removed recorded a native installation as ntfy.mode "native".
LegacyNtfy struct {
Mode string `json:"mode"`
} `json:"ntfy"`
Web struct {
@@ -70,7 +75,7 @@ func Load(executable string) (*Config, error) {
if config.Format != 1 || config.Prefix != prefix || config.ServerPort < 1024 || config.ServerPort > 65535 {
return nil, fmt.Errorf("invalid managed installation manifest")
}
if inferred && config.Ntfy.Mode != "native" {
if inferred && !config.Native() {
return nil, nil
}
if inferred {
@@ -82,6 +87,12 @@ func Load(executable string) (*Config, error) {
return &config, nil
}
// Native reports whether the manifest describes a native installation, in the
// current form or the one written before ntfy was removed.
func (c Config) Native() bool {
return c.Mode == "native" || (c.Mode == "" && c.LegacyNtfy.Mode == "native")
}
func (c Config) Environment() error {
for key, value := range c.OpenCodeEnv {
switch key {
+29 -2
View File
@@ -84,7 +84,7 @@ func nativeFixture(t *testing.T) (string, string) {
t.Fatal(err)
}
config := Config{Format: 1, Prefix: root, ServerPort: 18080, Python: filepath.Join(root, "python3")}
config.Ntfy.Mode = "native"
config.Mode = "native"
data, _ := json.Marshal(config)
if err = os.WriteFile(filepath.Join(root, "pipelines-install.json"), data, 0600); err != nil {
t.Fatal(err)
@@ -156,7 +156,7 @@ func TestNativeDiscoveryRejectsSymlinkManifestAndMismatchedPrefix(t *testing.T)
os.Symlink(target, manifest)
} else {
config := Config{Format: 1, Prefix: "/another/prefix", ServerPort: 18080}
config.Ntfy.Mode = "native"
config.Mode = "native"
data, _ := json.Marshal(config)
os.WriteFile(manifest, data, 0600)
}
@@ -166,3 +166,30 @@ func TestNativeDiscoveryRejectsSymlinkManifestAndMismatchedPrefix(t *testing.T)
})
}
}
// A manifest written before ntfy was removed marks a native installation as
// ntfy.mode "native" (with the rest of the old ntfy block); it must still be
// selected until a reinstall rewrites it with the top-level mode.
func TestLegacyNtfyManifestStillSelectsNativeInstallation(t *testing.T) {
t.Setenv("PIPELINES_PREFIX", "")
root, binary := nativeFixture(t)
legacy := map[string]any{"format": 1, "prefix": root, "server_port": 18080, "python": filepath.Join(root, "python3"),
"ntfy_port": 8090, "topic": "pipelines", "username": "phone-reader",
"ntfy": map[string]any{"mode": "native", "bin": filepath.Join(root, "bin", "ntfy"), "config": filepath.Join(root, "data", "ntfy", "server.yml"), "version": "v2.38.1"}}
data, _ := json.Marshal(legacy)
if err := os.WriteFile(filepath.Join(root, "pipelines-install.json"), data, 0600); err != nil {
t.Fatal(err)
}
loaded, err := Load(binary)
if err != nil || loaded == nil || !loaded.Native() {
t.Fatal("legacy native manifest not selected", loaded, err)
}
docker := Config{Mode: "docker"}
docker.LegacyNtfy.Mode = "native"
if docker.Native() {
t.Fatal("explicit docker mode overridden by the legacy block")
}
if !(Config{Mode: "native"}).Native() || (Config{}).Native() {
t.Fatal("top-level mode not honoured")
}
}
+5 -8
View File
@@ -77,8 +77,8 @@ func (d serviceDefinition) render(platform string) (string, error) {
}
// Only explicitly supported settings are captured, never the complete environment
// or provider credentials. File-based notification credentials remain references.
var serviceEnvironmentKeys = []string{"PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_OPENCODE_ENDPOINT_USERNAME", "PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL", "PIPELINES_CLAUDE"}
// or provider credentials. File-based credentials remain references.
var serviceEnvironmentKeys = []string{"PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_OPENCODE_ENDPOINT_USERNAME", "PIPELINES_WEB_PUBLIC_URL", "PIPELINES_CLAUDE"}
func envValues(env map[string]string) []string {
var values []string
@@ -169,7 +169,7 @@ func ServiceCommand(ctx context.Context, executable string, args []string, out,
if err != nil {
return err
}
if config != nil && config.Ntfy.Mode == "native" {
if config != nil && config.Native() {
// Use an internal verb so an older manager fails instead of forwarding
// "service" back into this CLI recursively. Reinstall refreshes manage.py.
command := exec.CommandContext(ctx, config.Python, append([]string{filepath.Join(config.Prefix, "lib/manage.py"), "--prefix", config.Prefix, "native-service"}, args...)...)
@@ -182,7 +182,7 @@ func ServiceCommand(ctx context.Context, executable string, args []string, out,
if config == nil && os.Getenv("PIPELINES_PREFIX") != "" {
return fmt.Errorf("PIPELINES_PREFIX does not select an existing installation; refusing to configure a standalone service")
}
help := "Usage: pipelines service enable [--print]\n pipelines service disable | status\nNative installs manage the existing server/web/ntfy supervisor, selected by PIPELINES_PREFIX or the installed CLI path.\nAutostart is per-user, at login. enable starts now; --print only previews.\nStandalone developer binaries also support enable --db FILE --addr HOST:PORT.\nRuns use the directory you invoke pipelines run from.\n"
help := "Usage: pipelines service enable [--print]\n pipelines service disable | status\nNative installs manage the existing server/web supervisor, selected by PIPELINES_PREFIX or the installed CLI path.\nAutostart is per-user, at login. enable starts now; --print only previews.\nStandalone developer binaries also support enable --db FILE --addr HOST:PORT.\nRuns use the directory you invoke pipelines run from.\n"
if len(args) == 0 || args[0] == "--help" || args[0] == "help" {
_, err := io.WriteString(out, help)
return err
@@ -221,9 +221,6 @@ func ServiceCommand(ctx context.Context, executable string, args []string, out,
if len(f.Args()) != 0 {
return fmt.Errorf("service enable takes no positional arguments")
}
if os.Getenv("PIPELINES_NTFY_TOKEN") != "" {
return fmt.Errorf("use PIPELINES_NTFY_TOKEN_FILE for autostart; inline tokens are not saved")
}
binary, err := ServerExecutable(executable)
if err != nil {
return err
@@ -242,7 +239,7 @@ func ServiceCommand(ctx context.Context, executable string, args []string, out,
d.Environment[key] = value
}
}
for _, key := range []string{"PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_NTFY_TOKEN_FILE"} {
for _, key := range []string{"PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE"} {
if value := d.Environment[key]; value != "" && (key != "PIPELINES_OPENCODE" || strings.ContainsRune(value, filepath.Separator)) {
absolute, err := filepath.Abs(value)
if err != nil {
+1 -2
View File
@@ -41,7 +41,7 @@ func TestSystemdDefinitionAcceptedByNativeValidator(t *testing.T) {
}
func TestServiceDefinitionsQuotePathsAndKeepEnvironmentLimited(t *testing.T) {
d := serviceDefinition{Binary: `/some bin/server`, Directory: `/repo "quoted" 100% $USER`, Args: []string{"-db", `/repo "quoted" 100% $USER/data.db`}, Environment: map[string]string{"PATH": "/usr/bin:/custom bin", "PIPELINES_NTFY_TOKEN_FILE": "/secret & token", "PIPELINES_CLAUDE": "/custom bin/claude", "PROVIDER_SECRET": "must-not-export"}}
d := serviceDefinition{Binary: `/some bin/server`, Directory: `/repo "quoted" 100% $USER`, Args: []string{"-db", `/repo "quoted" 100% $USER/data.db`}, Environment: map[string]string{"PATH": "/usr/bin:/custom bin", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE": "/secret & token", "PIPELINES_CLAUDE": "/custom bin/claude", "PROVIDER_SECRET": "must-not-export"}}
for _, platform := range []string{"linux", "darwin"} {
text, err := d.render(platform)
if err != nil {
@@ -142,7 +142,6 @@ func TestServiceConfigurationPreviewAndLifecycleWithMockOSManager(t *testing.T)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config"))
t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data"))
t.Setenv("PATH", bin)
t.Setenv("PIPELINES_NTFY_TOKEN", "")
server := filepath.Join(bin, "pipelines-server")
if err := os.WriteFile(server, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil {
t.Fatal(err)
+3 -4
View File
@@ -13,8 +13,8 @@ import (
// Environment keys for the operator-supplied OpenCode endpoint. The endpoint
// itself is opt-in: when none of the flag, these variables or the recorded
// setting is present the server keeps today's spawned default. The password is
// accepted only through a private file reference (never inline), mirroring the
// ntfy token-file rule; an optional username overrides the detected default.
// accepted only through a private file reference (never inline); an optional
// username overrides the detected default.
const (
EndpointEnvKey = "PIPELINES_OPENCODE_ENDPOINT"
EndpointPasswordFileEnvKey = "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE"
@@ -56,8 +56,7 @@ func NormalizeEndpointURL(raw string) (string, error) {
}
// ReadEndpointCredentialFile reads the optional endpoint password from a private
// file reference, mirroring the ntfy token-file rule: a regular, single-owner
// 0600 file with a bounded read. An empty path yields no password, so an endpoint
// file reference: a regular, single-owner 0600 file with a bounded read. An empty path yields no password, so an endpoint
// that authenticates with the default user only keeps working.
func ReadEndpointCredentialFile(path string) (string, error) {
if strings.TrimSpace(path) == "" {
+7 -111
View File
@@ -1,115 +1,11 @@
package pipeline
import (
"context"
"database/sql"
"errors"
"time"
)
// ChatNotification is one chat phone push (ntfy) in the durable outbox. It
// follows the run notification outbox (run_notifications.go): a row is leased
// for a bounded attempt, a crash during a lease is recovered when the lease
// expires, and attempts are bounded. ID is the chat's app notification id, so
// an enqueue is idempotent and a notification the operator already cleared in
// the app is never published late.
type ChatNotification struct {
ID, SessionID, Title, Body, Click string
// SequenceID is the ntfy sequence id the push is published with (so a later
// clear dismisses it on the phone); "" publishes without one.
SequenceID string
Priority int
Attempts int
}
// ChatNotificationAttempts bounds publication attempts per chat push.
const ChatNotificationAttempts = 5
// chatNotificationLease is how long one claimed attempt owns its row.
const chatNotificationLease = 60
// chatNotificationRetention bounds how long settled rows are kept.
const chatNotificationRetention = 7 * 24 * time.Hour
func (s *Store) initChatNotifications() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_notifications (
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, click TEXT NOT NULL,
sequence_id TEXT NOT NULL DEFAULT '', priority INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
next_attempt INTEGER NOT NULL DEFAULT 0, diagnostic TEXT NOT NULL DEFAULT '', message_id TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS chat_notifications_due ON chat_notifications(status,next_attempt);`)
// dropChatNotifications removes the chat_notifications table, the durable
// outbox an earlier server used to retry chat pushes to ntfy. ntfy was removed:
// chat notifications are recorded once on the app notification stream
// (app_notifications), so the old rows have nowhere to go and nothing reads
// them.
func (s *Store) dropChatNotifications() error {
_, err := s.db.Exec(`DROP TABLE IF EXISTS chat_notifications`)
return err
}
// EnqueueChatNotification records one chat push once (by id) and prunes
// settled rows past retention.
func (s *Store) EnqueueChatNotification(ctx context.Context, n ChatNotification, now time.Time) error {
if _, err := s.db.ExecContext(ctx, `DELETE FROM chat_notifications WHERE created_at<? AND status NOT IN ('pending','sending')`, now.Add(-chatNotificationRetention).Unix()); err != nil {
return err
}
_, err := s.db.ExecContext(ctx, `INSERT INTO chat_notifications(id,session_id,title,body,click,sequence_id,priority,created_at)
VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING`, n.ID, n.SessionID, n.Title, n.Body, n.Click, n.SequenceID, n.Priority, now.Unix())
return err
}
// ClaimChatNotification atomically leases one due push. A push whose app
// notification was cleared before it went out (the operator already answered
// in the app) is settled as cleared instead of published.
func (s *Store) ClaimChatNotification(ctx context.Context, now int64) (*ChatNotification, error) {
if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='cleared',diagnostic='cleared in the app before publication'
WHERE status IN ('pending','sending') AND next_attempt<=? AND EXISTS(SELECT 1 FROM app_notifications a WHERE a.id=chat_notifications.id AND a.cleared_at<>0)`, now); err != nil {
return nil, err
}
if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='failed',diagnostic='publisher acknowledgement unknown after final lease expired'
WHERE status='sending' AND attempts>=? AND next_attempt<=?`, ChatNotificationAttempts, now); err != nil {
return nil, err
}
n := new(ChatNotification)
err := s.db.QueryRowContext(ctx, `UPDATE chat_notifications SET status='sending',attempts=attempts+1,next_attempt=?
WHERE rowid=(SELECT rowid FROM chat_notifications WHERE status IN ('pending','sending') AND attempts<? AND next_attempt<=? ORDER BY next_attempt,rowid LIMIT 1)
RETURNING id,session_id,title,body,click,sequence_id,priority,attempts`, now+chatNotificationLease, ChatNotificationAttempts, now).Scan(&n.ID, &n.SessionID, &n.Title, &n.Body, &n.Click, &n.SequenceID, &n.Priority, &n.Attempts)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return n, nil
}
// FinishChatNotification settles a claimed attempt: sent, or pending again
// after an exponential backoff (5 s, 10 s, 20 s, ...) until attempts run out.
func (s *Store) FinishChatNotification(ctx context.Context, n ChatNotification, now int64, messageID string, failure error) error {
status, diagnostic, next := "sent", "", now
if failure != nil {
status, diagnostic = "pending", failure.Error()
next = now + int64(5)<<min(n.Attempts-1, 8)
if n.Attempts >= ChatNotificationAttempts {
status = "failed"
}
}
_, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status=?,diagnostic=?,message_id=?,next_attempt=?
WHERE id=? AND status='sending' AND attempts=?`, status, diagnostic, messageID, next, n.ID, n.Attempts)
return err
}
// ChatNotificationStatus reports one push's outbox status ("" when absent)
// and attempts.
func (s *Store) ChatNotificationStatus(ctx context.Context, id string) (string, int, error) {
var status string
var attempts int
err := s.db.QueryRowContext(ctx, `SELECT status,attempts FROM chat_notifications WHERE id=?`, id).Scan(&status, &attempts)
if errors.Is(err, sql.ErrNoRows) {
return "", 0, nil
}
return status, attempts, err
}
// ChatNotificationCleared reports whether id's app notification has been
// cleared; a publication that raced a clear then clears the phone too.
func (s *Store) ChatNotificationCleared(ctx context.Context, id string) (bool, error) {
var cleared bool
err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM app_notifications WHERE id=? AND cleared_at<>0)`, id).Scan(&cleared)
return cleared, err
}
@@ -1,76 +0,0 @@
package pipeline
import (
"context"
"errors"
"path/filepath"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestChatNotificationOutboxRetriesAndSkipsCleared(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "chat-outbox.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
now := time.Unix(1000, 0)
n := ChatNotification{ID: "chat:ses_a:form:q1", SessionID: "ses_a", Title: "T", Body: "B", Click: "pipelines://chat/ses_a", SequenceID: "pl-1"}
for range 2 { // idempotent by id
if err := s.EnqueueChatNotification(ctx, n, now); err != nil {
t.Fatal(err)
}
}
first, err := s.ClaimChatNotification(ctx, 1000)
if err != nil || first == nil || first.Attempts != 1 || first.SequenceID != "pl-1" {
t.Fatalf("claim = %+v %v", first, err)
}
if again, err := s.ClaimChatNotification(ctx, 1000); err != nil || again != nil {
t.Fatalf("leased row claimed twice: %+v %v", again, err)
}
if err := s.FinishChatNotification(ctx, *first, 1000, "", errors.New("ntfy down")); err != nil {
t.Fatal(err)
}
if early, _ := s.ClaimChatNotification(ctx, 1004); early != nil {
t.Fatalf("retried before backoff: %+v", early)
}
second, err := s.ClaimChatNotification(ctx, 1005)
if err != nil || second == nil || second.Attempts != 2 {
t.Fatalf("retry claim = %+v %v", second, err)
}
if err := s.FinishChatNotification(ctx, *second, 1005, "m1", nil); err != nil {
t.Fatal(err)
}
if status, attempts, _ := s.ChatNotificationStatus(ctx, n.ID); status != "sent" || attempts != 2 {
t.Fatalf("status = %s/%d", status, attempts)
}
// A lease lost to a crash is reclaimed after it expires.
crashed := ChatNotification{ID: "chat:ses_a:form:q2", SessionID: "ses_a", Title: "T", Body: "B"}
_ = s.EnqueueChatNotification(ctx, crashed, now)
if c, _ := s.ClaimChatNotification(ctx, 2000); c == nil {
t.Fatal("no claim")
}
if c, _ := s.ClaimChatNotification(ctx, 2061); c == nil || c.Attempts != 2 {
t.Fatalf("expired lease not reclaimed: %+v", c)
} else if err := s.FinishChatNotification(ctx, *c, 2061, "m2", nil); err != nil {
t.Fatal(err)
}
// A push whose app notification was cleared first is never published.
cleared := ChatNotification{ID: "chat:ses_b:form:q3", SessionID: "ses_b", Title: "T", Body: "B"}
if _, _, err := s.RecordAppNotification(ctx, AppNotificationRecord{AppNotification: protocol.AppNotification{ID: cleared.ID, Kind: protocol.NotificationChatQuestion, Title: "T"}, SessionID: "ses_b"}, now); err != nil {
t.Fatal(err)
}
if _, err := s.ClearAppNotifications(ctx, []string{cleared.ID}, now); err != nil {
t.Fatal(err)
}
_ = s.EnqueueChatNotification(ctx, cleared, now)
if c, _ := s.ClaimChatNotification(ctx, 3000); c != nil {
t.Fatalf("cleared push claimed: %+v", c)
}
if status, _, _ := s.ChatNotificationStatus(ctx, cleared.ID); status != "cleared" {
t.Fatalf("cleared push status = %q", status)
}
}
+4 -4
View File
@@ -5,11 +5,11 @@ import (
"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.
// TestMain isolates the package from the operator's environment: a developer
// shell may export the installed server's web origin, which tests must not
// pick up.
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"} {
for _, name := range []string{"PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
@@ -26,12 +26,12 @@ func TestNotificationSettingsDefaultPersistAndPartialUpdate(t *testing.T) {
t.Fatalf("default values changed: %+v", got)
}
got, err = s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true})
want := protocol.NotificationSettings{RunFinished: false, ChatNeedsYou: true, ChatReplyFinished: true, NtfyEnabled: true}
want := protocol.NotificationSettings{RunFinished: false, 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: true, protocol.NotifyChatNeedsYou: false})
want = protocol.NotificationSettings{RunFinished: true, ChatNeedsYou: false, ChatReplyFinished: true, NtfyEnabled: true}
want = protocol.NotificationSettings{RunFinished: true, ChatNeedsYou: false, ChatReplyFinished: true}
if err != nil || got != want {
t.Fatalf("second update = %+v, %v", got, err)
}
@@ -144,3 +144,37 @@ func TestLegacyRunFinishedValueIsIgnored(t *testing.T) {
t.Fatalf("notifications = %+v, %v", got, err)
}
}
// ntfy was removed. A stored notify.ntfy_enabled row from an earlier server is
// never read, the other stored choices keep their meaning, and an older client
// that still sends the ntfy_enabled switch is accepted without changing
// anything.
func TestLegacyNtfySettingIsIgnored(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "legacy-ntfy.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
for key, value := range map[string]string{"notify.ntfy_enabled": "false", "notify.chat_reply_finished": "true", "notify.any_run_ended": "true"} {
if _, err := s.db.ExecContext(ctx, `INSERT INTO server_settings(key,value) VALUES(?,?)`, key, value); err != nil {
t.Fatal(err)
}
}
want := protocol.NotificationSettings{RunFinished: true, ChatNeedsYou: true, ChatReplyFinished: true}
if got, err := s.NotificationSettings(ctx); err != nil || got != want {
t.Fatalf("settings with a stored ntfy row = %+v, %v", got, err)
}
if _, present := want.Map()[protocol.LegacyNotifyNtfyEnabled]; present {
t.Fatal("the wire form still carries ntfy_enabled")
}
got, err := s.UpdateNotificationSettings(ctx, map[string]any{protocol.LegacyNotifyNtfyEnabled: true})
if err != nil || got != want {
t.Fatalf("ntfy-only update = %+v, %v", got, err)
}
got, err = s.UpdateNotificationSettings(ctx, map[string]any{protocol.LegacyNotifyNtfyEnabled: false, protocol.NotifyChatNeedsYou: false})
want.ChatNeedsYou = false
if err != nil || got != want {
t.Fatalf("mixed update = %+v, %v", got, err)
}
}
+7 -2
View File
@@ -39,7 +39,12 @@ func TestNotifyPolicyParsing(t *testing.T) {
t.Fatal("notify link not validated", err)
}
source = "# stage native\n```configs\ntype=ntfy\ndestination=anime\n```\n```notify\non=failure\ndestination=anime\n```\n```edges\nsuccess -> #success\nerror -> #failure\n```"
if _, err := Parse(source); err != nil {
t.Fatal("notify not supported on native stage", err)
// ntfy stages were removed: an old definition is refused with what to use
// instead, by the parser and by `pipelines validate`'s report parser.
if _, err := Parse(source); err == nil || !strings.Contains(err.Error(), "ntfy stages were removed; notifications go to the Pipelines apps — use the stage notify hook") {
t.Fatal("type=ntfy stage not rejected with guidance:", err)
}
if _, _, err := ParseDefinitionReport(source); err == nil || !strings.Contains(err.Error(), "use the stage notify hook") {
t.Fatal("validate report accepted a type=ntfy stage:", err)
}
}
+2 -2
View File
@@ -10,7 +10,7 @@ import (
func overrideGraph() protocol.Graph {
return protocol.Graph{Stages: []protocol.Stage{
{Key: "plan", Type: "model", Configs: map[string]string{"provider": "pinned", "model": "pinned-model"}},
{Key: "note", Type: "ntfy", Configs: map[string]string{}},
{Key: "note", Type: "human", Configs: map[string]string{}},
{Key: "review", Type: "model", Configs: map[string]string{"provider": "pinned2", "model": "pinned2-model"}},
}}
}
@@ -97,7 +97,7 @@ func TestEffectiveModelsRejectsBadInput(t *testing.T) {
t.Fatalf("non-model stage override error = %v, want a cannot-honour refusal", err)
}
// A whole-run override on a graph with no model stage is accepted and inert.
inert := protocol.Graph{Stages: []protocol.Stage{{Key: "note", Type: "ntfy", Configs: map[string]string{}}}}
inert := protocol.Graph{Stages: []protocol.Stage{{Key: "note", Type: "human", Configs: map[string]string{}}}}
got, err := EffectiveModels(inert, "acme/whole", nil)
if err != nil || len(got) != 0 {
t.Fatalf("whole-run override on a no-model graph = %+v, %v; want inert", got, err)
+1 -1
View File
@@ -77,7 +77,7 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU
db.Close()
return nil, err
}
if err := s.initChatNotifications(); err != nil {
if err := s.dropChatNotifications(); err != nil {
db.Close()
return nil, err
}
+2 -1
View File
@@ -81,7 +81,8 @@ type ChatShownItem struct {
// 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).
// operator's signed-in Pipelines apps). Items recorded before ntfy was
// removed may also carry "phone".
Channels []string `json:"channels,omitempty"`
}
+49 -57
View File
@@ -67,13 +67,6 @@ type NotificationPolicy struct {
Link string `json:"link,omitempty"`
}
// Public phone setup only. Never include publishing endpoints or credentials.
type NotificationEndpoint struct {
Destination string `json:"destination"`
ServerURL string `json:"server_url,omitempty"`
Topic string `json:"topic"`
}
type Template struct {
Key string `json:"key"`
Name string `json:"name"`
@@ -142,56 +135,55 @@ type PipelineSummary struct {
// are optional so older peers ignore them. See search.go for the per-type payloads
// and the ranking/kind/bound vocabulary.
type Message struct {
SkillFiles []SkillFile `json:"skill_files,omitempty"`
SkillSummaries []SkillSummary `json:"skill_summaries,omitempty"`
SkillVersion *SkillVersion `json:"skill_version,omitempty"`
Storage *StorageOverview `json:"storage,omitempty"`
StoragePolicy *StoragePolicy `json:"storage_policy,omitempty"`
StorageCleanup *StorageCleanupResult `json:"storage_cleanup,omitempty"`
StorageCleanupToken string `json:"storage_cleanup_token,omitempty"`
Schedule *SavedSchedule `json:"schedule,omitempty"`
Schedules []SavedSchedule `json:"schedules,omitempty"`
ScheduleID int64 `json:"schedule_id,omitempty"`
ExpectedRevision int64 `json:"expected_revision,omitempty"`
DefaultHarness string `json:"default_harness,omitempty"`
Build *buildinfo.Info `json:"build,omitempty"`
Protocol int `json:"protocol,omitempty"`
DefaultModel string `json:"default_model,omitempty"`
Evidence []SessionEvidence `json:"evidence,omitempty"`
Usage *UsageStats `json:"usage,omitempty"`
Status *SystemStatus `json:"status,omitempty"`
Graph *Graph `json:"graph,omitempty"`
ExpectedVersion int `json:"expected_version,omitempty"`
Templates []Template `json:"templates,omitempty"`
CreateOnly bool `json:"create_only,omitempty"`
IncludeArchived bool `json:"include_archived,omitempty"`
NotificationEndpoints []NotificationEndpoint `json:"notification_endpoints,omitempty"`
Type string `json:"type"`
ID string `json:"id,omitempty"`
Time string `json:"time,omitempty"`
Error string `json:"error,omitempty"`
Warnings []string `json:"warnings,omitempty"` // non-blocking authoring lint for validate/submit
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Digest string `json:"digest,omitempty"`
SourcePath string `json:"source_path,omitempty"`
Source string `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Version int `json:"version,omitempty"`
Pipelines []PipelineSummary `json:"pipelines,omitempty"`
PipelineID int64 `json:"pipeline_id,omitempty"`
Detail *PipelineDetail `json:"detail,omitempty"`
RunID int64 `json:"run_id,omitempty"`
RunDetail *RunDetail `json:"run_detail,omitempty"`
Runs []RunSummary `json:"runs,omitempty"`
Stage string `json:"stage,omitempty"`
Option string `json:"option,omitempty"`
Feedback string `json:"feedback,omitempty"`
Input map[string]any `json:"input,omitempty"`
AllowTools bool `json:"allow_tools,omitempty"`
WritePaths []string `json:"write_paths,omitempty"`
RequestKey string `json:"request_key,omitempty"`
Workspace string `json:"workspace,omitempty"`
SkillFiles []SkillFile `json:"skill_files,omitempty"`
SkillSummaries []SkillSummary `json:"skill_summaries,omitempty"`
SkillVersion *SkillVersion `json:"skill_version,omitempty"`
Storage *StorageOverview `json:"storage,omitempty"`
StoragePolicy *StoragePolicy `json:"storage_policy,omitempty"`
StorageCleanup *StorageCleanupResult `json:"storage_cleanup,omitempty"`
StorageCleanupToken string `json:"storage_cleanup_token,omitempty"`
Schedule *SavedSchedule `json:"schedule,omitempty"`
Schedules []SavedSchedule `json:"schedules,omitempty"`
ScheduleID int64 `json:"schedule_id,omitempty"`
ExpectedRevision int64 `json:"expected_revision,omitempty"`
DefaultHarness string `json:"default_harness,omitempty"`
Build *buildinfo.Info `json:"build,omitempty"`
Protocol int `json:"protocol,omitempty"`
DefaultModel string `json:"default_model,omitempty"`
Evidence []SessionEvidence `json:"evidence,omitempty"`
Usage *UsageStats `json:"usage,omitempty"`
Status *SystemStatus `json:"status,omitempty"`
Graph *Graph `json:"graph,omitempty"`
ExpectedVersion int `json:"expected_version,omitempty"`
Templates []Template `json:"templates,omitempty"`
CreateOnly bool `json:"create_only,omitempty"`
IncludeArchived bool `json:"include_archived,omitempty"`
Type string `json:"type"`
ID string `json:"id,omitempty"`
Time string `json:"time,omitempty"`
Error string `json:"error,omitempty"`
Warnings []string `json:"warnings,omitempty"` // non-blocking authoring lint for validate/submit
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Digest string `json:"digest,omitempty"`
SourcePath string `json:"source_path,omitempty"`
Source string `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Version int `json:"version,omitempty"`
Pipelines []PipelineSummary `json:"pipelines,omitempty"`
PipelineID int64 `json:"pipeline_id,omitempty"`
Detail *PipelineDetail `json:"detail,omitempty"`
RunID int64 `json:"run_id,omitempty"`
RunDetail *RunDetail `json:"run_detail,omitempty"`
Runs []RunSummary `json:"runs,omitempty"`
Stage string `json:"stage,omitempty"`
Option string `json:"option,omitempty"`
Feedback string `json:"feedback,omitempty"`
Input map[string]any `json:"input,omitempty"`
AllowTools bool `json:"allow_tools,omitempty"`
WritePaths []string `json:"write_paths,omitempty"`
RequestKey string `json:"request_key,omitempty"`
Workspace string `json:"workspace,omitempty"`
// Model and StageModels are the launch-time model overrides: Model applies to
// every model stage of the run and StageModels overrides individual stages by
// key (per-stage wins over whole-run). Both are optional so older peers ignore
+16 -14
View File
@@ -6,12 +6,14 @@ import (
)
// Notification settings are the operator's global choices about which events
// publish through the server's ntfy connection. A client reads them with
// are recorded on the app notification stream (subscribe_notifications), and
// so reach every signed-in Pipelines app. 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.
// are refused (the removed ntfy_enabled key is accepted and ignored, so an
// older client's switch does not fail). Both replies have type
// "notification_settings" and carry every key with its stored value.
const (
GetNotificationSettings = "notification_settings"
SetNotificationSettings = "set_notification_settings"
@@ -23,7 +25,10 @@ const (
NotifyRunFinished = "run_finished"
NotifyChatNeedsYou = "chat_needs_you"
NotifyChatReplyFinished = "chat_reply_finished"
NotifyNtfyEnabled = "ntfy_enabled"
// LegacyNotifyNtfyEnabled is the removed "also send to ntfy" switch. A set
// that names it is accepted and the key ignored; a stored value is never
// read.
LegacyNotifyNtfyEnabled = "ntfy_enabled"
)
// NotificationSettings is the typed form of the global notification choices.
@@ -36,18 +41,14 @@ type NotificationSettings struct {
ChatNeedsYou bool
// ChatReplyFinished notifies when an assistant turn in a chat ends.
ChatReplyFinished bool
// NtfyEnabled publishes notifications to ntfy. On by default; when off the
// server still records and streams every notification to app clients
// (subscribe_notifications) but stops publishing to ntfy.
NtfyEnabled bool
}
// NotificationSettingKeys lists every setting key in a stable order.
var NotificationSettingKeys = []string{NotifyRunFinished, NotifyChatNeedsYou, NotifyChatReplyFinished, NotifyNtfyEnabled}
var NotificationSettingKeys = []string{NotifyRunFinished, NotifyChatNeedsYou, NotifyChatReplyFinished}
// DefaultNotificationSettings are the values before the operator changes any.
func DefaultNotificationSettings() NotificationSettings {
return NotificationSettings{RunFinished: false, ChatNeedsYou: true, ChatReplyFinished: false, NtfyEnabled: true}
return NotificationSettings{RunFinished: false, ChatNeedsYou: true, ChatReplyFinished: false}
}
// Map returns the wire form with every key present.
@@ -56,7 +57,6 @@ func (s NotificationSettings) Map() map[string]any {
NotifyRunFinished: s.RunFinished,
NotifyChatNeedsYou: s.ChatNeedsYou,
NotifyChatReplyFinished: s.ChatReplyFinished,
NotifyNtfyEnabled: s.NtfyEnabled,
}
}
@@ -69,14 +69,13 @@ func (s *NotificationSettings) Field(key string) *bool {
return &s.ChatNeedsYou
case NotifyChatReplyFinished:
return &s.ChatReplyFinished
case NotifyNtfyEnabled:
return &s.NtfyEnabled
}
return nil
}
// ValidateNotificationSettingsUpdate checks a partial update: at least one key,
// every key known and every value a boolean.
// every key known and every value a boolean. The legacy ntfy_enabled key is
// dropped from the result, so an update naming only it changes nothing.
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")
@@ -89,6 +88,9 @@ func ValidateNotificationSettingsUpdate(update map[string]any) (map[string]bool,
result := make(map[string]bool, len(update))
var probe NotificationSettings
for _, key := range keys {
if key == LegacyNotifyNtfyEnabled {
continue
}
if probe.Field(key) == nil {
return nil, fmt.Errorf("unknown notification setting %q", key)
}
+6 -9
View File
@@ -2,12 +2,10 @@ package protocol
import "fmt"
// App notifications are the same operator notifications the server publishes
// to ntfy, streamed over /connect so the Pipelines app can post them itself
// without the ntfy app. Every publication point records one notification
// (persisted, with a stable id) before it publishes to ntfy, so the stream
// carries exactly the set ntfy gets, governed by the same notification
// settings; notify.ntfy_enabled=false stops only the ntfy publish.
// App notifications are the operator's notifications, streamed over /connect
// so every Pipelines app can post them itself. Every notification point records
// one notification (persisted, with a stable id), governed by the notification
// settings.
//
// → {"type":"subscribe_notifications","id":"1","after":"run:7:3:waiting"}
// ← {"type":"notifications_subscribed","id":"1","notifications":[{...}],"ids":["chat:ses_x:form:f1"]}
@@ -58,8 +56,7 @@ const (
NotificationSchedule = "schedule"
)
// DefaultNotificationPriority is ntfy's default priority, which every ntfy
// publication uses today (the server sends no Priority header).
// DefaultNotificationPriority is the default of the 1-5 notification priority.
const DefaultNotificationPriority = 3
// MaxReplayedNotifications bounds a subscribe reply and MaxClearNotificationIDs
@@ -78,7 +75,7 @@ type AppNotification struct {
Kind string `json:"kind"`
Title string `json:"title"`
Message string `json:"message"`
// Click is the app tap target (normally the same run deep link ntfy gets).
// Click is the app tap target (normally the run or chat deep link).
Click string `json:"click"`
RunClick string `json:"run_click,omitempty"`
Artifact *NotificationArtifact `json:"artifact,omitempty"`
-3
View File
@@ -21,7 +21,6 @@ type SystemStatus struct {
Uptime string `json:"uptime"`
Addresses []NetworkAddress `json:"addresses"`
Server ServiceStatus `json:"server"`
Ntfy ServiceStatus `json:"ntfy"`
// OpenCode reports how brokered chat is attached to OpenCode. Health is
// "endpoint" when attached to the operator's configured endpoint,
// "fallback" when that endpoint could not be attached and chat fell back to
@@ -29,7 +28,5 @@ type SystemStatus struct {
// "unavailable" when chat is disabled. URL is the configured endpoint, if
// any. It never carries a credential.
OpenCode ServiceStatus `json:"opencode"`
Topic string `json:"topic,omitempty"`
NtfyUser string `json:"ntfy_user,omitempty"`
Note string `json:"note"`
}
+3 -3
View File
@@ -26,7 +26,7 @@ go test ./... # ~1 min for everything; `gofmt -l .` must print
- `internal/server/chat_*.go` — the chat broker: `chat_sessions`, claims, the stream, permissions,
session registry.
- `internal/stage/` — one client per harness and stage type: `opencode.go` (native sessions),
`pi.go` (RPC), `model.go`, `agent.go`, `human.go` (decision stages), `ntfy.go` (notifications),
`pi.go` (RPC), `model.go`, `agent.go`, `human.go` (decision stages),
`model_prompt.go` (file-based turn prompt), `budget.go` (usage accounting). Model stages return
markdown for `output.md`; only its `# outcome` section is parsed (`internal/turn`).
- `internal/pipeline/` — the store: definitions and immutable versions, runs and steps, the
@@ -40,11 +40,11 @@ go test ./... # ~1 min for everything; `gofmt -l .` must print
`scripts/run-local-server.sh` starts a scratch server, and the binary takes `-addr` and `-db`, so a
live check runs against a **scratch database and a free loopback port**. The operator's deployment is
`~/.local/share/pipelines` with the service on `0.0.0.0:8080` and ntfy on `8090`.
`~/.local/share/pipelines` with the service on `0.0.0.0:8080`.
## Hard rules
- **Never restart, rebuild or redeploy the deployed server, ntfy or a running run** to test a change:
- **Never restart, rebuild or redeploy the deployed server or a running run** to test a change:
a restart kills every run in flight. Deploying is the operator's step.
- Commit locally only, never push.
- One run per workspace at a time — the server refuses a second one rather than sharing a tree.
+3 -35
View File
@@ -11,7 +11,6 @@ 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"
)
// appNotificationStore persists the app notification outbox.
@@ -27,8 +26,8 @@ type appNotificationStore interface {
// that falls this far behind is dropped; it recovers with a resubscribe.
const appNotificationQueue = 512
// appNotifier records every operator notification (the same ones published to
// ntfy) and streams them to subscribed connections. One mutex orders store
// appNotifier records every operator notification and streams it to
// subscribed connections. One mutex orders store
// writes with fan-out, so each subscriber sees its snapshot reply and then
// every later push exactly in commit order.
type appNotifier struct {
@@ -133,7 +132,7 @@ func (a *appNotifier) detach(clientID string) {
// record persists n and pushes it when it is new, and reports whether it is
// recorded. Failures are logged only: recording must never block or fail the
// ntfy publication beside it.
// event that raised it.
func (a *appNotifier) record(ctx context.Context, n pipeline.AppNotificationRecord) bool {
if a == nil {
return false
@@ -162,7 +161,6 @@ 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
}
@@ -182,7 +180,6 @@ 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)
}
}
@@ -286,27 +283,6 @@ func handleAppNotifications(ctx context.Context, request protocol.Message, notes
return true
}
// ntfyEnabled reads notify.ntfy_enabled. Without a store, or when the read
// fails, ntfy stays enabled (the default) so a transient error never silences
// the operator.
func ntfyEnabled(ctx context.Context, store notificationSettingsStore) bool {
if store == nil {
return true
}
settings, err := store.NotificationSettings(ctx)
if err != nil {
log.Printf("read notification settings: %v", err)
return true
}
return settings.NtfyEnabled
}
// ntfyDisabledResult is what a publication reports when ntfy is turned off:
// the notification reached app clients only.
func ntfyDisabledResult() stage.Values {
return stage.Values{"destination": "system", "message_id": "", "ntfy": "disabled"}
}
// runNotificationKind maps a run outbox event to its app notification kind.
func runNotificationKind(event string) string {
switch event {
@@ -356,11 +332,3 @@ func runNotificationRecord(runID int64, sequence int, event, kind, title, messag
RunID: runID,
}
}
// settingsStore returns the runner's store as a settings reader, or nil.
func (r *runner) settingsStore() notificationSettingsStore {
if r.store == nil {
return nil
}
return r.store
}
+66 -87
View File
@@ -16,7 +16,6 @@ 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"
"git.a-wan.net/alan/pipelines/internal/summarise"
)
@@ -78,16 +77,12 @@ func newAppNotificationFixture(t *testing.T, ctx context.Context) *appNotificati
return &appNotificationFixture{t: t, ctx: ctx, store: store, runner: handler.(*runHandler).runner, hub: handler.(*runHandler).hub, url: srv.URL, def: def}
}
func TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
func TestToolNotificationRecordsAppNotification(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
hub := &chatHub{notes: newAppNotifier(store), settings: store}
got := hub.publishToolNotification(ctx, "session-1", chatToolNotice{ID: "shown_1", Title: "Build failed", Message: "Please inspect the run", Priority: "low"})
if !got.App || got.Phone || got.Detail != "phone notifications (ntfy) are turned off" {
if !got.App || got.Detail != "" {
t.Fatalf("tool notification result = %+v", got)
}
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
@@ -98,13 +93,15 @@ func TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
n.Message != "Please inspect the run" || n.Priority != 2 || n.Group != "chat:session-1" || n.Click != "pipelines://chat/session-1" {
t.Fatalf("wrong tool notification: %+v", n)
}
// Without the app stream there is nowhere to deliver: the agent is told.
if got := (&chatHub{}).publishToolNotification(ctx, "session-1", chatToolNotice{ID: "shown_2", Title: "t", Message: "m"}); got.App || got.Detail == "" {
t.Fatalf("store-less delivery = %+v", got)
}
}
// An agent's notify reaches every connected app, not only the clients watching
// that chat, and a client that connects later replays the ones still active.
func TestToolNotificationBroadcastsAndReplaysToReconnectingClients(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
f := newAppNotificationFixture(t, ctx)
@@ -114,7 +111,7 @@ func TestToolNotificationBroadcastsAndReplaysToReconnectingClients(t *testing.T)
subscribeNotifications(t, ctx, desktop, "")
notice := chatToolNotice{ID: "shown_a", Title: "Done", Message: "Build finished", Priority: "high"}
if got := hub.publishToolNotification(ctx, "ses_x", notice); !got.App || got.Phone || got.Detail == "" {
if got := hub.publishToolNotification(ctx, "ses_x", notice); !got.App || got.Detail != "" {
t.Fatalf("delivery = %+v", got)
}
for name, conn := range map[string]*websocket.Conn{"web": web, "desktop": desktop} {
@@ -226,11 +223,9 @@ func subscribeNotifications(t *testing.T, ctx context.Context, conn *websocket.C
return reply
}
func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
func TestAppNotificationStreamCarriesRunFailure(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
captured := newNtfyCapture(t)
f := newAppNotificationFixture(t, ctx)
phone := dialAckClient(t, ctx, f.url)
initial := subscribeNotifications(t, ctx, phone, "")
@@ -239,13 +234,9 @@ func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
}
run := f.failRun("stream")
push := readFrame(t, ctx, phone, protocol.NotificationPush)
got := captured()
if len(got) != 1 {
t.Fatalf("ntfy deliveries = %+v", got)
}
n := push.Notification
if n == nil || n.Title != got[0].Title || n.Message != got[0].Message || n.Click != got[0].Click {
t.Fatalf("stream %+v differs from ntfy %+v", n, got[0])
if n == nil || n.Title != "Run failed" || !strings.Contains(n.Message, fmt.Sprintf("Run #%d", run)) {
t.Fatalf("stream notification = %+v", n)
}
if n.ID != fmt.Sprintf("run:%d:0:failed", run) || n.Kind != protocol.NotificationRunFailed || n.Group != fmt.Sprintf("run:%d", run) ||
n.Priority != 3 || n.Tags == nil || len(n.Tags) != 0 || n.Click != fmt.Sprintf("pipelines://run/%d", run) {
@@ -264,7 +255,7 @@ func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
t.Fatalf("notification wire lacks %q: %s", key, raw)
}
}
// A retried publication of the same event is not streamed twice.
// A retried delivery of the same event is not streamed twice.
f.runner.deliverRunNotifications(time.Now().Add(time.Hour))
reply := subscribeNotifications(t, ctx, phone, "")
if len(reply.Notifications) != 1 || reply.Notifications[0].ID != n.ID || reply.Notifications[0].CreatedAt != n.CreatedAt {
@@ -273,11 +264,10 @@ func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
}
func TestAppNotificationReplayAfterCursorAndCrossDeviceClear(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
f := newAppNotificationFixture(t, ctx)
// Offline: two runs fail with no app connected (ntfy unconfigured too).
// Offline: two runs fail with no app connected.
first := f.failRun("first")
second := f.failRun("second")
firstID, secondID := fmt.Sprintf("run:%d:0:failed", first), fmt.Sprintf("run:%d:0:failed", second)
@@ -357,42 +347,41 @@ func TestAppNotificationReplayAfterCursorAndCrossDeviceClear(t *testing.T) {
}
}
func TestNtfyDisabledStillStreams(t *testing.T) {
// An older app may still send the removed ntfy_enabled switch: the server
// accepts it without changing anything, replies with exactly the three
// notification settings, and keeps streaming.
func TestLegacyNtfySwitchIsIgnoredAndRunsStillStream(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
captured := newNtfyCapture(t)
f := newAppNotificationFixture(t, ctx)
phone := dialAckClient(t, ctx, f.url)
set := ackExchange(t, ctx, phone, protocol.Message{Type: protocol.SetNotificationSettings, ID: "off", NotificationSettings: map[string]any{protocol.NotifyNtfyEnabled: false}})
if set.Type != protocol.NotificationSettingsReply || set.NotificationSettings[protocol.NotifyNtfyEnabled] != false {
set := ackExchange(t, ctx, phone, protocol.Message{Type: protocol.SetNotificationSettings, ID: "off", NotificationSettings: map[string]any{protocol.LegacyNotifyNtfyEnabled: false}})
want := protocol.DefaultNotificationSettings().Map()
if set.Type != protocol.NotificationSettingsReply || len(set.NotificationSettings) != 3 {
t.Fatalf("settings reply = %+v", set)
}
for key, value := range want {
if set.NotificationSettings[key] != value {
t.Fatalf("settings reply %s = %v, want %v: %+v", key, set.NotificationSettings[key], value, set)
}
}
if _, present := set.NotificationSettings[protocol.LegacyNotifyNtfyEnabled]; present {
t.Fatalf("reply still carries ntfy_enabled: %+v", set)
}
subscribeNotifications(t, ctx, phone, "")
run := f.failRun("quiet")
push := readFrame(t, ctx, phone, protocol.NotificationPush)
if push.Notification == nil || push.Notification.ID != fmt.Sprintf("run:%d:0:failed", run) || push.Notification.Title != "Run failed" {
t.Fatalf("push = %+v", push)
}
if got := captured(); len(got) != 0 {
t.Fatalf("ntfy published while disabled: %+v", got)
}
// The outbox is settled, not retried against ntfy.
// The outbox is settled once the app notification is recorded.
rows, err := f.store.RunNotifications(ctx, run)
if err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("outbox = %+v %v", rows, err)
}
}
func TestChatAppNotificationsRespectNtfyEnabledAndClearOnAnswer(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
var published []ntfyCapture
original := chatAttentionPublish
chatAttentionPublish = func(_ context.Context, _, title, message, _ string, _ []byte, click string, _ ...stage.NtfyView) (stage.Values, error) {
published = append(published, ntfyCapture{Title: title, Message: message, Click: click})
return stage.Values{}, nil
}
defer func() { chatAttentionPublish = original }()
func TestChatAppNotificationsClearOnAnswer(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
h := chatAttentionHub(t, "ses_a")
@@ -402,13 +391,13 @@ func TestChatAppNotificationsRespectNtfyEnabledAndClearOnAnswer(t *testing.T) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_a", Kind: protocol.ChatEventForm, Form: &form})
h.attentionWG.Wait()
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(published) != 1 || len(active) != 1 {
t.Fatalf("published=%+v active=%+v err=%v", published, active, err)
if err != nil || len(active) != 1 {
t.Fatalf("active=%+v err=%v", active, err)
}
n := active[0]
if n.ID != "chat:ses_a:form:que_1" || n.Kind != protocol.NotificationChatQuestion || n.Group != "chat:ses_a" ||
n.Title != published[0].Title || n.Message != published[0].Message || n.Click != published[0].Click {
t.Fatalf("chat notification %+v vs ntfy %+v", n, published[0])
n.Message != "Ship it?" || n.Click != "pipelines://chat/ses_a" {
t.Fatalf("chat notification %+v", n)
}
// Answering the question clears it.
form.Resolved = true
@@ -417,15 +406,11 @@ func TestChatAppNotificationsRespectNtfyEnabledAndClearOnAnswer(t *testing.T) {
if active, _, _ := store.ActiveAppNotifications(ctx, "", time.Now()); len(active) != 0 {
t.Fatalf("answered question still active: %+v", active)
}
// With ntfy off, the approval is streamed but not published.
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil {
t.Fatal(err)
}
h.pushPermission("ses_a", protocol.ChatPermissionFrame{SessionID: "ses_a", RequestID: "per_1", Message: "Allow rm?"})
h.attentionWG.Wait()
active, _, _ = store.ActiveAppNotifications(ctx, "", time.Now())
if len(published) != 1 || len(active) != 1 || active[0].Kind != protocol.NotificationChatApproval || active[0].ID != "chat:ses_a:permission:per_1" {
t.Fatalf("published=%+v active=%+v", published, active)
if len(active) != 1 || active[0].Kind != protocol.NotificationChatApproval || active[0].ID != "chat:ses_a:permission:per_1" {
t.Fatalf("active=%+v", active)
}
h.confirmPermission("ses_a", "per_1", "phone", "once")
h.attentionWG.Wait()
@@ -452,12 +437,9 @@ func TestRunLeavingWaitingClearsWaitingNotification(t *testing.T) {
}
}
// A stage notify hook streams one notification per step event (artifacts stay
// ntfy attachments) with the hook's title and summary, and with ntfy disabled
// it still streams while publishing nothing.
// A stage notify hook streams one notification per step event with the hook's
// title and summary, and audits the delivery as an app receipt.
func TestStageHookAppNotification(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
captured := newNtfyCapture(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
@@ -468,38 +450,35 @@ func TestStageHookAppNotification(t *testing.T) {
d, _ := store.Get(ctx, items[0].ID, 0)
workspace := t.TempDir()
r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store)}
// artifacts= is a legacy setting (it used to attach files to ntfy) and is
// accepted without effect.
policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Artifacts: []string{"markdown"}}
for i, ntfyOn := range []bool{true, false} {
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: ntfyOn}); err != nil {
t.Fatal(err)
}
id, _, err := store.CreateRun(ctx, d, fmt.Sprintf("hook%d", i), workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
t.Fatal(err)
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{"markdown": "# Digest"}}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := len(captured())
r.notifyStep(id, d.Name, workspace, policy, step)
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != i+1 {
t.Fatalf("active = %+v %v", active, err)
}
n := active[i]
if n.ID != fmt.Sprintf("run:%d:1:success", id) || n.Kind != protocol.NotificationStageSucceeded || n.Click != fmt.Sprintf("pipelines://run/%d", id) {
t.Fatalf("hook notification = %+v", n)
}
got := captured()
if ntfyOn && (len(got) != before+1 || got[before].Title != n.Title || got[before].Message != n.Message || got[before].Click != n.Click) {
t.Fatalf("ntfy %+v vs stream %+v", got, n)
}
if !ntfyOn && len(got) != before {
t.Fatalf("ntfy published while disabled: %+v", got)
}
id, _, err := store.CreateRun(ctx, d, "hook", workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
t.Fatal(err)
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{"markdown": "# Digest"}}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
r.notifyStep(id, d.Name, workspace, policy, step)
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != 1 {
t.Fatalf("active = %+v %v", active, err)
}
n := active[0]
if n.ID != fmt.Sprintf("run:%d:1:success", id) || n.Kind != protocol.NotificationStageSucceeded || n.Click != fmt.Sprintf("pipelines://run/%d", id) ||
n.Title != "Pipeline stage success" || !strings.Contains(n.Message, "stage one") {
t.Fatalf("hook notification = %+v", n)
}
detail, err := store.GetRun(ctx, id)
if err != nil || len(detail.Steps) != 1 || len(detail.Steps[0].Notifications) != 1 {
t.Fatalf("receipts = %+v %v", detail.Steps, err)
}
if receipt := detail.Steps[0].Notifications[0]; receipt.Destination != "app" || receipt.Status != "sent" || receipt.Filename != "" {
t.Fatalf("receipt = %+v", receipt)
}
}
-2
View File
@@ -58,7 +58,6 @@ func listActivity(t *testing.T, ctx context.Context, conn *websocket.Conn) *prot
// last one exits.
func TestChatActivityReachesEveryConnection(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, listedObservedChat{broker}, store)
@@ -113,7 +112,6 @@ func TestChatActivityReachesEveryConnection(t *testing.T) {
// invent completion. A terminal event releases it and clears list activity.
func TestChatBackgroundTaskWaitsForExitBeyondObserverTTL(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
limit := chatUnattendedTurnLimit
chatUnattendedTurnLimit = 300 * time.Millisecond
t.Cleanup(func() { chatUnattendedTurnLimit = limit })
+11 -27
View File
@@ -3,22 +3,17 @@ package server
import (
"context"
"net/url"
"os"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// chatAttentionRetainedLimit bounds the hub-wide set of form/permission ids that
// already produced (or never deserve) an attention notification.
const chatAttentionRetainedLimit = 1024
// chatAttentionPublish is the publisher; tests may replace it.
var chatAttentionPublish = stage.PublishNtfy
// chatAttention is one pending operator-attention notification for a chat.
type chatAttention struct {
sessionID string
@@ -115,14 +110,10 @@ func (h *chatHub) notePermissionAttentionLocked(frame protocol.ChatPermissionFra
h.startChatAttention(chatAttention{sessionID: frame.SessionID, approval: true, body: body, id: chatNotificationID(frame.SessionID, "permission", frame.RequestID)})
}
func chatAttentionConfigured() bool {
return os.Getenv("PIPELINES_NTFY_URL") != ""
}
// attentionWanted reports whether a chat attention item has anywhere to go:
// the ntfy connection or the app notification stream.
// the app notification stream.
func (h *chatHub) attentionWanted() bool {
return chatAttentionConfigured() || h.notes != nil
return h.notes != nil
}
// clearChatAttention clears one chat app notification asynchronously, off the
@@ -145,9 +136,8 @@ func (h *chatHub) clearChatAttention(sessionID, id string) {
}()
}
// startChatAttention publishes asynchronously within the 30-second notification
// budget. It never blocks or fails chat handling; the phone push goes through
// the durable outbox, which retries a failed attempt.
// startChatAttention records the app notification asynchronously within the
// 30-second notification budget. It never blocks or fails chat handling.
func (h *chatHub) startChatAttention(a chatAttention) {
base := h.baseCtx
if base == nil {
@@ -176,7 +166,7 @@ func (h *chatHub) startChatAttention(a chatAttention) {
if a.reply {
title, body = chatReplyText(name, a.body)
}
click, _ := chatAttentionLinks(a.sessionID)
click := chatAttentionClick(a.sessionID)
kind := protocol.NotificationChatQuestion
if a.reply {
kind = protocol.NotificationChatReply
@@ -188,16 +178,11 @@ func (h *chatHub) startChatAttention(a chatAttention) {
Priority: protocol.DefaultNotificationPriority, Tags: []string{}, Group: "chat:" + a.sessionID},
SessionID: a.sessionID,
})
if !chatAttentionConfigured() || !settings.NtfyEnabled {
return
}
// ntfy takes a single-line message of at most 2048 bytes.
h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: a.id, SessionID: a.sessionID, Title: title, Body: truncateUTF8(singleLine(body), 2000), Click: click, SequenceID: chatNtfySequence(a.id)})
}()
}
// chatAttentionText builds a single-line ntfy title/body within PublishNtfy's
// limits.
// chatAttentionText builds a single-line notification title/body of bounded
// length.
func chatAttentionText(name string, approval bool, body string) (string, string) {
name = singleLine(name)
if name == "" {
@@ -215,9 +200,8 @@ func singleLine(text string) string {
return strings.Join(strings.Fields(strings.ReplaceAll(text, "\x00", "")), " ")
}
// chatAttentionLinks opens the chat in the app; the web origin, when
// configured, is offered as an "Open in browser" action.
func chatAttentionLinks(sessionID string) (string, []stage.NtfyView) {
escaped := url.PathEscape(sessionID)
return "pipelines://chat/" + escaped, webAttentionViews("/chat/" + escaped)
// chatAttentionClick is the notification tap target that opens the chat in
// the app.
func chatAttentionClick(sessionID string) string {
return "pipelines://chat/" + url.PathEscape(sessionID)
}
@@ -17,7 +17,6 @@ import (
// switch to.
func autoContinueServer(t *testing.T) (*refusingChat, *queueServer, *pipeline.Store) {
t.Helper()
capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
broker.quiet = true
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) {
+3 -7
View File
@@ -32,7 +32,7 @@ const (
chatAutoContinuePrefix = "auto-continue-"
// chatAutoSwitchClient is the sender label of the continue prompt.
chatAutoSwitchClient = "Pipelines (automatic)"
// chatAutoSwitchPriority is ntfy's "low" priority.
// chatAutoSwitchPriority is the notification stream's "low" priority.
chatAutoSwitchPriority = 2
// chatAutoSwitchRemembered bounds the refusals remembered as handled.
chatAutoSwitchRemembered = 256
@@ -280,7 +280,7 @@ func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sess
}
// publishAutoSwitchNotice tells the operator, at low priority, through the
// app notification stream and (when enabled) ntfy.
// app notification stream.
func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.UsageRefusal, name, email string) {
name = singleLine(name)
if name == "" {
@@ -288,7 +288,7 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us
}
title := truncateUTF8("Switched "+name+" to "+singleLine(email)+" and continued", 256)
message := "Claude usage ran out, so Pipelines switched the account and asked the agent to check it is on track before continuing."
click, _ := chatAttentionLinks(refusal.SessionID)
click := chatAttentionClick(refusal.SessionID)
id := "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal)
if h.notes != nil {
h.notes.record(ctx, pipeline.AppNotificationRecord{
@@ -297,8 +297,4 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us
SessionID: refusal.SessionID,
})
}
if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled {
return
}
h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: id, SessionID: refusal.SessionID, Title: title, Body: message, Click: click, Priority: chatAutoSwitchPriority})
}
+14 -19
View File
@@ -12,7 +12,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// refusingChat is a channelChat that reports usage refusals and switches
@@ -69,24 +68,21 @@ type publishedNotice struct {
priority int
}
func capturePublications(t *testing.T) func() []publishedNotice {
// autoSwitchNotices returns the auto-switch notices recorded on the app
// notification stream.
func autoSwitchNotices(t *testing.T, store *pipeline.Store) []publishedNotice {
t.Helper()
t.Setenv("PIPELINES_NTFY_URL", "https://ntfy.invalid/pipelines")
var mu sync.Mutex
active, _, err := store.ActiveAppNotifications(context.Background(), "", time.Now())
if err != nil {
t.Fatal(err)
}
var got []publishedNotice
previous := chatAttentionPublish
chatAttentionPublish = func(ctx context.Context, _, title, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
mu.Lock()
got = append(got, publishedNotice{title, stage.NtfyPriority(ctx)})
mu.Unlock()
return stage.Values{}, nil
}
t.Cleanup(func() { chatAttentionPublish = previous })
return func() []publishedNotice {
mu.Lock()
defer mu.Unlock()
return append([]publishedNotice(nil), got...)
for _, n := range active {
if strings.Contains(n.ID, ":auto-switch:") {
got = append(got, publishedNotice{n.Title, n.Priority})
}
}
return got
}
func autoSwitchServer(t *testing.T, sessions ...string) (*refusingChat, *queueServer, *pipeline.Store) {
@@ -109,8 +105,8 @@ func autoSwitchServer(t *testing.T, sessions ...string) (*refusingChat, *queueSe
// for the refusal is taken out, and a late one is refused. The operator is
// told at low priority.
func TestUsageRefusalSwitchesAccountAndQueuesAGuardedContinue(t *testing.T) {
published := capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
published := func() []publishedNotice { return autoSwitchNotices(t, store) }
conn := dialChatConn(t, server.ctx, server.srv)
if ack := sendPrompt(t, server.ctx, conn, "p1", "work", "op-1"); ack.ChatQueued {
t.Fatalf("first prompt queued: %+v", ack)
@@ -170,8 +166,8 @@ func TestUsageRefusalSwitchesAccountAndQueuesAGuardedContinue(t *testing.T) {
func TestUsageRefusalWithoutASwitchLeavesTheChat(t *testing.T) {
for _, failure := range []error{claude.ErrNoAccountLeft, claude.ErrAutoSwitchOff} {
t.Run(failure.Error(), func(t *testing.T) {
published := capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
published := func() []publishedNotice { return autoSwitchNotices(t, store) }
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) { return claude.AutoSwitch{}, failure }
conn := dialChatConn(t, server.ctx, server.srv)
if ack := sendScheduled(t, server.ctx, conn, "p1", "continue", "auto-continue-refusal-1", time.Now().Add(time.Hour)); !ack.ChatQueued {
@@ -191,7 +187,6 @@ func TestUsageRefusalWithoutASwitchLeavesTheChat(t *testing.T) {
// Chats refused together each get their own continue prompt; a chat that is
// not the operator's is left alone.
func TestConcurrentUsageRefusalsContinueEveryChat(t *testing.T) {
capturePublications(t)
broker, _, _ := autoSwitchServer(t, "ses_1", "ses_2")
broker.quiet = true
var once sync.Once
-1
View File
@@ -78,7 +78,6 @@ func restartChatDB(t *testing.T) string {
func fastReattach(t *testing.T) {
t.Helper()
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
poll := chatReattachPoll
chatReattachPoll = 20 * time.Millisecond
t.Cleanup(func() { chatReattachPoll = poll })
+2 -5
View File
@@ -46,14 +46,11 @@ type chatHub struct {
// to the other clients, so each retained user message has a stable id.
userSeq int
// attentionSeen/attentionOrder are the bounded hub-wide record of forms and
// approval requests already considered for an ntfy attention notification;
// attentionWG tracks in-flight publications.
// approval requests already considered for an attention notification;
// attentionWG tracks in-flight recordings.
attentionSeen map[string]struct{}
attentionOrder []string
attentionWG sync.WaitGroup
// outbox makes chat phone pushes durable and retried (chat_ntfy_outbox.go);
// nil publishes each push once, directly.
outbox chatNotificationOutbox
// 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{}
+1 -1
View File
@@ -26,7 +26,7 @@ import (
// pipeline stage session (created as a raw OpenCode session and recorded in
// run_steps/run_session_owners exactly as a run does) never appears in
// chat_sessions. It is opt-in (real inference) and never touches the deployed
// server, ntfy or any lane; it runs on a t.TempDir workspace.
// server or any lane; it runs on a t.TempDir workspace.
func TestChatLiveEndToEnd(t *testing.T) {
if os.Getenv("PIPELINES_TEST_OPENCODE_CHAT_LIVE") != "1" {
t.Skip("set PIPELINES_TEST_OPENCODE_CHAT_LIVE=1 to run the live OpenCode chat end-to-end check")
-1
View File
@@ -47,7 +47,6 @@ func (c *reportingChat) setRunning(running bool) {
func TestChatRunnerEndsItsTurnWhoseEndFrameWasLost(t *testing.T) {
fastUnattended(t)
fastStaleTurnSettle(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := &reportingChat{observedChat: newObservedChat()}
server := startQueueServer(t, broker, store)
+21 -58
View File
@@ -2,22 +2,18 @@ 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 {
@@ -33,63 +29,50 @@ func TestAgentNotifySuppressesThatTurnsReplyNotification(t *testing.T) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
h.attentionWG.Wait()
}
kinds := func() []string {
t.Helper()
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil {
t.Fatal(err)
}
var got []string
for _, n := range active {
got = append(got, n.Kind+":"+n.Title)
}
return got
}
start("turn_1")
if got := h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n1", Title: "Halfway", Message: "Tests pass"}); !got.App || !got.Phone {
if got := h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n1", Title: "Halfway", Message: "Tests pass"}); !got.App {
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)
if got := kinds(); len(got) != 1 || got[0] != protocol.NotificationChatNotify+":Halfway" {
t.Fatalf("turn with a notify recorded %+v", got)
}
// 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" {
got := kinds()
if len(got) != 3 || got[2] != protocol.NotificationChatReply+":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")
// Clearing a chat app notification on one device pushes the clear to every
// other connected client.
func TestClearingAChatNotificationClearsEveryClient(t *testing.T) {
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 {
if got := hub.publishToolNotification(ctx, "ses_c", chatToolNotice{ID: "shown_c", Title: "Look", Message: "Now"}); !got.App {
t.Fatalf("delivery = %+v", got)
}
id := "chat:ses_c:notify:shown_c"
@@ -98,11 +81,6 @@ func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
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}})
@@ -114,19 +92,4 @@ func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
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
@@ -1,54 +0,0 @@
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)
}
}
}()
}
-128
View File
@@ -1,128 +0,0 @@
package server
import (
"context"
"log"
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// Chat phone pushes (attention items and Claude auto-switch notices) go
// through a durable outbox like run notifications: the push is recorded first,
// one attempt is made at once, and a background worker retries a failed or
// interrupted attempt with backoff, also after a restart. A push whose app
// notification the operator already cleared is never published late, and a
// publication that raced a clear is cleared on the phone again, so the ntfy
// sequence-id/clear behaviour (chat_ntfy_clear.go) holds.
// chatNotificationOutbox is the durable chat push outbox; *pipeline.Store
// implements it.
type chatNotificationOutbox interface {
EnqueueChatNotification(ctx context.Context, n pipeline.ChatNotification, now time.Time) error
ClaimChatNotification(ctx context.Context, now int64) (*pipeline.ChatNotification, error)
FinishChatNotification(ctx context.Context, n pipeline.ChatNotification, now int64, messageID string, failure error) error
ChatNotificationCleared(ctx context.Context, id string) (bool, error)
Done() <-chan struct{}
}
// chatOutboxInterval is how often the worker looks for due retries.
var chatOutboxInterval = time.Second
// chatOutboxSkew shifts the outbox clock; tests move it past a backoff.
var chatOutboxSkew atomic.Int64
func chatOutboxNow() time.Time { return time.Now().Add(time.Duration(chatOutboxSkew.Load())) }
// startChatNotificationOutbox wires the durable outbox and starts its retry
// worker for the life of ctx.
func (h *chatHub) startChatNotificationOutbox(ctx context.Context, outbox chatNotificationOutbox) {
h.outbox = outbox
go func() {
ticker := time.NewTicker(chatOutboxInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-outbox.Done():
return
case <-ticker.C:
h.deliverChatNotifications(ctx, 16)
}
}
}()
}
// pushChatNtfy publishes one chat phone push. With an outbox it is recorded
// durably and attempted at once; without one (a store-less hub) it is a single
// direct attempt, as before.
func (h *chatHub) pushChatNtfy(ctx context.Context, n pipeline.ChatNotification) {
if h.outbox != nil {
err := h.outbox.EnqueueChatNotification(ctx, n, chatOutboxNow())
if err == nil {
h.deliverChatNotifications(ctx, 1)
return
}
log.Printf("enqueue chat notification %s: %v; publishing directly", n.ID, err)
}
if _, err := chatAttentionPublish(chatNtfyContext(ctx, n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(n)...); err != nil {
log.Printf("chat notification session=%s: %v", n.SessionID, err)
}
}
func chatNtfyContext(ctx context.Context, n pipeline.ChatNotification) context.Context {
if n.SequenceID != "" {
ctx = stage.WithNtfySequenceID(ctx, n.SequenceID)
}
if n.Priority > 0 {
ctx = stage.WithNtfyPriority(ctx, n.Priority)
}
return ctx
}
// chatNtfyViews derives the push's actions at delivery, so a changed web
// origin applies to a retried push.
func chatNtfyViews(n pipeline.ChatNotification) []stage.NtfyView {
_, views := chatAttentionLinks(n.SessionID)
return views
}
// deliverChatNotifications attempts up to limit due pushes.
func (h *chatHub) deliverChatNotifications(ctx context.Context, limit int) {
outbox := h.outbox
if outbox == nil {
return
}
for i := 0; i < limit && ctx.Err() == nil; i++ {
n, err := outbox.ClaimChatNotification(ctx, chatOutboxNow().Unix())
if err != nil {
log.Printf("claim chat notification: %v", err)
return
}
if n == nil {
return
}
publish, cancel := context.WithTimeout(ctx, 30*time.Second)
result, publishErr := chatAttentionPublish(chatNtfyContext(publish, *n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(*n)...)
cancel()
if publishErr != nil {
log.Printf("chat notification session=%s attempt=%d: %v", n.SessionID, n.Attempts, publishErr)
}
messageID, _ := result["message_id"].(string)
save, done := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
if err := outbox.FinishChatNotification(save, *n, chatOutboxNow().Unix(), messageID, publishErr); err != nil {
log.Printf("save chat notification %s: %v", n.ID, err)
}
// The operator may have cleared it in the app while it was being
// published, after the clear went to ntfy: clear it there again.
if publishErr == nil && n.SequenceID != "" {
if cleared, err := outbox.ChatNotificationCleared(save, n.ID); err == nil && cleared {
clearChatNtfy([]string{n.ID})
}
}
done()
}
}
-61
View File
@@ -1,61 +0,0 @@
package server
import (
"context"
"errors"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// A chat attention push that ntfy refuses is kept in the durable outbox and
// retried by the worker with its sequence id, not lost after one attempt.
func TestChatAttentionPushIsRetriedFromTheOutbox(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
interval := chatOutboxInterval
chatOutboxInterval = 20 * time.Millisecond
defer func() { chatOutboxInterval = interval }()
var mu sync.Mutex
var sequences []string
original := chatAttentionPublish
chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
mu.Lock()
defer mu.Unlock()
sequences = append(sequences, stage.NtfySequence(ctx))
if len(sequences) == 1 {
return nil, errors.New("ntfy unavailable")
}
return stage.Values{"message_id": "m1"}, nil
}
defer func() { chatAttentionPublish = original }()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
h := chatAttentionHub(t, "ses_a")
h.settings = store
h.notes = newAppNotifier(store)
h.startChatNotificationOutbox(ctx, store)
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_a", Kind: "question", Title: "Ship it?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_a", Kind: protocol.ChatEventForm, Form: &form})
h.attentionWG.Wait()
id := "chat:ses_a:form:que_1"
if status, attempts, err := store.ChatNotificationStatus(ctx, id); err != nil || status != "pending" || attempts != 1 {
t.Fatalf("after a refused attempt: %s/%d %v", status, attempts, err)
}
// The first backoff is 5 s; move the outbox clock past it.
chatOutboxSkew.Store(int64(10 * time.Second))
defer chatOutboxSkew.Store(0)
waitFor(t, "retried push sent", func() bool {
status, _, _ := store.ChatNotificationStatus(ctx, id)
return status == "sent"
})
mu.Lock()
defer mu.Unlock()
if len(sequences) != 2 || sequences[0] != chatNtfySequence(id) || sequences[1] != sequences[0] {
t.Fatalf("sequence ids = %v", sequences)
}
}
-1
View File
@@ -89,7 +89,6 @@ func TestChatPromptBehindAnUnqueuedScheduledHeadRunsAfterRestart(t *testing.T) {
func TestChatQueueEndsAStaleObservedTurnOnceTheHarnessIsIdle(t *testing.T) {
fastUnattended(t)
fastStaleTurnSettle(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := newObservedChat()
server := startQueueServer(t, broker, store)
+1 -2
View File
@@ -130,8 +130,7 @@ func truncateRunes(text string, limit int) string {
}
// chatReplyText builds a finished reply's title and body. The body keeps the
// reply's paragraph breaks for the app's notifications; ntfy gets it on one
// line (see chatAttentionPublishBody).
// reply's paragraph breaks for the app's notifications.
func chatReplyText(name, body string) (string, string) {
name = singleLine(name)
if name == "" {
@@ -15,10 +15,6 @@ func TestReplyNotificationKeepsParagraphs(t *testing.T) {
if body != "One\n\nTwo" {
t.Fatalf("app body should keep paragraph breaks, got %q", body)
}
// ntfy gets the same text on one line.
if flat := singleLine(body); strings.Contains(flat, "\n") || flat != "One Two" {
t.Fatalf("ntfy body = %q", flat)
}
long := truncateRunes(strings.Repeat("a", 1500), chatReplyBodyRunes)
if n := utf8.RuneCountInString(long); n != chatReplyBodyRunes+1 || chatReplyBodyRunes != 1000 {
t.Fatalf("excerpt is %d runes (limit %d)", n, chatReplyBodyRunes)
+11 -24
View File
@@ -6,7 +6,6 @@ import (
"encoding/hex"
"errors"
"io"
"log"
"mime"
"net/http"
"net/url"
@@ -16,7 +15,6 @@ 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.
@@ -135,19 +133,17 @@ type chatToolNotice struct {
// chatToolDelivery reports where a chat tool notification went: App when it
// was recorded on the app notification stream (every connected Pipelines app
// receives it and a reconnecting one replays it), Phone when ntfy accepted it.
// Detail explains a phone delivery that was skipped or refused.
// receives it and a reconnecting one replays it). Detail explains a failure.
type chatToolDelivery struct {
App bool
Phone bool
Detail string
}
// chatToolNotifier delivers one model-requested notification for a chat.
type chatToolNotifier func(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery
// chatNotifyPriority maps the tool's priority word to the app stream's
// ntfy-style 1-5 priority.
// chatNotifyPriority maps the tool's priority word to the app stream's 1-5
// priority (3 is the default).
func chatNotifyPriority(priority string) int {
switch priority {
case "low":
@@ -160,14 +156,12 @@ func chatNotifyPriority(priority string) int {
// publishToolNotification records the notification on the app notification
// stream (kind chat_notify), which is pushed to every subscribed client and
// replayed to one that reconnects while it is still active, then publishes it
// through the operator's existing "system" ntfy destination (the one chat
// attention uses), honoring their ntfy switch. Tapping it opens the chat
// (pipelines://chat/<id>).
// replayed to one that reconnects while it is still active. Tapping it opens
// the chat (pipelines://chat/<id>).
func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
title := truncateUTF8(notice.Title, 256)
message := truncateUTF8(notice.Message, 2000)
click, views := chatAttentionLinks(sessionID)
click := chatAttentionClick(sessionID)
id := notice.ID
if id == "" {
digest := sha256.Sum256([]byte(title + "\x00" + message))
@@ -182,19 +176,12 @@ func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string,
})
}
switch {
case !chatAttentionConfigured():
delivery.Detail = "phone notifications (ntfy) are not configured"
case !chatNotificationSettings(ctx, h.settings).NtfyEnabled:
delivery.Detail = "phone notifications (ntfy) are turned off"
default:
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
}
case h.notes == nil:
delivery.Detail = "the app notification stream is not available"
case !delivery.App:
delivery.Detail = "the notification could not be recorded"
}
if delivery.App || delivery.Phone {
if delivery.App {
// This turn has pinged the operator; its end is not announced again.
h.markTurnNotified(sessionID)
}
+2 -12
View File
@@ -169,20 +169,10 @@ 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}
item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App, 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."}
case delivery.App:
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps; " + delivery.Detail + "."}
case delivery.Phone:
return &item, chattools.Result{Text: "Delivered to the operator's phone notifications."}
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps."}
}
return &item, chattools.Result{Text: "Not delivered: " + delivery.Detail + ".", IsError: true}
}
+9 -9
View File
@@ -38,7 +38,7 @@ func newChatToolFixture(t *testing.T) *chatToolFixture {
}
f.service.notify = func(_ context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
f.notified = append(f.notified, sessionID+": "+notice.Title)
return chatToolDelivery{App: true, Phone: true}
return chatToolDelivery{App: true}
}
return f
}
@@ -240,7 +240,7 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
f.service.now = func() time.Time { return now }
for i := range 5 {
if r := f.call(a, "notify", `{"title":"Done","message":"Build finished","priority":"high"}`); r.IsError ||
r.Text != "Delivered to the operator's Pipelines apps and phone notifications." {
r.Text != "Delivered to the operator's Pipelines apps." {
t.Fatalf("notification %d: %v", i, r)
}
}
@@ -261,30 +261,30 @@ 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" || strings.Join(got[0].Channels, ",") != "apps,phone" {
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" || strings.Join(got[0].Channels, ",") != "apps" {
t.Fatalf("items = %+v", got)
}
f.service.notify = func(context.Context, string, chatToolNotice) chatToolDelivery {
return chatToolDelivery{Detail: "ntfy is not configured"}
return chatToolDelivery{Detail: "the notification could not be recorded"}
}
r := f.call(b, "notify", `{"title":"Fails","message":"x"}`)
if !r.IsError || !strings.Contains(r.Text, "ntfy is not configured") {
if !r.IsError || !strings.Contains(r.Text, "the notification could not be recorded") {
t.Fatalf("an undelivered notification is reported: %v", r)
}
if last := f.items(t, "ses_n2"); len(last) != 2 || last[1].Delivered || last[1].Detail != "ntfy is not configured" {
if last := f.items(t, "ses_n2"); len(last) != 2 || last[1].Delivered || last[1].Detail != "the notification could not be recorded" {
t.Fatalf("the undelivered entry is recorded: %+v", last)
}
// Apps only (ntfy off): the agent is told where it went.
// Delivered: the agent is told where it went.
f.service.notify = func(_ context.Context, _ string, notice chatToolNotice) chatToolDelivery {
if !strings.HasPrefix(notice.ID, "shown_") || notice.Priority != "low" {
t.Errorf("notice = %+v", notice)
}
return chatToolDelivery{App: true, Detail: "phone notifications (ntfy) are turned off"}
return chatToolDelivery{App: true}
}
r = f.call(b, "notify", `{"title":"Apps","message":"x","priority":"low"}`)
if r.IsError || r.Text != "Delivered to the operator's Pipelines apps; phone notifications (ntfy) are turned off." {
if r.IsError || r.Text != "Delivered to the operator's Pipelines apps." {
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_") || strings.Join(last[2].Channels, ",") != "apps" {
+28 -14
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"path/filepath"
"strings"
"sync"
"testing"
"time"
@@ -105,6 +106,28 @@ func chatNotes(t *testing.T, store *pipeline.Store, kind string) []protocol.AppN
return out
}
// chatNoteTotal counts every chat notification ever recorded, active or
// cleared.
func chatNoteTotal(t *testing.T, store *pipeline.Store) int {
t.Helper()
active, cleared, err := store.ActiveAppNotifications(context.Background(), "", time.Now())
if err != nil {
t.Fatal(err)
}
total := 0
for _, n := range active {
if strings.HasPrefix(n.ID, "chat:") {
total++
}
}
for _, id := range cleared {
if strings.HasPrefix(id, "chat:") {
total++
}
}
return total
}
func stepFrameFor(status, turn string) protocol.ChatEventFrame {
return protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: status, TurnID: turn}}
}
@@ -114,11 +137,10 @@ func textFrame(text string) protocol.ChatEventFrame {
}
// A turn started from the app keeps being observed after the app closes, so
// its finished reply is recorded (app stream) and published (ntfy) once, and
// its finished reply is recorded on the app stream once, and
// the observer is torn down when the turn ends.
func TestChatReplyNotifiesAfterLastClientLeaves(t *testing.T) {
fastUnattended(t)
captured := newNtfyCapture(t)
store := unattendedStore(t, true)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -135,11 +157,10 @@ func TestChatReplyNotifiesAfterLastClientLeaves(t *testing.T) {
broker.push(stepFrameFor(protocol.ChatStepEnded, "turn_1"))
waitFor(t, "reply notification", func() bool { return len(chatNotes(t, store, protocol.NotificationChatReply)) == 1 })
waitFor(t, "observer torn down", func() bool { active, _ := broker.streams(); return active == 0 })
waitFor(t, "ntfy publish", func() bool { return len(captured()) == 1 })
time.Sleep(50 * time.Millisecond)
notes := chatNotes(t, store, protocol.NotificationChatReply)
if got := captured(); len(notes) != 1 || len(got) != 1 || got[0].Title != "Release prep replied" || got[0].Message != "The build is green." {
t.Fatalf("notes=%+v ntfy=%+v", notes, got)
if len(notes) != 1 || notes[0].Title != "Release prep replied" || chatNoteTotal(t, store) != 1 {
t.Fatalf("notes=%+v", notes)
}
if notes[0].Message != "The build is green." || notes[0].Click != "pipelines://chat/ses_1" {
t.Fatalf("note = %+v", notes[0])
@@ -150,7 +171,6 @@ func TestChatReplyNotifiesAfterLastClientLeaves(t *testing.T) {
// nothing, even though the unattended turn is observed.
func TestChatUnattendedReplyRespectsSetting(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -170,7 +190,6 @@ func TestChatUnattendedReplyRespectsSetting(t *testing.T) {
// A question the agent asks while no client is attached notifies.
func TestChatQuestionNotifiesWithNoClient(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -196,7 +215,6 @@ func TestChatQuestionNotifiesWithNoClient(t *testing.T) {
// announced exactly once and the client sees the turn end.
func TestChatReattachMidTurnDoesNotDuplicate(t *testing.T) {
fastUnattended(t)
captured := newNtfyCapture(t)
store := unattendedStore(t, true)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -227,8 +245,8 @@ func TestChatReattachMidTurnDoesNotDuplicate(t *testing.T) {
}
waitFor(t, "reply notification", func() bool { return len(chatNotes(t, store, protocol.NotificationChatReply)) == 1 })
time.Sleep(100 * time.Millisecond)
if got := captured(); len(got) != 2 {
t.Fatalf("ntfy deliveries = %+v, want one question and one reply", got)
if got := chatNoteTotal(t, store); got != 2 {
t.Fatalf("recorded notifications = %d, want one question and one reply", got)
}
if n := len(chatNotes(t, store, protocol.NotificationChatQuestion)) + len(chatNotes(t, store, protocol.NotificationChatReply)); n > 2 {
t.Fatalf("duplicate notifications: %d", n)
@@ -242,7 +260,6 @@ func TestChatReattachMidTurnDoesNotDuplicate(t *testing.T) {
// start does not observe sessions whose harness reports no running turn.
func TestChatIdleSessionWithNoClientIsNotObserved(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, true)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -266,7 +283,6 @@ func TestChatIdleSessionWithNoClientIsNotObserved(t *testing.T) {
// with no client, so its reply still notifies; then the observer goes away.
func TestChatRunningTurnObservedAfterRestart(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, true)
broker := newObservedChat()
broker.probe["ses_1"] = true
@@ -284,7 +300,6 @@ func TestChatRunningTurnObservedAfterRestart(t *testing.T) {
// a later authoritative idle result releases it.
func TestChatRecoveredBusySessionWaitsForAuthoritativeIdle(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, true)
broker := newObservedChat()
broker.probe["ses_1"] = true
@@ -303,7 +318,6 @@ func TestChatRecoveredBusySessionWaitsForAuthoritativeIdle(t *testing.T) {
// A turn that never reports its end does not hold an observer forever.
func TestChatStuckUnattendedTurnIsReleased(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
limit := chatUnattendedTurnLimit
chatUnattendedTurnLimit = 300 * time.Millisecond
t.Cleanup(func() { chatUnattendedTurnLimit = limit })
+4 -19
View File
@@ -2,14 +2,10 @@ package server
import (
"context"
"encoding/json"
"fmt"
"mime"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -386,19 +382,6 @@ func TestHumanStageWaitingNotification(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
filename, _ := new(mime.WordDecoder).DecodeHeader(r.Header.Get("Filename"))
ack := map[string]any{"id": "msg1", "event": "message"}
if filename != "" {
ack["attachment"] = map[string]string{"name": filename, "url": "https://ntfy.example.com/file/" + filename}
}
_ = json.NewEncoder(w).Encode(ack)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
source := strings.Replace(humanPipelineSource, "```configs\ntype=human\n```", "```notify\non=waiting\n```\n\n```configs\ntype=human\n```", 1)
if _, err := store.Submit(ctx, "human-notify", source); err != nil {
t.Fatal(err)
@@ -414,14 +397,16 @@ func TestHumanStageWaitingNotification(t *testing.T) {
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
defer r.wg.Wait()
run, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "human-notify", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if calls.Load() != 1 {
t.Fatalf("waiting notification fired %d times", calls.Load())
if got := recorder.recorded(); len(got) != 1 || got[0].Kind != protocol.NotificationRunWaiting {
t.Fatalf("waiting notification fired %d times: %+v", len(got), got)
}
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
+4 -4
View File
@@ -5,11 +5,11 @@ import (
"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.
// TestMain isolates the package from the operator's environment: a developer
// shell may export the installed server's web origin, which tests must not
// pick up.
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"} {
for _, name := range []string{"PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
+40 -10
View File
@@ -89,8 +89,34 @@ func TestNotificationSettingsProtocol(t *testing.T) {
wantSettings(t, replies[0], updated)
}
// ntfy was removed. An older app may still send its "also send to ntfy"
// switch, alone or beside a real setting: the key is accepted and ignored,
// and every reply carries exactly the three notification settings.
func TestLegacyNtfySettingIsAcceptedAndIgnored(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.SetNotificationSettings, ID: "ntfy", NotificationSettings: map[string]any{protocol.LegacyNotifyNtfyEnabled: false}},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "mixed", NotificationSettings: map[string]any{protocol.LegacyNotifyNtfyEnabled: true, protocol.NotifyRunFinished: true}},
protocol.Message{Type: protocol.GetNotificationSettings, ID: "get"},
)
want := protocol.DefaultNotificationSettings()
wantSettings(t, replies[0], want)
want.RunFinished = true
wantSettings(t, replies[1], want)
wantSettings(t, replies[2], want)
for _, reply := range replies {
if len(reply.NotificationSettings) != 3 {
t.Fatalf("reply carries %d settings: %+v", len(reply.NotificationSettings), reply)
}
if _, present := reply.NotificationSettings[protocol.LegacyNotifyNtfyEnabled]; present {
t.Fatalf("reply still carries ntfy_enabled: %+v", reply)
}
}
}
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)
@@ -98,6 +124,9 @@ func TestChatNeedsYouSettingSuppressesQuestionsAndApprovals(t *testing.T) {
h := chatAttentionHub(t, "ses_quiet")
h.registry = store
h.settings = store
notes, recorder := newNoteCapture(t, store)
h.notes = notes
captured := recorder.recorded
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?"})
@@ -127,8 +156,6 @@ func replyTurn(h *chatHub, session, turnID, messageID, text string) {
}
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 {
@@ -137,6 +164,9 @@ func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
h := chatAttentionHub(t, "ses_done", "ses_bare")
h.registry = store
h.settings = store
notes, recorder := newNoteCapture(t, store)
h.notes = notes
captured := recorder.recorded
// Off by default: a finished turn is silent.
replyTurn(h, "ses_done", "turn_0", "msg_0", "Quiet reply")
h.attentionWG.Wait()
@@ -162,10 +192,9 @@ func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
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)
if n := got[0]; n.Title != "Release prep replied" || n.Click != "pipelines://chat/ses_done" || n.Kind != protocol.NotificationChatReply ||
!strings.HasPrefix(n.Message, "The build\nis green. xxx") {
t.Fatalf("got %+v", n)
}
// The next genuine turn notifies again; a turn without text (and a
// session without a title or native turn ids) uses the fallback text.
@@ -186,8 +215,9 @@ func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
}
}
func TestChatReplyFinishedNeedsNtfyConfiguration(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
// Without the app notification stream a finished turn has nowhere to go and
// is not even considered.
func TestChatReplyFinishedNeedsTheAppStream(t *testing.T) {
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
t.Fatal(err)
@@ -199,6 +229,6 @@ func TestChatReplyFinishedNeedsNtfyConfiguration(t *testing.T) {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.attentionSeen) != 0 {
t.Fatalf("unconfigured ntfy still considered a publication: %v", h.attentionSeen)
t.Fatalf("a stream-less hub still considered a notification: %v", h.attentionSeen)
}
}
-31
View File
@@ -1,31 +0,0 @@
package server
import (
"git.a-wan.net/alan/pipelines/internal/protocol"
"net/url"
"os"
"regexp"
"strings"
)
var notificationTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
func publicNtfyBase(text string) string {
u, err := url.Parse(text)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
return ""
}
return strings.TrimRight(u.String(), "/")
}
func notificationEndpoints() []protocol.NotificationEndpoint {
u, err := url.Parse(os.Getenv("PIPELINES_NTFY_URL"))
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.RawPath != "" {
return nil
}
topic := strings.TrimPrefix(u.Path, "/")
if !notificationTopic.MatchString(topic) {
return nil
}
return []protocol.NotificationEndpoint{{Destination: "system", ServerURL: publicNtfyBase(os.Getenv("PIPELINES_NTFY_PUBLIC_URL")), Topic: topic}}
}
@@ -1,34 +0,0 @@
package server
import (
"testing"
)
func TestPublicNotificationSetup(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "private-token")
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "http://10.0.0.249:8090")
found := false
for _, endpoint := range notificationEndpoints() {
if endpoint.Destination == "system" {
found = true
if endpoint.ServerURL != "http://10.0.0.249:8090" || endpoint.Topic != "pipelines" {
t.Fatal(endpoint)
}
}
}
if !found {
t.Fatal("missing destination")
}
for _, value := range []string{"http://user:secret@example.com", "http://example.com?token=secret", "file:///tmp/secret", "http://example.com/topic"} {
if publicNtfyBase(value) != "" {
t.Fatal("unsafe public URL accepted", value)
}
}
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "")
for _, endpoint := range notificationEndpoints() {
if endpoint.ServerURL != "" {
t.Fatal("internal URL exposed", endpoint)
}
}
}
+116 -143
View File
@@ -2,136 +2,117 @@ package server
import (
"context"
"encoding/json"
"mime"
"net/http"
"net/http/httptest"
"errors"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func TestRunNotificationAppClickAndWebAction(t *testing.T) {
for _, tc := range []struct{ base, view string }{
{"https://pipelines.example.com", "https://pipelines.example.com/runs/20"},
{"http://10.0.0.75:8095/", "http://10.0.0.75:8095/runs/20"},
{"", ""}, // No web origin: the app link alone.
{"javascript:alert(1)", ""},
{"https://user:password@example.com", ""},
{"https://example.com?token=secret", ""},
{"https://example.com/#fragment", ""},
{"https://example.com/subpath", ""}, // Web app uses origin-root routes.
{"/runs", ""},
{"https://example.com\r\nClick:bad", ""},
} {
t.Run(tc.base, func(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", tc.base)
if got := runAttentionClick(20); got != "pipelines://run/20" {
t.Fatalf("click = %q", got)
}
views := runAttentionViews(20)
if tc.view == "" {
if len(views) != 0 {
t.Fatalf("unexpected views %+v", views)
}
return
}
if len(views) != 1 || views[0].Label != "Open in browser" || views[0].URL != tc.view {
t.Fatalf("views = %+v, want %q", views, tc.view)
}
})
func TestRunNotificationAppClick(t *testing.T) {
if got := runAttentionClick(20); got != "pipelines://run/20" {
t.Fatalf("click = %q", got)
}
if got := chatAttentionClick("ses/x"); got != "pipelines://chat/ses%2Fx" {
t.Fatalf("chat click = %q", got)
}
}
type ntfyCapture struct {
Title, Message, Click, Actions string
// recordingNotes wraps an app notification store and keeps every newly
// recorded notification, in order, so a test sees exactly what the app stream
// was given (also after a clear). fail makes every record fail, failNext the
// next few; calls counts every attempt, failed or not.
type recordingNotes struct {
appNotificationStore
mu sync.Mutex
got []protocol.AppNotification
fail bool
failNext int
calls int
}
// newNtfyCapture points the system destination at a mock ntfy endpoint.
func newNtfyCapture(t *testing.T) func() []ntfyCapture {
func (r *recordingNotes) RecordAppNotification(ctx context.Context, n pipeline.AppNotificationRecord, now time.Time) (protocol.AppNotification, bool, error) {
r.mu.Lock()
r.calls++
fail := r.fail || r.failNext > 0
if r.failNext > 0 {
r.failNext--
}
r.mu.Unlock()
if fail {
return protocol.AppNotification{}, false, errors.New("record refused")
}
stored, fresh, err := r.appNotificationStore.RecordAppNotification(ctx, n, now)
if err == nil && fresh {
r.mu.Lock()
r.got = append(r.got, stored)
r.mu.Unlock()
}
return stored, fresh, err
}
func (r *recordingNotes) attempts() int {
r.mu.Lock()
defer r.mu.Unlock()
return r.calls
}
func (r *recordingNotes) recorded() []protocol.AppNotification {
r.mu.Lock()
defer r.mu.Unlock()
return append([]protocol.AppNotification(nil), r.got...)
}
// newNoteCapture returns an app notifier over store (a scratch store when
// nil) and a reader of everything it recorded.
func newNoteCapture(t *testing.T, store *pipeline.Store) (*appNotifier, *recordingNotes) {
t.Helper()
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"))
mu.Lock()
got = append(got, ntfyCapture{title, message, r.Header.Get("Click"), r.Header.Get("Actions")})
mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]string{"id": "msg", "event": "message"})
}))
t.Cleanup(srv.Close)
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
return func() []ntfyCapture {
mu.Lock()
defer mu.Unlock()
return append([]ntfyCapture(nil), got...)
if store == nil {
store = newOperatorStore(t)
}
recorder := &recordingNotes{appNotificationStore: store}
return newAppNotifier(recorder), recorder
}
// Rows queued by older servers hold a web URL, the old placeholder deep link or
// an empty click (an invalid web origin). Each delivers with the app link and
// the current web action.
// an empty click (an invalid web origin). Each is recorded with the app link.
func TestQueuedLegacyRunNotificationsUseAppLink(t *testing.T) {
for _, web := range []string{"https://pipelines.example.com", ""} {
t.Run("web="+web, func(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", web)
captured := newNtfyCapture(t)
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "legacy.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
clicks := map[int64]string{7: "https://pipelines.example.com/runs/7", 8: "pipelines://run/8", 9: ""}
for id, click := range clicks {
if err := s.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "failed", Channel: "system", Title: "Run failed", Body: "Run failed", Click: click}); err != nil {
t.Fatal(err)
}
}
r := &runner{ctx: ctx, store: s}
r.deliverRunNotifications(time.Now())
got := captured()
if len(got) != 3 {
t.Fatalf("deliveries = %+v", got)
}
seen := map[string]bool{}
for _, n := range got {
seen[n.Click] = true
want := ""
if web != "" {
want = "view, Open in browser, " + web + "/runs/" + n.Click[len("pipelines://run/"):]
}
if n.Actions != want {
t.Fatalf("actions = %q, want %q", n.Actions, want)
}
}
for _, click := range []string{"pipelines://run/7", "pipelines://run/8", "pipelines://run/9"} {
if !seen[click] {
t.Fatalf("missing %s in %+v", click, got)
}
}
for id := range clicks {
rows, err := s.RunNotifications(ctx, id)
if err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("run %d rows = %+v %v", id, rows, err)
}
}
})
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "legacy.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
clicks := map[int64]string{7: "https://pipelines.example.com/runs/7", 8: "pipelines://run/8", 9: ""}
for id, click := range clicks {
if err := s.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "failed", Channel: "system", Title: "Run failed", Body: "Run failed", Click: click}); err != nil {
t.Fatal(err)
}
}
notes, recorder := newNoteCapture(t, s)
r := &runner{ctx: ctx, store: s, notes: notes}
r.deliverRunNotifications(time.Now())
got := recorder.recorded()
if len(got) != 3 {
t.Fatalf("deliveries = %+v", got)
}
seen := map[string]bool{}
for _, n := range got {
seen[n.Click] = true
}
for _, click := range []string{"pipelines://run/7", "pipelines://run/8", "pipelines://run/9"} {
if !seen[click] {
t.Fatalf("missing %s in %+v", click, got)
}
}
for id := range clicks {
rows, err := s.RunNotifications(ctx, id)
if err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("run %d rows = %+v %v", id, rows, err)
}
}
}
@@ -145,14 +126,14 @@ func chatAttentionHub(t *testing.T, sessions ...string) *chatHub {
}
func TestChatQuestionNotifiesOnceWithAppLink(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
captured := newNtfyCapture(t)
store := newOperatorStore(t)
if err := store.RecordOperatorSession(context.Background(), "ses_q", t.TempDir(), "Release prep", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_q")
h.registry = store
notes, recorder := newNoteCapture(t, store)
h.notes = notes
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_q", Kind: "question", Title: "Which branch\nshould ship?"}
frame := protocol.ChatEventFrame{SessionID: "ses_q", Kind: protocol.ChatEventForm, Form: &form}
h.emit(frame)
@@ -163,27 +144,27 @@ func TestChatQuestionNotifiesOnceWithAppLink(t *testing.T) {
h.mu.Unlock()
h.emit(frame)
h.attentionWG.Wait()
got := captured()
got := recorder.recorded()
if len(got) != 1 {
t.Fatalf("deliveries = %+v", got)
}
want := ntfyCapture{Title: "Release prep needs your answer", Message: "Which branch should ship?", Click: "pipelines://chat/ses_q", Actions: "view, Open in browser, https://pipelines.example.com/chat/ses_q"}
if got[0] != want {
t.Fatalf("got %+v, want %+v", got[0], want)
if n := got[0]; n.Title != "Release prep needs your answer" || n.Message != "Which branch should ship?" || n.Click != "pipelines://chat/ses_q" {
t.Fatalf("got %+v", n)
}
// Resolution and a later stale copy publish nothing more.
// Resolution and a later stale copy record nothing more.
resolved := form
resolved.Resolved = true
h.emit(protocol.ChatEventFrame{SessionID: "ses_q", Kind: protocol.ChatEventForm, Form: &resolved})
h.attentionWG.Wait()
if n := len(captured()); n != 1 {
t.Fatalf("resolution republished: %d", n)
if n := len(recorder.recorded()); n != 1 {
t.Fatalf("resolution re-recorded: %d", n)
}
}
func TestChatResolvedOrReplayedFormsDoNotNotify(t *testing.T) {
captured := newNtfyCapture(t)
h := chatAttentionHub(t, "ses_r")
notes, recorder := newNoteCapture(t, nil)
h.notes = notes
resolved := protocol.ChatForm{ID: "que_old", SessionID: "ses_r", Kind: "question", Title: "Old?", Resolved: true}
cancelled := protocol.ChatForm{ID: "que_gone", SessionID: "ses_r", Kind: "question", Title: "Gone?", Cancelled: true}
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventForm, Form: &resolved})
@@ -196,14 +177,15 @@ func TestChatResolvedOrReplayedFormsDoNotNotify(t *testing.T) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventText, MessageID: "msg_1", Part: &protocol.ChatPart{ID: "p1"}, Delta: "done"})
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}})
h.attentionWG.Wait()
if got := captured(); len(got) != 0 {
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("unexpected deliveries %+v", got)
}
}
func TestChatPermissionNotifiesOnce(t *testing.T) {
captured := newNtfyCapture(t) // No web origin: no browser action.
h := chatAttentionHub(t, "ses_p")
notes, recorder := newNoteCapture(t, nil)
h.notes = notes
frame := protocol.ChatPermissionFrame{SessionID: "ses_p", RequestID: "per_1", Action: "bash", Message: "Run rm -rf build?"}
h.pushPermission("ses_p", frame)
h.pushPermission("ses_p", frame)
@@ -215,40 +197,31 @@ func TestChatPermissionNotifiesOnce(t *testing.T) {
resolved := protocol.ChatPermissionFrame{SessionID: "ses_p", RequestID: "per_2", Message: "Already answered", Resolved: true}
h.pushPermission("ses_p", resolved)
h.attentionWG.Wait()
got := captured()
want := ntfyCapture{Title: "Chat needs your approval", Message: "Run rm -rf build?", Click: "pipelines://chat/ses_p"}
if len(got) != 1 || got[0] != want {
t.Fatalf("deliveries = %+v, want one %+v", got, want)
got := recorder.recorded()
if len(got) != 1 || got[0].Title != "Chat needs your approval" || got[0].Message != "Run rm -rf build?" || got[0].Click != "pipelines://chat/ses_p" {
t.Fatalf("deliveries = %+v", got)
}
}
func TestChatAttentionNeedsNtfyConfiguration(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
calls := 0
original := chatAttentionPublish
chatAttentionPublish = func(context.Context, string, string, string, string, []byte, string, ...stage.NtfyView) (stage.Values, error) {
calls++
return nil, nil
}
defer func() { chatAttentionPublish = original }()
// Without the app notification stream a chat attention item has nowhere to
// go, so it is not even claimed.
func TestChatAttentionNeedsTheAppStream(t *testing.T) {
h := chatAttentionHub(t, "ses_n")
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_n", Kind: "question", Title: "Ready?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventForm, Form: &form})
h.pushPermission("ses_n", protocol.ChatPermissionFrame{SessionID: "ses_n", RequestID: "per_1", Message: "Allow?"})
h.attentionWG.Wait()
if calls != 0 {
t.Fatalf("published %d without ntfy configuration", calls)
if len(h.attentionSeen) != 0 {
t.Fatalf("claimed without a notification stream: %v", h.attentionSeen)
}
}
// A failing ntfy endpoint never blocks or fails chat handling.
// A failing notification store never blocks or fails chat handling.
func TestChatAttentionFailureIsOnlyLogged(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusServiceUnavailable)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
h := chatAttentionHub(t, "ses_f")
notes, recorder := newNoteCapture(t, nil)
recorder.fail = true
h.notes = notes
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_f", Kind: "question", Title: "Ready?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_f", Kind: protocol.ChatEventForm, Form: &form})
h.attentionWG.Wait()
+31 -218
View File
@@ -5,7 +5,6 @@ import (
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"log"
"mime"
@@ -16,7 +15,6 @@ import (
"path/filepath"
"regexp"
"strings"
"syscall"
"time"
"unicode/utf8"
)
@@ -62,149 +60,41 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
summary := stageNotificationSummary(name, id, step.Stage, event, step.Outcome)
summary = truncateUTF8(summary, 1800)
title := fmt.Sprintf("Pipeline stage %s", event)
receipts := []protocol.NotificationReceipt{}
persist := func() bool {
save, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := r.store.SaveNotifications(save, id, step.Sequence, receipts); err != nil {
log.Printf("notification audit run=%d step=%d: %v", id, step.Sequence, err)
return false
}
return true
}
// The app stream gets one notification per step event, recorded before
// the first ntfy publication; artifacts stay ntfy attachments.
// The app stream gets one notification per step event.
appEvent, appKind := stageNotification(event, step.Target)
// A `link=` file decides the tap target; it is never the attached artifact.
link, linkFile, linkDiagnostic := r.resolveNotificationLink(id, policy.Link)
appArtifact, appPreview := r.resolveNotificationArtifact(id, step.Sequence, policy.Open, linkFile)
recorded := false
ntfyOn := ntfyEnabled(ctx, r.settingsStore())
views := runAttentionViews(id)
ntfyClick, linkNote := ntfyLinkClick(id, link, views)
if ntfyOn && linkDiagnostic == "" {
linkDiagnostic = linkNote
}
send := func(filename string, data []byte) {
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "sending", Filename: filename})
if !persist() {
return
receipt := protocol.NotificationReceipt{Destination: "app", Status: "sent", Diagnostic: linkDiagnostic}
if !r.notes.record(ctx, withNotificationLink(runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview), link)) {
receipt.Status = "failed"
if receipt.Diagnostic != "" {
receipt.Diagnostic += "; "
}
receipt := &receipts[len(receipts)-1]
if !recorded {
recorded = true
r.notes.record(ctx, withNotificationLink(runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview), link))
}
if !ntfyOn {
receipt.Status = "sent"
receipt.Diagnostic = "ntfy disabled; delivered to app clients only"
persist()
return
}
result, err := ntfyPublish(ctx, "system", title, summary, filename, data, ntfyClick, views...)
if err != nil {
receipt.Status = "failed"
receipt.Diagnostic = err.Error()
} else {
receipt.Status = "sent"
receipt.MessageID, _ = result["message_id"].(string)
receipt.AttachmentURL, _ = result["attachment_url"].(string)
}
persist()
}
reject := func(filename, diagnostic string) {
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "failed", Filename: filename, Diagnostic: diagnostic})
persist()
}
sentArtifact := false
for _, kind := range policy.Artifacts {
switch kind {
case "markdown":
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
sentArtifact = true
send("digest.md", []byte(markdown))
}
case "files":
raw, exists := step.Output["artifacts"]
if !exists {
continue
}
var names []string
switch files := raw.(type) {
case []string:
names = files
case []any:
for _, value := range files {
name, ok := value.(string)
if !ok {
reject("", "output.artifacts must be an array of relative file paths")
names = nil
break
}
names = append(names, name)
}
default:
reject("", "output.artifacts must be an array of relative file paths")
}
if len(names) > 10 {
reject("", "at most 10 file artifacts can be notified")
continue
}
seen := map[string]bool{}
for _, name := range names {
if seen[name] {
continue
}
seen[name] = true
data, err := notificationArtifact(workspace, name)
if err != nil {
reject(name, err.Error())
continue
}
sentArtifact = true
send(filepath.Base(name), data)
}
}
}
// No produced artifacts still merits an event, especially on failures.
if !sentArtifact {
send("", nil)
}
// The link note is recorded once, never as the run-level failure reason.
failure := "stage notification publication failed"
if len(receipts) > 0 && receipts[0].Diagnostic != "" {
failure = receipts[0].Diagnostic
}
if linkDiagnostic != "" && len(receipts) > 0 {
first := &receipts[0]
if first.Diagnostic != "" {
first.Diagnostic += "; "
}
first.Diagnostic += linkDiagnostic
persist()
}
// Only a successful publish covers the run alert. A failed stage publisher
// must not swallow the durable run-level fallback and its retries.
for _, receipt := range receipts {
if receipt.Status == "sent" {
covered := stageAttentionEvent(event)
if event == "success" && step.Target == protocol.SuccessEnd {
covered = "succeeded"
}
r.markAttentionSent(id, step.Sequence, covered)
return
receipt.Diagnostic += "the app notification was not recorded"
}
save, done := context.WithTimeout(context.Background(), 5*time.Second)
if err := r.store.SaveNotifications(save, id, step.Sequence, []protocol.NotificationReceipt{receipt}); err != nil {
log.Printf("notification audit run=%d step=%d: %v", id, step.Sequence, err)
}
done()
if receipt.Status == "sent" {
covered := stageAttentionEvent(event)
if event == "success" && step.Target == protocol.SuccessEnd {
covered = "succeeded"
}
r.markAttentionSent(id, step.Sequence, covered)
return
}
// A hook that recorded nothing must not swallow the durable run-level
// fallback and its retries.
if lease != nil {
if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("%s", failure)); err != nil {
if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("stage notification was not recorded")); err != nil {
log.Printf("release stage notification run=%d: %v", id, err)
}
}
}
// ntfyPublish is the run notification publisher; tests may replace it.
var ntfyPublish = stage.PublishNtfy
// stageNotification maps a stage hook event to the app notification event
// (the id suffix, shared with the run outbox for the same run event so the
// two never both appear) and kind.
@@ -360,35 +250,11 @@ func runAttentionClick(id int64) string {
return fmt.Sprintf("pipelines://run/%d", id)
}
// runAttentionViews is the optional "Open in browser" action for a run.
func runAttentionViews(id int64) []stage.NtfyView {
return webAttentionViews(fmt.Sprintf("/runs/%d", id))
}
// webAttentionViews returns an "Open in browser" ntfy action for path on the
// operator's authenticated web origin, or nothing when none is configured.
// Never infer a public address from a request Host, the unauthenticated API
// listener or the ntfy server URL.
func webAttentionViews(path string) []stage.NtfyView {
raw := os.Getenv("PIPELINES_WEB_PUBLIC_URL")
if raw == "" {
return nil
}
base := publicNtfyBase(raw)
if base == "" {
log.Printf("notification web link unavailable: PIPELINES_WEB_PUBLIC_URL must be an HTTP(S) origin without credentials, query or fragment")
return nil
}
return []stage.NtfyView{{Label: "Open in browser", URL: base + path}}
}
// notifyRun publishes one run-level attention notification to the operator's
// already-configured "system" destination. It is the run counterpart of
// notifyStep and reuses the same PublishNtfy machinery, destination and token
// handling, so no second publisher, topic or service is introduced. The run id
// and pipeline name identify the run and the click action opens it in the app.
// Attempts are persisted before publication. Publisher acknowledgement is not
// proof of device reception; a crash in that acknowledgement window can repeat.
// notifyRun records one run-level attention notification on the app
// notification stream. It is the run counterpart of notifyStep. The run id and
// pipeline name identify the run and the click action opens it in the app.
// The event goes through the durable run notification outbox, so a crash
// before it is recorded is recovered after a restart.
func (r *runner) notifyRun(id int64, name, status string, sequence int, currentStage, diagnostic string) {
if r.notifyMode(id) == "off" {
return
@@ -488,20 +354,13 @@ func (r *runner) deliverRunNotificationBatch(now time.Time, limit int) {
link, linkFile := r.stageHookLink(*n)
artifact, preview := r.resolveNotificationArtifact(n.RunID, n.Sequence, "", linkFile)
n.Click = notificationClick(n.RunID, n.Sequence, artifact)
r.notes.record(ctx, withNotificationLink(runNotificationRecord(n.RunID, n.Sequence, n.Event, runNotificationKind(n.Event), n.Title, n.Body, artifact, preview), link))
var result stage.Values
var publishErr error
if ntfyEnabled(ctx, r.settingsStore()) {
// ntfy retains its existing run-level tap target (or the hook's link);
// the richer artifact target is carried by the app notification stream.
views := runAttentionViews(n.RunID)
click, _ := ntfyLinkClick(n.RunID, link, views)
result, publishErr = ntfyPublish(ctx, n.Channel, n.Title, n.Body, "", nil, click, views...)
var recordErr error
if r.notes != nil && !r.notes.record(ctx, withNotificationLink(runNotificationRecord(n.RunID, n.Sequence, n.Event, runNotificationKind(n.Event), n.Title, n.Body, artifact, preview), link)) {
recordErr = fmt.Errorf("app notification was not recorded")
}
cancel()
messageID, _ := result["message_id"].(string)
save, done := context.WithTimeout(context.Background(), 5*time.Second)
err = r.store.FinishRunNotification(save, *n, now.Add(time.Since(started)).Unix(), messageID, publishErr)
err = r.store.FinishRunNotification(save, *n, now.Add(time.Since(started)).Unix(), "", recordErr)
done()
if err != nil {
log.Printf("save run notification run=%d: %v", n.RunID, err)
@@ -521,51 +380,6 @@ func truncateUTF8(text string, max int) string {
return text
}
func notificationArtifact(workspace, name string) ([]byte, error) {
if name == "" || filepath.IsAbs(name) || filepath.Clean(name) != name || strings.ContainsAny(name, "\\\x00\r\n") {
return nil, fmt.Errorf("artifact must be a clean workspace-relative file path")
}
for _, part := range strings.Split(filepath.ToSlash(name), "/") {
lower := strings.ToLower(part)
if strings.HasPrefix(part, ".") || lower == "secrets" || lower == "node_modules" || strings.HasSuffix(lower, ".pem") || strings.HasSuffix(lower, ".key") || strings.HasSuffix(lower, ".db") || strings.HasSuffix(lower, ".db-wal") || strings.HasSuffix(lower, ".db-shm") || strings.HasSuffix(lower, ".sqlite") || strings.HasSuffix(lower, ".sqlite3") {
return nil, fmt.Errorf("artifact path is protected")
}
}
root, err := filepath.EvalSymlinks(workspace)
if err != nil {
return nil, fmt.Errorf("artifact workspace unavailable")
}
// os.Root prevents symlink traversal outside the workspace; disallow symlinks
// altogether so aliases cannot bypass protected path names within it either.
current := root
for _, part := range strings.Split(name, string(os.PathSeparator)) {
current = filepath.Join(current, part)
info, err := os.Lstat(current)
if err != nil || info.Mode()&os.ModeSymlink != 0 {
return nil, fmt.Errorf("artifact is missing or uses a symlink")
}
}
scoped, err := os.OpenRoot(root)
if err != nil {
return nil, fmt.Errorf("artifact workspace unavailable")
}
defer scoped.Close()
file, err := scoped.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
if err != nil {
return nil, fmt.Errorf("cannot read artifact")
}
defer file.Close()
info, err := file.Stat()
if err != nil || !info.Mode().IsRegular() || info.Size() > 1<<20 {
return nil, fmt.Errorf("artifact must be a regular file at most 1 MiB")
}
data, err := io.ReadAll(io.LimitReader(file, (1<<20)+1))
if err != nil || len(data) > 1<<20 {
return nil, fmt.Errorf("cannot read artifact within size limit")
}
return data, nil
}
func notificationClick(runID int64, sequence int, artifact *protocol.NotificationArtifact) string {
if artifact == nil {
return runAttentionClick(runID)
@@ -578,7 +392,6 @@ func notificationClick(runID int64, sequence int, artifact *protocol.Notificatio
}
// resolveNotificationArtifact selects only files in the run's shared public/.
// It is deliberately independent of the ntfy attachment policy.
// The exclude file (a `link=` file) is never selected.
func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern, exclude string) (*protocol.NotificationArtifact, string) {
selected := r.publicNotificationFile(runID, pattern, exclude)
+12 -18
View File
@@ -4,7 +4,6 @@ import (
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"net/url"
"os"
@@ -12,6 +11,7 @@ import (
"slices"
"strings"
"syscall"
"unicode/utf8"
)
// notificationLinkLimit bounds a `link=` file: it holds one URL, not a document.
@@ -19,7 +19,7 @@ const notificationLinkLimit = 4 << 10
// resolveNotificationLink reads the tap target a stage's `link=` pattern names
// in the run's shared public/: the first non-empty line of the most recently
// modified match, when it is an absolute http(s) URL ntfy accepts as a click.
// modified match, when it is a valid absolute http(s) URL.
// It returns the link and its public/ file, or no link and the reason for the
// notification receipt.
func (r *runner) resolveNotificationLink(runID int64, pattern string) (string, string, string) {
@@ -83,23 +83,16 @@ func readNotificationLink(root, rel string) ([]byte, error) {
return data, nil
}
// validNotificationLink accepts only an absolute http(s) URL with a host that
// also passes the ntfy click rules (no credentials, no fragment, bounded).
// validNotificationLink accepts only an absolute http(s) URL with a host, no
// credentials, no fragment, no whitespace or control characters and a bounded
// length. The value is an operator-visible link, never a place to smuggle a
// token.
func validNotificationLink(link string) bool {
if len(link) > 2048 || !utf8.ValidString(link) || strings.ContainsAny(link, "\r\n\t\x00 ") {
return false
}
u, err := url.Parse(link)
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && stage.ValidNtfyClick(link)
}
// ntfyLinkClick is the ntfy tap target: the link only while the run stays
// reachable through a web run view, else the run itself with a note saying so.
func ntfyLinkClick(runID int64, link string, views []stage.NtfyView) (string, string) {
if link == "" {
return runAttentionClick(runID), ""
}
if len(views) == 0 {
return runAttentionClick(runID), "notify link: ntfy keeps the run tap target without a web run view (PIPELINES_WEB_PUBLIC_URL)"
}
return link, ""
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && u.User == nil && u.Fragment == ""
}
// withNotificationLink makes link the app notification's tap target, keeping
@@ -112,7 +105,8 @@ func withNotificationLink(record pipeline.AppNotificationRecord, link string) pi
}
// stageHookLink re-resolves the `link=` of the stage hook behind a queued run
// event, so the durable retry of the hook's failed publication keeps its link.
// event, so the durable retry of the hook's unrecorded notification keeps its
// link.
// It returns the link and its public/ file, or nothing.
func (r *runner) stageHookLink(n pipeline.RunNotification) (string, string) {
event := map[string]string{protocol.NotifyWaiting: protocol.NotifyWaiting, "failed": "failure", "succeeded": "success"}[n.Event]
+24 -96
View File
@@ -2,17 +2,12 @@ package server
import (
"context"
"encoding/json"
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
@@ -49,18 +44,14 @@ func appNotification(t *testing.T, store *pipeline.Store, id string) *protocol.A
return nil
}
// A stage hook's `link=` file decides the ntfy and app tap target when its
// first non-empty line is an http(s) URL, keeping the run one action away and
// never attaching the link file; anything else falls back to the run link and
// says why on the first receipt.
// A stage hook's `link=` file decides the app tap target when its first
// non-empty line is an http(s) URL, keeping the run one action away and never
// attaching the link file; anything else falls back to the attached artifact
// or the run link and says why on the receipt.
func TestStageHookLinkClick(t *testing.T) {
captured := newNtfyCapture(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: true}); err != nil {
t.Fatal(err)
}
if _, err := store.Submit(ctx, "standup", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
@@ -72,8 +63,6 @@ func TestStageHookLinkClick(t *testing.T) {
for _, test := range []struct {
name, link, open string
files map[string]string
noWeb bool // no web origin: ntfy has no run view
attach bool // markdown and a workspace file are also attached
click bool // the doc URL is the app tap target
artifact string // the attached artifact path
diagnostic string
@@ -81,13 +70,12 @@ func TestStageHookLinkClick(t *testing.T) {
{name: "valid", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "\n " + doc + " \r\nnotes\n", "notes.txt": "n", "more.txt": "m"}, click: true},
{name: "valid-only-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, click: true},
{name: "valid-other-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup"}, click: true, artifact: "standup.md"},
{name: "valid-no-web", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, noWeb: true, click: true, diagnostic: "notify link: ntfy keeps the run tap target"},
{name: "missing", link: "standup-link.txt", diagnostic: "notify link: no public file matches standup-link.txt"},
{name: "missing-other-file", link: "standup-link.txt", files: map[string]string{"report.md": "# Report"}, artifact: "report.md", diagnostic: "notify link: no public file matches standup-link.txt"},
{name: "missing-attachments", link: "standup-link.txt", attach: true, diagnostic: "notify link: no public file matches standup-link.txt"},
{name: "relative", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "standup.html\n" + doc}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt does not start with an absolute http(s) URL"},
{name: "scheme", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "javascript:alert(1)"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"},
{name: "fragment", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "#top"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"},
{name: "credentials", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "https://user:pw@example.com/doc"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"},
{name: "empty", link: "standup-link.txt", files: map[string]string{"standup-link.txt": " \n\n"}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt is empty"},
{name: "large", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "\n" + strings.Repeat("x", 4<<10)}, artifact: "standup-link.txt", diagnostic: "at most 4 KiB"},
{name: "absent", files: map[string]string{"standup-link.txt": doc, "notes.txt": "n"}},
@@ -95,15 +83,7 @@ func TestStageHookLinkClick(t *testing.T) {
{name: "with-open", link: "*-link.txt", open: "*", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup"}, click: true, artifact: "standup.md"},
} {
t.Run(test.name, func(t *testing.T) {
web := "https://pipelines.example.com"
if test.noWeb {
web = ""
}
t.Setenv("PIPELINES_WEB_PUBLIC_URL", web)
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "report.txt"), []byte("report"), 0600); err != nil {
t.Fatal(err)
}
id, _, err := store.CreateRun(ctx, d, test.name, workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
@@ -114,28 +94,13 @@ func TestStageHookLinkClick(t *testing.T) {
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{}}
policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Link: test.link, Open: test.open}
publications := 1
if test.attach {
step.Output = map[string]any{"markdown": "# Standup", "artifacts": []any{"report.txt"}}
policy.Artifacts = []string{"markdown", "files"}
publications = 2
}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := len(captured())
r.notifyStep(id, d.Name, workspace, policy, step)
// ntfy opens the link only beside a web run view; the app opens the
// link (else the attached artifact, else the run).
// The app opens the link, else the attached artifact, else the run.
runClick := fmt.Sprintf("pipelines://run/%d", id)
wantNtfy, wantActions := runClick, ""
if !test.noWeb {
wantActions = fmt.Sprintf("view, Open in browser, https://pipelines.example.com/runs/%d", id)
if test.click {
wantNtfy = doc
}
}
wantClick, wantRunClick := runClick, ""
if test.artifact != "" {
wantClick, wantRunClick = fmt.Sprintf("pipelines://artifact/%d/1/%s", id, test.artifact), runClick
@@ -143,15 +108,6 @@ func TestStageHookLinkClick(t *testing.T) {
if test.click {
wantClick, wantRunClick = doc, runClick
}
got := captured()[before:]
if len(got) != publications {
t.Fatalf("ntfy publications = %+v", got)
}
for _, publication := range got {
if publication.Click != wantNtfy || publication.Actions != wantActions {
t.Fatalf("ntfy click/actions = %q %q, want %q %q", publication.Click, publication.Actions, wantNtfy, wantActions)
}
}
n := appNotification(t, store, fmt.Sprintf("run:%d:1:success", id))
if n == nil || n.Click != wantClick || n.RunClick != wantRunClick {
t.Fatalf("app notification = %+v, want click %q run %q", n, wantClick, wantRunClick)
@@ -164,52 +120,23 @@ func TestStageHookLinkClick(t *testing.T) {
t.Fatal(err)
}
receipts := detail.Steps[0].Notifications
if len(receipts) != publications {
if len(receipts) != 1 || receipts[0].Status != "sent" || receipts[0].Destination != "app" {
t.Fatalf("receipts = %+v", receipts)
}
// The reason is recorded once, on the first receipt. (The capture
// acknowledges no attachment, so attachment receipts fail.)
for i, receipt := range receipts {
noted := strings.Contains(receipt.Diagnostic, "notify link")
if i == 0 && test.diagnostic != "" {
noted = !strings.Contains(receipt.Diagnostic, test.diagnostic)
}
if noted || (!test.attach && (receipt.Status != "sent" || (test.diagnostic == "") != (receipt.Diagnostic == ""))) {
t.Fatalf("receipts = %+v, want diagnostic %q on the first only", receipts, test.diagnostic)
}
if got := receipts[0].Diagnostic; (test.diagnostic == "") != (got == "") || !strings.Contains(got, test.diagnostic) {
t.Fatalf("receipt diagnostic = %q, want %q", got, test.diagnostic)
}
})
}
}
// A terminal stage hook whose publication fails hands the run event back to
// the durable outbox; the retry keeps the hook's link, and the run-level
// failure reason never carries the link note.
// A terminal stage hook whose notification is not recorded hands the run
// event back to the durable outbox; the retry keeps the hook's link, and the
// run-level failure reason never carries the link note.
func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
var mu sync.Mutex
var clicks []string
var fail atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
clicks = append(clicks, r.Header.Get("Click"))
mu.Unlock()
if fail.Swap(false) {
http.Error(w, "transient", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "msg", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: true}); err != nil {
t.Fatal(err)
}
source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\nlink=standup-link.txt\n```", 1)
if _, err := store.Submit(ctx, "standup", source); err != nil {
t.Fatal(err)
@@ -221,11 +148,12 @@ func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) {
t.Fatalf("stage policy = %+v", policy)
}
artifacts := t.TempDir()
r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store), artifactsRoot: artifacts}
notes, recorder := newNoteCapture(t, store)
r := &runner{ctx: ctx, store: store, notes: notes, artifactsRoot: artifacts}
for _, test := range []struct {
name string
files map[string]string
retry string // the retry's ntfy click; "" means the run
retry string // the retry's tap target; "" means the run
}{
{name: "valid", files: map[string]string{"standup-link.txt": standupDoc}, retry: standupDoc},
{name: "missing"},
@@ -247,25 +175,25 @@ func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) {
if err := store.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "succeeded", Channel: "system", Title: "Run succeeded", Body: "Run succeeded", Click: runAttentionClick(id)}); err != nil {
t.Fatal(err)
}
mu.Lock()
clicks = nil
mu.Unlock()
fail.Store(true)
recorder.mu.Lock()
recorder.fail, recorder.got = true, nil
recorder.mu.Unlock()
r.notifyStep(id, d.Name, t.TempDir(), policy, step)
rows, err := store.RunNotifications(ctx, id)
if err != nil || len(rows) != 1 || rows[0].Status != "pending" || rows[0].Diagnostic == "" || strings.Contains(rows[0].Diagnostic, "notify link") {
t.Fatalf("released run notification = %+v %v", rows, err)
}
recorder.mu.Lock()
recorder.fail = false
recorder.mu.Unlock()
r.deliverRunNotifications(time.Now().Add(time.Minute))
want := test.retry
if want == "" {
want = runAttentionClick(id)
}
mu.Lock()
got := append([]string(nil), clicks...)
mu.Unlock()
if len(got) != 2 || got[0] != want || got[1] != want {
t.Fatalf("hook and retry clicks = %q, want %q twice", got, want)
got := recorder.recorded()
if len(got) != 1 || got[0].Click != want || got[0].ID != fmt.Sprintf("run:%d:1:succeeded", id) {
t.Fatalf("retried notification = %+v, want click %q", got, want)
}
if rows, err = store.RunNotifications(ctx, id); err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("retried run notification = %+v %v", rows, err)
+80 -185
View File
@@ -2,28 +2,22 @@ package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"git.a-wan.net/alan/pipelines/examples"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"mime"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"syscall"
"testing"
"time"
)
func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com/")
// A stage notify hook records one app notification per matching step event
// and audits it as one app receipt; a non-matching event records nothing.
func TestStageNotificationEvents(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "notify.db"))
@@ -32,46 +26,22 @@ func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
}
defer store.Close()
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "report.txt"), []byte("created file"), 0600); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count := calls.Add(1)
if click, actions := r.Header.Get("Click"), r.Header.Get("Actions"); !strings.HasPrefix(click, "pipelines://run/") || actions != "view, Open in browser, https://pipelines.example.com/runs/"+strings.TrimPrefix(click, "pipelines://run/") {
t.Errorf("stage notification lacks app click/web action: %q %q", click, actions)
}
filename, _ := new(mime.WordDecoder).DecodeHeader(r.Header.Get("Filename"))
body, _ := io.ReadAll(r.Body)
if filename == "report.txt" && string(body) != "created file" {
t.Error("wrong file content")
}
if filename == "digest.md" && string(body) != "# Digest" {
t.Error("wrong markdown")
}
ack := map[string]any{"id": fmt.Sprintf("msg%d", count), "event": "message"}
if filename != "" {
ack["attachment"] = map[string]string{"name": filename, "url": "https://ntfy.example.com/file/" + filename}
}
_ = json.NewEncoder(w).Encode(ack)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
if _, err := store.Submit(ctx, "notifications", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
d, _ := store.Get(ctx, items[0].ID, 0)
r, _ := newRunner(ctx, store)
notes, recorder := newNoteCapture(t, store)
r.notes = notes
for i, test := range []struct {
status, outcome, target, on string
attachments bool
expected int32
kind string
}{
{"completed", "success", protocol.SuccessEnd, "success", true, 2},
{"completed", "blocked", protocol.FailureEnd, "failure", false, 1},
{"failed", "error", protocol.FailureEnd, "failure", false, 1},
{"completed", "error", protocol.FailureEnd, "success", false, 0},
{"completed", "success", protocol.SuccessEnd, "success", protocol.NotificationRunSucceeded},
{"completed", "blocked", protocol.FailureEnd, "failure", protocol.NotificationRunFailed},
{"failed", "error", protocol.FailureEnd, "failure", protocol.NotificationRunFailed},
{"completed", "error", protocol.FailureEnd, "success", ""},
} {
id, _, err := store.CreateRun(ctx, d, fmt.Sprintf("case%d", i), workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
@@ -82,26 +52,27 @@ func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: test.status, Outcome: test.outcome, Target: test.target, Output: map[string]any{}}
policy := &protocol.NotificationPolicy{On: []string{test.on}, Destination: "anime"}
if test.attachments {
policy.Artifacts = []string{"markdown", "files"}
step.Output = map[string]any{"markdown": "# Digest", "artifacts": []any{"report.txt"}}
}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := calls.Load()
before := len(recorder.recorded())
r.notifyStep(id, d.Name, workspace, policy, step)
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if calls.Load()-before != test.expected || len(detail.Steps[0].Notifications) != int(test.expected) {
t.Fatal("event/attachments mismatch", detail, calls.Load()-before)
}
for _, receipt := range detail.Steps[0].Notifications {
if receipt.Status != "sent" || receipt.MessageID == "" {
t.Fatal("notification receipt not persisted", receipt)
got := recorder.recorded()[before:]
if test.kind == "" {
if len(got) != 0 || len(detail.Steps[0].Notifications) != 0 {
t.Fatal("a non-matching event notified", got, detail.Steps[0].Notifications)
}
continue
}
if len(got) != 1 || got[0].Kind != test.kind || got[0].Click != fmt.Sprintf("pipelines://run/%d", id) || len(detail.Steps[0].Notifications) != 1 {
t.Fatal("event mismatch", got, detail.Steps[0].Notifications)
}
if receipt := detail.Steps[0].Notifications[0]; receipt.Status != "sent" || receipt.Destination != "app" {
t.Fatal("notification receipt not persisted", receipt)
}
}
}
@@ -135,27 +106,12 @@ func TestTerminalNotificationRecipe(t *testing.T) {
t.Fatal("recipe missing", err)
}
id := items[0].ID
var calls atomic.Int32
var deliveryFailure atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
if req.Header.Get("Filename") != "" {
t.Error("event alert unexpectedly changed output to add attachments")
}
if deliveryFailure.Load() {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "recipe-receipt", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
for index, test := range []struct {
name, stage, outcome, status string
executionError, deliveryError bool
@@ -169,7 +125,9 @@ func TestTerminalNotificationRecipe(t *testing.T) {
{"delivery error preserves success", "report", "success", "succeeded", false, true, true},
} {
t.Run(test.name, func(t *testing.T) {
deliveryFailure.Store(test.deliveryError)
recorder.mu.Lock()
recorder.fail = test.deliveryError
recorder.mu.Unlock()
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == test.stage {
if test.executionError {
@@ -179,7 +137,7 @@ func TestTerminalNotificationRecipe(t *testing.T) {
}
return stage.Result{Outcome: "success", Output: stage.Values{"question": "topic", "evidence": []any{"source fact"}}}, nil
}
before := calls.Load()
before := len(recorder.recorded())
run, err := r.start(protocol.Message{PipelineID: id, Version: 1, RequestKey: fmt.Sprintf("recipe-%d", index), Workspace: t.TempDir(), Input: map[string]any{"prompt": "research a topic"}})
if err != nil {
t.Fatal(err)
@@ -189,8 +147,9 @@ func TestTerminalNotificationRecipe(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if detail.Status != test.status || (calls.Load()-before == 1) != test.notify {
t.Fatal("wrong verdict or duplicate/missing terminal alert", detail.Status, calls.Load()-before)
recorded := len(recorder.recorded()) - before
if detail.Status != test.status || (!test.deliveryError && (recorded == 1) != test.notify) || (test.deliveryError && recorded != 0) {
t.Fatal("wrong verdict or duplicate/missing terminal alert", detail.Status, recorded)
}
last := detail.Steps[len(detail.Steps)-1]
if last.Stage != test.stage || (len(last.Notifications) == 1) != test.notify {
@@ -226,6 +185,7 @@ func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
// artifacts= is a legacy (ntfy attachment) setting, still accepted.
source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\ndestination=anime\nartifacts=markdown\n```", 1)
if _, err := store.Submit(ctx, "test", source); err != nil {
t.Fatal(err)
@@ -235,7 +195,10 @@ func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Result"}}, nil
}
t.Setenv("PIPELINES_NTFY_URL", "")
// The app stream refuses the notification.
notes, recorder := newNoteCapture(t, store)
recorder.fail = true
r.notes = notes
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "once", Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
@@ -247,29 +210,6 @@ func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
}
}
func TestNotificationArtifactPathSafety(t *testing.T) {
root := t.TempDir()
os.WriteFile(filepath.Join(root, "safe.txt"), []byte("safe"), 0600)
os.WriteFile(filepath.Join(root, ".env"), []byte("secret"), 0600)
os.Symlink(filepath.Join(root, ".env"), filepath.Join(root, "alias.txt"))
outside := filepath.Join(t.TempDir(), "outside.txt")
os.WriteFile(outside, []byte("secret"), 0600)
os.Symlink(outside, filepath.Join(root, "external.txt"))
os.Mkdir(filepath.Join(root, "directory"), 0700)
os.WriteFile(filepath.Join(root, "large.bin"), []byte(strings.Repeat("x", (1<<20)+1)), 0600)
if err := syscall.Mkfifo(filepath.Join(root, "pipe"), 0600); err != nil {
t.Fatal(err)
}
for _, name := range []string{"../outside.txt", outside, ".env", "alias.txt", "external.txt", "directory", "large.bin", "pipe", "pipelines.db", "secret.key", "secrets/file.txt", "sub/../safe.txt"} {
if _, err := notificationArtifact(root, name); err == nil {
t.Fatal("unsafe artifact accepted", name)
}
}
if data, err := notificationArtifact(root, "safe.txt"); err != nil || string(data) != "safe" {
t.Fatal("safe artifact rejected", err)
}
}
func TestNotificationArtifactSelectionAndPreview(t *testing.T) {
root := t.TempDir()
public := filepath.Join(root, "9", "public")
@@ -332,11 +272,9 @@ func TestRunAttentionEventMapping(t *testing.T) {
}
// TestRunAttentionNotificationDelivery proves the operator-facing contract: the
// already-configured "system" destination and topic are used, the payload names
// the run and its pipeline, the click action opens the run, only waiting/failed
// publish, and a run that stays waiting is never republished.
// notification names the run and its pipeline, the click action opens the run,
// only waiting/failed notify, and a run that stays waiting is never repeated.
func TestRunAttentionNotificationDelivery(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "attention.db"))
@@ -344,73 +282,46 @@ func TestRunAttentionNotificationDelivery(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
type delivered struct {
method, path, title, message, click, authorization, actions string
}
deliveries := make(chan delivered, 8)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
decoder := new(mime.WordDecoder)
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
deliveries <- delivered{r.Method, r.URL.Path, title, message, r.Header.Get("Click"), r.Header.Get("Authorization"), r.Header.Get("Actions")}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "attention-receipt", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
// A run that needs nobody publishes nothing.
notes, recorder := newNoteCapture(t, store)
r.notes = notes
// A run that needs nobody notifies nothing.
for _, status := range []string{"queued", "running", "succeeded", "canceled"} {
r.notifyRun(7, "release", status, 1, "build", "")
}
select {
case got := <-deliveries:
t.Fatalf("a run that needs nobody published: %+v", got)
default:
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("a run that needs nobody notified: %+v", got)
}
// A waiting run publishes once, with the destination, identity and click.
// A waiting run notifies once, with the identity and click.
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
// A run that stays waiting is never republished, on a later call or a re-request.
// A run that stays waiting is never repeated, on a later call or a re-request.
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
// An auto run's failure announces its end.
r.notifyRun(8, "release", "failed", 2, "deploy", "provider returned 500")
// A failed run marked "on" publishes once, with its diagnostic.
// A failed run marked "on" notifies once, with its diagnostic.
r.setNotifyMode(7, "on")
r.notifyRun(7, "release", "failed", 2, "deploy", "provider returned 500")
first := <-deliveries
if first.method != http.MethodPost || first.path != "/pipelines" {
t.Fatalf("wrong destination/topic: %+v", first)
got := recorder.recorded()
if len(got) != 3 {
t.Fatalf("notifications = %+v, want three genuine events", got)
}
if first.title != "Run needs your decision" || !strings.Contains(first.message, "Run #7") || !strings.Contains(first.message, "release") || !strings.Contains(first.message, "decision") || !strings.Contains(first.message, "approve") {
first := got[0]
if first.Title != "Run needs your decision" || !strings.Contains(first.Message, "Run #7") || !strings.Contains(first.Message, "release") || !strings.Contains(first.Message, "decision") || !strings.Contains(first.Message, "approve") {
t.Fatalf("waiting notification does not identify the run/pipeline/need: %+v", first)
}
if first.click != "pipelines://run/7" || first.actions != "view, Open in browser, https://pipelines.example.com/runs/7" {
t.Fatalf("waiting notification click does not open the run: %q", first.click)
if first.Click != "pipelines://run/7" || first.Kind != protocol.NotificationRunWaiting {
t.Fatalf("waiting notification click does not open the run: %+v", first)
}
if first.authorization != "" {
t.Fatalf("notification leaked an authorization header: %q", first.authorization)
}
second := <-deliveries
if second.title != "Run failed" || !strings.Contains(second.message, "Run #8") {
if second := got[1]; second.Title != "Run failed" || !strings.Contains(second.Message, "Run #8") || second.Click != "pipelines://run/8" {
t.Fatalf("failed notification is not actionable: %+v", second)
}
if second.click != "pipelines://run/8" || second.actions != "view, Open in browser, https://pipelines.example.com/runs/8" {
t.Fatalf("failed notification click does not open the run: %q", second.click)
}
third := <-deliveries
if third.title != "Run failed" || !strings.Contains(third.message, "Run #7") {
if third := got[2]; third.Title != "Run failed" || !strings.Contains(third.Message, "Run #7") || !strings.Contains(third.Message, "provider returned 500") {
t.Fatalf("marked failed notification is not actionable: %+v", third)
}
select {
case got := <-deliveries:
t.Fatalf("third notification delivered for two genuine events: %+v", got)
default:
}
}
// TestRunAttentionSuppressedByStagePolicy proves a stage's own notify policy and
@@ -428,29 +339,24 @@ func TestRunAttentionSuppressedByStagePolicy(t *testing.T) {
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
r.markAttentionSent(11, 5, "failed")
r.markAttentionSent(11, 6, "waiting")
if !r.attentionAlready(11, 5, "failed") || !r.attentionAlready(11, 6, "waiting") {
t.Fatal("stage-policy coverage not recorded")
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "suppressed", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
r.notifyRun(11, "release", "failed", 5, "deploy", "")
r.notifyRun(11, "release", protocol.RunStatusWaiting, 6, "approve", "")
if calls.Load() != 0 {
t.Fatalf("run-level default repeated a stage-policy event %d times", calls.Load())
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("run-level default repeated a stage-policy event: %+v", got)
}
}
// TestHumanRunAttentionNotification proves the run loop publishes the run-level
// TestHumanRunAttentionNotification proves the run loop records the run-level
// attention notification itself when the pipeline declares no notify policy: the
// transition to waiting reaches the operator's configured destination exactly
// once, with the run, pipeline and a run-opening click.
// transition to waiting reaches the operator exactly once, with the run,
// pipeline and a run-opening click.
func TestHumanRunAttentionNotification(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -459,17 +365,6 @@ func TestHumanRunAttentionNotification(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
type delivered struct{ title, message, click string }
deliveries := make(chan delivered, 4)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
decoder := new(mime.WordDecoder)
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
deliveries <- delivered{title, message, r.Header.Get("Click")}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "human-attention", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
if _, err := store.Submit(ctx, "human", humanPipelineSource); err != nil {
t.Fatal(err)
}
@@ -478,6 +373,8 @@ func TestHumanRunAttentionNotification(t *testing.T) {
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
defer r.wg.Wait()
r.execute = successExecute
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "human-attention", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
@@ -485,17 +382,20 @@ func TestHumanRunAttentionNotification(t *testing.T) {
t.Fatal(err)
}
r.wg.Wait()
got := <-deliveries
if got.title != "Run needs your decision" || !strings.Contains(got.message, fmt.Sprintf("Run #%d", run.ID)) || !strings.Contains(got.message, "human") {
t.Fatalf("run-level waiting notification wrong: %+v", got)
deadline := time.Now().Add(5 * time.Second)
for len(recorder.recorded()) == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if got.click != fmt.Sprintf("pipelines://run/%d", run.ID) {
t.Fatalf("run-level waiting notification click wrong: %q", got.click)
time.Sleep(50 * time.Millisecond)
got := recorder.recorded()
if len(got) != 1 {
t.Fatalf("waiting notifications = %+v, want exactly one", got)
}
select {
case extra := <-deliveries:
t.Fatalf("waiting run notified again: %+v", extra)
default:
if got[0].Title != "Run needs your decision" || !strings.Contains(got[0].Message, fmt.Sprintf("Run #%d", run.ID)) || !strings.Contains(got[0].Message, "human") {
t.Fatalf("run-level waiting notification wrong: %+v", got[0])
}
if got[0].Click != fmt.Sprintf("pipelines://run/%d", run.ID) {
t.Fatalf("run-level waiting notification click wrong: %q", got[0].Click)
}
}
@@ -514,17 +414,12 @@ func TestRunAttentionNotifiesEachGenuineWait(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "wait", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
notes, recorder := newNoteCapture(t, store)
r.notes = notes
r.notifyRun(1, "release", protocol.RunStatusWaiting, 1, "gate", "")
r.notifyRun(1, "release", protocol.RunStatusWaiting, 1, "gate", "")
r.notifyRun(1, "release", protocol.RunStatusWaiting, 5, "gate-again", "")
if calls.Load() != 2 {
t.Fatalf("two genuine waits produced %d notifications, want 2", calls.Load())
if got := recorder.recorded(); len(got) != 2 {
t.Fatalf("two genuine waits produced %d notifications, want 2", len(got))
}
}
-68
View File
@@ -1,68 +0,0 @@
package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
)
func TestRunnerNtfyDeliveryIsAuditedAndIdempotent(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "ntfy.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
calls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
body, _ := io.ReadAll(r.Body)
if string(body) != "# Anime\nA report." {
t.Error("wrong markdown", string(body))
}
_, _ = w.Write([]byte(`{"id":"delivery123","event":"message","attachment":{"name":"digest.md","url":"https://ntfy.example.com/file/digest.md"}}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
source := "# stage notify\n```configs\ntype=ntfy\ndestination=anime\n```\n```edges\nsuccess -> #success\nerror -> #failure\n```\n"
if _, err := store.Submit(ctx, "notify", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, _ := newRunner(ctx, store)
for i, approved := range []bool{false, true} {
key := []string{"notify", "approved-notify"}[i]
request := protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: key, AllowTools: approved, Input: map[string]any{"prompt": "notify", "title": "Anime", "summary": "Your digest is ready", "markdown": "# Anime\nA report."}}
run, err := r.start(request)
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ := store.GetRun(ctx, run.ID)
if detail.Status != "succeeded" || len(detail.Steps) != 1 || detail.Steps[0].Output["delivery"] == nil || detail.Steps[0].SessionID != "" {
t.Fatal("native delivery not audited", detail)
}
if duplicate, err := r.start(request); err != nil || duplicate.ID != run.ID {
t.Fatal("repeat not idempotent", err)
}
}
if calls != 2 {
t.Fatal("duplicate publication", calls)
}
t.Setenv("PIPELINES_NTFY_ANIME_URL", "")
failed, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "failure", Input: map[string]any{"prompt": "notify", "title": "Anime", "summary": "Ready", "markdown": "# report"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ := store.GetRun(ctx, failed.ID)
if detail.Status != "failed" || detail.Steps[0].Outcome != "error" {
t.Fatal("delivery failure not routed", detail)
}
}
+5 -16
View File
@@ -4,13 +4,10 @@ import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -219,16 +216,8 @@ func TestReferenceWorkflowsLive(t *testing.T) {
t.Fatal(err)
}
defer func() { cancel(); runner.wg.Wait() }()
var alerts atomic.Int32
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
alerts.Add(1)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"reference-local-receipt","event":"message"}`)
}))
defer endpoint.Close()
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/reference")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
notes, recorder := newNoteCapture(t, store)
runner.notes = notes
type result struct {
Name string `json:"name"`
Verified bool `json:"verified"`
@@ -292,7 +281,7 @@ func TestReferenceWorkflowsLive(t *testing.T) {
pid = p.ID
}
}
priorAlerts := alerts.Load()
priorAlerts := len(recorder.recorded())
run, err := runner.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: c.name, Workspace: workspace, Input: map[string]any{"prompt": c.prompt}})
if err != nil {
row.Diagnostic = err.Error()
@@ -327,11 +316,11 @@ func TestReferenceWorkflowsLive(t *testing.T) {
t.Fatal("workspace capture absent")
}
}
wantAlerts := int32(0)
wantAlerts := 0
if c.name == "incident-handoff" || c.name == "missing-input-failure" {
wantAlerts = 1
}
if alerts.Load()-priorAlerts != wantAlerts {
if len(recorder.recorded())-priorAlerts != wantAlerts {
t.Fatal("unexpected notification count")
}
t.Logf("Verified %s: run #%d status=%s visits=%d", c.name, run.ID, run.Status, len(run.Steps))
+1 -1
View File
@@ -200,7 +200,7 @@ func scratchEnvironment(t *testing.T, realHome, home string) []string {
env = append(env, entry)
}
return append(env, "HOME="+home, "XDG_CONFIG_HOME="+config, "XDG_DATA_HOME="+data, "XDG_CACHE_HOME="+cache, "XDG_STATE_HOME="+filepath.Join(home, ".local", "state"),
"PIPELINES_OPENCODE="+opencodePath(), "PIPELINES_NTFY_URL=", "PIPELINES_MDNS=off")
"PIPELINES_OPENCODE="+opencodePath(), "PIPELINES_MDNS=off")
}
func copyProviderLogin(t *testing.T, real, scratch, provider string) {
+48 -117
View File
@@ -2,13 +2,9 @@ package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -18,30 +14,19 @@ import (
"git.a-wan.net/alan/pipelines/internal/summarise"
)
func TestRunNotificationPublisherFailureRetriesAfterReopen(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
// An app notification that could not be recorded stays pending in the run
// outbox and is retried after the store is reopened; a repeated request is
// deduplicated.
func TestRunNotificationRecordFailureRetriesAfterReopen(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "retry.db")
s, err := pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got, actions := r.Header.Get("Click"), r.Header.Get("Actions"); got != "pipelines://run/7" || actions != "view, Open in browser, https://pipelines.example.com/runs/7" {
t.Errorf("wrong retry links: %q %q", got, actions)
}
if calls.Add(1) == 1 {
http.Error(w, "transient", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "ack", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s}
notes, recorder := newNoteCapture(t, s)
recorder.fail = true
r := &runner{ctx: ctx, store: s, notes: notes}
// The run was started with "Notify me", so its failure is announced.
r.setNotifyMode(7, "on")
// Emulate a durable transition intent saved before the runner callback.
@@ -61,17 +46,19 @@ func TestRunNotificationPublisherFailureRetriesAfterReopen(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
r = &runner{ctx: ctx, store: s}
notes, recorder = newNoteCapture(t, s)
r = &runner{ctx: ctx, store: s, notes: notes}
r.setNotifyMode(7, "on")
r.deliverRunNotifications(time.Now().Add(time.Minute))
r.notifyRun(7, "test", "failed", 1, "stage", "")
got, err = s.RunNotifications(ctx, 7)
if err != nil || len(got) != 1 || got[0].Status != "sent" || got[0].Attempts != 2 || got[0].MessageID != "ack" || calls.Load() != 2 {
t.Fatalf("retry/dedupe: %+v calls=%d %v", got, calls.Load(), err)
recorded := recorder.recorded()
if err != nil || len(got) != 1 || got[0].Status != "sent" || got[0].Attempts != 2 || recorder.attempts() != 1 || len(recorded) != 1 || recorded[0].Click != "pipelines://run/7" {
t.Fatalf("retry/dedupe: %+v recorded=%+v %v", got, recorded, err)
}
}
func TestTransactionalSuccessNotificationUsesWebLink(t *testing.T) {
func TestTransactionalSuccessNotificationUsesAppLink(t *testing.T) {
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "web-success.db"))
if err != nil {
@@ -93,28 +80,14 @@ func TestTransactionalSuccessNotificationUsesWebLink(t *testing.T) {
if err := s.FinishRun(ctx, id, "succeeded", "success", "", nil); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
if got, want := req.Header.Get("Click"), "pipelines://run/"+fmt.Sprint(id); got != want {
t.Errorf("click = %q, want %q", got, want)
}
if got, want := req.Header.Get("Actions"), "view, Open in browser, https://pipelines.example.com/runs/"+fmt.Sprint(id); got != want {
t.Errorf("actions = %q, want %q", got, want)
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "web-success", "event": "message"})
}))
defer endpoint.Close()
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s}
notes, recorder := newNoteCapture(t, s)
r := &runner{ctx: ctx, store: s, notes: notes}
r.notifyRun(id, "test", "succeeded", 0, "", "")
r.deliverRunNotifications(time.Now())
got, err := s.RunNotifications(ctx, id)
if err != nil || len(got) != 1 || got[0].Status != "sent" || calls.Load() != 1 {
t.Fatalf("notification: %+v calls=%d err=%v", got, calls.Load(), err)
recorded := recorder.recorded()
if err != nil || len(got) != 1 || got[0].Status != "sent" || len(recorded) != 1 || recorded[0].Click != fmt.Sprintf("pipelines://run/%d", id) || recorded[0].Kind != protocol.NotificationRunSucceeded {
t.Fatalf("notification: %+v recorded=%+v err=%v", got, recorded, err)
}
}
@@ -142,16 +115,8 @@ func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "wrong-success", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s, events: newRunEventHub()}
notes, recorder := newNoteCapture(t, s)
r := &runner{ctx: ctx, store: s, events: newRunEventHub(), notes: notes}
if err := s.BeginStep(ctx, id, 1, "one", nil); err != nil {
t.Fatal(err)
}
@@ -159,8 +124,8 @@ func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
if _, _, _, _, err := r.finishStage(id, "test", "workspace", d.Graph.Stages[0], state, protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: protocol.SuccessEnd, Output: map[string]any{"markdown": "result"}}); err != nil {
t.Fatal(err)
}
if calls.Load() != 0 {
t.Fatal("terminal stage success published before FinishRun")
if recorder.attempts() != 0 {
t.Fatal("terminal stage success announced before FinishRun")
}
sub := r.events.subscribe("test", "workspace", nil, func(protocol.Message) error { return nil })
defer sub.close()
@@ -170,8 +135,8 @@ func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if got.Status != "running" || len(got.Notifications) != 0 || calls.Load() != 0 {
t.Fatalf("unpersisted success announced: %+v calls=%d", got, calls.Load())
if got.Status != "running" || len(got.Notifications) != 0 || recorder.attempts() != 0 {
t.Fatalf("unpersisted success announced: %+v attempts=%d", got, recorder.attempts())
}
sub.mu.Lock()
defer sub.mu.Unlock()
@@ -190,18 +155,6 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) == 1 && failFirst {
http.Error(w, "transient", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "waiting-ack", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
source := strings.Replace(humanPipelineSource, "# stage gate", "# stage gate\n```notify\non=waiting\n```", 1)
if _, err := s.Submit(ctx, "waiting", source); err != nil {
t.Fatal(err)
@@ -215,6 +168,11 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
t.Fatal(err)
}
defer func() { cancel(); r.schedulerWG.Wait() }()
notes, recorder := newNoteCapture(t, s)
if failFirst {
recorder.failNext = 1
}
r.notes = notes
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "waiting-hook", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
@@ -225,12 +183,12 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
if err != nil {
t.Fatal(err)
}
wantCalls := int32(1)
wantCalls := 1
if failFirst {
wantCalls = 2
}
if calls.Load() != wantCalls || detail.Status != "waiting" || len(detail.Notifications) != 1 {
t.Fatalf("waiting hook duplicated/lost: calls=%d detail=%+v", calls.Load(), detail)
if recorder.attempts() != wantCalls || len(recorder.recorded()) != 1 || detail.Status != "waiting" || len(detail.Notifications) != 1 {
t.Fatalf("waiting hook duplicated/lost: attempts=%d recorded=%+v detail=%+v", recorder.attempts(), recorder.recorded(), detail)
}
status := detail.Notifications[0].Status
if status != "sent" && status != "covered" {
@@ -241,25 +199,16 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
}
func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "ack", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
for _, tc := range []struct {
mode string
hook bool
// any turns the global run_finished setting on (it defaults off), so
// every run end notifies, not only runs marked "on".
any bool
want int32
want int
}{
{"on", false, false, 1}, {"auto", false, false, 0}, {"auto", false, true, 1}, {"on", false, true, 1}, {"off", false, false, 0}, {"off", false, true, 0},
// A stage hook is the pipeline's own opt-in: it still publishes for an
// A stage hook is the pipeline's own opt-in: it still notifies for an
// auto run, and never doubles up with the run alert.
{"on", true, false, 1}, {"auto", true, false, 1}, {"auto", true, true, 1}, {"off", true, false, 0},
} {
@@ -291,15 +240,16 @@ func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success"}, nil
}
before := calls.Load()
notes, recorder := newNoteCapture(t, s)
r.notes = notes
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "mode", NotifyMode: tc.mode, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := s.GetRun(ctx, run.ID)
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 err != nil || detail.Status != "succeeded" || detail.NotifyMode != tc.mode || len(recorder.recorded()) != tc.want {
t.Fatalf("mode contract: %+v recorded=%+v %v", detail, recorder.recorded(), err)
}
if tc.want == 1 && !(tc.hook && tc.mode == "auto" && !tc.any) && (len(detail.Notifications) != 1 || (detail.Notifications[0].Status != "sent" && detail.Notifications[0].Status != "covered")) {
t.Fatalf("missing final audit: %+v", detail.Notifications)
@@ -317,16 +267,9 @@ func TestRunNotificationAttentionModesAndRetryBound(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
http.Error(w, "unavailable", http.StatusServiceUnavailable)
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s}
notes, recorder := newNoteCapture(t, s)
recorder.fail = true
r := &runner{ctx: ctx, store: s, notes: notes}
for i, mode := range []string{"auto", "on", "off"} {
id := int64(i + 1)
r.setNotifyMode(id, mode)
@@ -335,14 +278,14 @@ func TestRunNotificationAttentionModesAndRetryBound(t *testing.T) {
}
}
// auto and on waiting, plus auto and on failed; off never notifies.
if calls.Load() != 4 {
t.Fatalf("attention modes: %d calls, want 4", calls.Load())
if recorder.attempts() != 4 {
t.Fatalf("attention modes: %d attempts, want 4", recorder.attempts())
}
r.deliverRunNotifications(time.Now().Add(time.Minute))
r.deliverRunNotifications(time.Now().Add(2 * time.Minute))
r.deliverRunNotifications(time.Now().Add(3 * time.Minute))
if calls.Load() != 12 {
t.Fatalf("retry bound: %d calls, want 12", calls.Load())
if recorder.attempts() != 12 {
t.Fatalf("retry bound: %d attempts, want 12", recorder.attempts())
}
for _, id := range []int64{1, 2, 3} {
got, err := s.RunNotifications(ctx, id)
@@ -379,32 +322,20 @@ func TestRunNotificationWorkerResumesPendingAfterRestart(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
delivered := make(chan struct{}, 2)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]string{"id": "recovered", "event": "message"})
delivered <- struct{}{}
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r, err := newRunner(ctx, s)
if err != nil {
t.Fatal(err)
}
// As the handler does, before the worker's first tick.
r.notes = newAppNotifier(s)
defer func() { cancel(); r.schedulerWG.Wait() }()
select {
case <-delivered:
case <-time.After(5 * time.Second):
t.Fatal("pending outbox was not recovered")
}
deadline := time.Now().Add(5 * time.Second)
for {
got, err := s.RunNotifications(ctx, 7)
if err != nil {
t.Fatal(err)
}
if len(got) == 1 && got[0].Status == "sent" && got[0].MessageID == "recovered" {
if len(got) == 1 && got[0].Status == "sent" && appNotification(t, s, "run:7:1:failed") != nil {
break
}
if time.Now().After(deadline) {
+4 -5
View File
@@ -63,8 +63,7 @@ type runner struct {
// events pushes run state deltas to subscribed clients. When nil (tests that
// build a runner directly) emits are dropped, so nothing else changes.
events *runEventHub
// notes records and streams app notifications beside every ntfy
// publication. Nil (a runner built directly in a test) records nothing.
// notes records and streams app notifications. Nil (a runner built directly in a test) records nothing.
notes *appNotifier
// identMu guards idents: the pipeline identity and stored title (see
// runIdentity) that every emitted frame of a run carries, so a client with no
@@ -1032,7 +1031,7 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
return retryCheckpoint{}, fmt.Errorf("retry source %d has incompatible selected stage %q", sourceID, failed.Stage)
}
typ := stage.EffectiveType(declared.Type)
if typ == stage.HumanType || typ == stage.NtfyType {
if typ == stage.HumanType || typ == stage.RemovedNtfyType {
return retryCheckpoint{}, fmt.Errorf("retry source %d cannot replay completed external stage %s", sourceID, failed.Stage)
}
if typ == stage.ModelType {
@@ -1934,8 +1933,8 @@ func (r *runner) finishRunStateClass(id int64, name, workspace, status, outcome,
if detail.FinishedAt == "" {
return // Cleanup is not confirmed: never emit a false terminal event.
}
// Push the terminal delta before the attention notification, so a slow ntfy
// never delays the live update the app folds.
// Push the terminal delta before the attention notification, so a slow
// notification never delays the live update the app folds.
r.emitRun(protocol.RunEventFrame{
RunID: id,
Workspace: workspace,
+2 -9
View File
@@ -10,7 +10,6 @@ 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"
)
func (r *runner) scheduleLoop() {
@@ -124,7 +123,7 @@ var scheduleBusyRetry = func() (every, limit time.Duration) {
return every, limit
}
// scheduleNoticePriority is ntfy's "low" priority.
// scheduleNoticePriority is the notification stream's "low" priority.
const scheduleNoticePriority = 2
// admitScheduled starts one claimed schedule's run and records the outcome in
@@ -203,7 +202,7 @@ func scheduleLabel(item protocol.SavedSchedule) string {
}
// scheduleNotice tells the operator, at low priority, through the app
// notification stream and (when enabled) ntfy, that a scheduled run was
// notification stream, that a scheduled run was
// delayed or skipped.
func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second)
@@ -212,10 +211,4 @@ func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, even
r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{
ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule,
Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}})
if !chatAttentionConfigured() || !ntfyEnabled(ctx, r.settingsStore()) {
return
}
if _, err := ntfyPublish(stage.WithNtfyPriority(ctx, scheduleNoticePriority), "system", title, message, "", nil, click); err != nil {
log.Printf("schedule id=%d %s notice: %v", item.ID, event, err)
}
}
@@ -41,15 +41,6 @@ func TestSessionExportLive(t *testing.T) {
if !ok || !stage.ValidModel(provider, id) {
t.Fatal("explicit valid PIPELINES_SESSION_EXPORT_MODEL required")
}
// Isolate notifications from the operator's real ntfy service.
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"session-export-live-receipt","event":"message"}`)
}))
defer endpoint.Close()
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/live")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Minute)
defer cancel()
-8
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
@@ -19,13 +18,6 @@ import (
// Exercise the real V2 CLI/poll path, runner, SQLite retention and websocket CLI
// against an isolated loopback server/database, never the configured deployment.
func TestStageDeadlineDiagnosticThroughCLIAndWebsocket(t *testing.T) {
ntfy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"id":"scratch-receipt","event":"message"}`))
}))
defer ntfy.Close()
t.Setenv("PIPELINES_NTFY_URL", ntfy.URL+"/scratch")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
for _, mode := range []string{"active", "http", "connection"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
+1 -75
View File
@@ -1,9 +1,6 @@
package server
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"net/url"
@@ -44,16 +41,6 @@ func networkAddresses() []protocol.NetworkAddress {
return result
}
func endpointPort(u *url.URL) string {
if port := u.Port(); port != "" {
return port
}
if u.Scheme == "https" || u.Scheme == "wss" {
return "443"
}
return "80"
}
func candidateURLs(addresses []protocol.NetworkAddress, scheme, port, path string) []string {
result := []string{}
for _, address := range addresses {
@@ -63,22 +50,9 @@ func candidateURLs(addresses []protocol.NetworkAddress, scheme, port, path strin
return result
}
func localEndpoint(u *url.URL, hostname string, addresses []protocol.NetworkAddress) bool {
host := u.Hostname()
if host == "localhost" || host == hostname || net.ParseIP(host).IsLoopback() {
return true
}
for _, address := range addresses {
if host == address.IP {
return true
}
}
return false
}
func systemStatus(r *http.Request, started time.Time, runErr error) *protocol.SystemStatus {
hostname, _ := os.Hostname()
s := &protocol.SystemStatus{Hostname: hostname, StartedAt: started.UTC().Format(time.RFC3339), Uptime: time.Since(started).Round(time.Second).String(), Addresses: networkAddresses(), Server: protocol.ServiceStatus{Health: "healthy"}, Ntfy: protocol.ServiceStatus{Health: "not configured"}, Note: "Addresses belong to the server computer (or container). Candidate URLs are not reachability checks; binding, firewalls, port mapping and TLS may differ."}
s := &protocol.SystemStatus{Hostname: hostname, StartedAt: started.UTC().Format(time.RFC3339), Uptime: time.Since(started).Round(time.Second).String(), Addresses: networkAddresses(), Server: protocol.ServiceStatus{Health: "healthy"}, Note: "Addresses belong to the server computer (or container). Candidate URLs are not reachability checks; binding, firewalls, port mapping and TLS may differ."}
if runErr != nil {
s.Server.Health = "execution unavailable"
}
@@ -104,53 +78,5 @@ func systemStatus(r *http.Request, started time.Time, runErr error) *protocol.Sy
s.Server.Candidates = []string{s.Server.URL}
}
}
endpoints := notificationEndpoints()
if len(endpoints) == 0 {
return s
}
s.Topic = endpoints[0].Topic
s.NtfyUser = os.Getenv("PIPELINES_NTFY_READER")
s.Ntfy.Health = "not checked"
// Only the validated public base is returned. Publishing URL and tokens
// never leave the server, even on probe failure.
s.Ntfy.URL = endpoints[0].ServerURL
if u, err := url.Parse(s.Ntfy.URL); err == nil && u.Host != "" {
s.Ntfy.Port = endpointPort(u)
if localEndpoint(u, hostname, s.Addresses) {
s.Ntfy.Candidates = candidateURLs(s.Addresses, u.Scheme, s.Ntfy.Port, "/"+s.Topic)
}
}
publish, err := url.Parse(os.Getenv("PIPELINES_NTFY_URL"))
if err != nil {
return s
}
if s.Ntfy.URL == "" && localEndpoint(publish, hostname, s.Addresses) {
s.Ntfy.Port = endpointPort(publish)
s.Ntfy.Candidates = candidateURLs(s.Addresses, publish.Scheme, s.Ntfy.Port, "/"+s.Topic)
}
publish.Path = "/v1/health"
publish.RawPath = ""
publish.RawQuery = ""
publish.Fragment = ""
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, publish.String(), nil)
if err != nil {
return s
}
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(req)
s.Ntfy.Health = "unreachable"
if err != nil {
return s
}
defer response.Body.Close()
s.Ntfy.Health = "unhealthy"
var health struct {
Healthy bool `json:"healthy"`
}
if response.StatusCode == http.StatusOK && json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&health) == nil && health.Healthy {
s.Ntfy.Health = "healthy"
}
return s
}

Some files were not shown because too many files have changed in this diff Show More