Merge branch 'worktree-agent-ae6543d03d048d81f'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,10 @@ import '../shell/adaptive_shell.dart';
|
||||
import '../shell/destination.dart';
|
||||
import '../features/attention/notify/notification_controller.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/notification_service/notification_service_bridge.dart';
|
||||
import '../features/notification_service/notification_service_controller.dart';
|
||||
@@ -269,6 +273,11 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
);
|
||||
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
|
||||
/// 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
|
||||
@@ -472,18 +481,22 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
_chatQuestionNotices = ChatQuestionNotices(
|
||||
gateway: _session.gateway,
|
||||
canNotify: () => _notifications.canNotify,
|
||||
activeChatSessionId: () {
|
||||
final route = _delegate.shellRoute;
|
||||
return route.kind == AppRouteKind.chat ? route.chatSessionId : null;
|
||||
},
|
||||
activeChatSessionId: _activeChatSessionId,
|
||||
sessionTitle: _chatSessionTitle,
|
||||
openChat: (id) {
|
||||
if (!mounted) return;
|
||||
widget.servers?.requestChatOpen(id);
|
||||
_delegate.goTo(AppRoute.chatSession(id));
|
||||
},
|
||||
openChat: _openNotifiedChat,
|
||||
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>(
|
||||
routeInformationParser: const AppRouteParser(),
|
||||
routerDelegate: _delegate,
|
||||
@@ -595,6 +608,8 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
_notifications.dispose();
|
||||
_deliveryController.dispose();
|
||||
_chatQuestionNotices?.dispose();
|
||||
_agentNotices?.dispose();
|
||||
_pageSignals.dispose();
|
||||
if (identical(MachineElevation.defaultPrompt, _elevationPrompt)) {
|
||||
MachineElevation.defaultPrompt = null;
|
||||
}
|
||||
@@ -667,6 +682,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
// Every connected transition sends acknowledgements queued while offline
|
||||
// and re-reads the shared set, so a gap cannot leave this device stale.
|
||||
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
|
||||
@@ -879,6 +895,17 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
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 {
|
||||
id = widget.chatPool?.gateway.normalizeId(id) ?? id;
|
||||
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 set onclick(JSFunction? handler);
|
||||
|
||||
external void close();
|
||||
}
|
||||
|
||||
/// The `{ body, tag }` options object one notification is created with.
|
||||
@@ -83,7 +85,13 @@ class WebNotificationBridge implements NotificationBridge {
|
||||
);
|
||||
final open = onTap;
|
||||
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;
|
||||
} catch (_) {
|
||||
|
||||
@@ -71,6 +71,11 @@ class NotificationController extends ChangeNotifier {
|
||||
/// True once the persisted ledger and the platform facts have been read.
|
||||
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.
|
||||
bool get asked => _ledger.asked;
|
||||
|
||||
@@ -102,6 +107,7 @@ class NotificationController extends ChangeNotifier {
|
||||
_announced.clear();
|
||||
_permission = notificationStateOf(bridge.environment());
|
||||
_loaded = true;
|
||||
if (!_ready.isCompleted) _ready.complete();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -254,6 +260,17 @@ class NotificationController extends ChangeNotifier {
|
||||
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
|
||||
/// at a time so their order matches the calls.
|
||||
Future<void> _persist(NotificationLedger ledger) {
|
||||
|
||||
@@ -55,22 +55,61 @@ class NotificationLedger {
|
||||
const NotificationLedger({
|
||||
this.notified = const <String>{},
|
||||
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.
|
||||
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.
|
||||
final bool asked;
|
||||
|
||||
bool hasNotified(String identity) => notified.contains(identity);
|
||||
|
||||
/// The ledger with [identity] recorded.
|
||||
NotificationLedger recording(String identity) =>
|
||||
NotificationLedger(notified: {...notified, identity}, asked: asked);
|
||||
NotificationLedger recording(String identity) => NotificationLedger(
|
||||
notified: {...notified, identity},
|
||||
asked: asked,
|
||||
agentShown: agentShown,
|
||||
);
|
||||
|
||||
NotificationLedger withAsked(bool value) =>
|
||||
NotificationLedger(notified: notified, asked: value);
|
||||
NotificationLedger withAsked(bool value) => NotificationLedger(
|
||||
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.
|
||||
///
|
||||
@@ -81,7 +120,11 @@ class NotificationLedger {
|
||||
NotificationLedger pruning(Set<String> qualifying) {
|
||||
final kept = notified.where(qualifying.contains).toSet();
|
||||
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) {
|
||||
final identities = ledger.notified.where((id) => id.isNotEmpty).toList()
|
||||
..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
|
||||
@@ -111,7 +161,16 @@ NotificationLedger decodeNotificationLedger(String? stored) {
|
||||
}
|
||||
if (parsed is! Map) return const NotificationLedger();
|
||||
final raw = parsed['notified'];
|
||||
final agent = parsed['agent'];
|
||||
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: {
|
||||
if (raw is List)
|
||||
for (final value in raw)
|
||||
|
||||
@@ -78,10 +78,12 @@ const notificationUnsupportedCopy =
|
||||
'is the only channel.';
|
||||
const notificationInsecureCopy =
|
||||
'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 =
|
||||
'Notifications are on. Failed and waiting runs will raise a browser '
|
||||
'notification.';
|
||||
'Notifications are on. Failed and waiting runs, and agents asked to notify '
|
||||
'you, will raise a browser notification.';
|
||||
const notificationDeniedCopy =
|
||||
'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 '
|
||||
@@ -144,11 +146,12 @@ NotificationPermissionView notificationPermissionView(
|
||||
),
|
||||
NotificationPermissionState.needsSecureContext => (
|
||||
'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 => (
|
||||
'Alerts are on',
|
||||
'Failed and waiting runs raise a notification.',
|
||||
'Failed and waiting runs and agent notifications raise one.',
|
||||
),
|
||||
NotificationPermissionState.denied => (
|
||||
'Blocked by the browser',
|
||||
@@ -162,7 +165,8 @@ NotificationPermissionView notificationPermissionView(
|
||||
)
|
||||
: (
|
||||
'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(
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
Reference in New Issue
Block a user