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
+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
}