Notify: an agent's notify reaches every connected app
The notify tool now records a chat_notify app notification with its own id per call (no dedupe of repeated words) and the tool's priority, so every subscribed client gets it and a reconnecting client replays it. ntfy delivery is unchanged; the tool result names where it went. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -131,22 +131,24 @@ func (a *appNotifier) detach(clientID string) {
|
||||
}
|
||||
}
|
||||
|
||||
// record persists n and pushes it when it is new. Failures are logged only:
|
||||
// recording must never block or fail the ntfy publication beside it.
|
||||
func (a *appNotifier) record(ctx context.Context, n pipeline.AppNotificationRecord) {
|
||||
// record persists n and pushes it when it is new, and reports whether it is
|
||||
// recorded. Failures are logged only: recording must never block or fail the
|
||||
// ntfy publication beside it.
|
||||
func (a *appNotifier) record(ctx context.Context, n pipeline.AppNotificationRecord) bool {
|
||||
if a == nil {
|
||||
return
|
||||
return false
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
stored, fresh, err := a.store.RecordAppNotification(ctx, n, a.now())
|
||||
if err != nil {
|
||||
log.Printf("record app notification %s: %v", n.ID, err)
|
||||
return
|
||||
return false
|
||||
}
|
||||
if fresh {
|
||||
a.enqueueLocked(protocol.Message{Type: protocol.NotificationPush, Notification: &stored}, "")
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// clear clears ids and pushes the ones that changed to every subscriber but
|
||||
|
||||
@@ -51,6 +51,7 @@ type appNotificationFixture struct {
|
||||
ctx context.Context
|
||||
store *pipeline.Store
|
||||
runner *runner
|
||||
hub *chatHub
|
||||
url string
|
||||
def *protocol.PipelineDetail
|
||||
}
|
||||
@@ -74,7 +75,7 @@ func newAppNotificationFixture(t *testing.T, ctx context.Context) *appNotificati
|
||||
t.Cleanup(func() { stop(); WaitRuns(handler) })
|
||||
srv := httptest.NewServer(handler)
|
||||
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) {
|
||||
@@ -83,19 +84,86 @@ func TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
|
||||
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
|
||||
hub := &chatHub{notes: newAppNotifier(store), settings: store}
|
||||
if ok, diagnostic := hub.publishToolNotification(ctx, "session-1", "Build failed", "Please inspect the run"); !ok || diagnostic != "" {
|
||||
t.Fatalf("tool notification result = %v, %q", ok, diagnostic)
|
||||
got := hub.publishToolNotification(ctx, "session-1", chatToolNotice{ID: "shown_1", Title: "Build failed", Message: "Please inspect the run", Priority: "low"})
|
||||
if !got.App || got.Phone || got.Detail != "phone notifications (ntfy) are turned off" {
|
||||
t.Fatalf("tool notification result = %+v", got)
|
||||
}
|
||||
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
|
||||
if err != nil || len(active) != 1 {
|
||||
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" {
|
||||
t.Fatalf("wrong tool notification: %+v", active[0])
|
||||
if n := active[0]; n.ID != "chat:session-1:notify:shown_1" || n.Kind != protocol.NotificationChatNotify || n.Title != "Build failed" ||
|
||||
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
|
||||
// notification intent in the same transaction, then drains the outbox.
|
||||
func (f *appNotificationFixture) failRun(name string) int64 {
|
||||
|
||||
@@ -123,30 +123,74 @@ func shownImageURL(raw string) (string, error) {
|
||||
return parsed.String(), nil
|
||||
}
|
||||
|
||||
// chatToolNotifier sends one model-requested phone notification for a chat and
|
||||
// reports whether ntfy accepted it, or why not.
|
||||
type chatToolNotifier func(ctx context.Context, sessionID, title, message string) (bool, string)
|
||||
// chatToolNotice is one model-requested notification. ID is the chat's shown
|
||||
// item id, so every call is its own notification even with repeated words.
|
||||
type chatToolNotice struct {
|
||||
ID string
|
||||
Title string
|
||||
Message string
|
||||
Priority string // low, default or high
|
||||
}
|
||||
|
||||
// publishToolNotification publishes 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, title, message string) (bool, string) {
|
||||
title = truncateUTF8(title, 256)
|
||||
message = truncateUTF8(message, 2000)
|
||||
// chatToolDelivery reports where a chat tool notification went: App when it
|
||||
// was recorded on the app notification stream (every connected Pipelines app
|
||||
// receives it and a reconnecting one replays it), Phone when ntfy accepted it.
|
||||
// Detail explains a phone delivery that was skipped or refused.
|
||||
type chatToolDelivery struct {
|
||||
App bool
|
||||
Phone bool
|
||||
Detail string
|
||||
}
|
||||
|
||||
// chatToolNotifier delivers one model-requested notification for a chat.
|
||||
type chatToolNotifier func(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery
|
||||
|
||||
// chatNotifyPriority maps the tool's priority word to the app stream's
|
||||
// ntfy-style 1-5 priority.
|
||||
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)
|
||||
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 {
|
||||
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},
|
||||
delivery.App = h.notes.record(ctx, pipeline.AppNotificationRecord{
|
||||
AppNotification: protocol.AppNotification{ID: "chat:" + sessionID + ":notify:" + id, Kind: protocol.NotificationChatNotify, Title: title, Message: message, Click: click, Priority: chatNotifyPriority(notice.Priority), Tags: []string{}, Group: "chat:" + sessionID},
|
||||
SessionID: sessionID,
|
||||
})
|
||||
}
|
||||
if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled {
|
||||
return true, ""
|
||||
switch {
|
||||
case !chatAttentionConfigured():
|
||||
delivery.Detail = "phone notifications (ntfy) are not configured"
|
||||
case !chatNotificationSettings(ctx, h.settings).NtfyEnabled:
|
||||
delivery.Detail = "phone notifications (ntfy) are turned off"
|
||||
default:
|
||||
if _, err := chatAttentionPublish(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 {
|
||||
log.Printf("chat tool notification session=%s: %v", sessionID, err)
|
||||
return false, "the notification service refused it: " + err.Error()
|
||||
}
|
||||
return true, ""
|
||||
return delivery
|
||||
}
|
||||
|
||||
@@ -97,12 +97,18 @@ func (s *chatToolService) runNotify(ctx context.Context, sessionID, title, messa
|
||||
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}
|
||||
}
|
||||
delivered, detail := s.notify(ctx, sessionID, title, message)
|
||||
item := protocol.ChatShownItem{Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivered, Detail: detail}
|
||||
if !delivered {
|
||||
return &item, chattools.Result{Text: "Not delivered: " + detail + ".", IsError: true}
|
||||
id := newChatShownID()
|
||||
delivery := s.notify(ctx, sessionID, chatToolNotice{ID: id, Title: title, Message: message, Priority: priority})
|
||||
item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App || delivery.Phone, Detail: delivery.Detail}
|
||||
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.
|
||||
|
||||
@@ -71,7 +71,9 @@ func (s *chatToolService) Call(ctx context.Context, token, tool string, argument
|
||||
if item == nil {
|
||||
return result
|
||||
}
|
||||
item.ID = newChatShownID()
|
||||
if item.ID == "" {
|
||||
item.ID = newChatShownID()
|
||||
}
|
||||
item.CreatedAt = s.now().UnixMilli()
|
||||
if s.shown != nil {
|
||||
if err := s.shown.AppendChatShownItem(ctx, sessionID, *item); err != nil {
|
||||
|
||||
@@ -33,9 +33,9 @@ func newChatToolFixture(t *testing.T) *chatToolFixture {
|
||||
f.hub.shown = store
|
||||
f.service = newChatToolService(store, store, f.hub, store)
|
||||
f.service.home = func() (string, error) { return f.home, nil }
|
||||
f.service.notify = func(_ context.Context, sessionID, title, message string) (bool, string) {
|
||||
f.notified = append(f.notified, sessionID+": "+title)
|
||||
return true, ""
|
||||
f.service.notify = func(_ context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
|
||||
f.notified = append(f.notified, sessionID+": "+notice.Title)
|
||||
return chatToolDelivery{App: true, Phone: true}
|
||||
}
|
||||
return f
|
||||
}
|
||||
@@ -229,7 +229,8 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
|
||||
now := time.Unix(1_800_000_000, 0)
|
||||
f.service.now = func() time.Time { return now }
|
||||
for i := range 5 {
|
||||
if r := f.call(a, "notify", `{"title":"Done","message":"Build finished","priority":"high"}`); r.IsError {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -254,7 +255,9 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
|
||||
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"}`)
|
||||
if !r.IsError || !strings.Contains(r.Text, "ntfy is not configured") {
|
||||
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" {
|
||||
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) {
|
||||
|
||||
Reference in New Issue
Block a user