Notifications: agent notify reaches every device and clears everywhere
- Server: chat ntfy messages carry a sequence id derived from their app id; clearing a chat app notification also clears it in ntfy (PUT /<topic>/<seq>/clear, verified on ntfy v2.38.1). - Server: a turn that sent an agent notify does not also send chat_reply. - notify tool and MCP instructions: Pipelines already notifies at reply end and for questions/approvals; notify is for mid-turn or background news. - Shown notify items carry channels (apps/phone); the transcript row says where it went. - App: NotificationBridge.close(tag); web closes tracked Notifications and tells other tabs over a BroadcastChannel; native bridge cancels by tag and now supports macOS. AgentNotices closes on notifications_cleared and on resubscribe cleared ids, and a tap sends clear_notifications. - Docs: skill, chat reference, ntfy/notifications docs, app note. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -162,6 +162,7 @@ func (a *appNotifier) clear(ctx context.Context, ids []string, exclude string) (
|
||||
}
|
||||
if len(changed) > 0 {
|
||||
a.enqueueLocked(protocol.Message{Type: protocol.NotificationsCleared, IDs: recordIDs(changed)}, exclude)
|
||||
clearChatNtfy(recordIDs(changed))
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
@@ -181,6 +182,7 @@ func (a *appNotifier) clearFor(ctx context.Context, filter pipeline.AppNotificat
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
a.enqueueLocked(protocol.Message{Type: protocol.NotificationsCleared, IDs: ids}, "")
|
||||
clearChatNtfy(ids)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -192,7 +192,7 @@ func (h *chatHub) startChatAttention(a chatAttention) {
|
||||
return
|
||||
}
|
||||
// ntfy takes a single-line message of at most 2048 bytes.
|
||||
if _, err := chatAttentionPublish(ctx, "system", title, truncateUTF8(singleLine(body), 2000), "", nil, click, views...); err != nil {
|
||||
if _, err := chatAttentionPublish(stage.WithNtfySequenceID(ctx, chatNtfySequence(a.id)), "system", title, truncateUTF8(singleLine(body), 2000), "", nil, click, views...); err != nil {
|
||||
log.Printf("chat attention notification session=%s: %v", a.sessionID, err)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -275,7 +275,7 @@ func (h *chatHub) foldEndedTurn(ctx context.Context, broker chatBroker, session
|
||||
if key == "" {
|
||||
key = replyID
|
||||
}
|
||||
if !h.claimChatAttentionLocked("reply\x00" + id + "\x00" + key) {
|
||||
if !h.claimChatAttentionLocked("reply\x00"+id+"\x00"+key) || h.takeTurnNotifiedLocked(id) {
|
||||
return
|
||||
}
|
||||
if body == "" {
|
||||
|
||||
@@ -51,6 +51,9 @@ type chatHub struct {
|
||||
attentionSeen map[string]struct{}
|
||||
attentionOrder []string
|
||||
attentionWG sync.WaitGroup
|
||||
// notifiedTurns holds the chats whose current turn already sent an agent
|
||||
// notify, so that turn's end is not announced again (one turn, one ping).
|
||||
notifiedTurns map[string]struct{}
|
||||
// queueStore persists prompts queued behind a running turn; nil keeps the
|
||||
// queue in memory only (tests and store-less servers).
|
||||
queueStore chatPromptQueueStore
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// One turn, one ping: a turn that already sent an agent notify does not also
|
||||
// announce its end, while a later turn without one does, and a notify sent
|
||||
// after a turn ended (background work) does not silence the next turn.
|
||||
func TestAgentNotifySuppressesThatTurnsReplyNotification(t *testing.T) {
|
||||
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
|
||||
captured := newNtfyCapture(t)
|
||||
store := newOperatorStore(t)
|
||||
ctx := context.Background()
|
||||
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := chatAttentionHub(t, "ses_n")
|
||||
h.settings = store
|
||||
h.notes = newAppNotifier(store)
|
||||
start := func(turn string) {
|
||||
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
|
||||
}
|
||||
end := func(turn string) {
|
||||
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
|
||||
h.attentionWG.Wait()
|
||||
}
|
||||
|
||||
start("turn_1")
|
||||
if got := h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n1", Title: "Halfway", Message: "Tests pass"}); !got.App || !got.Phone {
|
||||
t.Fatalf("delivery = %+v", got)
|
||||
}
|
||||
end("turn_1")
|
||||
if got := captured(); len(got) != 1 || got[0].Title != "Halfway" {
|
||||
t.Fatalf("turn with a notify published %+v", got)
|
||||
}
|
||||
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
|
||||
if err != nil || len(active) != 1 || active[0].Kind != protocol.NotificationChatNotify {
|
||||
t.Fatalf("app notifications = %+v, %v", active, err)
|
||||
}
|
||||
|
||||
// Background work notifies after the turn; the next turn still announces.
|
||||
h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n2", Title: "Deploy done", Message: "Live"})
|
||||
start("turn_2")
|
||||
end("turn_2")
|
||||
got := captured()
|
||||
if len(got) != 3 || got[2].Title != "Chat replied" {
|
||||
t.Fatalf("later deliveries = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Every chat ntfy message carries a sequence id derived from its app id, and
|
||||
// clearing the app notification (here: on another device) clears it in ntfy
|
||||
// and pushes the clear to every other connected client.
|
||||
func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
|
||||
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
|
||||
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
var mu sync.Mutex
|
||||
var published []string
|
||||
originalPublish, originalClear := chatAttentionPublish, chatAttentionClear
|
||||
chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
|
||||
mu.Lock()
|
||||
published = append(published, stage.NtfySequence(ctx))
|
||||
mu.Unlock()
|
||||
return stage.Values{"message_id": "m"}, nil
|
||||
}
|
||||
cleared := make(chan string, 8)
|
||||
chatAttentionClear = func(_ context.Context, destination, sequence string) error {
|
||||
if destination == "system" {
|
||||
cleared <- sequence
|
||||
}
|
||||
return nil
|
||||
}
|
||||
defer func() { chatAttentionPublish, chatAttentionClear = originalPublish, originalClear }()
|
||||
|
||||
f := newAppNotificationFixture(t, ctx)
|
||||
hub := f.handlerHub()
|
||||
web, desktop, phone := dialAckClient(t, ctx, f.url), dialAckClient(t, ctx, f.url), dialAckClient(t, ctx, f.url)
|
||||
subscribeNotifications(t, ctx, web, "")
|
||||
subscribeNotifications(t, ctx, desktop, "")
|
||||
subscribeNotifications(t, ctx, phone, "")
|
||||
if got := hub.publishToolNotification(ctx, "ses_c", chatToolNotice{ID: "shown_c", Title: "Look", Message: "Now"}); !got.App || !got.Phone {
|
||||
t.Fatalf("delivery = %+v", got)
|
||||
}
|
||||
id := "chat:ses_c:notify:shown_c"
|
||||
for _, conn := range []*websocket.Conn{web, desktop, phone} {
|
||||
if push := readFrame(t, ctx, conn, protocol.NotificationPush).Notification; push == nil || push.ID != id {
|
||||
t.Fatalf("push = %+v", push)
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
if len(published) != 1 || published[0] != chatNtfySequence(id) {
|
||||
t.Fatalf("published sequences = %v", published)
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// Tapped on the phone: the phone gets the reply, every other client a push.
|
||||
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ClearNotifications, ID: "tap", IDs: []string{id}})
|
||||
if reply := readFrame(t, ctx, phone, protocol.NotificationsCleared); reply.ID != "tap" || len(reply.IDs) != 1 || reply.IDs[0] != id {
|
||||
t.Fatalf("phone reply = %+v", reply)
|
||||
}
|
||||
for name, conn := range map[string]*websocket.Conn{"web": web, "desktop": desktop} {
|
||||
if push := readUntil(t, ctx, conn, protocol.NotificationsCleared); len(push.IDs) != 1 || push.IDs[0] != id {
|
||||
t.Fatalf("%s cleared push = %+v", name, push)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case sequence := <-cleared:
|
||||
if sequence != chatNtfySequence(id) {
|
||||
t.Fatalf("ntfy cleared %q", sequence)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("ntfy was not cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatNtfySequenceIsAValidStableNtfyID(t *testing.T) {
|
||||
a, b := chatNtfySequence("chat:ses_x:notify:abc"), chatNtfySequence("chat:ses_x:notify:abd")
|
||||
if a != chatNtfySequence("chat:ses_x:notify:abc") || a == b || len(a) != 27 {
|
||||
t.Fatalf("sequences %q %q", a, b)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// chatAttentionClear dismisses one ntfy message by sequence id; tests may
|
||||
// replace it.
|
||||
var chatAttentionClear = stage.ClearNtfy
|
||||
|
||||
// chatNtfySequence is the ntfy sequence id a chat notification (app id
|
||||
// "chat:<session>:<what>:<id>") is published with, so clearing the app
|
||||
// notification can also clear it in the ntfy app. It is derived from the app
|
||||
// id, so nothing extra is stored and a restart still clears it.
|
||||
func chatNtfySequence(id string) string {
|
||||
digest := sha256.Sum256([]byte(id))
|
||||
return "pl-" + hex.EncodeToString(digest[:12])
|
||||
}
|
||||
|
||||
// clearChatNtfy asks ntfy to clear the chat notifications among ids (every
|
||||
// app notification id that was cleared), off the caller's goroutine. ntfy
|
||||
// emits message_clear and its clients dismiss the notification. Run
|
||||
// notifications are published without a sequence id and are left alone.
|
||||
func clearChatNtfy(ids []string) {
|
||||
if !chatAttentionConfigured() {
|
||||
return
|
||||
}
|
||||
var sequences []string
|
||||
for _, id := range ids {
|
||||
if strings.HasPrefix(id, "chat:") {
|
||||
sequences = append(sequences, chatNtfySequence(id))
|
||||
}
|
||||
}
|
||||
if len(sequences) == 0 {
|
||||
return
|
||||
}
|
||||
clear := chatAttentionClear
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
for _, sequence := range sequences {
|
||||
if err := clear(ctx, "system", sequence); err != nil {
|
||||
log.Printf("clear ntfy notification %s: %v", sequence, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -23,6 +23,10 @@ const chatReplyFallbackBody = "The agent finished its reply."
|
||||
// (chat_reply_finished). Callers must hold h.mu.
|
||||
func (h *chatHub) noteReplyAttentionLocked(prior *protocol.ChatStep, frame protocol.ChatEventFrame) {
|
||||
step := frame.Step
|
||||
if frame.Kind == protocol.ChatEventStep && step != nil && step.Status == protocol.ChatStepStarted && !step.Intermediate {
|
||||
// A new turn has not notified yet.
|
||||
delete(h.notifiedTurns, frame.SessionID)
|
||||
}
|
||||
if frame.Kind != protocol.ChatEventStep || step == nil || step.Status != protocol.ChatStepEnded || step.Intermediate || frame.SessionID == "" {
|
||||
return
|
||||
}
|
||||
@@ -35,6 +39,9 @@ func (h *chatHub) noteReplyAttentionLocked(prior *protocol.ChatStep, frame proto
|
||||
if step.TurnID != "" && !h.claimChatAttentionLocked("reply\x00"+frame.SessionID+"\x00"+step.TurnID) {
|
||||
return
|
||||
}
|
||||
if h.takeTurnNotifiedLocked(frame.SessionID) {
|
||||
return
|
||||
}
|
||||
body := h.finalReplyTextLocked(frame.SessionID)
|
||||
if body == "" {
|
||||
body = chatReplyFallbackBody
|
||||
@@ -46,6 +53,32 @@ func (h *chatHub) noteReplyAttentionLocked(prior *protocol.ChatStep, frame proto
|
||||
h.startChatAttention(chatAttention{sessionID: frame.SessionID, reply: true, body: body, id: chatNotificationID(frame.SessionID, "reply", turnID)})
|
||||
}
|
||||
|
||||
// markTurnNotified records that sessionID's turn in progress sent an agent
|
||||
// notify, so its end is not announced as a reply too. A notify outside a turn
|
||||
// the hub is following (background work after the turn) marks nothing.
|
||||
func (h *chatHub) markTurnNotified(sessionID string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turns[sessionID]
|
||||
if turn == nil || turn.step == nil || (turn.step.Status == protocol.ChatStepEnded && !turn.step.Intermediate) {
|
||||
return
|
||||
}
|
||||
if h.notifiedTurns == nil {
|
||||
h.notifiedTurns = map[string]struct{}{}
|
||||
}
|
||||
h.notifiedTurns[sessionID] = struct{}{}
|
||||
}
|
||||
|
||||
// takeTurnNotifiedLocked reports and forgets whether sessionID's ending turn
|
||||
// already sent an agent notify. Callers must hold h.mu.
|
||||
func (h *chatHub) takeTurnNotifiedLocked(sessionID string) bool {
|
||||
if _, ok := h.notifiedTurns[sessionID]; !ok {
|
||||
return false
|
||||
}
|
||||
delete(h.notifiedTurns, sessionID)
|
||||
return true
|
||||
}
|
||||
|
||||
// finalReplyTextLocked returns a bounded excerpt, paragraph breaks kept, of the latest
|
||||
// assistant message's text in the current turn: messages after the last user
|
||||
// message, scanned newest first. Callers must hold h.mu.
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// shownFile is a resolved file inside the operator's home.
|
||||
@@ -172,10 +173,11 @@ func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string,
|
||||
digest := sha256.Sum256([]byte(title + "\x00" + message))
|
||||
id = hex.EncodeToString(digest[:8])
|
||||
}
|
||||
appID := chatNotificationID(sessionID, "notify", id)
|
||||
var delivery chatToolDelivery
|
||||
if h.notes != nil {
|
||||
delivery.App = h.notes.record(ctx, pipeline.AppNotificationRecord{
|
||||
AppNotification: protocol.AppNotification{ID: "chat:" + sessionID + ":notify:" + id, Kind: protocol.NotificationChatNotify, Title: title, Message: message, Click: click, Priority: chatNotifyPriority(notice.Priority), Tags: []string{}, Group: "chat:" + sessionID},
|
||||
AppNotification: protocol.AppNotification{ID: appID, Kind: protocol.NotificationChatNotify, Title: title, Message: message, Click: click, Priority: chatNotifyPriority(notice.Priority), Tags: []string{}, Group: "chat:" + sessionID},
|
||||
SessionID: sessionID,
|
||||
})
|
||||
}
|
||||
@@ -185,12 +187,16 @@ func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string,
|
||||
case !chatNotificationSettings(ctx, h.settings).NtfyEnabled:
|
||||
delivery.Detail = "phone notifications (ntfy) are turned off"
|
||||
default:
|
||||
if _, err := chatAttentionPublish(ctx, "system", title, message, "", nil, click, views...); err != nil {
|
||||
if _, err := chatAttentionPublish(stage.WithNtfySequenceID(ctx, chatNtfySequence(appID)), "system", title, message, "", nil, click, views...); err != nil {
|
||||
log.Printf("chat tool notification session=%s: %v", sessionID, err)
|
||||
delivery.Detail = "the phone notification service refused it: " + err.Error()
|
||||
} else {
|
||||
delivery.Phone = true
|
||||
}
|
||||
}
|
||||
if delivery.App || delivery.Phone {
|
||||
// This turn has pinged the operator; its end is not announced again.
|
||||
h.markTurnNotified(sessionID)
|
||||
}
|
||||
return delivery
|
||||
}
|
||||
|
||||
@@ -100,6 +100,12 @@ func (s *chatToolService) runNotify(ctx context.Context, sessionID, title, messa
|
||||
id := newChatShownID()
|
||||
delivery := s.notify(ctx, sessionID, chatToolNotice{ID: id, Title: title, Message: message, Priority: priority})
|
||||
item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App || delivery.Phone, Detail: delivery.Detail}
|
||||
if delivery.App {
|
||||
item.Channels = append(item.Channels, "apps")
|
||||
}
|
||||
if delivery.Phone {
|
||||
item.Channels = append(item.Channels, "phone")
|
||||
}
|
||||
switch {
|
||||
case delivery.App && delivery.Phone:
|
||||
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps and phone notifications."}
|
||||
|
||||
@@ -251,7 +251,7 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
|
||||
t.Fatalf("notified = %v", f.notified)
|
||||
}
|
||||
got := f.items(t, "ses_n1")
|
||||
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" {
|
||||
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" || strings.Join(got[0].Channels, ",") != "apps,phone" {
|
||||
t.Fatalf("items = %+v", got)
|
||||
}
|
||||
|
||||
@@ -277,7 +277,7 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
|
||||
if r.IsError || r.Text != "Delivered to the operator's Pipelines apps; phone notifications (ntfy) are turned off." {
|
||||
t.Fatalf("apps-only result: %v", r)
|
||||
}
|
||||
if last := f.items(t, "ses_n2"); len(last) != 3 || !last[2].Delivered || !strings.HasPrefix(last[2].ID, "shown_") {
|
||||
if last := f.items(t, "ses_n2"); len(last) != 3 || !last[2].Delivered || !strings.HasPrefix(last[2].ID, "shown_") || strings.Join(last[2].Channels, ",") != "apps" {
|
||||
t.Fatalf("the apps-only entry is recorded: %+v", last)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -58,6 +59,11 @@ func newNtfyCapture(t *testing.T) func() []ntfyCapture {
|
||||
var mu sync.Mutex
|
||||
var got []ntfyCapture
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.Path, "/clear") {
|
||||
// A cleared chat notification's ntfy clear, not a delivery.
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id": "clr", "event": "message_clear"})
|
||||
return
|
||||
}
|
||||
decoder := new(mime.WordDecoder)
|
||||
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
|
||||
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
|
||||
|
||||
Reference in New Issue
Block a user