Merge branch 'worktree-agent-ae6543d03d048d81f'

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 16:10:47 +00:00
28 changed files with 1391 additions and 70 deletions
@@ -345,6 +345,7 @@ class NotificationPresenter(private val context: Context) {
"chat_question" to "Chat question", "chat_question" to "Chat question",
"chat_approval" to "Chat approval", "chat_approval" to "Chat approval",
"chat_reply" to "Chat reply", "chat_reply" to "Chat reply",
"chat_notify" to "Agent notification",
) )
fun importance(priority: Int): Int = when (priority) { fun importance(priority: Int): Int = when (priority) {
+36 -9
View File
@@ -16,6 +16,10 @@ import '../shell/adaptive_shell.dart';
import '../shell/destination.dart'; import '../shell/destination.dart';
import '../features/attention/notify/notification_controller.dart'; import '../features/attention/notify/notification_controller.dart';
import '../features/attention/notify/chat_question_notices.dart'; import '../features/attention/notify/chat_question_notices.dart';
import '../features/attention/notify/agent_notices.dart';
import '../features/attention/notify/page_signals.dart';
import '../features/attention/ui/agent_notice_toast.dart';
import 'clipboard_failures.dart' show appScaffoldMessengerKey;
import '../features/attention/notify/notification_store.dart'; import '../features/attention/notify/notification_store.dart';
import '../features/notification_service/notification_service_bridge.dart'; import '../features/notification_service/notification_service_bridge.dart';
import '../features/notification_service/notification_service_controller.dart'; import '../features/notification_service/notification_service_controller.dart';
@@ -269,6 +273,11 @@ class _PipelinesAppState extends State<PipelinesApp>
); );
ChatQuestionNotices? _chatQuestionNotices; ChatQuestionNotices? _chatQuestionNotices;
/// Agents' notify calls on this device: a system notification, a toast, the
/// tab title count. Subscribed on every connection so missed ones replay.
AgentNotices? _agentNotices;
final PageSignals _pageSignals = createPageSignals();
/// One attention surface for the app: the Runs heading's bell draws from it /// One attention surface for the app: the Runs heading's bell draws from it
/// and the shell mirrors its count on the Runs tab, so the badge is visible /// and the shell mirrors its count on the Runs tab, so the badge is visible
/// from every destination. The Runs list seeds the rows when it loads; pushed /// from every destination. The Runs list seeds the rows when it loads; pushed
@@ -472,18 +481,22 @@ class _PipelinesAppState extends State<PipelinesApp>
_chatQuestionNotices = ChatQuestionNotices( _chatQuestionNotices = ChatQuestionNotices(
gateway: _session.gateway, gateway: _session.gateway,
canNotify: () => _notifications.canNotify, canNotify: () => _notifications.canNotify,
activeChatSessionId: () { activeChatSessionId: _activeChatSessionId,
final route = _delegate.shellRoute;
return route.kind == AppRouteKind.chat ? route.chatSessionId : null;
},
sessionTitle: _chatSessionTitle, sessionTitle: _chatSessionTitle,
openChat: (id) { openChat: _openNotifiedChat,
if (!mounted) return;
widget.servers?.requestChatOpen(id);
_delegate.goTo(AppRoute.chatSession(id));
},
bridge: _notifications.bridge, bridge: _notifications.bridge,
); );
_agentNotices = AgentNotices(
gateway: _session.gateway,
notifications: _notifications,
page: _pageSignals,
activeChatSessionId: _activeChatSessionId,
sessionTitle: _chatSessionTitle,
openChat: _openNotifiedChat,
showToast: (toast) =>
showAgentNoticeToast(appScaffoldMessengerKey.currentState, toast),
sendOnly: _session.client.sendOnly,
);
_config = RouterConfig<AppRoute>( _config = RouterConfig<AppRoute>(
routeInformationParser: const AppRouteParser(), routeInformationParser: const AppRouteParser(),
routerDelegate: _delegate, routerDelegate: _delegate,
@@ -595,6 +608,8 @@ class _PipelinesAppState extends State<PipelinesApp>
_notifications.dispose(); _notifications.dispose();
_deliveryController.dispose(); _deliveryController.dispose();
_chatQuestionNotices?.dispose(); _chatQuestionNotices?.dispose();
_agentNotices?.dispose();
_pageSignals.dispose();
if (identical(MachineElevation.defaultPrompt, _elevationPrompt)) { if (identical(MachineElevation.defaultPrompt, _elevationPrompt)) {
MachineElevation.defaultPrompt = null; MachineElevation.defaultPrompt = null;
} }
@@ -667,6 +682,7 @@ class _PipelinesAppState extends State<PipelinesApp>
// Every connected transition sends acknowledgements queued while offline // Every connected transition sends acknowledgements queued while offline
// and re-reads the shared set, so a gap cannot leave this device stale. // and re-reads the shared set, so a gap cannot leave this device stale.
if (_session.connected) unawaited(_ackSync.connected()); if (_session.connected) unawaited(_ackSync.connected());
if (_session.connected) unawaited(_agentNotices?.connected());
} }
/// Mirrors attention and independent status counts for the shell. The Runs list seeds /// Mirrors attention and independent status counts for the shell. The Runs list seeds
@@ -879,6 +895,17 @@ class _PipelinesAppState extends State<PipelinesApp>
setState(() => _pendingRunSearch = null); setState(() => _pendingRunSearch = null);
} }
String? _activeChatSessionId() {
final route = _delegate.shellRoute;
return route.kind == AppRouteKind.chat ? route.chatSessionId : null;
}
void _openNotifiedChat(String id) {
if (!mounted) return;
widget.servers?.requestChatOpen(id);
_delegate.goTo(AppRoute.chatSession(id));
}
Future<String?> _chatSessionTitle(String id) async { Future<String?> _chatSessionTitle(String id) async {
id = widget.chatPool?.gateway.normalizeId(id) ?? id; id = widget.chatPool?.gateway.normalizeId(id) ?? id;
final reply = await (widget.chatPool?.gateway ?? _session.gateway).call( final reply = await (widget.chatPool?.gateway ?? _session.gateway).call(
@@ -0,0 +1,143 @@
/// 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).
library;
/// The stream kind of an agent's notify call.
const agentNoticeKind = 'chat_notify';
/// How far back a replayed notice is still worth showing. Older ones were
/// missed long enough ago that the chat itself is the better place to read
/// them; they are recorded as seen without being shown.
const agentNoticeReplayWindow = Duration(hours: 1);
/// The most replayed notices shown at once after a reconnect.
const agentNoticeReplayLimit = 5;
class AgentNotice {
const AgentNotice({
required this.id,
required this.sessionId,
required this.title,
required this.message,
required this.priority,
required this.createdAt,
});
/// The server's stable id, `chat:<session>:notify:<id>`.
final String id;
final String sessionId;
final String title;
final String message;
/// The ntfy-style priority: 2 low, 3 default, 4 high.
final int priority;
final DateTime? createdAt;
bool get low => priority < 3;
/// The notice in [value], or null when it is not a well-formed agent notice.
static AgentNotice? parse(Object? value) {
if (value is! Map || value['kind'] != agentNoticeKind) return null;
final id = value['id'];
if (id is! String || id.isEmpty) return null;
final session = _sessionOf(id, value['group']);
if (session == null) return null;
final priority = value['priority'];
final created = value['created_at'];
return AgentNotice(
id: id,
sessionId: session,
title: '${value['title'] ?? ''}'.trim(),
message: '${value['message'] ?? ''}'.trim(),
priority: priority is int ? priority : 3,
createdAt: created is String ? DateTime.tryParse(created) : null,
);
}
/// The chat id: the group `chat:<id>`, else the id's `chat:<id>:notify:` head.
static String? _sessionOf(String id, Object? group) {
if (group is String && group.startsWith('chat:') && group.length > 5) {
return group.substring(5);
}
final match = RegExp(r'^chat:(.+):notify:[^:]+$').firstMatch(id);
return match?.group(1);
}
/// The headline: `<chat title>: <title>`, with "Chat" for an unknown chat.
String headline(String? chatTitle) {
final chat = (chatTitle ?? '').trim();
final name = chat.isEmpty ? 'Chat' : chat;
return title.isEmpty ? name : '$name: $title';
}
}
/// Whether the operator is looking at the app right now.
enum PagePresence {
/// Visible and focused: the operator is in the app.
focused,
/// Visible but another window has focus.
visible,
/// Hidden: another tab, minimized, or the screen is off.
hidden,
}
/// How one notice reaches the operator.
class AgentNoticeDelivery {
const AgentNoticeDelivery({
this.system = false,
this.toast = false,
this.badge = false,
this.chime = false,
});
/// A system (browser or OS) notification.
final bool system;
/// An in-app toast with an Open action.
final bool toast;
/// A count in the tab title until the page is focused again.
final bool badge;
/// A short sound, only when nothing the operator would notice is posted.
final bool chime;
bool get none => !system && !toast && !badge && !chime;
@override
String toString() =>
'AgentNoticeDelivery(system: $system, toast: $toast, badge: $badge, '
'chime: $chime)';
}
/// Decides how [notice] is delivered.
///
/// A focused page shows a toast, or nothing when the notice's chat is already
/// in view. A page the operator is not looking at gets a system notification
/// when [canNotify] (permission granted) and a count in the tab title; a low
/// priority notice only raises a system notification when the page is hidden,
/// and otherwise waits as a toast. Without system notifications (denied, not
/// asked, or an insecure http page) the toast, the title count and, for
/// default and high priority, a short chime carry it. A [replay] (missed while
/// disconnected) never chimes.
AgentNoticeDelivery agentNoticeDelivery({
required AgentNotice notice,
required PagePresence presence,
required bool chatInView,
required bool canNotify,
bool replay = false,
}) {
if (presence == PagePresence.focused) {
return AgentNoticeDelivery(toast: !chatInView);
}
final system = canNotify && (!notice.low || presence == PagePresence.hidden);
return AgentNoticeDelivery(
system: system,
toast: !system,
badge: true,
chime: !system && !notice.low && !replay,
);
}
@@ -0,0 +1,206 @@
import 'dart:async';
import '../../../core/api_gateway.dart';
import 'agent_notice.dart';
import 'notification_controller.dart';
import 'notification_models.dart';
import 'page_signals.dart';
/// One in-app toast for an agent notice.
class AgentToast {
const AgentToast({
required this.headline,
required this.message,
required this.open,
});
final String headline;
final String message;
/// Opens the notice's chat.
final void Function() open;
}
/// Delivers agents' `notify` calls (the `chat_notify` app notifications) on
/// this device: a system notification, an in-app toast, a count in the tab
/// title and a chime, as [agentNoticeDelivery] decides for the page's presence
/// and the notification permission.
///
/// It subscribes to the server's notification stream on every connection
/// ([connected]), so notices sent while this client was away are replayed; the
/// ones within [agentNoticeReplayWindow] are shown once and every id is
/// recorded in the persisted notification ledger, so neither a reload nor a
/// reconnect repeats one.
class AgentNotices {
AgentNotices({
required this.gateway,
required this.notifications,
required this.page,
required this.activeChatSessionId,
required this.sessionTitle,
required this.openChat,
required this.showToast,
this.sendOnly,
DateTime Function()? now,
}) : _now = now ?? DateTime.now {
_frames = gateway.frames.listen(_onFrame);
_focus = page.focused.listen((_) => _clearBadge());
}
final ApiGateway gateway;
final NotificationController notifications;
final PageSignals page;
final String? Function() activeChatSessionId;
final Future<String?> Function(String sessionId) sessionTitle;
final void Function(String sessionId) openChat;
final void Function(AgentToast toast) showToast;
/// Sends a request without awaiting its reply; see [connected].
final String Function(String type, JsonMap fields)? sendOnly;
final DateTime Function() _now;
late final StreamSubscription<JsonMap> _frames;
late final StreamSubscription<void> _focus;
Future<void> _queue = Future<void>.value();
bool _disposed = false;
int _badge = 0;
/// The count shown in the tab title.
int get badge => _badge;
/// Subscribes to the notification stream on a new connection and shows the
/// recent notices it missed. Safe to call on every reconnect: the server
/// replaces the subscription and the ledger drops repeats.
///
/// With [sendOnly] (the app passes the socket's send-only path) the request
/// does not hold the request lane for its reply, and the reply is read from
/// the pushed frames like the notifications that follow it.
Future<void> connected() async {
if (_disposed) return;
final send = sendOnly;
if (send != null) {
try {
send('subscribe_notifications', const {});
} catch (_) {
// Not connected: the next connection subscribes.
}
return;
}
JsonMap reply;
try {
reply = await gateway.call('subscribe_notifications');
} catch (_) {
return; // An older server or a dropped socket: live pushes still work.
}
_onSubscribed(reply);
}
void _onSubscribed(JsonMap reply) {
final raw = reply['notifications'];
if (_disposed || raw is! List) return;
final notices = [for (final value in raw) ?AgentNotice.parse(value)];
_enqueue(() => _replay(notices));
}
void _onFrame(JsonMap frame) {
if (frame['type'] == 'notifications_subscribed') {
_onSubscribed(frame);
return;
}
if (frame['type'] != 'notification') return;
final notice = AgentNotice.parse(frame['notification']);
if (notice == null) return;
_enqueue(() async {
await notifications.ready;
if (_disposed || !notifications.claimAgentNotice(notice.id, _now())) {
return;
}
await _deliver(notice, replay: false);
});
}
/// Runs deliveries one at a time, in arrival order.
void _enqueue(Future<void> Function() step) {
_queue = _queue.then((_) => step()).catchError((Object _) {});
}
Future<void> _replay(List<AgentNotice> notices) async {
await notifications.ready;
if (_disposed) return;
final now = _now();
final fresh = <AgentNotice>[];
for (final notice in notices) {
if (!notifications.claimAgentNotice(notice.id, now)) continue;
final at = notice.createdAt;
if (at != null && now.difference(at) <= agentNoticeReplayWindow) {
fresh.add(notice);
}
}
final start = fresh.length > agentNoticeReplayLimit
? fresh.length - agentNoticeReplayLimit
: 0;
for (final notice in fresh.skip(start)) {
if (_disposed) return;
await _deliver(notice, replay: true);
}
}
Future<void> _deliver(AgentNotice notice, {required bool replay}) async {
String? chat;
try {
chat = await sessionTitle(notice.sessionId);
} catch (_) {
// An unavailable chat list leaves the generic "Chat" headline.
}
if (_disposed) return;
final delivery = agentNoticeDelivery(
notice: notice,
presence: page.presence,
chatInView: activeChatSessionId() == notice.sessionId,
canNotify: notifications.canNotify,
replay: replay,
);
final headline = notice.headline(chat);
void open() => openChat(notice.sessionId);
var toast = delivery.toast;
if (delivery.system && !_showSystem(notice, headline, open)) toast = true;
if (toast) {
showToast(
AgentToast(headline: headline, message: notice.message, open: open),
);
}
if (delivery.badge && page.presence != PagePresence.focused) {
_badge++;
page.setBadge(_badge);
}
if (delivery.chime) page.chime();
}
bool _showSystem(AgentNotice notice, String headline, void Function() open) {
try {
return notifications.bridge.show(
NotificationMessage(
chatSessionId: notice.sessionId,
title: headline,
body: notice.message,
tag: notice.id,
),
onTap: open,
);
} catch (_) {
return false;
}
}
void _clearBadge() {
if (_badge == 0) return;
_badge = 0;
page.setBadge(0);
}
void dispose() {
_disposed = true;
unawaited(_frames.cancel());
unawaited(_focus.cancel());
}
}
@@ -19,6 +19,8 @@ extension type _Notification._(JSObject _) implements JSObject {
external static JSPromise<JSString> requestPermission(); external static JSPromise<JSString> requestPermission();
external set onclick(JSFunction? handler); external set onclick(JSFunction? handler);
external void close();
} }
/// The `{ body, tag }` options object one notification is created with. /// The `{ body, tag }` options object one notification is created with.
@@ -83,7 +85,13 @@ class WebNotificationBridge implements NotificationBridge {
); );
final open = onTap; final open = onTap;
if (open != null) { if (open != null) {
notification.onclick = (() => open()).toJS; notification.onclick = (() {
// Bring this tab forward first: a click on a notification does not
// focus the page that posted it on its own.
globalContext.callMethod<JSAny?>('focus'.toJS);
notification.close();
open();
}).toJS;
} }
return true; return true;
} catch (_) { } catch (_) {
@@ -71,6 +71,11 @@ class NotificationController extends ChangeNotifier {
/// True once the persisted ledger and the platform facts have been read. /// True once the persisted ledger and the platform facts have been read.
bool get loaded => _loaded; bool get loaded => _loaded;
/// Completes once [load] has read the ledger, so a caller can claim agent
/// notices against the persisted record rather than an empty one.
Future<void> get ready => _ready.future;
final Completer<void> _ready = Completer<void>();
/// Whether the operator has ever been asked for permission. /// Whether the operator has ever been asked for permission.
bool get asked => _ledger.asked; bool get asked => _ledger.asked;
@@ -102,6 +107,7 @@ class NotificationController extends ChangeNotifier {
_announced.clear(); _announced.clear();
_permission = notificationStateOf(bridge.environment()); _permission = notificationStateOf(bridge.environment());
_loaded = true; _loaded = true;
if (!_ready.isCompleted) _ready.complete();
notifyListeners(); notifyListeners();
} }
@@ -254,6 +260,17 @@ class NotificationController extends ChangeNotifier {
return posted; return posted;
} }
/// Records agent notification [id] as shown on this device and reports
/// whether it is new. Only the first claim of an id, in this session or any
/// earlier one (the ledger persists), returns true, so a replay after a
/// reload or reconnect is shown once. Call it after [load] has completed.
bool claimAgentNotice(String id, DateTime now) {
if (_disposed || id.isEmpty || _ledger.hasShownAgent(id)) return false;
_ledger = _ledger.recordingAgent(id, now);
unawaited(_persist(_ledger));
return true;
}
/// Writes the ledger without ever throwing into the caller's frame, one write /// Writes the ledger without ever throwing into the caller's frame, one write
/// at a time so their order matches the calls. /// at a time so their order matches the calls.
Future<void> _persist(NotificationLedger ledger) { Future<void> _persist(NotificationLedger ledger) {
@@ -55,22 +55,61 @@ class NotificationLedger {
const NotificationLedger({ const NotificationLedger({
this.notified = const <String>{}, this.notified = const <String>{},
this.asked = false, this.asked = false,
this.agentShown = const <String, int>{},
}); });
/// How many agent notification ids the ledger keeps, newest first.
static const maxAgentShown = 200;
/// How long an agent notification id is kept: longer than the replay window
/// the client honours, so a replayed one is always recognised.
static const agentShownRetention = Duration(days: 2);
/// The transition identities already recorded, in no particular order. /// The transition identities already recorded, in no particular order.
final Set<String> notified; final Set<String> notified;
/// The agent notification ids (server ids of `chat_notify`) already shown on
/// this device, with when they were shown (epoch milliseconds). Unlike
/// [notified] they are not tied to a run state: they are only forgotten by
/// age and count, so a reload or reconnect never repeats one.
final Map<String, int> agentShown;
/// Whether the operator has ever been asked for permission. /// Whether the operator has ever been asked for permission.
final bool asked; final bool asked;
bool hasNotified(String identity) => notified.contains(identity); bool hasNotified(String identity) => notified.contains(identity);
/// The ledger with [identity] recorded. /// The ledger with [identity] recorded.
NotificationLedger recording(String identity) => NotificationLedger recording(String identity) => NotificationLedger(
NotificationLedger(notified: {...notified, identity}, asked: asked); notified: {...notified, identity},
asked: asked,
agentShown: agentShown,
);
NotificationLedger withAsked(bool value) => NotificationLedger withAsked(bool value) => NotificationLedger(
NotificationLedger(notified: notified, asked: value); notified: notified,
asked: value,
agentShown: agentShown,
);
bool hasShownAgent(String id) => agentShown.containsKey(id);
/// The ledger with agent notification [id] recorded as shown at [now], and
/// every entry older than [agentShownRetention] or beyond [maxAgentShown]
/// dropped.
NotificationLedger recordingAgent(String id, DateTime now) {
final at = now.millisecondsSinceEpoch;
final oldest = now.subtract(agentShownRetention).millisecondsSinceEpoch;
final entries = [
...agentShown.entries.where((e) => e.key != id && e.value >= oldest),
MapEntry(id, at),
]..sort((a, b) => b.value.compareTo(a.value));
return NotificationLedger(
notified: notified,
asked: asked,
agentShown: Map.fromEntries(entries.take(maxAgentShown)),
);
}
/// The ledger with every identity outside [qualifying] dropped. /// The ledger with every identity outside [qualifying] dropped.
/// ///
@@ -81,7 +120,11 @@ class NotificationLedger {
NotificationLedger pruning(Set<String> qualifying) { NotificationLedger pruning(Set<String> qualifying) {
final kept = notified.where(qualifying.contains).toSet(); final kept = notified.where(qualifying.contains).toSet();
if (kept.length == notified.length) return this; if (kept.length == notified.length) return this;
return NotificationLedger(notified: kept, asked: asked); return NotificationLedger(
notified: kept,
asked: asked,
agentShown: agentShown,
);
} }
} }
@@ -90,7 +133,14 @@ class NotificationLedger {
String encodeNotificationLedger(NotificationLedger ledger) { String encodeNotificationLedger(NotificationLedger ledger) {
final identities = ledger.notified.where((id) => id.isNotEmpty).toList() final identities = ledger.notified.where((id) => id.isNotEmpty).toList()
..sort(); ..sort();
return jsonEncode({'asked': ledger.asked, 'notified': identities}); final agent = ledger.agentShown.keys.where((id) => id.isNotEmpty).toList()
..sort();
return jsonEncode({
'asked': ledger.asked,
'notified': identities,
if (agent.isNotEmpty)
'agent': {for (final id in agent) id: ledger.agentShown[id]},
});
} }
/// Decodes a stored value into a ledger. Total: blank text, unreadable JSON, a /// Decodes a stored value into a ledger. Total: blank text, unreadable JSON, a
@@ -111,7 +161,16 @@ NotificationLedger decodeNotificationLedger(String? stored) {
} }
if (parsed is! Map) return const NotificationLedger(); if (parsed is! Map) return const NotificationLedger();
final raw = parsed['notified']; final raw = parsed['notified'];
final agent = parsed['agent'];
return NotificationLedger( return NotificationLedger(
agentShown: {
if (agent is Map)
for (final entry in agent.entries)
if (entry.key is String &&
(entry.key as String).isNotEmpty &&
entry.value is int)
entry.key as String: entry.value as int,
},
notified: { notified: {
if (raw is List) if (raw is List)
for (final value in raw) for (final value in raw)
@@ -78,10 +78,12 @@ const notificationUnsupportedCopy =
'is the only channel.'; 'is the only channel.';
const notificationInsecureCopy = const notificationInsecureCopy =
'Notifications need a secure context (https or localhost). This page is not ' 'Notifications need a secure context (https or localhost). This page is not '
'secure, so the in-app Needs you surface is the only channel.'; 'secure, so runs that need you appear only in the in-app Needs you surface, '
'and agent notifications show as an in-app message and a count in the tab '
'title. Open the https address to get browser notifications.';
const notificationGrantedCopy = const notificationGrantedCopy =
'Notifications are on. Failed and waiting runs will raise a browser ' 'Notifications are on. Failed and waiting runs, and agents asked to notify '
'notification.'; 'you, will raise a browser notification.';
const notificationDeniedCopy = const notificationDeniedCopy =
'Notifications are blocked for this site. Allow them in the browser\'s site ' 'Notifications are blocked for this site. Allow them in the browser\'s site '
'settings to use them; until then the in-app Needs you surface is the only ' 'settings to use them; until then the in-app Needs you surface is the only '
@@ -144,11 +146,12 @@ NotificationPermissionView notificationPermissionView(
), ),
NotificationPermissionState.needsSecureContext => ( NotificationPermissionState.needsSecureContext => (
'Needs a secure page', 'Needs a secure page',
'Open the app over https or localhost to turn them on.', 'Open the https address to turn them on. Until then agent notifications '
'show in the app and the tab title.',
), ),
NotificationPermissionState.granted => ( NotificationPermissionState.granted => (
'Alerts are on', 'Alerts are on',
'Failed and waiting runs raise a notification.', 'Failed and waiting runs and agent notifications raise one.',
), ),
NotificationPermissionState.denied => ( NotificationPermissionState.denied => (
'Blocked by the browser', 'Blocked by the browser',
@@ -162,7 +165,8 @@ NotificationPermissionView notificationPermissionView(
) )
: ( : (
'Alerts are off', 'Alerts are off',
'Get told when a run fails or needs your decision.', 'Get told when a run fails or needs you, or an agent '
'notifies you.',
), ),
}; };
return NotificationPermissionView( return NotificationPermissionView(
@@ -0,0 +1,38 @@
import 'page_signals_stub.dart'
if (dart.library.js_interop) 'page_signals_web.dart'
as impl;
import 'agent_notice.dart';
/// The page-level signals agent notices use besides system notifications:
/// whether the operator is looking, a count in the tab title, and a chime.
///
/// On the web these are the document's own visibility and focus, its title,
/// and a Web Audio tone; elsewhere presence follows the app lifecycle and the
/// title count and chime are absent (a native app has no tab title).
abstract interface class PageSignals {
/// Whether the operator is looking at the app right now.
PagePresence get presence;
/// Fires each time the page becomes visible and focused again.
Stream<void> get focused;
/// Shows [count] in the tab title ("(2) Pipelines"); 0 removes it.
void setBadge(int count);
/// Plays a short, quiet tone when the platform allows it.
void chime();
void dispose();
}
PageSignals createPageSignals() => impl.createPageSignals();
/// The title with a leading "(n) " count removed.
String unbadgedTitle(String title) =>
title.replaceFirst(RegExp(r'^\(\d+\) '), '');
/// [title] showing [count]; 0 shows the bare title.
String badgedTitle(String title, int count) {
final base = unbadgedTitle(title);
return count > 0 ? '($count) $base' : base;
}
@@ -0,0 +1,46 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'agent_notice.dart';
import 'page_signals.dart';
/// Presence from the app lifecycle: resumed is focused, inactive is visible
/// without focus, anything else is hidden. There is no tab title to badge and
/// no chime; the toast and the system notification carry the notice.
class LifecyclePageSignals with WidgetsBindingObserver implements PageSignals {
LifecyclePageSignals() {
WidgetsBinding.instance.addObserver(this);
}
final _focused = StreamController<void>.broadcast();
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) _focused.add(null);
}
@override
PagePresence get presence => switch (WidgetsBinding.instance.lifecycleState) {
null || AppLifecycleState.resumed => PagePresence.focused,
AppLifecycleState.inactive => PagePresence.visible,
_ => PagePresence.hidden,
};
@override
Stream<void> get focused => _focused.stream;
@override
void setBadge(int count) {}
@override
void chime() {}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
unawaited(_focused.close());
}
}
PageSignals createPageSignals() => LifecyclePageSignals();
@@ -0,0 +1,78 @@
import 'dart:async';
import 'dart:js_interop';
import 'package:web/web.dart' as web;
import 'agent_notice.dart';
import 'page_signals.dart';
/// The browser page's own signals: `document.visibilityState`,
/// `document.hasFocus()`, `document.title` and a Web Audio tone.
///
/// Focus is read from the document rather than the app lifecycle, because a
/// click into an embedded HTML view moves window focus into its iframe while
/// the operator is still looking at the page.
class BrowserPageSignals implements PageSignals {
BrowserPageSignals() {
_onFocus = ((web.Event _) => _maybeFocused()).toJS;
web.window.addEventListener('focus', _onFocus);
web.document.addEventListener('visibilitychange', _onFocus);
}
late final JSFunction _onFocus;
final _focused = StreamController<void>.broadcast();
web.AudioContext? _audio;
void _maybeFocused() {
if (presence == PagePresence.focused) _focused.add(null);
}
@override
PagePresence get presence {
if (web.document.visibilityState == 'hidden') return PagePresence.hidden;
return web.document.hasFocus()
? PagePresence.focused
: PagePresence.visible;
}
@override
Stream<void> get focused => _focused.stream;
@override
void setBadge(int count) {
final next = badgedTitle(web.document.title, count);
if (next != web.document.title) web.document.title = next;
}
@override
void chime() {
try {
final audio = _audio ??= web.AudioContext();
// A context created before any gesture starts suspended; resuming it
// succeeds once the operator has interacted with the page.
if (audio.state == 'suspended') unawaited(audio.resume().toDart);
final now = audio.currentTime;
final tone = audio.createOscillator()..type = 'sine';
tone.frequency.value = 880;
final volume = audio.createGain();
volume.gain.value = 0.06;
tone.connect(volume);
volume.connect(audio.destination);
tone.start(now);
tone.stop(now + 0.18);
} catch (_) {
// No audio (blocked autoplay, no device): the toast and title remain.
}
}
@override
void dispose() {
web.window.removeEventListener('focus', _onFocus);
web.document.removeEventListener('visibilitychange', _onFocus);
unawaited(_focused.close());
final audio = _audio;
if (audio != null) unawaited(audio.close().toDart);
}
}
PageSignals createPageSignals() => BrowserPageSignals();
@@ -0,0 +1,44 @@
import 'package:flutter/material.dart';
import '../notify/agent_notices.dart';
/// The toast's root, so tests and captures can find it.
const agentNoticeToastKey = ValueKey<String>('agent-notice-toast');
/// How long an agent notice toast stays up. Long enough to read while coming
/// back to the window; the Open action keeps it reachable.
const agentNoticeToastDuration = Duration(seconds: 10);
/// The in-app toast for one agent notice: the `<chat>: <title>` headline, the
/// message, and an Open action that opens the chat.
SnackBar agentNoticeSnackBar(AgentToast toast) => SnackBar(
key: agentNoticeToastKey,
behavior: SnackBarBehavior.floating,
duration: agentNoticeToastDuration,
showCloseIcon: true,
content: Builder(
builder: (context) {
final theme = Theme.of(context).snackBarTheme.contentTextStyle;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
toast.headline,
style:
theme?.copyWith(fontWeight: FontWeight.w600) ??
const TextStyle(fontWeight: FontWeight.w600),
),
if (toast.message.isNotEmpty)
Text(toast.message, maxLines: 4, overflow: TextOverflow.ellipsis),
],
);
},
),
action: SnackBarAction(label: 'Open', onPressed: toast.open),
);
/// Shows [toast] through [messenger], after any toast already showing.
void showAgentNoticeToast(ScaffoldMessengerState? messenger, AgentToast toast) {
messenger?.showSnackBar(agentNoticeSnackBar(toast));
}
+31
View File
@@ -0,0 +1,31 @@
# Agent notify reaches the web app
An agent's MCP `notify` call is recorded by the server as a `chat_notify` app
notification (id `chat:<session>:notify:<shown id>`, priority low 2 / default 3
/ high 4) on the existing notification stream (`subscribe_notifications`), so
every connected client receives it and a reconnecting client replays the ones
still active. ntfy delivery is unchanged.
The app (`lib/features/attention/notify/agent_notices.dart`) subscribes on every
connection through the send-only path and decides per notice
(`agent_notice.dart`, `agentNoticeDelivery`):
- focused page: an in-app toast with Open, nothing if that chat is in view;
- unfocused or hidden page with browser permission: a system notification
titled `<chat title>: <title>` (click focuses the tab and opens the chat) and a
`(n) ` count in the tab title until focus returns; low priority only posts
when the page is hidden, otherwise it waits as a toast;
- no permission or an insecure http page: toast, title count and, for default
and high priority live notices, a short Web Audio chime.
Replays older than one hour are recorded but not shown; at most five show. Shown
ids persist in the notification ledger (`agent` map, two days, 200 entries), so
reloads and reconnects never repeat one. Opening the chat clears the server copy
on every device (chat seen).
Captures (`tool/capture`, fixture `?ui-review=1&agentNotice=<ms>`): secure
focused toast, Open navigating to `/chat/ui-review`, no toast with the chat in
view, insecure unfocused toast with `document.title == "(1) Pipelines"` and back
to `Pipelines` on focus, and the Settings hints for secure and insecure pages.
Browser system notifications themselves were not captured (headless Chrome,
permission not granted); unit tests cover that path.
@@ -0,0 +1,329 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/attention/notify/agent_notice.dart';
import 'package:pipelines_app/features/attention/notify/agent_notices.dart';
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
import 'package:pipelines_app/features/attention/notify/notification_ledger.dart';
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
import 'package:pipelines_app/features/attention/notify/page_signals.dart';
import 'notification_test_support.dart';
final _now = DateTime.utc(2026, 12, 2, 12);
class _Gateway implements ApiGateway {
final controller = StreamController<JsonMap>.broadcast();
List<JsonMap> backlog = [];
final calls = <String>[];
@override
Stream<JsonMap> get frames => controller.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(type);
return {
'type': 'notifications_subscribed',
'notifications': backlog,
'ids': <String>[],
};
}
}
class _Page implements PageSignals {
PagePresence current = PagePresence.focused;
final badges = <int>[];
int chimes = 0;
final focus = StreamController<void>.broadcast();
@override
PagePresence get presence => current;
@override
Stream<void> get focused => focus.stream;
@override
void setBadge(int count) => badges.add(count);
@override
void chime() => chimes++;
@override
void dispose() {}
}
JsonMap _notice(
String id, {
String session = 'ses_1',
String kind = 'chat_notify',
int priority = 3,
Duration age = Duration.zero,
}) => {
'id': 'chat:$session:notify:$id',
'kind': kind,
'title': 'Build done',
'message': 'All tests pass',
'click': 'pipelines://chat/$session',
'priority': priority,
'tags': <String>[],
'created_at': _now.subtract(age).toIso8601String(),
'group': 'chat:$session',
};
JsonMap _push(JsonMap notice) => {
'type': 'notification',
'notification': notice,
};
void main() {
late _Gateway gateway;
late _Page page;
late FakeNotificationBridge bridge;
late MemoryNotificationStore store;
late NotificationController notifications;
late AgentNotices notices;
late List<AgentToast> toasts;
late List<String> opened;
late String? active;
AgentNotices build() => AgentNotices(
gateway: gateway,
notifications: notifications,
page: page,
activeChatSessionId: () => active,
sessionTitle: (id) async => id == 'ses_1' ? 'Release chat' : null,
openChat: opened.add,
showToast: toasts.add,
now: () => _now,
);
Future<void> setUpWith({
String permission = 'granted',
bool secure = true,
}) async {
gateway = _Gateway();
page = _Page();
bridge = FakeNotificationBridge(
permission: permission,
secureContext: secure,
);
store = MemoryNotificationStore();
notifications = NotificationController(store: store, bridge: bridge);
await notifications.load();
toasts = [];
opened = [];
active = null;
notices = build();
}
Future<void> pump() async {
for (var i = 0; i < 10; i++) {
await Future<void>.delayed(Duration.zero);
}
}
tearDown(() async {
notices.dispose();
notifications.dispose();
await gateway.controller.close();
});
test('a focused page shows a toast that opens the chat', () async {
await setUpWith();
gateway.controller.add(_push(_notice('a')));
await pump();
expect(bridge.shown, isEmpty);
expect(toasts.single.headline, 'Release chat: Build done');
expect(toasts.single.message, 'All tests pass');
expect(page.badges, isEmpty);
toasts.single.open();
expect(opened, ['ses_1']);
});
test('nothing shows when the chat is already in view', () async {
await setUpWith();
active = 'ses_1';
gateway.controller.add(_push(_notice('a')));
await pump();
expect(toasts, isEmpty);
expect(bridge.shown, isEmpty);
expect(
notifications.claimAgentNotice('chat:ses_1:notify:a', _now),
isFalse,
);
});
test('an unfocused page posts a system notification and badges the title; '
'focus clears the badge', () async {
await setUpWith();
page.current = PagePresence.hidden;
active = 'ses_1'; // In view but not looked at: still notified.
gateway.controller.add(_push(_notice('a')));
gateway.controller.add(_push(_notice('b', session: 'ses_2')));
await pump();
expect(bridge.shown.map((m) => m.title), [
'Release chat: Build done',
'Chat: Build done',
]);
expect(bridge.shown.first.tag, 'chat:ses_1:notify:a');
expect(bridge.shown.first.body, 'All tests pass');
expect(toasts, isEmpty);
expect(page.badges, [1, 2]);
expect(notices.badge, 2);
expect(page.chimes, 0);
bridge.taps.first!();
expect(opened, ['ses_1']);
page.current = PagePresence.focused;
page.focus.add(null);
await pump();
expect(page.badges.last, 0);
expect(notices.badge, 0);
});
test('a low priority notice waits as a toast on a visible page and posts '
'only when the page is hidden', () async {
await setUpWith();
page.current = PagePresence.visible;
gateway.controller.add(_push(_notice('low', priority: 2)));
await pump();
expect(bridge.shown, isEmpty);
expect(toasts, hasLength(1));
expect(page.badges, [1]);
expect(page.chimes, 0);
page.current = PagePresence.hidden;
gateway.controller.add(_push(_notice('low2', priority: 2)));
await pump();
expect(bridge.shown, hasLength(1));
});
test(
'an insecure page falls back to a toast, a title count and a chime',
() async {
await setUpWith(permission: 'default', secure: false);
page.current = PagePresence.hidden;
gateway.controller.add(_push(_notice('a', priority: 4)));
await pump();
expect(notifications.canNotify, isFalse);
expect(bridge.shown, isEmpty);
expect(toasts.single.headline, 'Release chat: Build done');
expect(page.badges, [1]);
expect(page.chimes, 1);
},
);
test('a refused system notification falls back to the toast', () async {
await setUpWith();
bridge.accepts = false;
page.current = PagePresence.hidden;
gateway.controller.add(_push(_notice('a')));
await pump();
expect(bridge.shown, hasLength(1));
expect(toasts, hasLength(1));
});
test('other notification kinds are left to their own surfaces', () async {
await setUpWith();
gateway.controller.add(_push(_notice('r', kind: 'chat_reply')));
gateway.controller.add({'type': 'chat_event', 'chat_event': {}});
await pump();
expect(toasts, isEmpty);
expect(bridge.shown, isEmpty);
});
test(
'a repeated push and a replay of a shown notice are deduplicated',
() async {
await setUpWith();
gateway.controller.add(_push(_notice('a')));
gateway.controller.add(_push(_notice('a')));
await pump();
gateway.backlog = [_notice('a')];
await notices.connected();
await pump();
expect(toasts, hasLength(1));
},
);
test(
'a reconnect replays recent missed notices once, across a reload',
() async {
await setUpWith();
gateway.backlog = [
_notice('old', age: const Duration(hours: 2)),
_notice('recent', age: const Duration(minutes: 20)),
_notice('reply', kind: 'chat_reply'),
];
await notices.connected();
await pump();
expect(gateway.calls, ['subscribe_notifications']);
expect(toasts.map((t) => t.headline), ['Release chat: Build done']);
// The ledger persisted both chat_notify ids, so a reload shows neither.
final stored = decodeNotificationLedger(store.stored);
expect(stored.agentShown.keys, {
'chat:ses_1:notify:old',
'chat:ses_1:notify:recent',
});
notices.dispose();
notifications.dispose();
notifications = NotificationController(
store: MemoryNotificationStore(stored: store.stored),
bridge: bridge,
);
await notifications.load();
toasts.clear();
notices = build();
await notices.connected();
await pump();
expect(toasts, isEmpty);
},
);
test('with a send-only path the subscribe reply is read from the frames, '
'so it never holds the request lane', () async {
await setUpWith();
notices.dispose();
final sent = <String>[];
notices = AgentNotices(
gateway: gateway,
notifications: notifications,
page: page,
activeChatSessionId: () => active,
sessionTitle: (id) async => 'Release chat',
openChat: opened.add,
showToast: toasts.add,
sendOnly: (type, fields) {
sent.add(type);
return 'flutter-1';
},
now: () => _now,
);
await notices.connected();
expect(sent, ['subscribe_notifications']);
expect(gateway.calls, isEmpty);
gateway.controller.add({
'type': 'notifications_subscribed',
'id': 'flutter-1',
'notifications': [_notice('missed', age: const Duration(minutes: 5))],
});
await pump();
expect(toasts.single.headline, 'Release chat: Build done');
});
test('a replay shows at most the newest few and never chimes', () async {
await setUpWith(permission: 'default', secure: false);
page.current = PagePresence.hidden;
gateway.backlog = [
for (var i = 0; i < 8; i++)
_notice('n$i', age: Duration(minutes: 30 - i)),
];
await notices.connected();
await pump();
expect(toasts, hasLength(agentNoticeReplayLimit));
expect(page.chimes, 0);
expect(page.badges.last, agentNoticeReplayLimit);
});
}
@@ -140,4 +140,49 @@ void main() {
); );
}); });
}); });
group('the ledger keeps agent ids apart from run identities', () {
test('pruning runs keeps agent ids; age and count bound them', () {
var ledger = const NotificationLedger()
.recording('7:Failed')
.recordingAgent('chat:a:notify:1', _agentNow);
ledger = ledger.pruning({});
expect(ledger.notified, isEmpty);
expect(ledger.hasShownAgent('chat:a:notify:1'), isTrue);
ledger = ledger.recordingAgent(
'chat:a:notify:2',
_agentNow.add(NotificationLedger.agentShownRetention * 2),
);
expect(ledger.agentShown.keys, ['chat:a:notify:2']);
for (var i = 0; i < NotificationLedger.maxAgentShown + 10; i++) {
ledger = ledger.recordingAgent(
'x$i',
_agentNow.add(Duration(seconds: i)),
);
}
expect(ledger.agentShown, hasLength(NotificationLedger.maxAgentShown));
expect(ledger.hasShownAgent('x0'), isFalse);
});
test('the encoding round-trips and an old value decodes', () {
final ledger = const NotificationLedger(
asked: true,
).recordingAgent('chat:a:notify:1', _agentNow);
final decoded = decodeNotificationLedger(
encodeNotificationLedger(ledger),
);
expect(decoded.asked, isTrue);
expect(decoded.agentShown, ledger.agentShown);
expect(
decodeNotificationLedger(
'{"asked":false,"notified":["1:Failed"]}',
).agentShown,
isEmpty,
);
});
});
} }
final _agentNow = DateTime.utc(2026, 12, 2, 12);
@@ -0,0 +1,44 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/notify/agent_notices.dart';
import 'package:pipelines_app/features/attention/notify/page_signals.dart';
import 'package:pipelines_app/features/attention/ui/agent_notice_toast.dart';
void main() {
testWidgets('the toast shows the headline and message; Open opens the chat', (
tester,
) async {
final messenger = GlobalKey<ScaffoldMessengerState>();
var opened = 0;
await tester.pumpWidget(
MaterialApp(
scaffoldMessengerKey: messenger,
home: const Scaffold(body: SizedBox.expand()),
),
);
showAgentNoticeToast(
messenger.currentState,
AgentToast(
headline: 'Release chat: Build done',
message: 'All tests pass',
open: () => opened++,
),
);
await tester.pumpAndSettle();
expect(find.byKey(agentNoticeToastKey), findsOneWidget);
expect(find.text('Release chat: Build done'), findsOneWidget);
expect(find.text('All tests pass'), findsOneWidget);
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
expect(opened, 1);
expect(find.byKey(agentNoticeToastKey), findsNothing);
});
test('the tab title count is added, replaced and removed', () {
expect(badgedTitle('Pipelines', 1), '(1) Pipelines');
expect(badgedTitle('(1) Pipelines', 3), '(3) Pipelines');
expect(badgedTitle('(3) Pipelines', 0), 'Pipelines');
expect(unbadgedTitle('(12) Runs (2)'), 'Runs (2)');
});
}
+49
View File
@@ -0,0 +1,49 @@
// An agent's notify call for captures of the web notification paths. Off by
// default.
//
// `?agentNotice=<ms>` answers subscribe_notifications with no backlog, then
// <ms> after it pushes one `chat_notify` notification
// for the `ui-review` chat (add `ui-review=1` so the
// chat has its title). `agentNoticePriority=2|3|4`
// sets its priority (default 3).
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
Map<String, String> _params = const {};
void configureAgentNoticeFixture(Map<String, String> params) =>
_params = params;
/// The subscribe reply for [request], or null when the fixture is off or the
/// request is not a subscription. Schedules the push through [emit].
JsonMap? agentNoticeReply(JsonMap request, void Function(JsonMap) emit) {
if (request['type'] != 'subscribe_notifications') return null;
final delay = int.tryParse(_params['agentNotice'] ?? '');
if (delay != null) {
final priority = int.tryParse(_params['agentNoticePriority'] ?? '') ?? 3;
Timer(Duration(milliseconds: delay), () {
emit({
'type': 'notification',
'notification': {
'id': 'chat:ui-review:notify:shown_capture',
'kind': 'chat_notify',
'title': 'Build finished',
'message':
'All 412 tests pass. The release branch is ready to merge.',
'click': 'pipelines://chat/ui-review',
'priority': priority,
'tags': <String>[],
'created_at': DateTime.now().toUtc().toIso8601String(),
'group': 'chat:ui-review',
},
});
});
}
return {
'id': request['id'],
'type': 'notifications_subscribed',
'notifications': <JsonMap>[],
'ids': <String>[],
};
}
+6 -1
View File
@@ -44,6 +44,7 @@ import 'perf/chat_search_fixture.dart';
import 'perf/chat_shown_fixture.dart'; import 'perf/chat_shown_fixture.dart';
import 'perf/chat_claude_accounts_fixture.dart'; import 'perf/chat_claude_accounts_fixture.dart';
import 'perf/chat_question_fixture.dart'; import 'perf/chat_question_fixture.dart';
import 'perf/agent_notice_fixture.dart';
import 'capture/window_probe.dart'; import 'capture/window_probe.dart';
import 'perf/chat_scroll_fixture.dart'; import 'perf/chat_scroll_fixture.dart';
import 'perf/perf_fixture.dart'; import 'perf/perf_fixture.dart';
@@ -823,7 +824,10 @@ class _FixtureChannel implements WebSocketChannel {
'type': 'status', 'type': 'status',
'status': {'hostname': hostname}, 'status': {'hostname': hostname},
} }
: probeReply(decoded); : agentNoticeReply(decoded, (frame) {
if (!_incoming.isClosed) _incoming.add(jsonEncode(frame));
}) ??
probeReply(decoded);
final followUps = perfChatFollowUps(decoded); final followUps = perfChatFollowUps(decoded);
final subscribe = decoded['chat_subscribe']; final subscribe = decoded['chat_subscribe'];
if (subscribe is Map) { if (subscribe is Map) {
@@ -936,6 +940,7 @@ Future<void> main() async {
return; return;
} }
configurePerfFixture(params); configurePerfFixture(params);
configureAgentNoticeFixture(params);
installSpeechFixture(params); installSpeechFixture(params);
if (params['files'] == '1') { if (params['files'] == '1') {
probeMissingRememberedFolder = params['filesMissing'] == '1'; probeMissingRememberedFolder = params['filesMissing'] == '1';
+7 -3
View File
@@ -242,10 +242,14 @@ N = {"id":"run:7:3:waiting","kind":"run_waiting","title":"Run needs your decisio
- `id` is stable: `run:<run>:<step>:<event>` (event `waiting`, `failed`, - `id` is stable: `run:<run>:<step>:<event>` (event `waiting`, `failed`,
`succeeded`, or `success` for a mid-run stage hook) or `succeeded`, or `success` for a mid-run stage hook) or
`chat:<session>:<form|permission|reply>:<id>`. `kind` is one of `run_waiting`, `chat:<session>:<form|permission|reply|notify>:<id>`. `kind` is one of `run_waiting`,
`run_failed`, `run_succeeded`, `stage_failed`, `stage_succeeded`, `run_failed`, `run_succeeded`, `stage_failed`, `stage_succeeded`,
`chat_question`, `chat_approval`, `chat_reply`. `group` is `run:<id>` or `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. `chat:<id>`. `priority` is 3 and `tags` empty, matching what ntfy receives,
except `chat_notify`: an agent's `notify` tool call, whose priority is the
tool's (`low` 2, `default` 3, `high` 4). Every subscribed client receives it,
whichever chat it shows; the web app posts it as a browser notification or an
in-app alert, so an agent's notify reaches the operator without ntfy.
- The subscribe reply holds the active (uncleared) notifications newer than the - The subscribe reply holds the active (uncleared) notifications newer than the
`after` cursor (the last id the client holds), oldest first, at most 100; `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 an empty, unknown or pruned cursor replays them all. Its `ids` lists
+1 -1
View File
@@ -1,6 +1,6 @@
// Package chattools is the harness-neutral half of the Pipelines chat tools: // Package chattools is the harness-neutral half of the Pipelines chat tools:
// the MCP server a chat's model calls to show the operator a file, an image or // the MCP server a chat's model calls to show the operator a file, an image or
// an HTML view, or to notify their phone. The tools act on Pipelines itself, // an HTML view, or to notify them. The tools act on Pipelines itself,
// never on the harness or the workspace. // never on the harness or the workspace.
// //
// The server (internal/server) owns tokens, persistence and the tool effects. // The server (internal/server) owns tokens, persistence and the tool effects.
+3 -3
View File
@@ -26,7 +26,7 @@ func IsTool(name string) bool {
const Instructions = "These tools act on Pipelines, the app the operator reads this chat in, not on your workspace. " + const Instructions = "These tools act on Pipelines, the app the operator reads this chat in, not on your workspace. " +
"Use show_file / show_image instead of telling the operator a path to open, show_html for diagrams, charts or small visual views, " + "Use show_file / show_image instead of telling the operator a path to open, show_html for diagrams, charts or small visual views, " +
"show_diff when the operator asks to see changes or a diff (for example before submitting a pull request), " + "show_diff when the operator asks to see changes or a diff (for example before submitting a pull request), " +
"and notify only when the operator should look at their phone now. " + "and notify only when the operator should look at Pipelines now (it reaches their open Pipelines apps and their phone). " +
"Your thinking is not shown to the operator: before asking them a question (for example with AskUserQuestion), " + "Your thinking is not shown to the operator: before asking them a question (for example with AskUserQuestion), " +
"write what you found and why you are asking as a normal message, because the question form shows only the question and its options." "write what you found and why you are asking as a normal message, because the question form shows only the question and its options."
@@ -108,8 +108,8 @@ func definitions() []toolDefinition {
}, },
{ {
Name: ToolNotify, Name: ToolNotify,
Title: "Notify the operator's phone", Title: "Notify the operator",
Description: "Send a push notification to the operator's phone that opens this chat when tapped. " + Description: "Send a notification to the operator's open Pipelines apps (web, desktop) and their phone; it opens this chat when tapped. " +
"Use it sparingly, for things they should know now (a long task finished, you are blocked on them). " + "Use it sparingly, for things they should know now (a long task finished, you are blocked on them). " +
"Limited to 5 per minute per chat. Returns whether delivery was accepted.", "Limited to 5 per minute per chat. Returns whether delivery was accepted.",
InputSchema: objectSchema([]string{"title", "message"}, map[string]any{ InputSchema: objectSchema([]string{"title", "message"}, map[string]any{
+3
View File
@@ -50,6 +50,9 @@ const (
NotificationChatQuestion = "chat_question" // a chat asked a question NotificationChatQuestion = "chat_question" // a chat asked a question
NotificationChatApproval = "chat_approval" // a chat asks for permission/approval NotificationChatApproval = "chat_approval" // a chat asks for permission/approval
NotificationChatReply = "chat_reply" // a chat finished its reply NotificationChatReply = "chat_reply" // a chat finished its reply
// NotificationChatNotify is an agent's own notify tool call. Its priority
// is the tool's: low 2, default 3, high 4.
NotificationChatNotify = "chat_notify"
) )
// DefaultNotificationPriority is ntfy's default priority, which every ntfy // DefaultNotificationPriority is ntfy's default priority, which every ntfy
+7 -5
View File
@@ -131,22 +131,24 @@ func (a *appNotifier) detach(clientID string) {
} }
} }
// record persists n and pushes it when it is new. Failures are logged only: // record persists n and pushes it when it is new, and reports whether it is
// recording must never block or fail the ntfy publication beside it. // recorded. Failures are logged only: recording must never block or fail the
func (a *appNotifier) record(ctx context.Context, n pipeline.AppNotificationRecord) { // ntfy publication beside it.
func (a *appNotifier) record(ctx context.Context, n pipeline.AppNotificationRecord) bool {
if a == nil { if a == nil {
return return false
} }
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
stored, fresh, err := a.store.RecordAppNotification(ctx, n, a.now()) stored, fresh, err := a.store.RecordAppNotification(ctx, n, a.now())
if err != nil { if err != nil {
log.Printf("record app notification %s: %v", n.ID, err) log.Printf("record app notification %s: %v", n.ID, err)
return return false
} }
if fresh { if fresh {
a.enqueueLocked(protocol.Message{Type: protocol.NotificationPush, Notification: &stored}, "") a.enqueueLocked(protocol.Message{Type: protocol.NotificationPush, Notification: &stored}, "")
} }
return true
} }
// clear clears ids and pushes the ones that changed to every subscriber but // clear clears ids and pushes the ones that changed to every subscriber but
+73 -5
View File
@@ -51,6 +51,7 @@ type appNotificationFixture struct {
ctx context.Context ctx context.Context
store *pipeline.Store store *pipeline.Store
runner *runner runner *runner
hub *chatHub
url string url string
def *protocol.PipelineDetail def *protocol.PipelineDetail
} }
@@ -74,7 +75,7 @@ func newAppNotificationFixture(t *testing.T, ctx context.Context) *appNotificati
t.Cleanup(func() { stop(); WaitRuns(handler) }) t.Cleanup(func() { stop(); WaitRuns(handler) })
srv := httptest.NewServer(handler) srv := httptest.NewServer(handler)
t.Cleanup(srv.Close) t.Cleanup(srv.Close)
return &appNotificationFixture{t: t, ctx: ctx, store: store, runner: handler.(*runHandler).runner, url: srv.URL, def: def} 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 TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
@@ -83,19 +84,86 @@ func TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil { if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil {
t.Fatal(err) t.Fatal(err)
} }
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
hub := &chatHub{notes: newAppNotifier(store), settings: store} hub := &chatHub{notes: newAppNotifier(store), settings: store}
if ok, diagnostic := hub.publishToolNotification(ctx, "session-1", "Build failed", "Please inspect the run"); !ok || diagnostic != "" { got := hub.publishToolNotification(ctx, "session-1", chatToolNotice{ID: "shown_1", Title: "Build failed", Message: "Please inspect the run", Priority: "low"})
t.Fatalf("tool notification result = %v, %q", ok, diagnostic) if !got.App || got.Phone || got.Detail != "phone notifications (ntfy) are turned off" {
t.Fatalf("tool notification result = %+v", got)
} }
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now()) active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != 1 { if err != nil || len(active) != 1 {
t.Fatalf("app notifications = %+v, %v", active, err) t.Fatalf("app notifications = %+v, %v", active, err)
} }
if active[0].Kind != protocol.NotificationChatReply || active[0].Title != "Build failed" || active[0].Message != "Please inspect the run" { if n := active[0]; n.ID != "chat:session-1:notify:shown_1" || n.Kind != protocol.NotificationChatNotify || n.Title != "Build failed" ||
t.Fatalf("wrong tool notification: %+v", active[0]) 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)
} }
} }
// 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)
hub := f.handlerHub()
web, desktop := dialAckClient(t, ctx, f.url), dialAckClient(t, ctx, f.url)
subscribeNotifications(t, ctx, web, "")
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 == "" {
t.Fatalf("delivery = %+v", got)
}
for name, conn := range map[string]*websocket.Conn{"web": web, "desktop": desktop} {
push := readFrame(t, ctx, conn, protocol.NotificationPush).Notification
if push == nil || push.ID != "chat:ses_x:notify:shown_a" || push.Kind != protocol.NotificationChatNotify || push.Priority != 4 ||
push.Title != "Done" || push.Message != "Build finished" || push.Group != "chat:ses_x" {
t.Fatalf("%s push = %+v", name, push)
}
}
// The same words again are a new notification, not a duplicate.
notice.ID = "shown_b"
hub.publishToolNotification(ctx, "ses_x", notice)
if push := readFrame(t, ctx, web, protocol.NotificationPush).Notification; push == nil || push.ID != "chat:ses_x:notify:shown_b" {
t.Fatalf("second push = %+v", push)
}
// A client that was away replays what it missed, after its cursor.
late := dialAckClient(t, ctx, f.url)
if all := subscribeNotifications(t, ctx, late, ""); len(all.Notifications) != 2 || all.Notifications[0].ID != "chat:ses_x:notify:shown_a" {
t.Fatalf("replay = %+v", all.Notifications)
}
late.CloseNow()
late = dialAckClient(t, ctx, f.url)
if missed := subscribeNotifications(t, ctx, late, "chat:ses_x:notify:shown_a"); len(missed.Notifications) != 1 || missed.Notifications[0].ID != "chat:ses_x:notify:shown_b" {
t.Fatalf("replay after cursor = %+v", missed.Notifications)
}
// Opened on one device: the chat is seen, so none of its notifications
// replay anywhere.
if err := wsjson.Write(ctx, web, protocol.Message{Type: protocol.ClearNotifications, ID: "clr", IDs: []string{"chat:ses_x:notify:shown_a"}}); err != nil {
t.Fatal(err)
}
if reply := readFrame(t, ctx, web, protocol.NotificationsCleared); len(reply.IDs) != 1 {
t.Fatalf("clear reply = %+v", reply)
}
again := dialAckClient(t, ctx, f.url)
if left := subscribeNotifications(t, ctx, again, ""); len(left.Notifications) != 0 {
t.Fatalf("replay after clear = %+v", left.Notifications)
}
}
func (f *appNotificationFixture) handlerHub() *chatHub {
f.t.Helper()
if f.hub == nil {
f.t.Fatal("the handler has no chat hub")
}
return f.hub
}
// failRun creates a "Notify me" run and fails it, which commits a durable run // failRun creates a "Notify me" run and fails it, which commits a durable run
// notification intent in the same transaction, then drains the outbox. // notification intent in the same transaction, then drains the outbox.
func (f *appNotificationFixture) failRun(name string) int64 { func (f *appNotificationFixture) failRun(name string) int64 {
+63 -19
View File
@@ -123,30 +123,74 @@ func shownImageURL(raw string) (string, error) {
return parsed.String(), nil return parsed.String(), nil
} }
// chatToolNotifier sends one model-requested phone notification for a chat and // chatToolNotice is one model-requested notification. ID is the chat's shown
// reports whether ntfy accepted it, or why not. // item id, so every call is its own notification even with repeated words.
type chatToolNotifier func(ctx context.Context, sessionID, title, message string) (bool, string) type chatToolNotice struct {
ID string
Title string
Message string
Priority string // low, default or high
}
// publishToolNotification publishes through the operator's existing "system" // chatToolDelivery reports where a chat tool notification went: App when it
// ntfy destination (the one chat attention uses), honoring their ntfy switch. // was recorded on the app notification stream (every connected Pipelines app
// Tapping it opens the chat (pipelines://chat/<id>). // receives it and a reconnecting one replays it), Phone when ntfy accepted it.
func (h *chatHub) publishToolNotification(ctx context.Context, sessionID, title, message string) (bool, string) { // Detail explains a phone delivery that was skipped or refused.
title = truncateUTF8(title, 256) type chatToolDelivery struct {
message = truncateUTF8(message, 2000) 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.
func chatNotifyPriority(priority string) int {
switch priority {
case "low":
return 2
case "high":
return 4
}
return protocol.DefaultNotificationPriority
}
// 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>).
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, views := chatAttentionLinks(sessionID)
digest := sha256.Sum256([]byte(title + "\x00" + message)) id := notice.ID
if id == "" {
digest := sha256.Sum256([]byte(title + "\x00" + message))
id = hex.EncodeToString(digest[:8])
}
var delivery chatToolDelivery
if h.notes != nil { if h.notes != nil {
h.notes.record(ctx, pipeline.AppNotificationRecord{ delivery.App = h.notes.record(ctx, pipeline.AppNotificationRecord{
AppNotification: protocol.AppNotification{ID: "chat:" + sessionID + ":notify:" + hex.EncodeToString(digest[:8]), Kind: protocol.NotificationChatReply, Title: title, Message: message, Click: click, Priority: protocol.DefaultNotificationPriority, Tags: []string{}, Group: "chat:" + sessionID}, AppNotification: protocol.AppNotification{ID: "chat:" + sessionID + ":notify:" + id, Kind: protocol.NotificationChatNotify, Title: title, Message: message, Click: click, Priority: chatNotifyPriority(notice.Priority), Tags: []string{}, Group: "chat:" + sessionID},
SessionID: sessionID, SessionID: sessionID,
}) })
} }
if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled { switch {
return true, "" 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(ctx, "system", title, message, "", nil, click, views...); err != nil {
log.Printf("chat tool notification session=%s: %v", sessionID, err)
delivery.Detail = "the phone notification service refused it: " + err.Error()
} else {
delivery.Phone = true
}
} }
if _, err := chatAttentionPublish(ctx, "system", title, message, "", nil, click, views...); err != nil { return delivery
log.Printf("chat tool notification session=%s: %v", sessionID, err)
return false, "the notification service refused it: " + err.Error()
}
return true, ""
} }
+11 -5
View File
@@ -97,12 +97,18 @@ func (s *chatToolService) runNotify(ctx context.Context, sessionID, title, messa
if !s.limiter.allow(sessionID, s.now()) { if !s.limiter.allow(sessionID, s.now()) {
return nil, chattools.Result{Text: "Not sent: this chat already sent 5 notifications in the last minute. Wait before notifying again.", IsError: true} return nil, chattools.Result{Text: "Not sent: this chat already sent 5 notifications in the last minute. Wait before notifying again.", IsError: true}
} }
delivered, detail := s.notify(ctx, sessionID, title, message) id := newChatShownID()
item := protocol.ChatShownItem{Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivered, Detail: detail} delivery := s.notify(ctx, sessionID, chatToolNotice{ID: id, Title: title, Message: message, Priority: priority})
if !delivered { item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App || delivery.Phone, Detail: delivery.Detail}
return &item, chattools.Result{Text: "Not delivered: " + detail + ".", IsError: true} 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: "Delivery accepted: the notification was handed to the operator's phone notification service (ntfy)."} return &item, chattools.Result{Text: "Not delivered: " + delivery.Detail + ".", IsError: true}
} }
// boundedLine folds text to one line of at most limit bytes. // boundedLine folds text to one line of at most limit bytes.
+3 -1
View File
@@ -71,7 +71,9 @@ func (s *chatToolService) Call(ctx context.Context, token, tool string, argument
if item == nil { if item == nil {
return result return result
} }
item.ID = newChatShownID() if item.ID == "" {
item.ID = newChatShownID()
}
item.CreatedAt = s.now().UnixMilli() item.CreatedAt = s.now().UnixMilli()
if s.shown != nil { if s.shown != nil {
if err := s.shown.AppendChatShownItem(ctx, sessionID, *item); err != nil { if err := s.shown.AppendChatShownItem(ctx, sessionID, *item); err != nil {
+23 -5
View File
@@ -33,9 +33,9 @@ func newChatToolFixture(t *testing.T) *chatToolFixture {
f.hub.shown = store f.hub.shown = store
f.service = newChatToolService(store, store, f.hub, store) f.service = newChatToolService(store, store, f.hub, store)
f.service.home = func() (string, error) { return f.home, nil } f.service.home = func() (string, error) { return f.home, nil }
f.service.notify = func(_ context.Context, sessionID, title, message string) (bool, string) { f.service.notify = func(_ context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
f.notified = append(f.notified, sessionID+": "+title) f.notified = append(f.notified, sessionID+": "+notice.Title)
return true, "" return chatToolDelivery{App: true, Phone: true}
} }
return f return f
} }
@@ -229,7 +229,8 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
now := time.Unix(1_800_000_000, 0) now := time.Unix(1_800_000_000, 0)
f.service.now = func() time.Time { return now } f.service.now = func() time.Time { return now }
for i := range 5 { for i := range 5 {
if r := f.call(a, "notify", `{"title":"Done","message":"Build finished","priority":"high"}`); r.IsError { 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." {
t.Fatalf("notification %d: %v", i, r) t.Fatalf("notification %d: %v", i, r)
} }
} }
@@ -254,7 +255,9 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
t.Fatalf("items = %+v", got) t.Fatalf("items = %+v", got)
} }
f.service.notify = func(context.Context, string, string, string) (bool, string) { return false, "ntfy is not configured" } f.service.notify = func(context.Context, string, chatToolNotice) chatToolDelivery {
return chatToolDelivery{Detail: "ntfy is not configured"}
}
r := f.call(b, "notify", `{"title":"Fails","message":"x"}`) 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, "ntfy is not configured") {
t.Fatalf("an undelivered notification is reported: %v", r) t.Fatalf("an undelivered notification is reported: %v", r)
@@ -262,6 +265,21 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
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 != "ntfy is not configured" {
t.Fatalf("the undelivered entry is recorded: %+v", last) t.Fatalf("the undelivered entry is recorded: %+v", last)
} }
// Apps only (ntfy off): 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"}
}
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." {
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_") {
t.Fatalf("the apps-only entry is recorded: %+v", last)
}
} }
func TestInstanceTokenCallsNeedOneMatchingRunningToolCall(t *testing.T) { func TestInstanceTokenCallsNeedOneMatchingRunningToolCall(t *testing.T) {