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:
2026-12-02 19:43:55 +00:00
parent c441400f36
commit b91ef04ab0
32 changed files with 743 additions and 73 deletions
+4 -1
View File
@@ -78,7 +78,10 @@ only when asked). Stage use: `references/format.md`.
A chat's agent has a `pipelines` MCP server: `show_file`, `show_image`,
`show_html`, `show_diff` (show the operator changes, e.g. before a pull request)
and `notify` (phone, only when the operator must look now). Show instead of
and `notify` (every Pipelines app the operator is signed in to plus their phone;
cleared everywhere once they read it or open the chat). Pipelines already
notifies when a reply ends or the agent asks something, so `notify` is only for
news mid-turn or after work the turn does not wait for. Show instead of
telling the operator a path. Details, limits, chat RPCs: `references/chat.md`.
## References
+1 -1
View File
@@ -15,7 +15,7 @@ operator's home (absolute, `~/...`, or relative to the chat's directory).
| `show_image` | `url_or_path`, `title?`, `alt?` | A home `image/*` file or an `https://` URL (no credentials, at most 2048 chars). |
| `show_html` | `html`, `title?`, `height_hint?` (120-600) | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `<details>`, `:hover`. Refused above 512 KiB. |
| `show_diff` | `path?`, `base?`, `committed_only?`, `title?` | A Git diff card when the operator asks to see the changes, or before submitting a pull request. No `base`: uncommitted work (staged, unstaged, untracked) against HEAD. `base` (e.g. `main`): everything since the merge base, which is what a PR contains, plus uncommitted work unless `committed_only`. Pipelines runs Git; do not paste the diff. |
| `notify` | `title`, `message`, `priority?` | A phone push that opens this chat. Only when the operator must look now (long task done, blocked on them). 5 per minute per chat; undelivered sends report why. |
| `notify` | `title`, `message`, `priority?` | A notification on every Pipelines app the operator is signed in to (web tabs, desktop, Android) and their phone (ntfy); a tap opens this chat. Opening the chat, or tapping or dismissing it on any device, clears it on all of them. Pipelines already notifies when the reply ends and for questions and approvals, so use it only for news mid-turn or after background work the turn does not wait for; a turn that notified sends no separate "replied" notification. 5 per minute per chat; the result says where it went, and undelivered sends report why. |
`show_diff` lists at most 300 files; a file patch over 256 KiB or a total over
1 MiB is shown partially and says so; binaries have no patch; renames show as
+8 -3
View File
@@ -26,7 +26,10 @@ 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 Pipelines now (it reaches their open Pipelines apps and their phone). " +
"and notify only for something the operator should know mid-turn or after work the turn does not wait for: " +
"Pipelines already notifies them when your reply ends and when you ask a question or need an approval, so do not notify for those " +
"(a notify replaces this turn's end-of-reply notification). It reaches every Pipelines app they are signed in to and their phone, " +
"and clears everywhere once they open the chat. " +
"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."
@@ -109,8 +112,10 @@ func definitions() []toolDefinition {
{
Name: ToolNotify,
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). " +
Description: "Send a notification to every Pipelines app the operator is signed in to (web, desktop, Android) and their phone; it opens this chat when tapped " +
"and is cleared on every device once they read it or open the chat. " +
"Pipelines already notifies when your reply ends and when you ask a question or request an approval, so do not notify for those. " +
"Use it only for something they should know mid-turn, or for background work that finishes after the turn (one notify in a turn replaces that turn's end-of-reply notification). " +
"Limited to 5 per minute per chat. Returns whether delivery was accepted.",
InputSchema: objectSchema([]string{"title", "message"}, map[string]any{
"title": stringProperty("Short notification title (one line)."),
+4 -1
View File
@@ -55,8 +55,11 @@ type ChatShownItem struct {
Message string `json:"message,omitempty"`
Priority string `json:"priority,omitempty"`
Delivered bool `json:"delivered,omitempty"`
// Detail says why a notification was not delivered.
// Detail says why a notification was not delivered (or not to the phone).
Detail string `json:"detail,omitempty"`
// Channels says where a delivered notification went: "apps" (the
// operator's signed-in Pipelines apps) and/or "phone" (ntfy).
Channels []string `json:"channels,omitempty"`
}
// ChatShownDiffBody is one Git comparison a chat's model showed: the work tree
+2
View File
@@ -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)
}
}
+1 -1
View File
@@ -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)
}
}()
+1 -1
View File
@@ -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 == "" {
+3
View File
@@ -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
+132
View File
@@ -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)
}
}
+54
View File
@@ -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)
}
}
}()
}
+33
View File
@@ -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.
+8 -2
View File
@@ -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
}
+6
View File
@@ -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."}
+2 -2
View File
@@ -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)
}
}
+6
View File
@@ -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"))
+97 -30
View File
@@ -105,6 +105,60 @@ func NtfyPriority(ctx context.Context) int {
return priority
}
type ntfySequenceKey struct{}
// ntfySequenceID is the form of a sequence id this package sends: ntfy
// accepts the same characters as a topic name.
var ntfySequenceID = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
// WithNtfySequenceID makes PublishNtfy calls under ctx publish with ntfy
// sequence id sequence (X-Sequence-ID), so ClearNtfy can later dismiss the
// message on every subscribed client. An invalid id is ignored.
func WithNtfySequenceID(ctx context.Context, sequence string) context.Context {
return context.WithValue(ctx, ntfySequenceKey{}, sequence)
}
// NtfySequence is the sequence id WithNtfySequenceID set on ctx, "" when none.
func NtfySequence(ctx context.Context) string {
sequence, _ := ctx.Value(ntfySequenceKey{}).(string)
return sequence
}
// ClearNtfy marks the messages published with sequence id sequence on
// destination as read: ntfy (v2.15+) emits a message_clear event and its
// Android and web clients dismiss the notification. Clearing an unknown
// sequence id is harmless (ntfy still answers 200).
func ClearNtfy(ctx context.Context, destination, sequence string) error {
if !destinationName.MatchString(destination) || !ntfySequenceID.MatchString(sequence) {
return fmt.Errorf("invalid ntfy clear request")
}
endpoint, token, err := ntfyConnection(destination)
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPut, strings.TrimSuffix(endpoint, "/")+"/"+sequence+"/clear", nil)
if err != nil {
return fmt.Errorf("cannot create ntfy request")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(request)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("ntfy clear unconfirmed")
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64<<10))
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("ntfy clear returned HTTP %d", response.StatusCode)
}
return nil
}
// PublishNtfy is shared by native delivery stages and stage notification hooks.
// An empty filename publishes an event without an attachment. A non-empty click
// is an optional ntfy Click action (an absolute URL) so a tap on the notification
@@ -125,36 +179,9 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
if len(data) > 1<<20 || (filename != "" && (filename != filepath.Base(filename) || filename == "." || strings.ContainsAny(filename, "/\\\r\n\x00") || len(filename) > 200)) {
return nil, fmt.Errorf("invalid ntfy attachment")
}
prefix := "PIPELINES_NTFY_" + strings.ToUpper(destination)
if destination == "system" {
prefix = "PIPELINES_NTFY"
}
endpoint := os.Getenv(prefix + "_URL")
token := os.Getenv(prefix + "_TOKEN")
if path := os.Getenv(prefix + "_TOKEN_FILE"); path != "" {
if token != "" {
return nil, fmt.Errorf("configure only one ntfy token source")
}
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("cannot read ntfy token file")
}
contents, err := io.ReadAll(io.LimitReader(file, 4097))
file.Close()
if err != nil || len(contents) > 4096 {
return nil, fmt.Errorf("invalid ntfy token file")
}
token = strings.TrimSpace(string(contents))
if token == "" {
return nil, fmt.Errorf("ntfy token file is empty")
}
}
u, err := url.Parse(endpoint)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || !ntfyTopic.MatchString(strings.TrimPrefix(u.Path, "/")) || u.RawPath != "" {
return nil, fmt.Errorf("configure %s_URL with an HTTP(S) ntfy topic URL (no credentials or query)", prefix)
}
if token != "" && (len(token) > 4096 || !ntfyTokenValue.MatchString(token)) {
return nil, fmt.Errorf("invalid ntfy token configuration")
endpoint, token, err := ntfyConnection(destination)
if err != nil {
return nil, err
}
method := http.MethodPut
if filename == "" {
@@ -179,6 +206,9 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
if priority, ok := ctx.Value(ntfyPriorityKey{}).(int); ok && priority >= 1 && priority <= 5 {
request.Header.Set("Priority", strconv.Itoa(priority))
}
if sequence, ok := ctx.Value(ntfySequenceKey{}).(string); ok && ntfySequenceID.MatchString(sequence) {
request.Header.Set("X-Sequence-ID", sequence)
}
if actions != "" {
request.Header.Set("Actions", actions)
}
@@ -227,6 +257,43 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
return Values{"destination": destination, "message_id": ack.ID, "attachment_url": ack.Attachment.URL, "filename": filename}, nil
}
// ntfyConnection resolves destination's topic URL and token from the
// environment ("system" reads PIPELINES_NTFY_URL and its token).
func ntfyConnection(destination string) (string, string, error) {
prefix := "PIPELINES_NTFY_" + strings.ToUpper(destination)
if destination == "system" {
prefix = "PIPELINES_NTFY"
}
endpoint := os.Getenv(prefix + "_URL")
token := os.Getenv(prefix + "_TOKEN")
if path := os.Getenv(prefix + "_TOKEN_FILE"); path != "" {
if token != "" {
return "", "", fmt.Errorf("configure only one ntfy token source")
}
file, err := os.Open(path)
if err != nil {
return "", "", fmt.Errorf("cannot read ntfy token file")
}
contents, err := io.ReadAll(io.LimitReader(file, 4097))
file.Close()
if err != nil || len(contents) > 4096 {
return "", "", fmt.Errorf("invalid ntfy token file")
}
token = strings.TrimSpace(string(contents))
if token == "" {
return "", "", fmt.Errorf("ntfy token file is empty")
}
}
u, err := url.Parse(endpoint)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || !ntfyTopic.MatchString(strings.TrimPrefix(u.Path, "/")) || u.RawPath != "" {
return "", "", fmt.Errorf("configure %s_URL with an HTTP(S) ntfy topic URL (no credentials or query)", prefix)
}
if token != "" && (len(token) > 4096 || !ntfyTokenValue.MatchString(token)) {
return "", "", fmt.Errorf("invalid ntfy token configuration")
}
return endpoint, token, nil
}
// ValidNtfyClick accepts an empty click or an absolute URL the ntfy server will
// hand to the operating system on tap: a scheme, no credentials, no fragment,
// no control characters and a bounded length. The value is an operator-visible
+38
View File
@@ -234,3 +234,41 @@ func TestNtfyClickAndViewActions(t *testing.T) {
t.Fatalf("invalid actions still published: %d", len(click))
}
}
func TestNtfySequenceIDPublishAndClear(t *testing.T) {
var requests []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests = append(requests, r.Method+" "+r.URL.Path+" seq="+r.Header.Get("X-Sequence-ID")+" auth="+r.Header.Get("Authorization"))
if r.Method == http.MethodPost {
_, _ = w.Write([]byte(`{"id":"m1","event":"message","sequence_id":"pl-abc"}`))
return
}
_, _ = w.Write([]byte(`{"id":"m2","event":"message_clear","sequence_id":"pl-abc"}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "tok")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
ctx := WithNtfySequenceID(context.Background(), "pl-abc")
if _, err := PublishNtfy(ctx, "system", "Title", "Body", "", nil, ""); err != nil {
t.Fatal(err)
}
if err := ClearNtfy(context.Background(), "system", "pl-abc"); err != nil {
t.Fatal(err)
}
if err := ClearNtfy(context.Background(), "system", "bad/id"); err == nil {
t.Fatal("invalid sequence id accepted")
}
// An invalid sequence id on publish is dropped rather than sent.
if _, err := PublishNtfy(WithNtfySequenceID(context.Background(), "a:b"), "system", "Title", "Body", "", nil, ""); err != nil {
t.Fatal(err)
}
want := []string{
"POST /pipelines seq=pl-abc auth=Bearer tok",
"PUT /pipelines/pl-abc/clear seq= auth=Bearer tok",
"POST /pipelines seq= auth=Bearer tok",
}
if strings.Join(requests, "\n") != strings.Join(want, "\n") {
t.Fatalf("requests:\n%s", strings.Join(requests, "\n"))
}
}