Files
pipelines/internal/server/notify_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

426 lines
16 KiB
Go

package server
import (
"context"
"errors"
"fmt"
"git.a-wan.net/alan/pipelines/examples"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// A stage notify hook records one app notification per matching step event
// and audits it as one app receipt; a non-matching event records nothing.
func TestStageNotificationEvents(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "notify.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
workspace := t.TempDir()
if _, err := store.Submit(ctx, "notifications", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
d, _ := store.Get(ctx, items[0].ID, 0)
r, _ := newRunner(ctx, store)
notes, recorder := newNoteCapture(t, store)
r.notes = notes
for i, test := range []struct {
status, outcome, target, on string
kind string
}{
{"completed", "success", protocol.SuccessEnd, "success", protocol.NotificationRunSucceeded},
{"completed", "blocked", protocol.FailureEnd, "failure", protocol.NotificationRunFailed},
{"failed", "error", protocol.FailureEnd, "failure", protocol.NotificationRunFailed},
{"completed", "error", protocol.FailureEnd, "success", ""},
} {
id, _, err := store.CreateRun(ctx, d, fmt.Sprintf("case%d", i), workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
t.Fatal(err)
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: test.status, Outcome: test.outcome, Target: test.target, Output: map[string]any{}}
policy := &protocol.NotificationPolicy{On: []string{test.on}, Destination: "anime"}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := len(recorder.recorded())
r.notifyStep(id, d.Name, workspace, policy, step)
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
got := recorder.recorded()[before:]
if test.kind == "" {
if len(got) != 0 || len(detail.Steps[0].Notifications) != 0 {
t.Fatal("a non-matching event notified", got, detail.Steps[0].Notifications)
}
continue
}
if len(got) != 1 || got[0].Kind != test.kind || got[0].Click != fmt.Sprintf("pipelines://run/%d", id) || len(detail.Steps[0].Notifications) != 1 {
t.Fatal("event mismatch", got, detail.Steps[0].Notifications)
}
if receipt := detail.Steps[0].Notifications[0]; receipt.Status != "sent" || receipt.Destination != "app" {
t.Fatal("notification receipt not persisted", receipt)
}
}
}
// Regress the terminal-path recipe from the authoring guide on the bundled
// research -> report starter.
// A completion-alert request must not require native delivery or change run routing.
func TestTerminalNotificationRecipe(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "recipe.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
var source string
for _, template := range examples.Catalog() {
if template.Key == "research" {
source = template.Source
}
}
if source == "" {
t.Fatal("research template missing")
}
source = strings.Replace(source, "# stage report", "# stage report\n```notify\non=success,failure\n```", 1)
if _, err = store.Submit(ctx, "research notification recipe", source); err != nil {
t.Fatal(err)
}
items, err := store.List(ctx)
if err != nil || len(items) != 1 {
t.Fatal("recipe missing", err)
}
id := items[0].ID
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
for index, test := range []struct {
name, stage, outcome, status string
executionError, deliveryError bool
notify bool
}{
{"success", "report", "success", "succeeded", false, false, true},
{"research blocked", "research", "blocked", "failed", false, false, false},
{"research execution error", "research", "error", "failed", true, false, true},
{"report blocked", "report", "blocked", "failed", false, false, false},
{"report execution error", "report", "error", "failed", true, false, true},
{"delivery error preserves success", "report", "success", "succeeded", false, true, true},
} {
t.Run(test.name, func(t *testing.T) {
recorder.mu.Lock()
recorder.fail = test.deliveryError
recorder.mu.Unlock()
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == test.stage {
if test.executionError {
return stage.Result{}, errors.New("fixture execution failed")
}
return stage.Result{Outcome: test.outcome, Output: stage.Values{"report": "retained evidence"}}, nil
}
return stage.Result{Outcome: "success", Output: stage.Values{"question": "topic", "evidence": []any{"source fact"}}}, nil
}
before := len(recorder.recorded())
run, err := r.start(protocol.Message{PipelineID: id, Version: 1, RequestKey: fmt.Sprintf("recipe-%d", index), Workspace: t.TempDir(), Input: map[string]any{"prompt": "research a topic"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
recorded := len(recorder.recorded()) - before
if detail.Status != test.status || (!test.deliveryError && (recorded == 1) != test.notify) || (test.deliveryError && recorded != 0) {
t.Fatal("wrong verdict or duplicate/missing terminal alert", detail.Status, recorded)
}
last := detail.Steps[len(detail.Steps)-1]
if last.Stage != test.stage || (len(last.Notifications) == 1) != test.notify {
t.Fatal("notification not retained on terminal stage", last)
}
if !test.notify {
return
}
for _, step := range detail.Steps[:len(detail.Steps)-1] {
if len(step.Notifications) != 0 {
t.Fatal("intermediate success alerted", step)
}
}
want := "sent"
if test.deliveryError {
want = "failed"
}
if last.Notifications[0].Status != want {
t.Fatal("delivery receipt wrong", last.Notifications)
}
if !test.executionError && detail.Output["report"] != "retained evidence" {
t.Fatal("notification changed output handoff", detail.Output)
}
})
}
}
func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "routing.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
// artifacts= is a legacy (ntfy attachment) setting, still accepted.
source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\ndestination=anime\nartifacts=markdown\n```", 1)
if _, err := store.Submit(ctx, "test", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, _ := newRunner(ctx, store)
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Result"}}, nil
}
// The app stream refuses the notification.
notes, recorder := newNoteCapture(t, store)
recorder.fail = true
r.notes = notes
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "once", Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ := store.GetRun(ctx, run.ID)
if detail.Status != "succeeded" || len(detail.Steps[0].Notifications) != 1 || detail.Steps[0].Notifications[0].Status != "failed" {
t.Fatal("notification altered routing or lost failure audit", detail)
}
}
func TestNotificationArtifactSelectionAndPreview(t *testing.T) {
root := t.TempDir()
public := filepath.Join(root, "9", "public")
if err := os.MkdirAll(filepath.Join(public, "reports"), 0700); err != nil {
t.Fatal(err)
}
old := filepath.Join(public, "reports", "old.md")
newer := filepath.Join(public, "reports", "new.md")
if err := os.WriteFile(old, []byte("old"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(newer, []byte("# Hello world\n\n"+strings.Repeat("word ", 200)), 0600); err != nil {
t.Fatal(err)
}
oldTime := time.Now().Add(-time.Hour)
if err := os.Chtimes(old, oldTime, oldTime); err != nil {
t.Fatal(err)
}
r := &runner{artifactsRoot: root}
a, preview := r.resolveNotificationArtifact(9, 3, "reports/*.md", "")
if a == nil || a.Path != "reports/new.md" || a.URL != "/artifacts/9/3/public/reports/new.md" {
t.Fatalf("wrong selected artifact: %+v", a)
}
if len([]rune(preview)) > 600 || !strings.HasPrefix(preview, "Hello world") || !strings.HasSuffix(preview, "…") {
t.Fatalf("wrong preview: %q", preview)
}
if got := notificationClick(9, 3, a); got != "pipelines://artifact/9/3/reports/new.md" {
t.Fatal(got)
}
if got, _ := r.resolveNotificationArtifact(9, 3, "", ""); got != nil {
t.Fatal("multiple files selected automatically")
}
if err := os.Remove(old); err != nil {
t.Fatal(err)
}
if got, _ := r.resolveNotificationArtifact(9, 3, "", ""); got == nil || got.Path != "reports/new.md" {
t.Fatal("single artifact not selected automatically")
}
}
// TestRunAttentionEventMapping pins the single decision of whether a run needs
// the operator: a run parked on a person (waiting) or a failed run, and nothing
// else. A queued, running, succeeded, canceled or interrupted run never notifies.
func TestRunAttentionEventMapping(t *testing.T) {
for _, test := range []struct{ status, want string }{
{"waiting", protocol.NotifyWaiting},
{"failed", "failed"},
{"Warning", ""},
{"queued", ""},
{"running", ""},
{"succeeded", ""},
{"canceled", ""},
{"interrupted", "interrupted"},
{"", ""},
} {
if got := runAttentionEvent(test.status); got != test.want {
t.Errorf("runAttentionEvent(%q) = %q, want %q", test.status, got, test.want)
}
}
}
// TestRunAttentionNotificationDelivery proves the operator-facing contract: the
// notification names the run and its pipeline, the click action opens the run,
// only waiting/failed notify, and a run that stays waiting is never repeated.
func TestRunAttentionNotificationDelivery(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "attention.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
// A run that needs nobody notifies nothing.
for _, status := range []string{"queued", "running", "succeeded", "canceled"} {
r.notifyRun(7, "release", status, 1, "build", "")
}
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("a run that needs nobody notified: %+v", got)
}
// A waiting run notifies once, with the identity and click.
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
// A run that stays waiting is never repeated, on a later call or a re-request.
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
// An auto run's failure announces its end.
r.notifyRun(8, "release", "failed", 2, "deploy", "provider returned 500")
// A failed run marked "on" notifies once, with its diagnostic.
r.setNotifyMode(7, "on")
r.notifyRun(7, "release", "failed", 2, "deploy", "provider returned 500")
got := recorder.recorded()
if len(got) != 3 {
t.Fatalf("notifications = %+v, want three genuine events", got)
}
first := got[0]
if first.Title != "Run needs your decision" || !strings.Contains(first.Message, "Run #7") || !strings.Contains(first.Message, "release") || !strings.Contains(first.Message, "decision") || !strings.Contains(first.Message, "approve") {
t.Fatalf("waiting notification does not identify the run/pipeline/need: %+v", first)
}
if first.Click != "pipelines://run/7" || first.Kind != protocol.NotificationRunWaiting {
t.Fatalf("waiting notification click does not open the run: %+v", first)
}
if second := got[1]; second.Title != "Run failed" || !strings.Contains(second.Message, "Run #8") || second.Click != "pipelines://run/8" {
t.Fatalf("failed notification is not actionable: %+v", second)
}
if third := got[2]; third.Title != "Run failed" || !strings.Contains(third.Message, "Run #7") || !strings.Contains(third.Message, "provider returned 500") {
t.Fatalf("marked failed notification is not actionable: %+v", third)
}
}
// TestRunAttentionSuppressedByStagePolicy proves a stage's own notify policy and
// the run-level default cannot both fire for the same event: the author's policy
// wins, so the operator gets exactly one notification.
func TestRunAttentionSuppressedByStagePolicy(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "suppress.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
r.markAttentionSent(11, 5, "failed")
r.markAttentionSent(11, 6, "waiting")
if !r.attentionAlready(11, 5, "failed") || !r.attentionAlready(11, 6, "waiting") {
t.Fatal("stage-policy coverage not recorded")
}
r.notifyRun(11, "release", "failed", 5, "deploy", "")
r.notifyRun(11, "release", protocol.RunStatusWaiting, 6, "approve", "")
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("run-level default repeated a stage-policy event: %+v", got)
}
}
// TestHumanRunAttentionNotification proves the run loop records the run-level
// attention notification itself when the pipeline declares no notify policy: the
// transition to waiting reaches the operator exactly once, with the run,
// pipeline and a run-opening click.
func TestHumanRunAttentionNotification(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "human-attention.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "human", humanPipelineSource); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
defer r.wg.Wait()
r.execute = successExecute
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "human-attention", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
deadline := time.Now().Add(5 * time.Second)
for len(recorder.recorded()) == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
time.Sleep(50 * time.Millisecond)
got := recorder.recorded()
if len(got) != 1 {
t.Fatalf("waiting notifications = %+v, want exactly one", got)
}
if got[0].Title != "Run needs your decision" || !strings.Contains(got[0].Message, fmt.Sprintf("Run #%d", run.ID)) || !strings.Contains(got[0].Message, "human") {
t.Fatalf("run-level waiting notification wrong: %+v", got[0])
}
if got[0].Click != fmt.Sprintf("pipelines://run/%d", run.ID) {
t.Fatalf("run-level waiting notification click wrong: %q", got[0].Click)
}
}
// TestRunAttentionNotifiesEachGenuineWait proves the step sequence is part of the
// dedup key: a run that waits on a person twice notifies each time (two genuine
// events), while the same wait is never repeated.
func TestRunAttentionNotifiesEachGenuineWait(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "waits.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
r.notifyRun(1, "release", protocol.RunStatusWaiting, 1, "gate", "")
r.notifyRun(1, "release", protocol.RunStatusWaiting, 1, "gate", "")
r.notifyRun(1, "release", protocol.RunStatusWaiting, 5, "gate-again", "")
if got := recorder.recorded(); len(got) != 2 {
t.Fatalf("two genuine waits produced %d notifications, want 2", len(got))
}
}