Files
pipelines/internal/server/run_notification_outbox_test.go
T
alan fc7dbb0ac0 Remove ntfy: notifications go only through the app notification stream
Server: drop ntfy publishing (stage hooks, run outbox, chat attention, chat
tool notify, auto-switch and schedule notices), the chat push outbox (its
table is dropped at startup), ntfy status/endpoints and PIPELINES_NTFY_*.
The app_notifications stream, subscribe/clear and kinds are unchanged.
Notification settings keep run_finished/chat_needs_you/chat_reply_finished;
ntfy_enabled is accepted and ignored and its stored row is never read.

Stage type=ntfy is rejected: "ntfy stages were removed; notifications go to
the Pipelines apps — use the stage notify hook". The notify hook remains.

Installer: no ntfy build, accounts, config or supervisor child; manifest
gets top-level "mode" (legacy ntfy.mode still read). Reinstall retires an
old ntfy (safe PID-file stop, deletes binary, config, data dir, token, log,
with a note in logs/install.log); uninstall cleans leftovers.

App: ntfy settings section replaced by "Notification events"; texts updated.
Docs: docs/ntfy.md folded into docs/notifications.md; install, docker, cli,
author skill references updated; security review M1 marked resolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 23:24:24 +00:00

347 lines
12 KiB
Go

package server
import (
"context"
"fmt"
"path/filepath"
"strings"
"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"
"git.a-wan.net/alan/pipelines/internal/summarise"
)
// An app notification that could not be recorded stays pending in the run
// outbox and is retried after the store is reopened; a repeated request is
// deduplicated.
func TestRunNotificationRecordFailureRetriesAfterReopen(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "retry.db")
s, err := pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, s)
recorder.fail = true
r := &runner{ctx: ctx, store: s, notes: notes}
// The run was started with "Notify me", so its failure is announced.
r.setNotifyMode(7, "on")
// Emulate a durable transition intent saved before the runner callback.
if err := s.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: 7, Sequence: 1, Event: "failed", Channel: "system", Title: "Run failed", Body: "Run 7", Click: "pipelines://run/7"}); err != nil {
t.Fatal(err)
}
r.notifyRun(7, "test", "failed", 1, "stage", "")
got, err := s.RunNotifications(ctx, 7)
if err != nil || len(got) != 1 || got[0].Status != "pending" || got[0].Attempts != 1 || got[0].Diagnostic == "" {
t.Fatalf("failed attempt not audited: %+v %v", got, err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
s, err = pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
notes, recorder = newNoteCapture(t, s)
r = &runner{ctx: ctx, store: s, notes: notes}
r.setNotifyMode(7, "on")
r.deliverRunNotifications(time.Now().Add(time.Minute))
r.notifyRun(7, "test", "failed", 1, "stage", "")
got, err = s.RunNotifications(ctx, 7)
recorded := recorder.recorded()
if err != nil || len(got) != 1 || got[0].Status != "sent" || got[0].Attempts != 2 || recorder.attempts() != 1 || len(recorded) != 1 || recorded[0].Click != "pipelines://run/7" {
t.Fatalf("retry/dedupe: %+v recorded=%+v %v", got, recorded, err)
}
}
func TestTransactionalSuccessNotificationUsesAppLink(t *testing.T) {
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "web-success.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
if _, err := s.Submit(ctx, "test", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := s.List(ctx)
d, err := s.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
id, _, err := s.CreateRunTitled(ctx, d, "web-success", t.TempDir(), false, nil, nil, pipeline.RunOverrides{NotifyMode: "on"}, summarise.Title{})
if err != nil {
t.Fatal(err)
}
if err := s.FinishRun(ctx, id, "succeeded", "success", "", nil); err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, s)
r := &runner{ctx: ctx, store: s, notes: notes}
r.notifyRun(id, "test", "succeeded", 0, "", "")
r.deliverRunNotifications(time.Now())
got, err := s.RunNotifications(ctx, id)
recorded := recorder.recorded()
if err != nil || len(got) != 1 || got[0].Status != "sent" || len(recorded) != 1 || recorded[0].Click != fmt.Sprintf("pipelines://run/%d", id) || recorded[0].Kind != protocol.NotificationRunSucceeded {
t.Fatalf("notification: %+v recorded=%+v err=%v", got, recorded, err)
}
}
func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "not-finished.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\n```", 1)
if _, err := s.Submit(ctx, "test", source); err != nil {
t.Fatal(err)
}
items, err := s.List(ctx)
if err != nil {
t.Fatal(err)
}
d, err := s.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
id, _, err := s.CreateRunTitled(ctx, d, "not-finished", "workspace", false, nil, nil, pipeline.RunOverrides{NotifyMode: "on"}, summarise.Title{})
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, s)
r := &runner{ctx: ctx, store: s, events: newRunEventHub(), notes: notes}
if err := s.BeginStep(ctx, id, 1, "one", nil); err != nil {
t.Fatal(err)
}
state := &runState{memory: map[string]memoryValue{}}
if _, _, _, _, err := r.finishStage(id, "test", "workspace", d.Graph.Stages[0], state, protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: protocol.SuccessEnd, Output: map[string]any{"markdown": "result"}}); err != nil {
t.Fatal(err)
}
if recorder.attempts() != 0 {
t.Fatal("terminal stage success announced before FinishRun")
}
sub := r.events.subscribe("test", "workspace", nil, func(protocol.Message) error { return nil })
defer sub.close()
// Marshal failure occurs before FinishRun can commit its proposed success.
r.finishRunState(id, "test", "workspace", "succeeded", "success", "", 0, 0, "", stage.Values{"invalid": make(chan int)})
got, err := s.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if got.Status != "running" || len(got.Notifications) != 0 || recorder.attempts() != 0 {
t.Fatalf("unpersisted success announced: %+v attempts=%d", got, recorder.attempts())
}
sub.mu.Lock()
defer sub.mu.Unlock()
if len(sub.pending) != 0 {
t.Fatalf("unpersisted terminal event emitted: %+v", sub.pending)
}
}
func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
for _, failFirst := range []bool{false, true} {
t.Run(map[bool]string{false: "covered", true: "retry"}[failFirst], func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "waiting-hook.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
source := strings.Replace(humanPipelineSource, "# stage gate", "# stage gate\n```notify\non=waiting\n```", 1)
if _, err := s.Submit(ctx, "waiting", source); err != nil {
t.Fatal(err)
}
items, err := s.List(ctx)
if err != nil {
t.Fatal(err)
}
r, err := newRunner(ctx, s)
if err != nil {
t.Fatal(err)
}
defer func() { cancel(); r.schedulerWG.Wait() }()
notes, recorder := newNoteCapture(t, s)
if failFirst {
recorder.failNext = 1
}
r.notes = notes
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "waiting-hook", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
r.deliverRunNotifications(time.Now().Add(time.Minute))
detail, err := s.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
wantCalls := 1
if failFirst {
wantCalls = 2
}
if recorder.attempts() != wantCalls || len(recorder.recorded()) != 1 || detail.Status != "waiting" || len(detail.Notifications) != 1 {
t.Fatalf("waiting hook duplicated/lost: attempts=%d recorded=%+v detail=%+v", recorder.attempts(), recorder.recorded(), detail)
}
status := detail.Notifications[0].Status
if status != "sent" && status != "covered" {
t.Fatalf("missing acknowledgement: %+v", detail.Notifications)
}
})
}
}
func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
for _, tc := range []struct {
mode string
hook bool
// any turns the global run_finished setting on (it defaults off), so
// every run end notifies, not only runs marked "on".
any bool
want int
}{
{"on", false, false, 1}, {"auto", false, false, 0}, {"auto", false, true, 1}, {"on", false, true, 1}, {"off", false, false, 0}, {"off", false, true, 0},
// A stage hook is the pipeline's own opt-in: it still notifies for an
// auto run, and never doubles up with the run alert.
{"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]+map[bool]string{true: "-any", false: ""}[tc.any], func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "modes.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
if tc.any {
if _, err := s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: true}); 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)
}
if _, err := s.Submit(ctx, "mode-test", source); err != nil {
t.Fatal(err)
}
items, _ := s.List(ctx)
r, err := newRunner(ctx, s)
if err != nil {
t.Fatal(err)
}
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success"}, nil
}
notes, recorder := newNoteCapture(t, s)
r.notes = notes
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "mode", NotifyMode: tc.mode, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := s.GetRun(ctx, run.ID)
if err != nil || detail.Status != "succeeded" || detail.NotifyMode != tc.mode || len(recorder.recorded()) != tc.want {
t.Fatalf("mode contract: %+v recorded=%+v %v", detail, recorder.recorded(), err)
}
if tc.want == 1 && !(tc.hook && tc.mode == "auto" && !tc.any) && (len(detail.Notifications) != 1 || (detail.Notifications[0].Status != "sent" && detail.Notifications[0].Status != "covered")) {
t.Fatalf("missing final audit: %+v", detail.Notifications)
}
cancel()
r.schedulerWG.Wait()
})
}
}
func TestRunNotificationAttentionModesAndRetryBound(t *testing.T) {
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "attention.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
notes, recorder := newNoteCapture(t, s)
recorder.fail = true
r := &runner{ctx: ctx, store: s, notes: notes}
for i, mode := range []string{"auto", "on", "off"} {
id := int64(i + 1)
r.setNotifyMode(id, mode)
for sequence, status := range []string{"waiting", "failed"} {
r.notifyRun(id, "test", status, sequence, "stage", "")
}
}
// auto and on waiting, plus auto and on failed; off never notifies.
if recorder.attempts() != 4 {
t.Fatalf("attention modes: %d attempts, want 4", recorder.attempts())
}
r.deliverRunNotifications(time.Now().Add(time.Minute))
r.deliverRunNotifications(time.Now().Add(2 * time.Minute))
r.deliverRunNotifications(time.Now().Add(3 * time.Minute))
if recorder.attempts() != 12 {
t.Fatalf("retry bound: %d attempts, want 12", recorder.attempts())
}
for _, id := range []int64{1, 2, 3} {
got, err := s.RunNotifications(ctx, id)
if err != nil {
t.Fatal(err)
}
if id == 3 && len(got) != 0 {
t.Fatalf("off created attempts: %+v", got)
}
for _, n := range got {
if n.Status != "failed" || n.Attempts != 3 {
t.Fatalf("missing exhausted audit: %+v", n)
}
}
}
}
func TestRunNotificationWorkerResumesPendingAfterRestart(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
path := filepath.Join(t.TempDir(), "worker.db")
s, err := pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
if err := s.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: 7, Sequence: 1, Event: "failed", Channel: "system", Title: "Run failed", Body: "pending"}); err != nil {
t.Fatal(err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
s, err = pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
r, err := newRunner(ctx, s)
if err != nil {
t.Fatal(err)
}
// As the handler does, before the worker's first tick.
r.notes = newAppNotifier(s)
defer func() { cancel(); r.schedulerWG.Wait() }()
deadline := time.Now().Add(5 * time.Second)
for {
got, err := s.RunNotifications(ctx, 7)
if err != nil {
t.Fatal(err)
}
if len(got) == 1 && got[0].Status == "sent" && appNotification(t, s, "run:7:1:failed") != nil {
break
}
if time.Now().After(deadline) {
t.Fatalf("recovery audit: %+v", got)
}
time.Sleep(10 * time.Millisecond)
}
}