Files
pipelines/internal/server/notification_web_test.go
alan 40ba2ac117 Open ntfy notifications in the app and notify chats that need the operator
Run notifications now always click through to pipelines://run/<id>; a valid
PIPELINES_WEB_PUBLIC_URL adds an "Open in browser" ntfy view action instead
of replacing the click. Queued rows derive links from the run id at delivery,
so legacy rows holding a web URL still open the app.

Unresolved chat questions/forms and permission requests publish one async,
bounded notification to the system destination (pipelines://chat/<id> plus the
browser action), deduplicated per form/request id across reconnects and
replays. stage.PublishNtfy gains optional, strictly validated view actions.
Server tests now clear the operator's real ntfy environment.
2026-10-30 20:40:06 +00:00

253 lines
9.5 KiB
Go

package server
import (
"context"
"encoding/json"
"mime"
"net/http"
"net/http/httptest"
"path/filepath"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func TestRunNotificationAppClickAndWebAction(t *testing.T) {
for _, tc := range []struct{ base, view string }{
{"https://pipelines.example.com", "https://pipelines.example.com/runs/20"},
{"http://10.0.0.75:8095/", "http://10.0.0.75:8095/runs/20"},
{"", ""}, // No web origin: the app link alone.
{"javascript:alert(1)", ""},
{"https://user:password@example.com", ""},
{"https://example.com?token=secret", ""},
{"https://example.com/#fragment", ""},
{"https://example.com/subpath", ""}, // Web app uses origin-root routes.
{"/runs", ""},
{"https://example.com\r\nClick:bad", ""},
} {
t.Run(tc.base, func(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", tc.base)
if got := runAttentionClick(20); got != "pipelines://run/20" {
t.Fatalf("click = %q", got)
}
views := runAttentionViews(20)
if tc.view == "" {
if len(views) != 0 {
t.Fatalf("unexpected views %+v", views)
}
return
}
if len(views) != 1 || views[0].Label != "Open in browser" || views[0].URL != tc.view {
t.Fatalf("views = %+v, want %q", views, tc.view)
}
})
}
}
type ntfyCapture struct {
Title, Message, Click, Actions string
}
// newNtfyCapture points the system destination at a mock ntfy endpoint.
func newNtfyCapture(t *testing.T) func() []ntfyCapture {
t.Helper()
var mu sync.Mutex
var got []ntfyCapture
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
decoder := new(mime.WordDecoder)
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
mu.Lock()
got = append(got, ntfyCapture{title, message, r.Header.Get("Click"), r.Header.Get("Actions")})
mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]string{"id": "msg", "event": "message"})
}))
t.Cleanup(srv.Close)
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
return func() []ntfyCapture {
mu.Lock()
defer mu.Unlock()
return append([]ntfyCapture(nil), got...)
}
}
// Rows queued by older servers hold a web URL, the old placeholder deep link or
// an empty click (an invalid web origin). Each delivers with the app link and
// the current web action.
func TestQueuedLegacyRunNotificationsUseAppLink(t *testing.T) {
for _, web := range []string{"https://pipelines.example.com", ""} {
t.Run("web="+web, func(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", web)
captured := newNtfyCapture(t)
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "legacy.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
clicks := map[int64]string{7: "https://pipelines.example.com/runs/7", 8: "pipelines://run/8", 9: ""}
for id, click := range clicks {
if err := s.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "failed", Channel: "system", Title: "Run failed", Body: "Run failed", Click: click}); err != nil {
t.Fatal(err)
}
}
r := &runner{ctx: ctx, store: s}
r.deliverRunNotifications(time.Now())
got := captured()
if len(got) != 3 {
t.Fatalf("deliveries = %+v", got)
}
seen := map[string]bool{}
for _, n := range got {
seen[n.Click] = true
want := ""
if web != "" {
want = "view, Open in browser, " + web + "/runs/" + n.Click[len("pipelines://run/"):]
}
if n.Actions != want {
t.Fatalf("actions = %q, want %q", n.Actions, want)
}
}
for _, click := range []string{"pipelines://run/7", "pipelines://run/8", "pipelines://run/9"} {
if !seen[click] {
t.Fatalf("missing %s in %+v", click, got)
}
}
for id := range clicks {
rows, err := s.RunNotifications(ctx, id)
if err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("run %d rows = %+v %v", id, rows, err)
}
}
})
}
}
func chatAttentionHub(t *testing.T, sessions ...string) *chatHub {
t.Helper()
h := newChatHub()
for _, id := range sessions {
h.rooms[id] = newChatRoom(context.Background(), id)
}
return h
}
func TestChatQuestionNotifiesOnceWithAppLink(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
captured := newNtfyCapture(t)
store := newOperatorStore(t)
if err := store.RecordOperatorSession(context.Background(), "ses_q", t.TempDir(), "Release prep", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_q")
h.registry = store
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_q", Kind: "question", Title: "Which branch\nshould ship?"}
frame := protocol.ChatEventFrame{SessionID: "ses_q", Kind: protocol.ChatEventForm, Form: &form}
h.emit(frame)
h.emit(frame) // duplicate live event
// A reconnect builds a new room whose readback re-emits the pending form.
h.mu.Lock()
h.rooms["ses_q"] = newChatRoom(context.Background(), "ses_q")
h.mu.Unlock()
h.emit(frame)
h.attentionWG.Wait()
got := captured()
if len(got) != 1 {
t.Fatalf("deliveries = %+v", got)
}
want := ntfyCapture{Title: "Release prep needs your answer", Message: "Which branch should ship?", Click: "pipelines://chat/ses_q", Actions: "view, Open in browser, https://pipelines.example.com/chat/ses_q"}
if got[0] != want {
t.Fatalf("got %+v, want %+v", got[0], want)
}
// Resolution and a later stale copy publish nothing more.
resolved := form
resolved.Resolved = true
h.emit(protocol.ChatEventFrame{SessionID: "ses_q", Kind: protocol.ChatEventForm, Form: &resolved})
h.attentionWG.Wait()
if n := len(captured()); n != 1 {
t.Fatalf("resolution republished: %d", n)
}
}
func TestChatResolvedOrReplayedFormsDoNotNotify(t *testing.T) {
captured := newNtfyCapture(t)
h := chatAttentionHub(t, "ses_r")
resolved := protocol.ChatForm{ID: "que_old", SessionID: "ses_r", Kind: "question", Title: "Old?", Resolved: true}
cancelled := protocol.ChatForm{ID: "que_gone", SessionID: "ses_r", Kind: "question", Title: "Gone?", Cancelled: true}
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventForm, Form: &resolved})
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventForm, Form: &cancelled})
// A stale unresolved copy of an already-resolved form is not announced.
stale := resolved
stale.Resolved = false
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventForm, Form: &stale})
// Ordinary reply frames never notify.
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventText, MessageID: "msg_1", Part: &protocol.ChatPart{ID: "p1"}, Delta: "done"})
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}})
h.attentionWG.Wait()
if got := captured(); len(got) != 0 {
t.Fatalf("unexpected deliveries %+v", got)
}
}
func TestChatPermissionNotifiesOnce(t *testing.T) {
captured := newNtfyCapture(t) // No web origin: no browser action.
h := chatAttentionHub(t, "ses_p")
frame := protocol.ChatPermissionFrame{SessionID: "ses_p", RequestID: "per_1", Action: "bash", Message: "Run rm -rf build?"}
h.pushPermission("ses_p", frame)
h.pushPermission("ses_p", frame)
// The last subscriber left; a reconnect replays the pending request.
h.mu.Lock()
h.rooms["ses_p"] = newChatRoom(context.Background(), "ses_p")
h.mu.Unlock()
h.pushPermission("ses_p", frame)
resolved := protocol.ChatPermissionFrame{SessionID: "ses_p", RequestID: "per_2", Message: "Already answered", Resolved: true}
h.pushPermission("ses_p", resolved)
h.attentionWG.Wait()
got := captured()
want := ntfyCapture{Title: "Chat needs your approval", Message: "Run rm -rf build?", Click: "pipelines://chat/ses_p"}
if len(got) != 1 || got[0] != want {
t.Fatalf("deliveries = %+v, want one %+v", got, want)
}
}
func TestChatAttentionNeedsNtfyConfiguration(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
calls := 0
original := chatAttentionPublish
chatAttentionPublish = func(context.Context, string, string, string, string, []byte, string, ...stage.NtfyView) (stage.Values, error) {
calls++
return nil, nil
}
defer func() { chatAttentionPublish = original }()
h := chatAttentionHub(t, "ses_n")
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_n", Kind: "question", Title: "Ready?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventForm, Form: &form})
h.pushPermission("ses_n", protocol.ChatPermissionFrame{SessionID: "ses_n", RequestID: "per_1", Message: "Allow?"})
h.attentionWG.Wait()
if calls != 0 {
t.Fatalf("published %d without ntfy configuration", calls)
}
}
// A failing ntfy endpoint never blocks or fails chat handling.
func TestChatAttentionFailureIsOnlyLogged(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusServiceUnavailable)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
h := chatAttentionHub(t, "ses_f")
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_f", Kind: "question", Title: "Ready?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_f", Kind: protocol.ChatEventForm, Form: &form})
h.attentionWG.Wait()
if forms := h.pendingForms("ses_f"); len(forms) != 1 || forms[0].ID != "que_1" {
t.Fatalf("chat state disturbed: %+v", forms)
}
}