Add server notification settings with app checkboxes

Persist three global ntfy switches in server_settings: run_finished
(default on: auto-mode runs notify on success, read inside the
transition transaction; on/off modes unchanged), chat_needs_you
(default on: gates chat question/approval alerts) and
chat_reply_finished (default off: one alert per finished assistant
turn). Expose notification_settings / set_notification_settings over
the websocket protocol, add a Phone notifications section with
Material and Cupertino checkboxes in Settings, document the settings,
and keep the cli, tui, stage and pipeline test packages from
inheriting a real ntfy configuration.
This commit is contained in:
2026-10-30 21:36:27 +00:00
parent 39d9150c3a
commit 498c6f17a6
26 changed files with 1381 additions and 28 deletions
+16
View File
@@ -0,0 +1,16 @@
package cli
import (
"os"
"testing"
)
// TestMain isolates the package from an operator's real notification setup:
// these tests run real servers and runs, a developer shell may export the
// installed server's ntfy configuration, and no test may publish to it.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
}
+16
View File
@@ -0,0 +1,16 @@
package pipeline
import (
"os"
"testing"
)
// TestMain isolates the package from an operator's real notification setup.
// The store only enqueues notifications, but a developer shell may export the
// installed server's ntfy configuration and no test may ever publish to it.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
}
@@ -0,0 +1,70 @@
package pipeline
import (
"context"
"database/sql"
"fmt"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// notificationSettingPrefix namespaces the global notification choices inside
// server_settings; each key stores "true" or "false". A missing row means the
// default from protocol.DefaultNotificationSettings.
const notificationSettingPrefix = "notify."
type settingsQuerier interface {
QueryContext(context.Context, string, ...any) (*sql.Rows, error)
}
// readNotificationSettings reads the stored choices through q, which may be the
// database or an open transaction (run-transition enqueue reads inside its tx).
func readNotificationSettings(ctx context.Context, q settingsQuerier) (protocol.NotificationSettings, error) {
settings := protocol.DefaultNotificationSettings()
rows, err := q.QueryContext(ctx, `SELECT key,value FROM server_settings WHERE key LIKE 'notify.%'`)
if err != nil {
return settings, err
}
defer rows.Close()
for rows.Next() {
var key, value string
if err := rows.Scan(&key, &value); err != nil {
return settings, err
}
if field := settings.Field(key[len(notificationSettingPrefix):]); field != nil {
*field = value == "true"
}
}
return settings, rows.Err()
}
// NotificationSettings returns the operator's global notification choices.
func (s *Store) NotificationSettings(ctx context.Context) (protocol.NotificationSettings, error) {
return readNotificationSettings(ctx, s.db)
}
// UpdateNotificationSettings applies a validated partial update atomically and
// returns the stored result. Unknown keys and non-boolean values are refused
// before anything is written.
func (s *Store) UpdateNotificationSettings(ctx context.Context, update map[string]any) (protocol.NotificationSettings, error) {
values, err := protocol.ValidateNotificationSettingsUpdate(update)
if err != nil {
return protocol.NotificationSettings{}, err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return protocol.NotificationSettings{}, err
}
defer tx.Rollback()
for key, value := range values {
if _, err := tx.ExecContext(ctx, `INSERT INTO server_settings(key,value) VALUES(?,?)
ON CONFLICT(key) DO UPDATE SET value=excluded.value`, notificationSettingPrefix+key, fmt.Sprint(value)); err != nil {
return protocol.NotificationSettings{}, err
}
}
settings, err := readNotificationSettings(ctx, tx)
if err != nil {
return protocol.NotificationSettings{}, err
}
return settings, tx.Commit()
}
@@ -0,0 +1,133 @@
package pipeline
import (
"context"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestNotificationSettingsDefaultPersistAndPartialUpdate(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "notify-settings.db")
s, err := Open(path)
if err != nil {
t.Fatal(err)
}
got, err := s.NotificationSettings(ctx)
if err != nil || got != protocol.DefaultNotificationSettings() {
t.Fatalf("defaults = %+v, %v", got, err)
}
if !got.RunFinished || !got.ChatNeedsYou || got.ChatReplyFinished {
t.Fatalf("default values changed: %+v", got)
}
got, err = s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true})
want := protocol.NotificationSettings{RunFinished: true, ChatNeedsYou: true, ChatReplyFinished: true}
if err != nil || got != want {
t.Fatalf("partial update = %+v, %v", got, err)
}
got, err = s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: false, protocol.NotifyChatNeedsYou: false})
want = protocol.NotificationSettings{RunFinished: false, ChatNeedsYou: false, ChatReplyFinished: true}
if err != nil || got != want {
t.Fatalf("second update = %+v, %v", got, err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
s, err = Open(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
if got, err := s.NotificationSettings(ctx); err != nil || got != want {
t.Fatalf("after reopen = %+v, %v", got, err)
}
// The OpenCode endpoint row shares the table and is unaffected.
if endpoint, err := s.OpenCodeEndpoint(ctx); err != nil || endpoint != "" {
t.Fatalf("endpoint = %q, %v", endpoint, err)
}
}
func TestNotificationSettingsRejectUnknownOrInvalid(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "reject.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
for name, update := range map[string]map[string]any{
"unknown": {protocol.NotifyRunFinished: false, "run_started": true},
"non-bool": {protocol.NotifyChatNeedsYou: "false"},
"empty": {},
"nil value": {protocol.NotifyChatReplyFinished: nil},
} {
if _, err := s.UpdateNotificationSettings(ctx, update); err == nil {
t.Fatalf("%s update accepted", name)
}
}
// A rejected update writes nothing, not even its valid keys.
if got, err := s.NotificationSettings(ctx); err != nil || got != protocol.DefaultNotificationSettings() {
t.Fatalf("rejected update changed settings: %+v, %v", got, err)
}
if _, err := s.UpdateNotificationSettings(ctx, map[string]any{"bogus": true}); err == nil || !strings.Contains(err.Error(), `"bogus"`) {
t.Fatalf("unknown key error = %v", err)
}
}
// A run reaching succeeded enqueues its generic alert according to its notify
// mode and, for auto, the run_finished setting read in the same transaction.
func TestSucceededRunEnqueueFollowsRunFinishedSetting(t *testing.T) {
for _, tc := range []struct {
mode string
runFinished bool
want int
}{
{"auto", true, 1}, {"auto", false, 0}, {"on", true, 1}, {"on", false, 1}, {"off", true, 0}, {"off", false, 0},
} {
t.Run(tc.mode+map[bool]string{true: "-enabled", false: "-disabled"}[tc.runFinished], func(t *testing.T) {
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "succeeded.db"), tc.mode)
defer s.Close()
if _, err := s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: tc.runFinished}); err != nil {
t.Fatal(err)
}
if err := notificationTransition(ctx, s, id, "succeeded"); err != nil {
t.Fatal(err)
}
got, err := s.RunNotifications(ctx, id)
if err != nil || len(got) != tc.want {
t.Fatalf("notifications = %+v, %v; want %d", got, err, tc.want)
}
if tc.want == 1 {
n, err := s.ClaimRunNotification(ctx, time.Now().Unix())
if err != nil || n == nil || n.Event != "succeeded" || n.Title != "Run succeeded" || n.Click != "pipelines://run/"+strconv.FormatInt(id, 10) {
t.Fatalf("claimed = %+v, %v", n, err)
}
}
})
}
}
// Waiting and failed alerts do not depend on run_finished.
func TestRunFinishedSettingLeavesAttentionAlone(t *testing.T) {
for _, status := range []string{"waiting", "failed"} {
t.Run(status, func(t *testing.T) {
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "attention.db"), "auto")
defer s.Close()
if _, err := s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: false}); err != nil {
t.Fatal(err)
}
if err := notificationTransition(ctx, s, id, status); err != nil {
t.Fatal(err)
}
if got, err := s.RunNotifications(ctx, id); err != nil || len(got) != 1 || got[0].Event != status {
t.Fatalf("notifications = %+v, %v", got, err)
}
})
}
}
@@ -144,8 +144,9 @@ func TestRunNotificationTransitionModesAndCoverage(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// run_finished defaults on, so an auto run announces success too.
want := 1
if mode == "off" || status == "succeeded" && mode != "on" {
if mode == "off" {
want = 0
}
if len(ns) != want {
@@ -154,21 +155,23 @@ func TestRunNotificationTransitionModesAndCoverage(t *testing.T) {
})
}
}
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "covered.db"), "on")
defer s.Close()
if err := s.CoverRunNotification(ctx, id, 1, "succeeded"); err != nil {
t.Fatal(err)
}
if err := notificationTransition(ctx, s, id, "succeeded"); err != nil {
t.Fatal(err)
}
ns, err := s.RunNotifications(ctx, id)
if err != nil || len(ns) != 1 || ns[0].Status != "covered" {
t.Fatalf("stage coverage lost: %+v %v", ns, err)
}
if n, err := s.ClaimRunNotification(ctx, 100); err != nil || n != nil {
t.Fatalf("covered stage duplicated: %+v %v", n, err)
for _, mode := range []string{"on", "auto"} {
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), mode+"-covered.db"), mode)
defer s.Close()
if err := s.CoverRunNotification(ctx, id, 1, "succeeded"); err != nil {
t.Fatal(err)
}
if err := notificationTransition(ctx, s, id, "succeeded"); err != nil {
t.Fatal(err)
}
ns, err := s.RunNotifications(ctx, id)
if err != nil || len(ns) != 1 || ns[0].Status != "covered" {
t.Fatalf("stage coverage lost: %+v %v", ns, err)
}
if n, err := s.ClaimRunNotification(ctx, 100); err != nil || n != nil {
t.Fatalf("covered stage duplicated: %+v %v", n, err)
}
}
}
+9 -1
View File
@@ -46,8 +46,16 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version
title = "Run failed"
body = "run failed"
case "succeeded":
// "on" always announces success; any other (auto/legacy) mode follows
// the operator's run_finished choice, read in this transaction.
if mode != "on" {
return nil
settings, err := readNotificationSettings(ctx, tx)
if err != nil {
return err
}
if !settings.RunFinished {
return nil
}
}
title = "Run succeeded"
body = "run succeeded"
+3
View File
@@ -238,4 +238,7 @@ type Message struct {
// displays. Both are optional so older peers ignore them.
RunEvent *RunEventFrame `json:"run_event,omitempty"`
RunIDs []int64 `json:"run_ids,omitempty"`
// NotificationSettings is the set_notification_settings partial update and
// the notification_settings reply (every key). See notification_settings.go.
NotificationSettings map[string]any `json:"notification_settings,omitempty"`
}
@@ -0,0 +1,93 @@
package protocol
import (
"fmt"
"sort"
)
// Notification settings are the operator's global choices about which events
// publish through the server's ntfy connection. A client reads them with
// {"type":"notification_settings"} and changes them with
// {"type":"set_notification_settings","notification_settings":{"<key>":bool}};
// a set may name any subset of keys, and unknown keys or non-boolean values
// are refused. Both replies have type "notification_settings" and carry every
// key with its stored value.
const (
GetNotificationSettings = "notification_settings"
SetNotificationSettings = "set_notification_settings"
NotificationSettingsReply = "notification_settings"
)
// Notification setting keys, as carried on the wire.
const (
NotifyRunFinished = "run_finished"
NotifyChatNeedsYou = "chat_needs_you"
NotifyChatReplyFinished = "chat_reply_finished"
)
// NotificationSettings is the typed form of the global notification choices.
type NotificationSettings struct {
// RunFinished notifies when a run with notify mode "auto" succeeds. Runs
// started with notifications "on" always notify and "off" never do.
RunFinished bool
// ChatNeedsYou notifies when a chat asks a question or requests approval.
ChatNeedsYou bool
// ChatReplyFinished notifies when an assistant turn in a chat ends.
ChatReplyFinished bool
}
// NotificationSettingKeys lists every setting key in a stable order.
var NotificationSettingKeys = []string{NotifyRunFinished, NotifyChatNeedsYou, NotifyChatReplyFinished}
// DefaultNotificationSettings are the values before the operator changes any.
func DefaultNotificationSettings() NotificationSettings {
return NotificationSettings{RunFinished: true, ChatNeedsYou: true, ChatReplyFinished: false}
}
// Map returns the wire form with every key present.
func (s NotificationSettings) Map() map[string]any {
return map[string]any{
NotifyRunFinished: s.RunFinished,
NotifyChatNeedsYou: s.ChatNeedsYou,
NotifyChatReplyFinished: s.ChatReplyFinished,
}
}
// Field returns a pointer to the setting named key, or nil for an unknown key.
func (s *NotificationSettings) Field(key string) *bool {
switch key {
case NotifyRunFinished:
return &s.RunFinished
case NotifyChatNeedsYou:
return &s.ChatNeedsYou
case NotifyChatReplyFinished:
return &s.ChatReplyFinished
}
return nil
}
// ValidateNotificationSettingsUpdate checks a partial update: at least one key,
// every key known and every value a boolean.
func ValidateNotificationSettingsUpdate(update map[string]any) (map[string]bool, error) {
if len(update) == 0 {
return nil, fmt.Errorf("notification_settings must name at least one setting")
}
keys := make([]string, 0, len(update))
for key := range update {
keys = append(keys, key)
}
sort.Strings(keys)
result := make(map[string]bool, len(update))
var probe NotificationSettings
for _, key := range keys {
if probe.Field(key) == nil {
return nil, fmt.Errorf("unknown notification setting %q", key)
}
value, ok := update[key].(bool)
if !ok {
return nil, fmt.Errorf("notification setting %q must be true or false", key)
}
result[key] = value
}
return result, nil
}
+13 -1
View File
@@ -23,7 +23,10 @@ var chatAttentionPublish = stage.PublishNtfy
type chatAttention struct {
sessionID string
approval bool
body string
// reply marks a finished assistant turn (gated by chat_reply_finished)
// rather than a question/approval (gated by chat_needs_you).
reply bool
body string
}
// claimChatAttentionLocked records key in the hub-wide dedupe set and reports
@@ -113,11 +116,17 @@ func (h *chatHub) startChatAttention(a chatAttention) {
base = context.Background()
}
registry := h.registry
settingsStore := h.settings
h.attentionWG.Add(1)
go func() {
defer h.attentionWG.Done()
ctx, cancel := context.WithTimeout(base, 30*time.Second)
defer cancel()
// The operator's choice is read here, off the hub mutex, at publish time.
settings := chatNotificationSettings(ctx, settingsStore)
if (a.reply && !settings.ChatReplyFinished) || (!a.reply && !settings.ChatNeedsYou) {
return
}
name := ""
if registry != nil {
if session, found, err := registry.OperatorSession(ctx, a.sessionID); err == nil && found {
@@ -125,6 +134,9 @@ func (h *chatHub) startChatAttention(a chatAttention) {
}
}
title, body := chatAttentionText(name, a.approval, a.body)
if a.reply {
title, body = chatReplyText(name, a.body)
}
click, views := chatAttentionLinks(a.sessionID)
if _, err := chatAttentionPublish(ctx, "system", title, body, "", nil, click, views...); err != nil {
log.Printf("chat attention notification session=%s: %v", a.sessionID, err)
+2
View File
@@ -37,6 +37,8 @@ type chatHub struct {
rooms map[string]*chatRoom
baseCtx context.Context
registry operatorRegistry
// settings holds the operator's notification choices; nil means defaults.
settings notificationSettingsStore
now func() time.Time
// userSeq is a monotonic source of ids for the user turns the server echoes
// to the other clients, so each retained user message has a stable id.
+98
View File
@@ -0,0 +1,98 @@
package server
import (
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatReplyBodyRunes bounds the reply excerpt carried in the notification body.
const chatReplyBodyRunes = 200
// chatReplyFallbackBody is used when the finished turn produced no text the
// hub retained (tool-only turns, or text beyond the retention cap).
const chatReplyFallbackBody = "The agent finished its reply."
// noteReplyAttentionLocked announces a finished assistant turn once. prior is
// the session's step state before frame was folded. Only an authoritative
// (non-intermediate) ended step that follows an observed, unfinished turn
// counts, so a repeated or replayed end with no turn in between never
// republishes; a native turn id is also claimed in the hub-wide dedupe set.
// Whether the operator wants these is decided at publish time
// (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.ChatStepEnded || step.Intermediate || frame.SessionID == "" {
return
}
if prior == nil || (prior.Status == protocol.ChatStepEnded && !prior.Intermediate) {
return
}
if !chatAttentionConfigured() {
return
}
if step.TurnID != "" && !h.claimChatAttentionLocked("reply\x00"+frame.SessionID+"\x00"+step.TurnID) {
return
}
body := h.finalReplyTextLocked(frame.SessionID)
if body == "" {
body = chatReplyFallbackBody
}
h.startChatAttention(chatAttention{sessionID: frame.SessionID, reply: true, body: body})
}
// finalReplyTextLocked returns a bounded single-line excerpt 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.
func (h *chatHub) finalReplyTextLocked(sessionID string) string {
turn := h.turns[sessionID]
if turn == nil {
return ""
}
for i := len(turn.order) - 1; i >= 0; i-- {
message := turn.messages[turn.order[i]]
if message == nil {
continue
}
if message.role == protocol.ChatRoleUser {
return ""
}
var text strings.Builder
for _, id := range message.order {
part := message.parts[id]
if part == nil || part.part.Type != protocol.ChatEventText || len(part.text) == 0 {
continue
}
if text.Len() > 0 {
text.WriteByte(' ')
}
text.Write(part.text)
if text.Len() > chatReplyBodyRunes*4 {
break
}
}
if excerpt := singleLine(text.String()); excerpt != "" {
return truncateRunes(excerpt, chatReplyBodyRunes)
}
}
return ""
}
// truncateRunes shortens text to at most limit runes, marking the cut.
func truncateRunes(text string, limit int) string {
runes := []rune(text)
if len(runes) <= limit {
return text
}
return strings.TrimSpace(string(runes[:limit])) + "…"
}
// chatReplyText builds the single-line ntfy title/body for a finished reply.
func chatReplyText(name, body string) (string, string) {
name = singleLine(name)
if name == "" {
name = "Chat"
}
const suffix = " replied"
return truncateUTF8(name, 256-len(suffix)) + suffix, truncateUTF8(singleLine(body), 2000)
}
+5
View File
@@ -407,8 +407,13 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) {
if room != nil && frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded && !frame.Step.Intermediate {
h.clearCompactionLocked(room)
}
var priorStep *protocol.ChatStep
if frame.Kind == protocol.ChatEventStep && frame.SessionID != "" {
priorStep = h.turnLocked(frame.SessionID).step
}
h.applyLocked(frame)
h.noteFormAttentionLocked(frame)
h.noteReplyAttentionLocked(priorStep, frame)
buffered := false
var targets []*chatSub
if room != nil {
+59
View File
@@ -0,0 +1,59 @@
package server
import (
"context"
"log"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// notificationSettingsStore persists the operator's global notification
// choices. *pipeline.Store implements it.
type notificationSettingsStore interface {
NotificationSettings(context.Context) (protocol.NotificationSettings, error)
UpdateNotificationSettings(context.Context, map[string]any) (protocol.NotificationSettings, error)
}
// handleNotificationSettings answers notification_settings and
// set_notification_settings. It reports whether request was one of them.
func handleNotificationSettings(ctx context.Context, request protocol.Message, store notificationSettingsStore, write func(protocol.Message) error) bool {
if request.Type != protocol.GetNotificationSettings && request.Type != protocol.SetNotificationSettings {
return false
}
response := protocol.Message{Type: protocol.NotificationSettingsReply, ID: request.ID}
var settings protocol.NotificationSettings
var err error
switch {
case store == nil:
response.Type = protocol.Error
response.Error = "notification settings are unavailable: no store"
case request.Type == protocol.GetNotificationSettings:
settings, err = store.NotificationSettings(ctx)
default:
settings, err = store.UpdateNotificationSettings(ctx, request.NotificationSettings)
}
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
} else if response.Type != protocol.Error {
response.NotificationSettings = settings.Map()
}
_ = write(response)
return true
}
// chatNotificationSettings reads the chat-related choices for a pending
// publication. Without a store the defaults apply; a read failure is logged and
// also falls back to the defaults so a transient database error neither
// silences the operator nor fails chat handling.
func chatNotificationSettings(ctx context.Context, store notificationSettingsStore) protocol.NotificationSettings {
if store == nil {
return protocol.DefaultNotificationSettings()
}
settings, err := store.NotificationSettings(ctx)
if err != nil {
log.Printf("read notification settings: %v", err)
return protocol.DefaultNotificationSettings()
}
return settings
}
@@ -0,0 +1,204 @@
package server
import (
"context"
"net/http/httptest"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
)
func notificationSettingsRoundTrip(t *testing.T, ctx context.Context, store *pipeline.Store, requests ...protocol.Message) []protocol.Message {
t.Helper()
handlerCtx, cancel := context.WithCancel(ctx)
handler := Handler(handlerCtx, store)
defer func() { cancel(); WaitRuns(handler) }()
srv := httptest.NewServer(handler)
defer srv.Close()
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
t.Fatal(err)
}
defer conn.CloseNow()
var welcome protocol.Message
if err := wsjson.Read(ctx, conn, &welcome); err != nil {
t.Fatal(err)
}
var replies []protocol.Message
for _, request := range requests {
if err := wsjson.Write(ctx, conn, request); err != nil {
t.Fatal(err)
}
var reply protocol.Message
if err := wsjson.Read(ctx, conn, &reply); err != nil {
t.Fatal(err)
}
replies = append(replies, reply)
}
return replies
}
func wantSettings(t *testing.T, reply protocol.Message, want protocol.NotificationSettings) {
t.Helper()
if reply.Type != protocol.NotificationSettingsReply || len(reply.NotificationSettings) != 3 {
t.Fatalf("reply = %+v", reply)
}
for key, value := range want.Map() {
if reply.NotificationSettings[key] != value {
t.Fatalf("%s = %v, want %v (reply %+v)", key, reply.NotificationSettings[key], value, reply.NotificationSettings)
}
}
}
func TestNotificationSettingsProtocol(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
store := newOperatorStore(t)
replies := notificationSettingsRoundTrip(t, ctx, store,
protocol.Message{Type: protocol.GetNotificationSettings, ID: "get"},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "set", NotificationSettings: map[string]any{protocol.NotifyChatReplyFinished: true}},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "unknown", NotificationSettings: map[string]any{protocol.NotifyRunFinished: false, "run_started": true}},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "string", NotificationSettings: map[string]any{protocol.NotifyRunFinished: "no"}},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "empty"},
protocol.Message{Type: protocol.GetNotificationSettings, ID: "again"},
)
defaults := protocol.DefaultNotificationSettings()
wantSettings(t, replies[0], defaults)
if replies[0].ID != "get" || replies[1].ID != "set" {
t.Fatalf("ids not echoed: %+v", replies)
}
updated := defaults
updated.ChatReplyFinished = true
wantSettings(t, replies[1], updated)
for _, reply := range replies[2:5] {
if reply.Type != protocol.Error || reply.Error == "" || reply.NotificationSettings != nil {
t.Fatalf("invalid update not refused: %+v", reply)
}
}
if !strings.Contains(replies[2].Error, "run_started") {
t.Fatalf("unknown key error = %q", replies[2].Error)
}
wantSettings(t, replies[5], updated)
// A new server on the same database (a restart) reads the stored choice.
replies = notificationSettingsRoundTrip(t, ctx, store, protocol.Message{Type: protocol.GetNotificationSettings, ID: "restart"})
wantSettings(t, replies[0], updated)
}
func TestChatNeedsYouSettingSuppressesQuestionsAndApprovals(t *testing.T) {
captured := newNtfyCapture(t)
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatNeedsYou: false}); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_quiet")
h.registry = store
h.settings = store
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_quiet", Kind: "question", Title: "Ship?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_quiet", Kind: protocol.ChatEventForm, Form: &form})
h.pushPermission("ses_quiet", protocol.ChatPermissionFrame{SessionID: "ses_quiet", RequestID: "per_1", Message: "Allow?"})
h.attentionWG.Wait()
if got := captured(); len(got) != 0 {
t.Fatalf("disabled chat_needs_you published %+v", got)
}
// Turning it back on announces new requests again.
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatNeedsYou: true}); err != nil {
t.Fatal(err)
}
h.pushPermission("ses_quiet", protocol.ChatPermissionFrame{SessionID: "ses_quiet", RequestID: "per_2", Message: "Allow now?"})
h.attentionWG.Wait()
if got := captured(); len(got) != 1 || got[0].Title != "Chat needs your approval" {
t.Fatalf("re-enabled chat_needs_you = %+v", got)
}
}
func replyTurn(h *chatHub, session, turnID, messageID, text string) {
h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turnID}})
if text != "" {
h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventText, MessageID: messageID, Part: &protocol.ChatPart{ID: messageID + "_p"}, Delta: text})
}
// A provider step boundary inside the turn is not the end of the reply.
h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turnID, Intermediate: true}})
h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turnID}})
}
func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
captured := newNtfyCapture(t)
store := newOperatorStore(t)
ctx := context.Background()
if err := store.RecordOperatorSession(ctx, "ses_done", t.TempDir(), "Release prep", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_done", "ses_bare")
h.registry = store
h.settings = store
// Off by default: a finished turn is silent.
replyTurn(h, "ses_done", "turn_0", "msg_0", "Quiet reply")
h.attentionWG.Wait()
if got := captured(); len(got) != 0 {
t.Fatalf("default published %+v", got)
}
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
t.Fatal(err)
}
long := "The build\nis green. " + strings.Repeat("x", 300)
replyTurn(h, "ses_done", "turn_1", "msg_1", long)
// Duplicate and replayed ends of the same turn, including after a
// reconnect builds a new room, publish nothing more.
ended := protocol.ChatEventFrame{SessionID: "ses_done", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}
h.emit(ended)
h.mu.Lock()
h.rooms["ses_done"] = newChatRoom(context.Background(), "ses_done")
h.mu.Unlock()
h.emit(ended)
h.emit(protocol.ChatEventFrame{SessionID: "ses_done", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}})
h.attentionWG.Wait()
got := captured()
if len(got) != 1 {
t.Fatalf("deliveries = %+v", got)
}
wantBody := truncateRunes("The build is green. "+strings.Repeat("x", 300), chatReplyBodyRunes)
want := ntfyCapture{Title: "Release prep replied", Message: wantBody, Click: "pipelines://chat/ses_done", Actions: "view, Open in browser, https://pipelines.example.com/chat/ses_done"}
if got[0] != want {
t.Fatalf("got %+v, want %+v", got[0], want)
}
// The next genuine turn notifies again; a turn without text (and a
// session without a title or native turn ids) uses the fallback text.
replyTurn(h, "ses_done", "turn_2", "msg_2", "Second answer")
h.emit(protocol.ChatEventFrame{SessionID: "ses_bare", Kind: protocol.ChatEventUser, MessageID: "usr_1", Part: &protocol.ChatPart{ID: "u1", Text: "do it"}})
replyTurn(h, "ses_bare", "", "", "")
h.attentionWG.Wait()
got = captured()
if len(got) != 3 {
t.Fatalf("deliveries = %+v", got)
}
bodies := map[string]string{}
for _, n := range got[1:] {
bodies[n.Title] = n.Message
}
if bodies["Release prep replied"] != "Second answer" || bodies["Chat replied"] != chatReplyFallbackBody {
t.Fatalf("later deliveries = %+v", got[1:])
}
}
func TestChatReplyFinishedNeedsNtfyConfiguration(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_off")
h.settings = store
replyTurn(h, "ses_off", "turn_1", "msg_1", "hello")
h.attentionWG.Wait()
h.mu.Lock()
defer h.mu.Unlock()
if len(h.attentionSeen) != 0 {
t.Fatalf("unconfigured ntfy still considered a publication: %v", h.attentionSeen)
}
}
@@ -250,11 +250,14 @@ func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
for _, tc := range []struct {
mode string
hook bool
want int32
// quiet turns the global run_finished setting off (it defaults on).
quiet bool
want int32
}{
{"on", false, 1}, {"auto", false, 0}, {"off", false, 0}, {"on", true, 1}, {"auto", true, 1}, {"off", true, 0},
{"on", false, false, 1}, {"auto", false, false, 1}, {"auto", false, true, 0}, {"on", false, true, 1}, {"off", false, false, 0},
{"on", true, false, 1}, {"auto", true, false, 1}, {"auto", true, true, 1}, {"off", true, false, 0},
} {
t.Run(tc.mode+map[bool]string{true: "-hook", false: "-no-hook"}[tc.hook], func(t *testing.T) {
t.Run(tc.mode+map[bool]string{true: "-hook", false: "-no-hook"}[tc.hook]+map[bool]string{true: "-quiet", false: ""}[tc.quiet], func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "modes.db"))
@@ -262,6 +265,11 @@ func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
if tc.quiet {
if _, err := s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: false}); err != nil {
t.Fatal(err)
}
}
source := pipeline.Template([]string{"one"}, true)
if tc.hook {
source = strings.Replace(source, "# stage one", "# stage one\n```notify\non=success\n```", 1)
@@ -287,7 +295,7 @@ func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
if err != nil || detail.Status != "succeeded" || detail.NotifyMode != tc.mode || calls.Load()-before != tc.want {
t.Fatalf("mode contract: %+v calls=%d %v", detail, calls.Load()-before, err)
}
if tc.mode == "on" && (len(detail.Notifications) != 1 || (detail.Notifications[0].Status != "sent" && detail.Notifications[0].Status != "covered")) {
if tc.want == 1 && !(tc.hook && tc.quiet) && (len(detail.Notifications) != 1 || (detail.Notifications[0].Status != "sent" && detail.Notifications[0].Status != "covered")) {
t.Fatalf("missing final audit: %+v", detail.Notifications)
}
cancel()
+8
View File
@@ -108,6 +108,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
}
hub.baseCtx = ctx
hub.registry = registry
var settingsStore notificationSettingsStore
if len(stores) > 0 {
settingsStore = stores[0]
}
hub.settings = settingsStore
mux.HandleFunc("GET /artifacts/{run}/{step}/{name...}", func(w http.ResponseWriter, r *http.Request) {
if runs == nil {
http.NotFound(w, r)
@@ -188,6 +193,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
if handleChat(connCtx, request, options.Chat, hub, registry, clientID, write) {
continue
}
if handleNotificationSettings(ctx, request, settingsStore, write) {
continue
}
if handleRunEvents(request, events, runs, clientID, write) {
continue
}
+16
View File
@@ -0,0 +1,16 @@
package stage
import (
"os"
"testing"
)
// TestMain isolates the package from an operator's real notification setup: a
// developer shell may export the installed server's ntfy configuration, and no
// test may publish to it. Tests that need ntfy point it at an httptest server.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
}
+16
View File
@@ -0,0 +1,16 @@
package tui
import (
"os"
"testing"
)
// TestMain isolates the package from an operator's real notification setup:
// these tests run real servers and runs, a developer shell may export the
// installed server's ntfy configuration, and no test may publish to it.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
}