From c8541f29b7cdae309ef8ae294bb22b9920e2f21b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 2 Dec 2026 15:44:39 +0000 Subject: [PATCH] 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 --- .../notify/NotificationPresenter.kt | 1 + docs/ntfy.md | 10 ++- internal/chattools/registry.go | 2 +- internal/chattools/tools.go | 6 +- internal/protocol/notifications.go | 3 + internal/server/app_notifications.go | 12 +-- internal/server/app_notifications_test.go | 78 ++++++++++++++++-- internal/server/chat_tools_files.go | 82 ++++++++++++++----- internal/server/chat_tools_run.go | 16 ++-- internal/server/chat_tools_service.go | 4 +- internal/server/chat_tools_test.go | 28 +++++-- 11 files changed, 195 insertions(+), 47 deletions(-) diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt index 55cef433..67b263eb 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt @@ -345,6 +345,7 @@ class NotificationPresenter(private val context: Context) { "chat_question" to "Chat question", "chat_approval" to "Chat approval", "chat_reply" to "Chat reply", + "chat_notify" to "Agent notification", ) fun importance(priority: Int): Int = when (priority) { diff --git a/docs/ntfy.md b/docs/ntfy.md index c3bf6883..ca8dc2d1 100644 --- a/docs/ntfy.md +++ b/docs/ntfy.md @@ -242,10 +242,14 @@ N = {"id":"run:7:3:waiting","kind":"run_waiting","title":"Run needs your decisio - `id` is stable: `run:::` (event `waiting`, `failed`, `succeeded`, or `success` for a mid-run stage hook) or - `chat:::`. `kind` is one of `run_waiting`, + `chat:::`. `kind` is one of `run_waiting`, `run_failed`, `run_succeeded`, `stage_failed`, `stage_succeeded`, - `chat_question`, `chat_approval`, `chat_reply`. `group` is `run:` or - `chat:`. `priority` is 3 and `tags` empty, matching what ntfy receives. + `chat_question`, `chat_approval`, `chat_reply`, `chat_notify`. `group` is `run:` or + `chat:`. `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 `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 diff --git a/internal/chattools/registry.go b/internal/chattools/registry.go index a97fd6ab..a5202fa1 100644 --- a/internal/chattools/registry.go +++ b/internal/chattools/registry.go @@ -1,6 +1,6 @@ // 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 -// 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. // // The server (internal/server) owns tokens, persistence and the tool effects. diff --git a/internal/chattools/tools.go b/internal/chattools/tools.go index e6c065ad..40e481c3 100644 --- a/internal/chattools/tools.go +++ b/internal/chattools/tools.go @@ -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. " + "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), " + - "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), " + "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, - Title: "Notify the operator's phone", - Description: "Send a push notification to the operator's phone that opens this chat when tapped. " + + Title: "Notify the operator", + 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). " + "Limited to 5 per minute per chat. Returns whether delivery was accepted.", InputSchema: objectSchema([]string{"title", "message"}, map[string]any{ diff --git a/internal/protocol/notifications.go b/internal/protocol/notifications.go index a8fa32c8..b6d86d75 100644 --- a/internal/protocol/notifications.go +++ b/internal/protocol/notifications.go @@ -50,6 +50,9 @@ const ( NotificationChatQuestion = "chat_question" // a chat asked a question NotificationChatApproval = "chat_approval" // a chat asks for permission/approval 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 diff --git a/internal/server/app_notifications.go b/internal/server/app_notifications.go index 453fdef7..90d0f7e7 100644 --- a/internal/server/app_notifications.go +++ b/internal/server/app_notifications.go @@ -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 diff --git a/internal/server/app_notifications_test.go b/internal/server/app_notifications_test.go index ad0cbde2..ff7a45d6 100644 --- a/internal/server/app_notifications_test.go +++ b/internal/server/app_notifications_test.go @@ -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 { diff --git a/internal/server/chat_tools_files.go b/internal/server/chat_tools_files.go index 331390d7..95a4e31f 100644 --- a/internal/server/chat_tools_files.go +++ b/internal/server/chat_tools_files.go @@ -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/). -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/). +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 } diff --git a/internal/server/chat_tools_run.go b/internal/server/chat_tools_run.go index af9ddde5..7efc9fcd 100644 --- a/internal/server/chat_tools_run.go +++ b/internal/server/chat_tools_run.go @@ -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. diff --git a/internal/server/chat_tools_service.go b/internal/server/chat_tools_service.go index 5389d34f..ee78eb42 100644 --- a/internal/server/chat_tools_service.go +++ b/internal/server/chat_tools_service.go @@ -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 { diff --git a/internal/server/chat_tools_test.go b/internal/server/chat_tools_test.go index 16386883..a6b7f3cb 100644 --- a/internal/server/chat_tools_test.go +++ b/internal/server/chat_tools_test.go @@ -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) {