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>
This commit is contained in:
2026-12-03 23:24:24 +00:00
parent 806b5eca46
commit fc7dbb0ac0
138 changed files with 1958 additions and 4651 deletions
+3 -3
View File
@@ -26,7 +26,7 @@ go test ./... # ~1 min for everything; `gofmt -l .` must print
- `internal/server/chat_*.go` — the chat broker: `chat_sessions`, claims, the stream, permissions,
session registry.
- `internal/stage/` — one client per harness and stage type: `opencode.go` (native sessions),
`pi.go` (RPC), `model.go`, `agent.go`, `human.go` (decision stages), `ntfy.go` (notifications),
`pi.go` (RPC), `model.go`, `agent.go`, `human.go` (decision stages),
`model_prompt.go` (file-based turn prompt), `budget.go` (usage accounting). Model stages return
markdown for `output.md`; only its `# outcome` section is parsed (`internal/turn`).
- `internal/pipeline/` — the store: definitions and immutable versions, runs and steps, the
@@ -40,11 +40,11 @@ go test ./... # ~1 min for everything; `gofmt -l .` must print
`scripts/run-local-server.sh` starts a scratch server, and the binary takes `-addr` and `-db`, so a
live check runs against a **scratch database and a free loopback port**. The operator's deployment is
`~/.local/share/pipelines` with the service on `0.0.0.0:8080` and ntfy on `8090`.
`~/.local/share/pipelines` with the service on `0.0.0.0:8080`.
## Hard rules
- **Never restart, rebuild or redeploy the deployed server, ntfy or a running run** to test a change:
- **Never restart, rebuild or redeploy the deployed server or a running run** to test a change:
a restart kills every run in flight. Deploying is the operator's step.
- Commit locally only, never push.
- One run per workspace at a time — the server refuses a second one rather than sharing a tree.
+3 -35
View File
@@ -11,7 +11,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// appNotificationStore persists the app notification outbox.
@@ -27,8 +26,8 @@ type appNotificationStore interface {
// that falls this far behind is dropped; it recovers with a resubscribe.
const appNotificationQueue = 512
// appNotifier records every operator notification (the same ones published to
// ntfy) and streams them to subscribed connections. One mutex orders store
// appNotifier records every operator notification and streams it to
// subscribed connections. One mutex orders store
// writes with fan-out, so each subscriber sees its snapshot reply and then
// every later push exactly in commit order.
type appNotifier struct {
@@ -133,7 +132,7 @@ func (a *appNotifier) detach(clientID string) {
// record persists n and pushes it when it is new, and reports whether it is
// recorded. Failures are logged only: recording must never block or fail the
// ntfy publication beside it.
// event that raised it.
func (a *appNotifier) record(ctx context.Context, n pipeline.AppNotificationRecord) bool {
if a == nil {
return false
@@ -162,7 +161,6 @@ func (a *appNotifier) clear(ctx context.Context, ids []string, exclude string) (
}
if len(changed) > 0 {
a.enqueueLocked(protocol.Message{Type: protocol.NotificationsCleared, IDs: recordIDs(changed)}, exclude)
clearChatNtfy(recordIDs(changed))
}
return changed, nil
}
@@ -182,7 +180,6 @@ func (a *appNotifier) clearFor(ctx context.Context, filter pipeline.AppNotificat
}
if len(ids) > 0 {
a.enqueueLocked(protocol.Message{Type: protocol.NotificationsCleared, IDs: ids}, "")
clearChatNtfy(ids)
}
}
@@ -286,27 +283,6 @@ func handleAppNotifications(ctx context.Context, request protocol.Message, notes
return true
}
// ntfyEnabled reads notify.ntfy_enabled. Without a store, or when the read
// fails, ntfy stays enabled (the default) so a transient error never silences
// the operator.
func ntfyEnabled(ctx context.Context, store notificationSettingsStore) bool {
if store == nil {
return true
}
settings, err := store.NotificationSettings(ctx)
if err != nil {
log.Printf("read notification settings: %v", err)
return true
}
return settings.NtfyEnabled
}
// ntfyDisabledResult is what a publication reports when ntfy is turned off:
// the notification reached app clients only.
func ntfyDisabledResult() stage.Values {
return stage.Values{"destination": "system", "message_id": "", "ntfy": "disabled"}
}
// runNotificationKind maps a run outbox event to its app notification kind.
func runNotificationKind(event string) string {
switch event {
@@ -356,11 +332,3 @@ func runNotificationRecord(runID int64, sequence int, event, kind, title, messag
RunID: runID,
}
}
// settingsStore returns the runner's store as a settings reader, or nil.
func (r *runner) settingsStore() notificationSettingsStore {
if r.store == nil {
return nil
}
return r.store
}
+66 -87
View File
@@ -16,7 +16,6 @@ import (
"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"
)
@@ -78,16 +77,12 @@ func newAppNotificationFixture(t *testing.T, ctx context.Context) *appNotificati
return &appNotificationFixture{t: t, ctx: ctx, store: store, runner: handler.(*runHandler).runner, hub: handler.(*runHandler).hub, url: srv.URL, def: def}
}
func TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
func TestToolNotificationRecordsAppNotification(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
hub := &chatHub{notes: newAppNotifier(store), settings: store}
got := hub.publishToolNotification(ctx, "session-1", chatToolNotice{ID: "shown_1", Title: "Build failed", Message: "Please inspect the run", Priority: "low"})
if !got.App || got.Phone || got.Detail != "phone notifications (ntfy) are turned off" {
if !got.App || got.Detail != "" {
t.Fatalf("tool notification result = %+v", got)
}
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
@@ -98,13 +93,15 @@ func TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
n.Message != "Please inspect the run" || n.Priority != 2 || n.Group != "chat:session-1" || n.Click != "pipelines://chat/session-1" {
t.Fatalf("wrong tool notification: %+v", n)
}
// Without the app stream there is nowhere to deliver: the agent is told.
if got := (&chatHub{}).publishToolNotification(ctx, "session-1", chatToolNotice{ID: "shown_2", Title: "t", Message: "m"}); got.App || got.Detail == "" {
t.Fatalf("store-less delivery = %+v", got)
}
}
// An agent's notify reaches every connected app, not only the clients watching
// that chat, and a client that connects later replays the ones still active.
func TestToolNotificationBroadcastsAndReplaysToReconnectingClients(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
f := newAppNotificationFixture(t, ctx)
@@ -114,7 +111,7 @@ func TestToolNotificationBroadcastsAndReplaysToReconnectingClients(t *testing.T)
subscribeNotifications(t, ctx, desktop, "")
notice := chatToolNotice{ID: "shown_a", Title: "Done", Message: "Build finished", Priority: "high"}
if got := hub.publishToolNotification(ctx, "ses_x", notice); !got.App || got.Phone || got.Detail == "" {
if got := hub.publishToolNotification(ctx, "ses_x", notice); !got.App || got.Detail != "" {
t.Fatalf("delivery = %+v", got)
}
for name, conn := range map[string]*websocket.Conn{"web": web, "desktop": desktop} {
@@ -226,11 +223,9 @@ func subscribeNotifications(t *testing.T, ctx context.Context, conn *websocket.C
return reply
}
func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
func TestAppNotificationStreamCarriesRunFailure(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
captured := newNtfyCapture(t)
f := newAppNotificationFixture(t, ctx)
phone := dialAckClient(t, ctx, f.url)
initial := subscribeNotifications(t, ctx, phone, "")
@@ -239,13 +234,9 @@ func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
}
run := f.failRun("stream")
push := readFrame(t, ctx, phone, protocol.NotificationPush)
got := captured()
if len(got) != 1 {
t.Fatalf("ntfy deliveries = %+v", got)
}
n := push.Notification
if n == nil || n.Title != got[0].Title || n.Message != got[0].Message || n.Click != got[0].Click {
t.Fatalf("stream %+v differs from ntfy %+v", n, got[0])
if n == nil || n.Title != "Run failed" || !strings.Contains(n.Message, fmt.Sprintf("Run #%d", run)) {
t.Fatalf("stream notification = %+v", n)
}
if n.ID != fmt.Sprintf("run:%d:0:failed", run) || n.Kind != protocol.NotificationRunFailed || n.Group != fmt.Sprintf("run:%d", run) ||
n.Priority != 3 || n.Tags == nil || len(n.Tags) != 0 || n.Click != fmt.Sprintf("pipelines://run/%d", run) {
@@ -264,7 +255,7 @@ func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
t.Fatalf("notification wire lacks %q: %s", key, raw)
}
}
// A retried publication of the same event is not streamed twice.
// A retried delivery of the same event is not streamed twice.
f.runner.deliverRunNotifications(time.Now().Add(time.Hour))
reply := subscribeNotifications(t, ctx, phone, "")
if len(reply.Notifications) != 1 || reply.Notifications[0].ID != n.ID || reply.Notifications[0].CreatedAt != n.CreatedAt {
@@ -273,11 +264,10 @@ func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
}
func TestAppNotificationReplayAfterCursorAndCrossDeviceClear(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
f := newAppNotificationFixture(t, ctx)
// Offline: two runs fail with no app connected (ntfy unconfigured too).
// Offline: two runs fail with no app connected.
first := f.failRun("first")
second := f.failRun("second")
firstID, secondID := fmt.Sprintf("run:%d:0:failed", first), fmt.Sprintf("run:%d:0:failed", second)
@@ -357,42 +347,41 @@ func TestAppNotificationReplayAfterCursorAndCrossDeviceClear(t *testing.T) {
}
}
func TestNtfyDisabledStillStreams(t *testing.T) {
// An older app may still send the removed ntfy_enabled switch: the server
// accepts it without changing anything, replies with exactly the three
// notification settings, and keeps streaming.
func TestLegacyNtfySwitchIsIgnoredAndRunsStillStream(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
captured := newNtfyCapture(t)
f := newAppNotificationFixture(t, ctx)
phone := dialAckClient(t, ctx, f.url)
set := ackExchange(t, ctx, phone, protocol.Message{Type: protocol.SetNotificationSettings, ID: "off", NotificationSettings: map[string]any{protocol.NotifyNtfyEnabled: false}})
if set.Type != protocol.NotificationSettingsReply || set.NotificationSettings[protocol.NotifyNtfyEnabled] != false {
set := ackExchange(t, ctx, phone, protocol.Message{Type: protocol.SetNotificationSettings, ID: "off", NotificationSettings: map[string]any{protocol.LegacyNotifyNtfyEnabled: false}})
want := protocol.DefaultNotificationSettings().Map()
if set.Type != protocol.NotificationSettingsReply || len(set.NotificationSettings) != 3 {
t.Fatalf("settings reply = %+v", set)
}
for key, value := range want {
if set.NotificationSettings[key] != value {
t.Fatalf("settings reply %s = %v, want %v: %+v", key, set.NotificationSettings[key], value, set)
}
}
if _, present := set.NotificationSettings[protocol.LegacyNotifyNtfyEnabled]; present {
t.Fatalf("reply still carries ntfy_enabled: %+v", set)
}
subscribeNotifications(t, ctx, phone, "")
run := f.failRun("quiet")
push := readFrame(t, ctx, phone, protocol.NotificationPush)
if push.Notification == nil || push.Notification.ID != fmt.Sprintf("run:%d:0:failed", run) || push.Notification.Title != "Run failed" {
t.Fatalf("push = %+v", push)
}
if got := captured(); len(got) != 0 {
t.Fatalf("ntfy published while disabled: %+v", got)
}
// The outbox is settled, not retried against ntfy.
// The outbox is settled once the app notification is recorded.
rows, err := f.store.RunNotifications(ctx, run)
if err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("outbox = %+v %v", rows, err)
}
}
func TestChatAppNotificationsRespectNtfyEnabledAndClearOnAnswer(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
var published []ntfyCapture
original := chatAttentionPublish
chatAttentionPublish = func(_ context.Context, _, title, message, _ string, _ []byte, click string, _ ...stage.NtfyView) (stage.Values, error) {
published = append(published, ntfyCapture{Title: title, Message: message, Click: click})
return stage.Values{}, nil
}
defer func() { chatAttentionPublish = original }()
func TestChatAppNotificationsClearOnAnswer(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
h := chatAttentionHub(t, "ses_a")
@@ -402,13 +391,13 @@ func TestChatAppNotificationsRespectNtfyEnabledAndClearOnAnswer(t *testing.T) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_a", Kind: protocol.ChatEventForm, Form: &form})
h.attentionWG.Wait()
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(published) != 1 || len(active) != 1 {
t.Fatalf("published=%+v active=%+v err=%v", published, active, err)
if err != nil || len(active) != 1 {
t.Fatalf("active=%+v err=%v", active, err)
}
n := active[0]
if n.ID != "chat:ses_a:form:que_1" || n.Kind != protocol.NotificationChatQuestion || n.Group != "chat:ses_a" ||
n.Title != published[0].Title || n.Message != published[0].Message || n.Click != published[0].Click {
t.Fatalf("chat notification %+v vs ntfy %+v", n, published[0])
n.Message != "Ship it?" || n.Click != "pipelines://chat/ses_a" {
t.Fatalf("chat notification %+v", n)
}
// Answering the question clears it.
form.Resolved = true
@@ -417,15 +406,11 @@ func TestChatAppNotificationsRespectNtfyEnabledAndClearOnAnswer(t *testing.T) {
if active, _, _ := store.ActiveAppNotifications(ctx, "", time.Now()); len(active) != 0 {
t.Fatalf("answered question still active: %+v", active)
}
// With ntfy off, the approval is streamed but not published.
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil {
t.Fatal(err)
}
h.pushPermission("ses_a", protocol.ChatPermissionFrame{SessionID: "ses_a", RequestID: "per_1", Message: "Allow rm?"})
h.attentionWG.Wait()
active, _, _ = store.ActiveAppNotifications(ctx, "", time.Now())
if len(published) != 1 || len(active) != 1 || active[0].Kind != protocol.NotificationChatApproval || active[0].ID != "chat:ses_a:permission:per_1" {
t.Fatalf("published=%+v active=%+v", published, active)
if len(active) != 1 || active[0].Kind != protocol.NotificationChatApproval || active[0].ID != "chat:ses_a:permission:per_1" {
t.Fatalf("active=%+v", active)
}
h.confirmPermission("ses_a", "per_1", "phone", "once")
h.attentionWG.Wait()
@@ -452,12 +437,9 @@ func TestRunLeavingWaitingClearsWaitingNotification(t *testing.T) {
}
}
// A stage notify hook streams one notification per step event (artifacts stay
// ntfy attachments) with the hook's title and summary, and with ntfy disabled
// it still streams while publishing nothing.
// A stage notify hook streams one notification per step event with the hook's
// title and summary, and audits the delivery as an app receipt.
func TestStageHookAppNotification(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
captured := newNtfyCapture(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
@@ -468,38 +450,35 @@ func TestStageHookAppNotification(t *testing.T) {
d, _ := store.Get(ctx, items[0].ID, 0)
workspace := t.TempDir()
r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store)}
// artifacts= is a legacy setting (it used to attach files to ntfy) and is
// accepted without effect.
policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Artifacts: []string{"markdown"}}
for i, ntfyOn := range []bool{true, false} {
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: ntfyOn}); err != nil {
t.Fatal(err)
}
id, _, err := store.CreateRun(ctx, d, fmt.Sprintf("hook%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: "completed", Outcome: "success", Target: "two", Output: map[string]any{"markdown": "# Digest"}}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := len(captured())
r.notifyStep(id, d.Name, workspace, policy, step)
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != i+1 {
t.Fatalf("active = %+v %v", active, err)
}
n := active[i]
if n.ID != fmt.Sprintf("run:%d:1:success", id) || n.Kind != protocol.NotificationStageSucceeded || n.Click != fmt.Sprintf("pipelines://run/%d", id) {
t.Fatalf("hook notification = %+v", n)
}
got := captured()
if ntfyOn && (len(got) != before+1 || got[before].Title != n.Title || got[before].Message != n.Message || got[before].Click != n.Click) {
t.Fatalf("ntfy %+v vs stream %+v", got, n)
}
if !ntfyOn && len(got) != before {
t.Fatalf("ntfy published while disabled: %+v", got)
}
id, _, err := store.CreateRun(ctx, d, "hook", 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: "completed", Outcome: "success", Target: "two", Output: map[string]any{"markdown": "# Digest"}}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
r.notifyStep(id, d.Name, workspace, policy, step)
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != 1 {
t.Fatalf("active = %+v %v", active, err)
}
n := active[0]
if n.ID != fmt.Sprintf("run:%d:1:success", id) || n.Kind != protocol.NotificationStageSucceeded || n.Click != fmt.Sprintf("pipelines://run/%d", id) ||
n.Title != "Pipeline stage success" || !strings.Contains(n.Message, "stage one") {
t.Fatalf("hook notification = %+v", n)
}
detail, err := store.GetRun(ctx, id)
if err != nil || len(detail.Steps) != 1 || len(detail.Steps[0].Notifications) != 1 {
t.Fatalf("receipts = %+v %v", detail.Steps, err)
}
if receipt := detail.Steps[0].Notifications[0]; receipt.Destination != "app" || receipt.Status != "sent" || receipt.Filename != "" {
t.Fatalf("receipt = %+v", receipt)
}
}
-2
View File
@@ -58,7 +58,6 @@ func listActivity(t *testing.T, ctx context.Context, conn *websocket.Conn) *prot
// last one exits.
func TestChatActivityReachesEveryConnection(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, listedObservedChat{broker}, store)
@@ -113,7 +112,6 @@ func TestChatActivityReachesEveryConnection(t *testing.T) {
// invent completion. A terminal event releases it and clears list activity.
func TestChatBackgroundTaskWaitsForExitBeyondObserverTTL(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
limit := chatUnattendedTurnLimit
chatUnattendedTurnLimit = 300 * time.Millisecond
t.Cleanup(func() { chatUnattendedTurnLimit = limit })
+11 -27
View File
@@ -3,22 +3,17 @@ package server
import (
"context"
"net/url"
"os"
"strings"
"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"
)
// chatAttentionRetainedLimit bounds the hub-wide set of form/permission ids that
// already produced (or never deserve) an attention notification.
const chatAttentionRetainedLimit = 1024
// chatAttentionPublish is the publisher; tests may replace it.
var chatAttentionPublish = stage.PublishNtfy
// chatAttention is one pending operator-attention notification for a chat.
type chatAttention struct {
sessionID string
@@ -115,14 +110,10 @@ func (h *chatHub) notePermissionAttentionLocked(frame protocol.ChatPermissionFra
h.startChatAttention(chatAttention{sessionID: frame.SessionID, approval: true, body: body, id: chatNotificationID(frame.SessionID, "permission", frame.RequestID)})
}
func chatAttentionConfigured() bool {
return os.Getenv("PIPELINES_NTFY_URL") != ""
}
// attentionWanted reports whether a chat attention item has anywhere to go:
// the ntfy connection or the app notification stream.
// the app notification stream.
func (h *chatHub) attentionWanted() bool {
return chatAttentionConfigured() || h.notes != nil
return h.notes != nil
}
// clearChatAttention clears one chat app notification asynchronously, off the
@@ -145,9 +136,8 @@ func (h *chatHub) clearChatAttention(sessionID, id string) {
}()
}
// startChatAttention publishes asynchronously within the 30-second notification
// budget. It never blocks or fails chat handling; the phone push goes through
// the durable outbox, which retries a failed attempt.
// startChatAttention records the app notification asynchronously within the
// 30-second notification budget. It never blocks or fails chat handling.
func (h *chatHub) startChatAttention(a chatAttention) {
base := h.baseCtx
if base == nil {
@@ -176,7 +166,7 @@ func (h *chatHub) startChatAttention(a chatAttention) {
if a.reply {
title, body = chatReplyText(name, a.body)
}
click, _ := chatAttentionLinks(a.sessionID)
click := chatAttentionClick(a.sessionID)
kind := protocol.NotificationChatQuestion
if a.reply {
kind = protocol.NotificationChatReply
@@ -188,16 +178,11 @@ func (h *chatHub) startChatAttention(a chatAttention) {
Priority: protocol.DefaultNotificationPriority, Tags: []string{}, Group: "chat:" + a.sessionID},
SessionID: a.sessionID,
})
if !chatAttentionConfigured() || !settings.NtfyEnabled {
return
}
// ntfy takes a single-line message of at most 2048 bytes.
h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: a.id, SessionID: a.sessionID, Title: title, Body: truncateUTF8(singleLine(body), 2000), Click: click, SequenceID: chatNtfySequence(a.id)})
}()
}
// chatAttentionText builds a single-line ntfy title/body within PublishNtfy's
// limits.
// chatAttentionText builds a single-line notification title/body of bounded
// length.
func chatAttentionText(name string, approval bool, body string) (string, string) {
name = singleLine(name)
if name == "" {
@@ -215,9 +200,8 @@ func singleLine(text string) string {
return strings.Join(strings.Fields(strings.ReplaceAll(text, "\x00", "")), " ")
}
// chatAttentionLinks opens the chat in the app; the web origin, when
// configured, is offered as an "Open in browser" action.
func chatAttentionLinks(sessionID string) (string, []stage.NtfyView) {
escaped := url.PathEscape(sessionID)
return "pipelines://chat/" + escaped, webAttentionViews("/chat/" + escaped)
// chatAttentionClick is the notification tap target that opens the chat in
// the app.
func chatAttentionClick(sessionID string) string {
return "pipelines://chat/" + url.PathEscape(sessionID)
}
@@ -17,7 +17,6 @@ import (
// switch to.
func autoContinueServer(t *testing.T) (*refusingChat, *queueServer, *pipeline.Store) {
t.Helper()
capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
broker.quiet = true
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) {
+3 -7
View File
@@ -32,7 +32,7 @@ const (
chatAutoContinuePrefix = "auto-continue-"
// chatAutoSwitchClient is the sender label of the continue prompt.
chatAutoSwitchClient = "Pipelines (automatic)"
// chatAutoSwitchPriority is ntfy's "low" priority.
// chatAutoSwitchPriority is the notification stream's "low" priority.
chatAutoSwitchPriority = 2
// chatAutoSwitchRemembered bounds the refusals remembered as handled.
chatAutoSwitchRemembered = 256
@@ -280,7 +280,7 @@ func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sess
}
// publishAutoSwitchNotice tells the operator, at low priority, through the
// app notification stream and (when enabled) ntfy.
// app notification stream.
func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.UsageRefusal, name, email string) {
name = singleLine(name)
if name == "" {
@@ -288,7 +288,7 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us
}
title := truncateUTF8("Switched "+name+" to "+singleLine(email)+" and continued", 256)
message := "Claude usage ran out, so Pipelines switched the account and asked the agent to check it is on track before continuing."
click, _ := chatAttentionLinks(refusal.SessionID)
click := chatAttentionClick(refusal.SessionID)
id := "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal)
if h.notes != nil {
h.notes.record(ctx, pipeline.AppNotificationRecord{
@@ -297,8 +297,4 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us
SessionID: refusal.SessionID,
})
}
if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled {
return
}
h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: id, SessionID: refusal.SessionID, Title: title, Body: message, Click: click, Priority: chatAutoSwitchPriority})
}
+14 -19
View File
@@ -12,7 +12,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// refusingChat is a channelChat that reports usage refusals and switches
@@ -69,24 +68,21 @@ type publishedNotice struct {
priority int
}
func capturePublications(t *testing.T) func() []publishedNotice {
// autoSwitchNotices returns the auto-switch notices recorded on the app
// notification stream.
func autoSwitchNotices(t *testing.T, store *pipeline.Store) []publishedNotice {
t.Helper()
t.Setenv("PIPELINES_NTFY_URL", "https://ntfy.invalid/pipelines")
var mu sync.Mutex
active, _, err := store.ActiveAppNotifications(context.Background(), "", time.Now())
if err != nil {
t.Fatal(err)
}
var got []publishedNotice
previous := chatAttentionPublish
chatAttentionPublish = func(ctx context.Context, _, title, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
mu.Lock()
got = append(got, publishedNotice{title, stage.NtfyPriority(ctx)})
mu.Unlock()
return stage.Values{}, nil
}
t.Cleanup(func() { chatAttentionPublish = previous })
return func() []publishedNotice {
mu.Lock()
defer mu.Unlock()
return append([]publishedNotice(nil), got...)
for _, n := range active {
if strings.Contains(n.ID, ":auto-switch:") {
got = append(got, publishedNotice{n.Title, n.Priority})
}
}
return got
}
func autoSwitchServer(t *testing.T, sessions ...string) (*refusingChat, *queueServer, *pipeline.Store) {
@@ -109,8 +105,8 @@ func autoSwitchServer(t *testing.T, sessions ...string) (*refusingChat, *queueSe
// for the refusal is taken out, and a late one is refused. The operator is
// told at low priority.
func TestUsageRefusalSwitchesAccountAndQueuesAGuardedContinue(t *testing.T) {
published := capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
published := func() []publishedNotice { return autoSwitchNotices(t, store) }
conn := dialChatConn(t, server.ctx, server.srv)
if ack := sendPrompt(t, server.ctx, conn, "p1", "work", "op-1"); ack.ChatQueued {
t.Fatalf("first prompt queued: %+v", ack)
@@ -170,8 +166,8 @@ func TestUsageRefusalSwitchesAccountAndQueuesAGuardedContinue(t *testing.T) {
func TestUsageRefusalWithoutASwitchLeavesTheChat(t *testing.T) {
for _, failure := range []error{claude.ErrNoAccountLeft, claude.ErrAutoSwitchOff} {
t.Run(failure.Error(), func(t *testing.T) {
published := capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
published := func() []publishedNotice { return autoSwitchNotices(t, store) }
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) { return claude.AutoSwitch{}, failure }
conn := dialChatConn(t, server.ctx, server.srv)
if ack := sendScheduled(t, server.ctx, conn, "p1", "continue", "auto-continue-refusal-1", time.Now().Add(time.Hour)); !ack.ChatQueued {
@@ -191,7 +187,6 @@ func TestUsageRefusalWithoutASwitchLeavesTheChat(t *testing.T) {
// Chats refused together each get their own continue prompt; a chat that is
// not the operator's is left alone.
func TestConcurrentUsageRefusalsContinueEveryChat(t *testing.T) {
capturePublications(t)
broker, _, _ := autoSwitchServer(t, "ses_1", "ses_2")
broker.quiet = true
var once sync.Once
-1
View File
@@ -78,7 +78,6 @@ func restartChatDB(t *testing.T) string {
func fastReattach(t *testing.T) {
t.Helper()
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
poll := chatReattachPoll
chatReattachPoll = 20 * time.Millisecond
t.Cleanup(func() { chatReattachPoll = poll })
+2 -5
View File
@@ -46,14 +46,11 @@ type chatHub struct {
// to the other clients, so each retained user message has a stable id.
userSeq int
// attentionSeen/attentionOrder are the bounded hub-wide record of forms and
// approval requests already considered for an ntfy attention notification;
// attentionWG tracks in-flight publications.
// approval requests already considered for an attention notification;
// attentionWG tracks in-flight recordings.
attentionSeen map[string]struct{}
attentionOrder []string
attentionWG sync.WaitGroup
// outbox makes chat phone pushes durable and retried (chat_ntfy_outbox.go);
// nil publishes each push once, directly.
outbox chatNotificationOutbox
// notifiedTurns holds the chats whose current turn already sent an agent
// notify, so that turn's end is not announced again (one turn, one ping).
notifiedTurns map[string]struct{}
+1 -1
View File
@@ -26,7 +26,7 @@ import (
// pipeline stage session (created as a raw OpenCode session and recorded in
// run_steps/run_session_owners exactly as a run does) never appears in
// chat_sessions. It is opt-in (real inference) and never touches the deployed
// server, ntfy or any lane; it runs on a t.TempDir workspace.
// server or any lane; it runs on a t.TempDir workspace.
func TestChatLiveEndToEnd(t *testing.T) {
if os.Getenv("PIPELINES_TEST_OPENCODE_CHAT_LIVE") != "1" {
t.Skip("set PIPELINES_TEST_OPENCODE_CHAT_LIVE=1 to run the live OpenCode chat end-to-end check")
-1
View File
@@ -47,7 +47,6 @@ func (c *reportingChat) setRunning(running bool) {
func TestChatRunnerEndsItsTurnWhoseEndFrameWasLost(t *testing.T) {
fastUnattended(t)
fastStaleTurnSettle(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := &reportingChat{observedChat: newObservedChat()}
server := startQueueServer(t, broker, store)
+21 -58
View File
@@ -2,22 +2,18 @@ package server
import (
"context"
"sync"
"testing"
"time"
"github.com/coder/websocket"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// One turn, one ping: a turn that already sent an agent notify does not also
// announce its end, while a later turn without one does, and a notify sent
// after a turn ended (background work) does not silence the next turn.
func TestAgentNotifySuppressesThatTurnsReplyNotification(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
captured := newNtfyCapture(t)
store := newOperatorStore(t)
ctx := context.Background()
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
@@ -33,63 +29,50 @@ func TestAgentNotifySuppressesThatTurnsReplyNotification(t *testing.T) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
h.attentionWG.Wait()
}
kinds := func() []string {
t.Helper()
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil {
t.Fatal(err)
}
var got []string
for _, n := range active {
got = append(got, n.Kind+":"+n.Title)
}
return got
}
start("turn_1")
if got := h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n1", Title: "Halfway", Message: "Tests pass"}); !got.App || !got.Phone {
if got := h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n1", Title: "Halfway", Message: "Tests pass"}); !got.App {
t.Fatalf("delivery = %+v", got)
}
end("turn_1")
if got := captured(); len(got) != 1 || got[0].Title != "Halfway" {
t.Fatalf("turn with a notify published %+v", got)
}
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != 1 || active[0].Kind != protocol.NotificationChatNotify {
t.Fatalf("app notifications = %+v, %v", active, err)
if got := kinds(); len(got) != 1 || got[0] != protocol.NotificationChatNotify+":Halfway" {
t.Fatalf("turn with a notify recorded %+v", got)
}
// Background work notifies after the turn; the next turn still announces.
h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n2", Title: "Deploy done", Message: "Live"})
start("turn_2")
end("turn_2")
got := captured()
if len(got) != 3 || got[2].Title != "Chat replied" {
got := kinds()
if len(got) != 3 || got[2] != protocol.NotificationChatReply+":Chat replied" {
t.Fatalf("later deliveries = %+v", got)
}
}
// Every chat ntfy message carries a sequence id derived from its app id, and
// clearing the app notification (here: on another device) clears it in ntfy
// and pushes the clear to every other connected client.
func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
// Clearing a chat app notification on one device pushes the clear to every
// other connected client.
func TestClearingAChatNotificationClearsEveryClient(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var mu sync.Mutex
var published []string
originalPublish, originalClear := chatAttentionPublish, chatAttentionClear
chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
mu.Lock()
published = append(published, stage.NtfySequence(ctx))
mu.Unlock()
return stage.Values{"message_id": "m"}, nil
}
cleared := make(chan string, 8)
chatAttentionClear = func(_ context.Context, destination, sequence string) error {
if destination == "system" {
cleared <- sequence
}
return nil
}
defer func() { chatAttentionPublish, chatAttentionClear = originalPublish, originalClear }()
f := newAppNotificationFixture(t, ctx)
hub := f.handlerHub()
web, desktop, phone := dialAckClient(t, ctx, f.url), dialAckClient(t, ctx, f.url), dialAckClient(t, ctx, f.url)
subscribeNotifications(t, ctx, web, "")
subscribeNotifications(t, ctx, desktop, "")
subscribeNotifications(t, ctx, phone, "")
if got := hub.publishToolNotification(ctx, "ses_c", chatToolNotice{ID: "shown_c", Title: "Look", Message: "Now"}); !got.App || !got.Phone {
if got := hub.publishToolNotification(ctx, "ses_c", chatToolNotice{ID: "shown_c", Title: "Look", Message: "Now"}); !got.App {
t.Fatalf("delivery = %+v", got)
}
id := "chat:ses_c:notify:shown_c"
@@ -98,11 +81,6 @@ func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
t.Fatalf("push = %+v", push)
}
}
mu.Lock()
if len(published) != 1 || published[0] != chatNtfySequence(id) {
t.Fatalf("published sequences = %v", published)
}
mu.Unlock()
// Tapped on the phone: the phone gets the reply, every other client a push.
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ClearNotifications, ID: "tap", IDs: []string{id}})
@@ -114,19 +92,4 @@ func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
t.Fatalf("%s cleared push = %+v", name, push)
}
}
select {
case sequence := <-cleared:
if sequence != chatNtfySequence(id) {
t.Fatalf("ntfy cleared %q", sequence)
}
case <-ctx.Done():
t.Fatal("ntfy was not cleared")
}
}
func TestChatNtfySequenceIsAValidStableNtfyID(t *testing.T) {
a, b := chatNtfySequence("chat:ses_x:notify:abc"), chatNtfySequence("chat:ses_x:notify:abd")
if a != chatNtfySequence("chat:ses_x:notify:abc") || a == b || len(a) != 27 {
t.Fatalf("sequences %q %q", a, b)
}
}
-54
View File
@@ -1,54 +0,0 @@
package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"log"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// chatAttentionClear dismisses one ntfy message by sequence id; tests may
// replace it.
var chatAttentionClear = stage.ClearNtfy
// chatNtfySequence is the ntfy sequence id a chat notification (app id
// "chat:<session>:<what>:<id>") is published with, so clearing the app
// notification can also clear it in the ntfy app. It is derived from the app
// id, so nothing extra is stored and a restart still clears it.
func chatNtfySequence(id string) string {
digest := sha256.Sum256([]byte(id))
return "pl-" + hex.EncodeToString(digest[:12])
}
// clearChatNtfy asks ntfy to clear the chat notifications among ids (every
// app notification id that was cleared), off the caller's goroutine. ntfy
// emits message_clear and its clients dismiss the notification. Run
// notifications are published without a sequence id and are left alone.
func clearChatNtfy(ids []string) {
if !chatAttentionConfigured() {
return
}
var sequences []string
for _, id := range ids {
if strings.HasPrefix(id, "chat:") {
sequences = append(sequences, chatNtfySequence(id))
}
}
if len(sequences) == 0 {
return
}
clear := chatAttentionClear
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
for _, sequence := range sequences {
if err := clear(ctx, "system", sequence); err != nil {
log.Printf("clear ntfy notification %s: %v", sequence, err)
}
}
}()
}
-128
View File
@@ -1,128 +0,0 @@
package server
import (
"context"
"log"
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// Chat phone pushes (attention items and Claude auto-switch notices) go
// through a durable outbox like run notifications: the push is recorded first,
// one attempt is made at once, and a background worker retries a failed or
// interrupted attempt with backoff, also after a restart. A push whose app
// notification the operator already cleared is never published late, and a
// publication that raced a clear is cleared on the phone again, so the ntfy
// sequence-id/clear behaviour (chat_ntfy_clear.go) holds.
// chatNotificationOutbox is the durable chat push outbox; *pipeline.Store
// implements it.
type chatNotificationOutbox interface {
EnqueueChatNotification(ctx context.Context, n pipeline.ChatNotification, now time.Time) error
ClaimChatNotification(ctx context.Context, now int64) (*pipeline.ChatNotification, error)
FinishChatNotification(ctx context.Context, n pipeline.ChatNotification, now int64, messageID string, failure error) error
ChatNotificationCleared(ctx context.Context, id string) (bool, error)
Done() <-chan struct{}
}
// chatOutboxInterval is how often the worker looks for due retries.
var chatOutboxInterval = time.Second
// chatOutboxSkew shifts the outbox clock; tests move it past a backoff.
var chatOutboxSkew atomic.Int64
func chatOutboxNow() time.Time { return time.Now().Add(time.Duration(chatOutboxSkew.Load())) }
// startChatNotificationOutbox wires the durable outbox and starts its retry
// worker for the life of ctx.
func (h *chatHub) startChatNotificationOutbox(ctx context.Context, outbox chatNotificationOutbox) {
h.outbox = outbox
go func() {
ticker := time.NewTicker(chatOutboxInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-outbox.Done():
return
case <-ticker.C:
h.deliverChatNotifications(ctx, 16)
}
}
}()
}
// pushChatNtfy publishes one chat phone push. With an outbox it is recorded
// durably and attempted at once; without one (a store-less hub) it is a single
// direct attempt, as before.
func (h *chatHub) pushChatNtfy(ctx context.Context, n pipeline.ChatNotification) {
if h.outbox != nil {
err := h.outbox.EnqueueChatNotification(ctx, n, chatOutboxNow())
if err == nil {
h.deliverChatNotifications(ctx, 1)
return
}
log.Printf("enqueue chat notification %s: %v; publishing directly", n.ID, err)
}
if _, err := chatAttentionPublish(chatNtfyContext(ctx, n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(n)...); err != nil {
log.Printf("chat notification session=%s: %v", n.SessionID, err)
}
}
func chatNtfyContext(ctx context.Context, n pipeline.ChatNotification) context.Context {
if n.SequenceID != "" {
ctx = stage.WithNtfySequenceID(ctx, n.SequenceID)
}
if n.Priority > 0 {
ctx = stage.WithNtfyPriority(ctx, n.Priority)
}
return ctx
}
// chatNtfyViews derives the push's actions at delivery, so a changed web
// origin applies to a retried push.
func chatNtfyViews(n pipeline.ChatNotification) []stage.NtfyView {
_, views := chatAttentionLinks(n.SessionID)
return views
}
// deliverChatNotifications attempts up to limit due pushes.
func (h *chatHub) deliverChatNotifications(ctx context.Context, limit int) {
outbox := h.outbox
if outbox == nil {
return
}
for i := 0; i < limit && ctx.Err() == nil; i++ {
n, err := outbox.ClaimChatNotification(ctx, chatOutboxNow().Unix())
if err != nil {
log.Printf("claim chat notification: %v", err)
return
}
if n == nil {
return
}
publish, cancel := context.WithTimeout(ctx, 30*time.Second)
result, publishErr := chatAttentionPublish(chatNtfyContext(publish, *n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(*n)...)
cancel()
if publishErr != nil {
log.Printf("chat notification session=%s attempt=%d: %v", n.SessionID, n.Attempts, publishErr)
}
messageID, _ := result["message_id"].(string)
save, done := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
if err := outbox.FinishChatNotification(save, *n, chatOutboxNow().Unix(), messageID, publishErr); err != nil {
log.Printf("save chat notification %s: %v", n.ID, err)
}
// The operator may have cleared it in the app while it was being
// published, after the clear went to ntfy: clear it there again.
if publishErr == nil && n.SequenceID != "" {
if cleared, err := outbox.ChatNotificationCleared(save, n.ID); err == nil && cleared {
clearChatNtfy([]string{n.ID})
}
}
done()
}
}
-61
View File
@@ -1,61 +0,0 @@
package server
import (
"context"
"errors"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// A chat attention push that ntfy refuses is kept in the durable outbox and
// retried by the worker with its sequence id, not lost after one attempt.
func TestChatAttentionPushIsRetriedFromTheOutbox(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
interval := chatOutboxInterval
chatOutboxInterval = 20 * time.Millisecond
defer func() { chatOutboxInterval = interval }()
var mu sync.Mutex
var sequences []string
original := chatAttentionPublish
chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
mu.Lock()
defer mu.Unlock()
sequences = append(sequences, stage.NtfySequence(ctx))
if len(sequences) == 1 {
return nil, errors.New("ntfy unavailable")
}
return stage.Values{"message_id": "m1"}, nil
}
defer func() { chatAttentionPublish = original }()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
h := chatAttentionHub(t, "ses_a")
h.settings = store
h.notes = newAppNotifier(store)
h.startChatNotificationOutbox(ctx, store)
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_a", Kind: "question", Title: "Ship it?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_a", Kind: protocol.ChatEventForm, Form: &form})
h.attentionWG.Wait()
id := "chat:ses_a:form:que_1"
if status, attempts, err := store.ChatNotificationStatus(ctx, id); err != nil || status != "pending" || attempts != 1 {
t.Fatalf("after a refused attempt: %s/%d %v", status, attempts, err)
}
// The first backoff is 5 s; move the outbox clock past it.
chatOutboxSkew.Store(int64(10 * time.Second))
defer chatOutboxSkew.Store(0)
waitFor(t, "retried push sent", func() bool {
status, _, _ := store.ChatNotificationStatus(ctx, id)
return status == "sent"
})
mu.Lock()
defer mu.Unlock()
if len(sequences) != 2 || sequences[0] != chatNtfySequence(id) || sequences[1] != sequences[0] {
t.Fatalf("sequence ids = %v", sequences)
}
}
-1
View File
@@ -89,7 +89,6 @@ func TestChatPromptBehindAnUnqueuedScheduledHeadRunsAfterRestart(t *testing.T) {
func TestChatQueueEndsAStaleObservedTurnOnceTheHarnessIsIdle(t *testing.T) {
fastUnattended(t)
fastStaleTurnSettle(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := newObservedChat()
server := startQueueServer(t, broker, store)
+1 -2
View File
@@ -130,8 +130,7 @@ func truncateRunes(text string, limit int) string {
}
// chatReplyText builds a finished reply's title and body. The body keeps the
// reply's paragraph breaks for the app's notifications; ntfy gets it on one
// line (see chatAttentionPublishBody).
// reply's paragraph breaks for the app's notifications.
func chatReplyText(name, body string) (string, string) {
name = singleLine(name)
if name == "" {
@@ -15,10 +15,6 @@ func TestReplyNotificationKeepsParagraphs(t *testing.T) {
if body != "One\n\nTwo" {
t.Fatalf("app body should keep paragraph breaks, got %q", body)
}
// ntfy gets the same text on one line.
if flat := singleLine(body); strings.Contains(flat, "\n") || flat != "One Two" {
t.Fatalf("ntfy body = %q", flat)
}
long := truncateRunes(strings.Repeat("a", 1500), chatReplyBodyRunes)
if n := utf8.RuneCountInString(long); n != chatReplyBodyRunes+1 || chatReplyBodyRunes != 1000 {
t.Fatalf("excerpt is %d runes (limit %d)", n, chatReplyBodyRunes)
+11 -24
View File
@@ -6,7 +6,6 @@ import (
"encoding/hex"
"errors"
"io"
"log"
"mime"
"net/http"
"net/url"
@@ -16,7 +15,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// shownFile is a resolved file inside the operator's home.
@@ -135,19 +133,17 @@ type chatToolNotice struct {
// chatToolDelivery reports where a chat tool notification went: App when it
// was recorded on the app notification stream (every connected Pipelines app
// receives it and a reconnecting one replays it), Phone when ntfy accepted it.
// Detail explains a phone delivery that was skipped or refused.
// receives it and a reconnecting one replays it). Detail explains a failure.
type chatToolDelivery struct {
App bool
Phone bool
Detail string
}
// chatToolNotifier delivers one model-requested notification for a chat.
type chatToolNotifier func(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery
// chatNotifyPriority maps the tool's priority word to the app stream's
// ntfy-style 1-5 priority.
// chatNotifyPriority maps the tool's priority word to the app stream's 1-5
// priority (3 is the default).
func chatNotifyPriority(priority string) int {
switch priority {
case "low":
@@ -160,14 +156,12 @@ func chatNotifyPriority(priority string) int {
// publishToolNotification records the notification on the app notification
// stream (kind chat_notify), which is pushed to every subscribed client and
// replayed to one that reconnects while it is still active, then publishes it
// through the operator's existing "system" ntfy destination (the one chat
// attention uses), honoring their ntfy switch. Tapping it opens the chat
// (pipelines://chat/<id>).
// replayed to one that reconnects while it is still active. Tapping it opens
// the chat (pipelines://chat/<id>).
func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
title := truncateUTF8(notice.Title, 256)
message := truncateUTF8(notice.Message, 2000)
click, views := chatAttentionLinks(sessionID)
click := chatAttentionClick(sessionID)
id := notice.ID
if id == "" {
digest := sha256.Sum256([]byte(title + "\x00" + message))
@@ -182,19 +176,12 @@ func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string,
})
}
switch {
case !chatAttentionConfigured():
delivery.Detail = "phone notifications (ntfy) are not configured"
case !chatNotificationSettings(ctx, h.settings).NtfyEnabled:
delivery.Detail = "phone notifications (ntfy) are turned off"
default:
if _, err := chatAttentionPublish(stage.WithNtfySequenceID(ctx, chatNtfySequence(appID)), "system", title, message, "", nil, click, views...); err != nil {
log.Printf("chat tool notification session=%s: %v", sessionID, err)
delivery.Detail = "the phone notification service refused it: " + err.Error()
} else {
delivery.Phone = true
}
case h.notes == nil:
delivery.Detail = "the app notification stream is not available"
case !delivery.App:
delivery.Detail = "the notification could not be recorded"
}
if delivery.App || delivery.Phone {
if delivery.App {
// This turn has pinged the operator; its end is not announced again.
h.markTurnNotified(sessionID)
}
+2 -12
View File
@@ -169,20 +169,10 @@ func (s *chatToolService) runNotify(ctx context.Context, sessionID, title, messa
}
id := newChatShownID()
delivery := s.notify(ctx, sessionID, chatToolNotice{ID: id, Title: title, Message: message, Priority: priority})
item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App || delivery.Phone, Detail: delivery.Detail}
item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App, Detail: delivery.Detail}
if delivery.App {
item.Channels = append(item.Channels, "apps")
}
if delivery.Phone {
item.Channels = append(item.Channels, "phone")
}
switch {
case delivery.App && delivery.Phone:
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps and phone notifications."}
case delivery.App:
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps; " + delivery.Detail + "."}
case delivery.Phone:
return &item, chattools.Result{Text: "Delivered to the operator's phone notifications."}
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps."}
}
return &item, chattools.Result{Text: "Not delivered: " + delivery.Detail + ".", IsError: true}
}
+9 -9
View File
@@ -38,7 +38,7 @@ func newChatToolFixture(t *testing.T) *chatToolFixture {
}
f.service.notify = func(_ context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
f.notified = append(f.notified, sessionID+": "+notice.Title)
return chatToolDelivery{App: true, Phone: true}
return chatToolDelivery{App: true}
}
return f
}
@@ -240,7 +240,7 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
f.service.now = func() time.Time { return now }
for i := range 5 {
if r := f.call(a, "notify", `{"title":"Done","message":"Build finished","priority":"high"}`); r.IsError ||
r.Text != "Delivered to the operator's Pipelines apps and phone notifications." {
r.Text != "Delivered to the operator's Pipelines apps." {
t.Fatalf("notification %d: %v", i, r)
}
}
@@ -261,30 +261,30 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
t.Fatalf("notified = %v", f.notified)
}
got := f.items(t, "ses_n1")
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" || strings.Join(got[0].Channels, ",") != "apps,phone" {
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" || strings.Join(got[0].Channels, ",") != "apps" {
t.Fatalf("items = %+v", got)
}
f.service.notify = func(context.Context, string, chatToolNotice) chatToolDelivery {
return chatToolDelivery{Detail: "ntfy is not configured"}
return chatToolDelivery{Detail: "the notification could not be recorded"}
}
r := f.call(b, "notify", `{"title":"Fails","message":"x"}`)
if !r.IsError || !strings.Contains(r.Text, "ntfy is not configured") {
if !r.IsError || !strings.Contains(r.Text, "the notification could not be recorded") {
t.Fatalf("an undelivered notification is reported: %v", r)
}
if last := f.items(t, "ses_n2"); len(last) != 2 || last[1].Delivered || last[1].Detail != "ntfy is not configured" {
if last := f.items(t, "ses_n2"); len(last) != 2 || last[1].Delivered || last[1].Detail != "the notification could not be recorded" {
t.Fatalf("the undelivered entry is recorded: %+v", last)
}
// Apps only (ntfy off): the agent is told where it went.
// Delivered: the agent is told where it went.
f.service.notify = func(_ context.Context, _ string, notice chatToolNotice) chatToolDelivery {
if !strings.HasPrefix(notice.ID, "shown_") || notice.Priority != "low" {
t.Errorf("notice = %+v", notice)
}
return chatToolDelivery{App: true, Detail: "phone notifications (ntfy) are turned off"}
return chatToolDelivery{App: true}
}
r = f.call(b, "notify", `{"title":"Apps","message":"x","priority":"low"}`)
if r.IsError || r.Text != "Delivered to the operator's Pipelines apps; phone notifications (ntfy) are turned off." {
if r.IsError || r.Text != "Delivered to the operator's Pipelines apps." {
t.Fatalf("apps-only result: %v", r)
}
if last := f.items(t, "ses_n2"); len(last) != 3 || !last[2].Delivered || !strings.HasPrefix(last[2].ID, "shown_") || strings.Join(last[2].Channels, ",") != "apps" {
+28 -14
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"path/filepath"
"strings"
"sync"
"testing"
"time"
@@ -105,6 +106,28 @@ func chatNotes(t *testing.T, store *pipeline.Store, kind string) []protocol.AppN
return out
}
// chatNoteTotal counts every chat notification ever recorded, active or
// cleared.
func chatNoteTotal(t *testing.T, store *pipeline.Store) int {
t.Helper()
active, cleared, err := store.ActiveAppNotifications(context.Background(), "", time.Now())
if err != nil {
t.Fatal(err)
}
total := 0
for _, n := range active {
if strings.HasPrefix(n.ID, "chat:") {
total++
}
}
for _, id := range cleared {
if strings.HasPrefix(id, "chat:") {
total++
}
}
return total
}
func stepFrameFor(status, turn string) protocol.ChatEventFrame {
return protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: status, TurnID: turn}}
}
@@ -114,11 +137,10 @@ func textFrame(text string) protocol.ChatEventFrame {
}
// A turn started from the app keeps being observed after the app closes, so
// its finished reply is recorded (app stream) and published (ntfy) once, and
// its finished reply is recorded on the app stream once, and
// the observer is torn down when the turn ends.
func TestChatReplyNotifiesAfterLastClientLeaves(t *testing.T) {
fastUnattended(t)
captured := newNtfyCapture(t)
store := unattendedStore(t, true)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -135,11 +157,10 @@ func TestChatReplyNotifiesAfterLastClientLeaves(t *testing.T) {
broker.push(stepFrameFor(protocol.ChatStepEnded, "turn_1"))
waitFor(t, "reply notification", func() bool { return len(chatNotes(t, store, protocol.NotificationChatReply)) == 1 })
waitFor(t, "observer torn down", func() bool { active, _ := broker.streams(); return active == 0 })
waitFor(t, "ntfy publish", func() bool { return len(captured()) == 1 })
time.Sleep(50 * time.Millisecond)
notes := chatNotes(t, store, protocol.NotificationChatReply)
if got := captured(); len(notes) != 1 || len(got) != 1 || got[0].Title != "Release prep replied" || got[0].Message != "The build is green." {
t.Fatalf("notes=%+v ntfy=%+v", notes, got)
if len(notes) != 1 || notes[0].Title != "Release prep replied" || chatNoteTotal(t, store) != 1 {
t.Fatalf("notes=%+v", notes)
}
if notes[0].Message != "The build is green." || notes[0].Click != "pipelines://chat/ses_1" {
t.Fatalf("note = %+v", notes[0])
@@ -150,7 +171,6 @@ func TestChatReplyNotifiesAfterLastClientLeaves(t *testing.T) {
// nothing, even though the unattended turn is observed.
func TestChatUnattendedReplyRespectsSetting(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -170,7 +190,6 @@ func TestChatUnattendedReplyRespectsSetting(t *testing.T) {
// A question the agent asks while no client is attached notifies.
func TestChatQuestionNotifiesWithNoClient(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -196,7 +215,6 @@ func TestChatQuestionNotifiesWithNoClient(t *testing.T) {
// announced exactly once and the client sees the turn end.
func TestChatReattachMidTurnDoesNotDuplicate(t *testing.T) {
fastUnattended(t)
captured := newNtfyCapture(t)
store := unattendedStore(t, true)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -227,8 +245,8 @@ func TestChatReattachMidTurnDoesNotDuplicate(t *testing.T) {
}
waitFor(t, "reply notification", func() bool { return len(chatNotes(t, store, protocol.NotificationChatReply)) == 1 })
time.Sleep(100 * time.Millisecond)
if got := captured(); len(got) != 2 {
t.Fatalf("ntfy deliveries = %+v, want one question and one reply", got)
if got := chatNoteTotal(t, store); got != 2 {
t.Fatalf("recorded notifications = %d, want one question and one reply", got)
}
if n := len(chatNotes(t, store, protocol.NotificationChatQuestion)) + len(chatNotes(t, store, protocol.NotificationChatReply)); n > 2 {
t.Fatalf("duplicate notifications: %d", n)
@@ -242,7 +260,6 @@ func TestChatReattachMidTurnDoesNotDuplicate(t *testing.T) {
// start does not observe sessions whose harness reports no running turn.
func TestChatIdleSessionWithNoClientIsNotObserved(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, true)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -266,7 +283,6 @@ func TestChatIdleSessionWithNoClientIsNotObserved(t *testing.T) {
// with no client, so its reply still notifies; then the observer goes away.
func TestChatRunningTurnObservedAfterRestart(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, true)
broker := newObservedChat()
broker.probe["ses_1"] = true
@@ -284,7 +300,6 @@ func TestChatRunningTurnObservedAfterRestart(t *testing.T) {
// a later authoritative idle result releases it.
func TestChatRecoveredBusySessionWaitsForAuthoritativeIdle(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, true)
broker := newObservedChat()
broker.probe["ses_1"] = true
@@ -303,7 +318,6 @@ func TestChatRecoveredBusySessionWaitsForAuthoritativeIdle(t *testing.T) {
// A turn that never reports its end does not hold an observer forever.
func TestChatStuckUnattendedTurnIsReleased(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
limit := chatUnattendedTurnLimit
chatUnattendedTurnLimit = 300 * time.Millisecond
t.Cleanup(func() { chatUnattendedTurnLimit = limit })
+4 -19
View File
@@ -2,14 +2,10 @@ package server
import (
"context"
"encoding/json"
"fmt"
"mime"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -386,19 +382,6 @@ func TestHumanStageWaitingNotification(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
filename, _ := new(mime.WordDecoder).DecodeHeader(r.Header.Get("Filename"))
ack := map[string]any{"id": "msg1", "event": "message"}
if filename != "" {
ack["attachment"] = map[string]string{"name": filename, "url": "https://ntfy.example.com/file/" + filename}
}
_ = json.NewEncoder(w).Encode(ack)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
source := strings.Replace(humanPipelineSource, "```configs\ntype=human\n```", "```notify\non=waiting\n```\n\n```configs\ntype=human\n```", 1)
if _, err := store.Submit(ctx, "human-notify", source); err != nil {
t.Fatal(err)
@@ -414,14 +397,16 @@ func TestHumanStageWaitingNotification(t *testing.T) {
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
defer r.wg.Wait()
run, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "human-notify", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if calls.Load() != 1 {
t.Fatalf("waiting notification fired %d times", calls.Load())
if got := recorder.recorded(); len(got) != 1 || got[0].Kind != protocol.NotificationRunWaiting {
t.Fatalf("waiting notification fired %d times: %+v", len(got), got)
}
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
+4 -4
View File
@@ -5,11 +5,11 @@ import (
"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.
// TestMain isolates the package from the operator's environment: a developer
// shell may export the installed server's web origin, which tests must not
// pick up.
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"} {
for _, name := range []string{"PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
+40 -10
View File
@@ -89,8 +89,34 @@ func TestNotificationSettingsProtocol(t *testing.T) {
wantSettings(t, replies[0], updated)
}
// ntfy was removed. An older app may still send its "also send to ntfy"
// switch, alone or beside a real setting: the key is accepted and ignored,
// and every reply carries exactly the three notification settings.
func TestLegacyNtfySettingIsAcceptedAndIgnored(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.SetNotificationSettings, ID: "ntfy", NotificationSettings: map[string]any{protocol.LegacyNotifyNtfyEnabled: false}},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "mixed", NotificationSettings: map[string]any{protocol.LegacyNotifyNtfyEnabled: true, protocol.NotifyRunFinished: true}},
protocol.Message{Type: protocol.GetNotificationSettings, ID: "get"},
)
want := protocol.DefaultNotificationSettings()
wantSettings(t, replies[0], want)
want.RunFinished = true
wantSettings(t, replies[1], want)
wantSettings(t, replies[2], want)
for _, reply := range replies {
if len(reply.NotificationSettings) != 3 {
t.Fatalf("reply carries %d settings: %+v", len(reply.NotificationSettings), reply)
}
if _, present := reply.NotificationSettings[protocol.LegacyNotifyNtfyEnabled]; present {
t.Fatalf("reply still carries ntfy_enabled: %+v", reply)
}
}
}
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)
@@ -98,6 +124,9 @@ func TestChatNeedsYouSettingSuppressesQuestionsAndApprovals(t *testing.T) {
h := chatAttentionHub(t, "ses_quiet")
h.registry = store
h.settings = store
notes, recorder := newNoteCapture(t, store)
h.notes = notes
captured := recorder.recorded
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?"})
@@ -127,8 +156,6 @@ func replyTurn(h *chatHub, session, turnID, messageID, text string) {
}
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 {
@@ -137,6 +164,9 @@ func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
h := chatAttentionHub(t, "ses_done", "ses_bare")
h.registry = store
h.settings = store
notes, recorder := newNoteCapture(t, store)
h.notes = notes
captured := recorder.recorded
// Off by default: a finished turn is silent.
replyTurn(h, "ses_done", "turn_0", "msg_0", "Quiet reply")
h.attentionWG.Wait()
@@ -162,10 +192,9 @@ func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
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)
if n := got[0]; n.Title != "Release prep replied" || n.Click != "pipelines://chat/ses_done" || n.Kind != protocol.NotificationChatReply ||
!strings.HasPrefix(n.Message, "The build\nis green. xxx") {
t.Fatalf("got %+v", n)
}
// The next genuine turn notifies again; a turn without text (and a
// session without a title or native turn ids) uses the fallback text.
@@ -186,8 +215,9 @@ func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
}
}
func TestChatReplyFinishedNeedsNtfyConfiguration(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
// Without the app notification stream a finished turn has nowhere to go and
// is not even considered.
func TestChatReplyFinishedNeedsTheAppStream(t *testing.T) {
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
t.Fatal(err)
@@ -199,6 +229,6 @@ func TestChatReplyFinishedNeedsNtfyConfiguration(t *testing.T) {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.attentionSeen) != 0 {
t.Fatalf("unconfigured ntfy still considered a publication: %v", h.attentionSeen)
t.Fatalf("a stream-less hub still considered a notification: %v", h.attentionSeen)
}
}
-31
View File
@@ -1,31 +0,0 @@
package server
import (
"git.a-wan.net/alan/pipelines/internal/protocol"
"net/url"
"os"
"regexp"
"strings"
)
var notificationTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
func publicNtfyBase(text string) string {
u, err := url.Parse(text)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
return ""
}
return strings.TrimRight(u.String(), "/")
}
func notificationEndpoints() []protocol.NotificationEndpoint {
u, err := url.Parse(os.Getenv("PIPELINES_NTFY_URL"))
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.RawPath != "" {
return nil
}
topic := strings.TrimPrefix(u.Path, "/")
if !notificationTopic.MatchString(topic) {
return nil
}
return []protocol.NotificationEndpoint{{Destination: "system", ServerURL: publicNtfyBase(os.Getenv("PIPELINES_NTFY_PUBLIC_URL")), Topic: topic}}
}
@@ -1,34 +0,0 @@
package server
import (
"testing"
)
func TestPublicNotificationSetup(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "private-token")
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "http://10.0.0.249:8090")
found := false
for _, endpoint := range notificationEndpoints() {
if endpoint.Destination == "system" {
found = true
if endpoint.ServerURL != "http://10.0.0.249:8090" || endpoint.Topic != "pipelines" {
t.Fatal(endpoint)
}
}
}
if !found {
t.Fatal("missing destination")
}
for _, value := range []string{"http://user:secret@example.com", "http://example.com?token=secret", "file:///tmp/secret", "http://example.com/topic"} {
if publicNtfyBase(value) != "" {
t.Fatal("unsafe public URL accepted", value)
}
}
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "")
for _, endpoint := range notificationEndpoints() {
if endpoint.ServerURL != "" {
t.Fatal("internal URL exposed", endpoint)
}
}
}
+116 -143
View File
@@ -2,136 +2,117 @@ package server
import (
"context"
"encoding/json"
"mime"
"net/http"
"net/http/httptest"
"errors"
"path/filepath"
"strings"
"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)
}
})
func TestRunNotificationAppClick(t *testing.T) {
if got := runAttentionClick(20); got != "pipelines://run/20" {
t.Fatalf("click = %q", got)
}
if got := chatAttentionClick("ses/x"); got != "pipelines://chat/ses%2Fx" {
t.Fatalf("chat click = %q", got)
}
}
type ntfyCapture struct {
Title, Message, Click, Actions string
// recordingNotes wraps an app notification store and keeps every newly
// recorded notification, in order, so a test sees exactly what the app stream
// was given (also after a clear). fail makes every record fail, failNext the
// next few; calls counts every attempt, failed or not.
type recordingNotes struct {
appNotificationStore
mu sync.Mutex
got []protocol.AppNotification
fail bool
failNext int
calls int
}
// newNtfyCapture points the system destination at a mock ntfy endpoint.
func newNtfyCapture(t *testing.T) func() []ntfyCapture {
func (r *recordingNotes) RecordAppNotification(ctx context.Context, n pipeline.AppNotificationRecord, now time.Time) (protocol.AppNotification, bool, error) {
r.mu.Lock()
r.calls++
fail := r.fail || r.failNext > 0
if r.failNext > 0 {
r.failNext--
}
r.mu.Unlock()
if fail {
return protocol.AppNotification{}, false, errors.New("record refused")
}
stored, fresh, err := r.appNotificationStore.RecordAppNotification(ctx, n, now)
if err == nil && fresh {
r.mu.Lock()
r.got = append(r.got, stored)
r.mu.Unlock()
}
return stored, fresh, err
}
func (r *recordingNotes) attempts() int {
r.mu.Lock()
defer r.mu.Unlock()
return r.calls
}
func (r *recordingNotes) recorded() []protocol.AppNotification {
r.mu.Lock()
defer r.mu.Unlock()
return append([]protocol.AppNotification(nil), r.got...)
}
// newNoteCapture returns an app notifier over store (a scratch store when
// nil) and a reader of everything it recorded.
func newNoteCapture(t *testing.T, store *pipeline.Store) (*appNotifier, *recordingNotes) {
t.Helper()
var mu sync.Mutex
var got []ntfyCapture
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/clear") {
// A cleared chat notification's ntfy clear, not a delivery.
_ = json.NewEncoder(w).Encode(map[string]string{"id": "clr", "event": "message_clear"})
return
}
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...)
if store == nil {
store = newOperatorStore(t)
}
recorder := &recordingNotes{appNotificationStore: store}
return newAppNotifier(recorder), recorder
}
// 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.
// an empty click (an invalid web origin). Each is recorded with the app link.
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)
}
}
})
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)
}
}
notes, recorder := newNoteCapture(t, s)
r := &runner{ctx: ctx, store: s, notes: notes}
r.deliverRunNotifications(time.Now())
got := recorder.recorded()
if len(got) != 3 {
t.Fatalf("deliveries = %+v", got)
}
seen := map[string]bool{}
for _, n := range got {
seen[n.Click] = true
}
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)
}
}
}
@@ -145,14 +126,14 @@ func chatAttentionHub(t *testing.T, sessions ...string) *chatHub {
}
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
notes, recorder := newNoteCapture(t, store)
h.notes = notes
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)
@@ -163,27 +144,27 @@ func TestChatQuestionNotifiesOnceWithAppLink(t *testing.T) {
h.mu.Unlock()
h.emit(frame)
h.attentionWG.Wait()
got := captured()
got := recorder.recorded()
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)
if n := got[0]; n.Title != "Release prep needs your answer" || n.Message != "Which branch should ship?" || n.Click != "pipelines://chat/ses_q" {
t.Fatalf("got %+v", n)
}
// Resolution and a later stale copy publish nothing more.
// Resolution and a later stale copy record 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)
if n := len(recorder.recorded()); n != 1 {
t.Fatalf("resolution re-recorded: %d", n)
}
}
func TestChatResolvedOrReplayedFormsDoNotNotify(t *testing.T) {
captured := newNtfyCapture(t)
h := chatAttentionHub(t, "ses_r")
notes, recorder := newNoteCapture(t, nil)
h.notes = notes
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})
@@ -196,14 +177,15 @@ func TestChatResolvedOrReplayedFormsDoNotNotify(t *testing.T) {
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 {
if got := recorder.recorded(); 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")
notes, recorder := newNoteCapture(t, nil)
h.notes = notes
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)
@@ -215,40 +197,31 @@ func TestChatPermissionNotifiesOnce(t *testing.T) {
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)
got := recorder.recorded()
if len(got) != 1 || got[0].Title != "Chat needs your approval" || got[0].Message != "Run rm -rf build?" || got[0].Click != "pipelines://chat/ses_p" {
t.Fatalf("deliveries = %+v", got)
}
}
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 }()
// Without the app notification stream a chat attention item has nowhere to
// go, so it is not even claimed.
func TestChatAttentionNeedsTheAppStream(t *testing.T) {
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)
if len(h.attentionSeen) != 0 {
t.Fatalf("claimed without a notification stream: %v", h.attentionSeen)
}
}
// A failing ntfy endpoint never blocks or fails chat handling.
// A failing notification store 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")
notes, recorder := newNoteCapture(t, nil)
recorder.fail = true
h.notes = notes
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()
+31 -218
View File
@@ -5,7 +5,6 @@ import (
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"log"
"mime"
@@ -16,7 +15,6 @@ import (
"path/filepath"
"regexp"
"strings"
"syscall"
"time"
"unicode/utf8"
)
@@ -62,149 +60,41 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
summary := stageNotificationSummary(name, id, step.Stage, event, step.Outcome)
summary = truncateUTF8(summary, 1800)
title := fmt.Sprintf("Pipeline stage %s", event)
receipts := []protocol.NotificationReceipt{}
persist := func() bool {
save, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := r.store.SaveNotifications(save, id, step.Sequence, receipts); err != nil {
log.Printf("notification audit run=%d step=%d: %v", id, step.Sequence, err)
return false
}
return true
}
// The app stream gets one notification per step event, recorded before
// the first ntfy publication; artifacts stay ntfy attachments.
// The app stream gets one notification per step event.
appEvent, appKind := stageNotification(event, step.Target)
// A `link=` file decides the tap target; it is never the attached artifact.
link, linkFile, linkDiagnostic := r.resolveNotificationLink(id, policy.Link)
appArtifact, appPreview := r.resolveNotificationArtifact(id, step.Sequence, policy.Open, linkFile)
recorded := false
ntfyOn := ntfyEnabled(ctx, r.settingsStore())
views := runAttentionViews(id)
ntfyClick, linkNote := ntfyLinkClick(id, link, views)
if ntfyOn && linkDiagnostic == "" {
linkDiagnostic = linkNote
}
send := func(filename string, data []byte) {
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "sending", Filename: filename})
if !persist() {
return
receipt := protocol.NotificationReceipt{Destination: "app", Status: "sent", Diagnostic: linkDiagnostic}
if !r.notes.record(ctx, withNotificationLink(runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview), link)) {
receipt.Status = "failed"
if receipt.Diagnostic != "" {
receipt.Diagnostic += "; "
}
receipt := &receipts[len(receipts)-1]
if !recorded {
recorded = true
r.notes.record(ctx, withNotificationLink(runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview), link))
}
if !ntfyOn {
receipt.Status = "sent"
receipt.Diagnostic = "ntfy disabled; delivered to app clients only"
persist()
return
}
result, err := ntfyPublish(ctx, "system", title, summary, filename, data, ntfyClick, views...)
if err != nil {
receipt.Status = "failed"
receipt.Diagnostic = err.Error()
} else {
receipt.Status = "sent"
receipt.MessageID, _ = result["message_id"].(string)
receipt.AttachmentURL, _ = result["attachment_url"].(string)
}
persist()
}
reject := func(filename, diagnostic string) {
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "failed", Filename: filename, Diagnostic: diagnostic})
persist()
}
sentArtifact := false
for _, kind := range policy.Artifacts {
switch kind {
case "markdown":
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
sentArtifact = true
send("digest.md", []byte(markdown))
}
case "files":
raw, exists := step.Output["artifacts"]
if !exists {
continue
}
var names []string
switch files := raw.(type) {
case []string:
names = files
case []any:
for _, value := range files {
name, ok := value.(string)
if !ok {
reject("", "output.artifacts must be an array of relative file paths")
names = nil
break
}
names = append(names, name)
}
default:
reject("", "output.artifacts must be an array of relative file paths")
}
if len(names) > 10 {
reject("", "at most 10 file artifacts can be notified")
continue
}
seen := map[string]bool{}
for _, name := range names {
if seen[name] {
continue
}
seen[name] = true
data, err := notificationArtifact(workspace, name)
if err != nil {
reject(name, err.Error())
continue
}
sentArtifact = true
send(filepath.Base(name), data)
}
}
}
// No produced artifacts still merits an event, especially on failures.
if !sentArtifact {
send("", nil)
}
// The link note is recorded once, never as the run-level failure reason.
failure := "stage notification publication failed"
if len(receipts) > 0 && receipts[0].Diagnostic != "" {
failure = receipts[0].Diagnostic
}
if linkDiagnostic != "" && len(receipts) > 0 {
first := &receipts[0]
if first.Diagnostic != "" {
first.Diagnostic += "; "
}
first.Diagnostic += linkDiagnostic
persist()
}
// Only a successful publish covers the run alert. A failed stage publisher
// must not swallow the durable run-level fallback and its retries.
for _, receipt := range receipts {
if receipt.Status == "sent" {
covered := stageAttentionEvent(event)
if event == "success" && step.Target == protocol.SuccessEnd {
covered = "succeeded"
}
r.markAttentionSent(id, step.Sequence, covered)
return
receipt.Diagnostic += "the app notification was not recorded"
}
save, done := context.WithTimeout(context.Background(), 5*time.Second)
if err := r.store.SaveNotifications(save, id, step.Sequence, []protocol.NotificationReceipt{receipt}); err != nil {
log.Printf("notification audit run=%d step=%d: %v", id, step.Sequence, err)
}
done()
if receipt.Status == "sent" {
covered := stageAttentionEvent(event)
if event == "success" && step.Target == protocol.SuccessEnd {
covered = "succeeded"
}
r.markAttentionSent(id, step.Sequence, covered)
return
}
// A hook that recorded nothing must not swallow the durable run-level
// fallback and its retries.
if lease != nil {
if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("%s", failure)); err != nil {
if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("stage notification was not recorded")); err != nil {
log.Printf("release stage notification run=%d: %v", id, err)
}
}
}
// ntfyPublish is the run notification publisher; tests may replace it.
var ntfyPublish = stage.PublishNtfy
// stageNotification maps a stage hook event to the app notification event
// (the id suffix, shared with the run outbox for the same run event so the
// two never both appear) and kind.
@@ -360,35 +250,11 @@ func runAttentionClick(id int64) string {
return fmt.Sprintf("pipelines://run/%d", id)
}
// runAttentionViews is the optional "Open in browser" action for a run.
func runAttentionViews(id int64) []stage.NtfyView {
return webAttentionViews(fmt.Sprintf("/runs/%d", id))
}
// webAttentionViews returns an "Open in browser" ntfy action for path on the
// operator's authenticated web origin, or nothing when none is configured.
// Never infer a public address from a request Host, the unauthenticated API
// listener or the ntfy server URL.
func webAttentionViews(path string) []stage.NtfyView {
raw := os.Getenv("PIPELINES_WEB_PUBLIC_URL")
if raw == "" {
return nil
}
base := publicNtfyBase(raw)
if base == "" {
log.Printf("notification web link unavailable: PIPELINES_WEB_PUBLIC_URL must be an HTTP(S) origin without credentials, query or fragment")
return nil
}
return []stage.NtfyView{{Label: "Open in browser", URL: base + path}}
}
// notifyRun publishes one run-level attention notification to the operator's
// already-configured "system" destination. It is the run counterpart of
// notifyStep and reuses the same PublishNtfy machinery, destination and token
// handling, so no second publisher, topic or service is introduced. The run id
// and pipeline name identify the run and the click action opens it in the app.
// Attempts are persisted before publication. Publisher acknowledgement is not
// proof of device reception; a crash in that acknowledgement window can repeat.
// notifyRun records one run-level attention notification on the app
// notification stream. It is the run counterpart of notifyStep. The run id and
// pipeline name identify the run and the click action opens it in the app.
// The event goes through the durable run notification outbox, so a crash
// before it is recorded is recovered after a restart.
func (r *runner) notifyRun(id int64, name, status string, sequence int, currentStage, diagnostic string) {
if r.notifyMode(id) == "off" {
return
@@ -488,20 +354,13 @@ func (r *runner) deliverRunNotificationBatch(now time.Time, limit int) {
link, linkFile := r.stageHookLink(*n)
artifact, preview := r.resolveNotificationArtifact(n.RunID, n.Sequence, "", linkFile)
n.Click = notificationClick(n.RunID, n.Sequence, artifact)
r.notes.record(ctx, withNotificationLink(runNotificationRecord(n.RunID, n.Sequence, n.Event, runNotificationKind(n.Event), n.Title, n.Body, artifact, preview), link))
var result stage.Values
var publishErr error
if ntfyEnabled(ctx, r.settingsStore()) {
// ntfy retains its existing run-level tap target (or the hook's link);
// the richer artifact target is carried by the app notification stream.
views := runAttentionViews(n.RunID)
click, _ := ntfyLinkClick(n.RunID, link, views)
result, publishErr = ntfyPublish(ctx, n.Channel, n.Title, n.Body, "", nil, click, views...)
var recordErr error
if r.notes != nil && !r.notes.record(ctx, withNotificationLink(runNotificationRecord(n.RunID, n.Sequence, n.Event, runNotificationKind(n.Event), n.Title, n.Body, artifact, preview), link)) {
recordErr = fmt.Errorf("app notification was not recorded")
}
cancel()
messageID, _ := result["message_id"].(string)
save, done := context.WithTimeout(context.Background(), 5*time.Second)
err = r.store.FinishRunNotification(save, *n, now.Add(time.Since(started)).Unix(), messageID, publishErr)
err = r.store.FinishRunNotification(save, *n, now.Add(time.Since(started)).Unix(), "", recordErr)
done()
if err != nil {
log.Printf("save run notification run=%d: %v", n.RunID, err)
@@ -521,51 +380,6 @@ func truncateUTF8(text string, max int) string {
return text
}
func notificationArtifact(workspace, name string) ([]byte, error) {
if name == "" || filepath.IsAbs(name) || filepath.Clean(name) != name || strings.ContainsAny(name, "\\\x00\r\n") {
return nil, fmt.Errorf("artifact must be a clean workspace-relative file path")
}
for _, part := range strings.Split(filepath.ToSlash(name), "/") {
lower := strings.ToLower(part)
if strings.HasPrefix(part, ".") || lower == "secrets" || lower == "node_modules" || strings.HasSuffix(lower, ".pem") || strings.HasSuffix(lower, ".key") || strings.HasSuffix(lower, ".db") || strings.HasSuffix(lower, ".db-wal") || strings.HasSuffix(lower, ".db-shm") || strings.HasSuffix(lower, ".sqlite") || strings.HasSuffix(lower, ".sqlite3") {
return nil, fmt.Errorf("artifact path is protected")
}
}
root, err := filepath.EvalSymlinks(workspace)
if err != nil {
return nil, fmt.Errorf("artifact workspace unavailable")
}
// os.Root prevents symlink traversal outside the workspace; disallow symlinks
// altogether so aliases cannot bypass protected path names within it either.
current := root
for _, part := range strings.Split(name, string(os.PathSeparator)) {
current = filepath.Join(current, part)
info, err := os.Lstat(current)
if err != nil || info.Mode()&os.ModeSymlink != 0 {
return nil, fmt.Errorf("artifact is missing or uses a symlink")
}
}
scoped, err := os.OpenRoot(root)
if err != nil {
return nil, fmt.Errorf("artifact workspace unavailable")
}
defer scoped.Close()
file, err := scoped.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
if err != nil {
return nil, fmt.Errorf("cannot read artifact")
}
defer file.Close()
info, err := file.Stat()
if err != nil || !info.Mode().IsRegular() || info.Size() > 1<<20 {
return nil, fmt.Errorf("artifact must be a regular file at most 1 MiB")
}
data, err := io.ReadAll(io.LimitReader(file, (1<<20)+1))
if err != nil || len(data) > 1<<20 {
return nil, fmt.Errorf("cannot read artifact within size limit")
}
return data, nil
}
func notificationClick(runID int64, sequence int, artifact *protocol.NotificationArtifact) string {
if artifact == nil {
return runAttentionClick(runID)
@@ -578,7 +392,6 @@ func notificationClick(runID int64, sequence int, artifact *protocol.Notificatio
}
// resolveNotificationArtifact selects only files in the run's shared public/.
// It is deliberately independent of the ntfy attachment policy.
// The exclude file (a `link=` file) is never selected.
func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern, exclude string) (*protocol.NotificationArtifact, string) {
selected := r.publicNotificationFile(runID, pattern, exclude)
+12 -18
View File
@@ -4,7 +4,6 @@ import (
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"net/url"
"os"
@@ -12,6 +11,7 @@ import (
"slices"
"strings"
"syscall"
"unicode/utf8"
)
// notificationLinkLimit bounds a `link=` file: it holds one URL, not a document.
@@ -19,7 +19,7 @@ const notificationLinkLimit = 4 << 10
// resolveNotificationLink reads the tap target a stage's `link=` pattern names
// in the run's shared public/: the first non-empty line of the most recently
// modified match, when it is an absolute http(s) URL ntfy accepts as a click.
// modified match, when it is a valid absolute http(s) URL.
// It returns the link and its public/ file, or no link and the reason for the
// notification receipt.
func (r *runner) resolveNotificationLink(runID int64, pattern string) (string, string, string) {
@@ -83,23 +83,16 @@ func readNotificationLink(root, rel string) ([]byte, error) {
return data, nil
}
// validNotificationLink accepts only an absolute http(s) URL with a host that
// also passes the ntfy click rules (no credentials, no fragment, bounded).
// validNotificationLink accepts only an absolute http(s) URL with a host, no
// credentials, no fragment, no whitespace or control characters and a bounded
// length. The value is an operator-visible link, never a place to smuggle a
// token.
func validNotificationLink(link string) bool {
if len(link) > 2048 || !utf8.ValidString(link) || strings.ContainsAny(link, "\r\n\t\x00 ") {
return false
}
u, err := url.Parse(link)
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && stage.ValidNtfyClick(link)
}
// ntfyLinkClick is the ntfy tap target: the link only while the run stays
// reachable through a web run view, else the run itself with a note saying so.
func ntfyLinkClick(runID int64, link string, views []stage.NtfyView) (string, string) {
if link == "" {
return runAttentionClick(runID), ""
}
if len(views) == 0 {
return runAttentionClick(runID), "notify link: ntfy keeps the run tap target without a web run view (PIPELINES_WEB_PUBLIC_URL)"
}
return link, ""
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && u.User == nil && u.Fragment == ""
}
// withNotificationLink makes link the app notification's tap target, keeping
@@ -112,7 +105,8 @@ func withNotificationLink(record pipeline.AppNotificationRecord, link string) pi
}
// stageHookLink re-resolves the `link=` of the stage hook behind a queued run
// event, so the durable retry of the hook's failed publication keeps its link.
// event, so the durable retry of the hook's unrecorded notification keeps its
// link.
// It returns the link and its public/ file, or nothing.
func (r *runner) stageHookLink(n pipeline.RunNotification) (string, string) {
event := map[string]string{protocol.NotifyWaiting: protocol.NotifyWaiting, "failed": "failure", "succeeded": "success"}[n.Event]
+24 -96
View File
@@ -2,17 +2,12 @@ package server
import (
"context"
"encoding/json"
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
@@ -49,18 +44,14 @@ func appNotification(t *testing.T, store *pipeline.Store, id string) *protocol.A
return nil
}
// A stage hook's `link=` file decides the ntfy and app tap target when its
// first non-empty line is an http(s) URL, keeping the run one action away and
// never attaching the link file; anything else falls back to the run link and
// says why on the first receipt.
// A stage hook's `link=` file decides the app tap target when its first
// non-empty line is an http(s) URL, keeping the run one action away and never
// attaching the link file; anything else falls back to the attached artifact
// or the run link and says why on the receipt.
func TestStageHookLinkClick(t *testing.T) {
captured := newNtfyCapture(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: true}); err != nil {
t.Fatal(err)
}
if _, err := store.Submit(ctx, "standup", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
@@ -72,8 +63,6 @@ func TestStageHookLinkClick(t *testing.T) {
for _, test := range []struct {
name, link, open string
files map[string]string
noWeb bool // no web origin: ntfy has no run view
attach bool // markdown and a workspace file are also attached
click bool // the doc URL is the app tap target
artifact string // the attached artifact path
diagnostic string
@@ -81,13 +70,12 @@ func TestStageHookLinkClick(t *testing.T) {
{name: "valid", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "\n " + doc + " \r\nnotes\n", "notes.txt": "n", "more.txt": "m"}, click: true},
{name: "valid-only-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, click: true},
{name: "valid-other-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup"}, click: true, artifact: "standup.md"},
{name: "valid-no-web", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, noWeb: true, click: true, diagnostic: "notify link: ntfy keeps the run tap target"},
{name: "missing", link: "standup-link.txt", diagnostic: "notify link: no public file matches standup-link.txt"},
{name: "missing-other-file", link: "standup-link.txt", files: map[string]string{"report.md": "# Report"}, artifact: "report.md", diagnostic: "notify link: no public file matches standup-link.txt"},
{name: "missing-attachments", link: "standup-link.txt", attach: true, diagnostic: "notify link: no public file matches standup-link.txt"},
{name: "relative", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "standup.html\n" + doc}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt does not start with an absolute http(s) URL"},
{name: "scheme", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "javascript:alert(1)"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"},
{name: "fragment", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "#top"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"},
{name: "credentials", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "https://user:pw@example.com/doc"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"},
{name: "empty", link: "standup-link.txt", files: map[string]string{"standup-link.txt": " \n\n"}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt is empty"},
{name: "large", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "\n" + strings.Repeat("x", 4<<10)}, artifact: "standup-link.txt", diagnostic: "at most 4 KiB"},
{name: "absent", files: map[string]string{"standup-link.txt": doc, "notes.txt": "n"}},
@@ -95,15 +83,7 @@ func TestStageHookLinkClick(t *testing.T) {
{name: "with-open", link: "*-link.txt", open: "*", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup"}, click: true, artifact: "standup.md"},
} {
t.Run(test.name, func(t *testing.T) {
web := "https://pipelines.example.com"
if test.noWeb {
web = ""
}
t.Setenv("PIPELINES_WEB_PUBLIC_URL", web)
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "report.txt"), []byte("report"), 0600); err != nil {
t.Fatal(err)
}
id, _, err := store.CreateRun(ctx, d, test.name, workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
@@ -114,28 +94,13 @@ func TestStageHookLinkClick(t *testing.T) {
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{}}
policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Link: test.link, Open: test.open}
publications := 1
if test.attach {
step.Output = map[string]any{"markdown": "# Standup", "artifacts": []any{"report.txt"}}
policy.Artifacts = []string{"markdown", "files"}
publications = 2
}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := len(captured())
r.notifyStep(id, d.Name, workspace, policy, step)
// ntfy opens the link only beside a web run view; the app opens the
// link (else the attached artifact, else the run).
// The app opens the link, else the attached artifact, else the run.
runClick := fmt.Sprintf("pipelines://run/%d", id)
wantNtfy, wantActions := runClick, ""
if !test.noWeb {
wantActions = fmt.Sprintf("view, Open in browser, https://pipelines.example.com/runs/%d", id)
if test.click {
wantNtfy = doc
}
}
wantClick, wantRunClick := runClick, ""
if test.artifact != "" {
wantClick, wantRunClick = fmt.Sprintf("pipelines://artifact/%d/1/%s", id, test.artifact), runClick
@@ -143,15 +108,6 @@ func TestStageHookLinkClick(t *testing.T) {
if test.click {
wantClick, wantRunClick = doc, runClick
}
got := captured()[before:]
if len(got) != publications {
t.Fatalf("ntfy publications = %+v", got)
}
for _, publication := range got {
if publication.Click != wantNtfy || publication.Actions != wantActions {
t.Fatalf("ntfy click/actions = %q %q, want %q %q", publication.Click, publication.Actions, wantNtfy, wantActions)
}
}
n := appNotification(t, store, fmt.Sprintf("run:%d:1:success", id))
if n == nil || n.Click != wantClick || n.RunClick != wantRunClick {
t.Fatalf("app notification = %+v, want click %q run %q", n, wantClick, wantRunClick)
@@ -164,52 +120,23 @@ func TestStageHookLinkClick(t *testing.T) {
t.Fatal(err)
}
receipts := detail.Steps[0].Notifications
if len(receipts) != publications {
if len(receipts) != 1 || receipts[0].Status != "sent" || receipts[0].Destination != "app" {
t.Fatalf("receipts = %+v", receipts)
}
// The reason is recorded once, on the first receipt. (The capture
// acknowledges no attachment, so attachment receipts fail.)
for i, receipt := range receipts {
noted := strings.Contains(receipt.Diagnostic, "notify link")
if i == 0 && test.diagnostic != "" {
noted = !strings.Contains(receipt.Diagnostic, test.diagnostic)
}
if noted || (!test.attach && (receipt.Status != "sent" || (test.diagnostic == "") != (receipt.Diagnostic == ""))) {
t.Fatalf("receipts = %+v, want diagnostic %q on the first only", receipts, test.diagnostic)
}
if got := receipts[0].Diagnostic; (test.diagnostic == "") != (got == "") || !strings.Contains(got, test.diagnostic) {
t.Fatalf("receipt diagnostic = %q, want %q", got, test.diagnostic)
}
})
}
}
// A terminal stage hook whose publication fails hands the run event back to
// the durable outbox; the retry keeps the hook's link, and the run-level
// failure reason never carries the link note.
// A terminal stage hook whose notification is not recorded hands the run
// event back to the durable outbox; the retry keeps the hook's link, and the
// run-level failure reason never carries the link note.
func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
var mu sync.Mutex
var clicks []string
var fail atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
clicks = append(clicks, r.Header.Get("Click"))
mu.Unlock()
if fail.Swap(false) {
http.Error(w, "transient", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "msg", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: true}); err != nil {
t.Fatal(err)
}
source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\nlink=standup-link.txt\n```", 1)
if _, err := store.Submit(ctx, "standup", source); err != nil {
t.Fatal(err)
@@ -221,11 +148,12 @@ func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) {
t.Fatalf("stage policy = %+v", policy)
}
artifacts := t.TempDir()
r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store), artifactsRoot: artifacts}
notes, recorder := newNoteCapture(t, store)
r := &runner{ctx: ctx, store: store, notes: notes, artifactsRoot: artifacts}
for _, test := range []struct {
name string
files map[string]string
retry string // the retry's ntfy click; "" means the run
retry string // the retry's tap target; "" means the run
}{
{name: "valid", files: map[string]string{"standup-link.txt": standupDoc}, retry: standupDoc},
{name: "missing"},
@@ -247,25 +175,25 @@ func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) {
if err := store.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "succeeded", Channel: "system", Title: "Run succeeded", Body: "Run succeeded", Click: runAttentionClick(id)}); err != nil {
t.Fatal(err)
}
mu.Lock()
clicks = nil
mu.Unlock()
fail.Store(true)
recorder.mu.Lock()
recorder.fail, recorder.got = true, nil
recorder.mu.Unlock()
r.notifyStep(id, d.Name, t.TempDir(), policy, step)
rows, err := store.RunNotifications(ctx, id)
if err != nil || len(rows) != 1 || rows[0].Status != "pending" || rows[0].Diagnostic == "" || strings.Contains(rows[0].Diagnostic, "notify link") {
t.Fatalf("released run notification = %+v %v", rows, err)
}
recorder.mu.Lock()
recorder.fail = false
recorder.mu.Unlock()
r.deliverRunNotifications(time.Now().Add(time.Minute))
want := test.retry
if want == "" {
want = runAttentionClick(id)
}
mu.Lock()
got := append([]string(nil), clicks...)
mu.Unlock()
if len(got) != 2 || got[0] != want || got[1] != want {
t.Fatalf("hook and retry clicks = %q, want %q twice", got, want)
got := recorder.recorded()
if len(got) != 1 || got[0].Click != want || got[0].ID != fmt.Sprintf("run:%d:1:succeeded", id) {
t.Fatalf("retried notification = %+v, want click %q", got, want)
}
if rows, err = store.RunNotifications(ctx, id); err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("retried run notification = %+v %v", rows, err)
+80 -185
View File
@@ -2,28 +2,22 @@ package server
import (
"context"
"encoding/json"
"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"
"io"
"mime"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"syscall"
"testing"
"time"
)
func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com/")
// 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"))
@@ -32,46 +26,22 @@ func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
}
defer store.Close()
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "report.txt"), []byte("created file"), 0600); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count := calls.Add(1)
if click, actions := r.Header.Get("Click"), r.Header.Get("Actions"); !strings.HasPrefix(click, "pipelines://run/") || actions != "view, Open in browser, https://pipelines.example.com/runs/"+strings.TrimPrefix(click, "pipelines://run/") {
t.Errorf("stage notification lacks app click/web action: %q %q", click, actions)
}
filename, _ := new(mime.WordDecoder).DecodeHeader(r.Header.Get("Filename"))
body, _ := io.ReadAll(r.Body)
if filename == "report.txt" && string(body) != "created file" {
t.Error("wrong file content")
}
if filename == "digest.md" && string(body) != "# Digest" {
t.Error("wrong markdown")
}
ack := map[string]any{"id": fmt.Sprintf("msg%d", count), "event": "message"}
if filename != "" {
ack["attachment"] = map[string]string{"name": filename, "url": "https://ntfy.example.com/file/" + filename}
}
_ = json.NewEncoder(w).Encode(ack)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
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
attachments bool
expected int32
kind string
}{
{"completed", "success", protocol.SuccessEnd, "success", true, 2},
{"completed", "blocked", protocol.FailureEnd, "failure", false, 1},
{"failed", "error", protocol.FailureEnd, "failure", false, 1},
{"completed", "error", protocol.FailureEnd, "success", false, 0},
{"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 {
@@ -82,26 +52,27 @@ func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
}
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 test.attachments {
policy.Artifacts = []string{"markdown", "files"}
step.Output = map[string]any{"markdown": "# Digest", "artifacts": []any{"report.txt"}}
}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := calls.Load()
before := len(recorder.recorded())
r.notifyStep(id, d.Name, workspace, policy, step)
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if calls.Load()-before != test.expected || len(detail.Steps[0].Notifications) != int(test.expected) {
t.Fatal("event/attachments mismatch", detail, calls.Load()-before)
}
for _, receipt := range detail.Steps[0].Notifications {
if receipt.Status != "sent" || receipt.MessageID == "" {
t.Fatal("notification receipt not persisted", receipt)
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)
}
}
}
@@ -135,27 +106,12 @@ func TestTerminalNotificationRecipe(t *testing.T) {
t.Fatal("recipe missing", err)
}
id := items[0].ID
var calls atomic.Int32
var deliveryFailure atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
if req.Header.Get("Filename") != "" {
t.Error("event alert unexpectedly changed output to add attachments")
}
if deliveryFailure.Load() {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "recipe-receipt", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
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
@@ -169,7 +125,9 @@ func TestTerminalNotificationRecipe(t *testing.T) {
{"delivery error preserves success", "report", "success", "succeeded", false, true, true},
} {
t.Run(test.name, func(t *testing.T) {
deliveryFailure.Store(test.deliveryError)
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 {
@@ -179,7 +137,7 @@ func TestTerminalNotificationRecipe(t *testing.T) {
}
return stage.Result{Outcome: "success", Output: stage.Values{"question": "topic", "evidence": []any{"source fact"}}}, nil
}
before := calls.Load()
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)
@@ -189,8 +147,9 @@ func TestTerminalNotificationRecipe(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if detail.Status != test.status || (calls.Load()-before == 1) != test.notify {
t.Fatal("wrong verdict or duplicate/missing terminal alert", detail.Status, calls.Load()-before)
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 {
@@ -226,6 +185,7 @@ func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
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)
@@ -235,7 +195,10 @@ func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Result"}}, nil
}
t.Setenv("PIPELINES_NTFY_URL", "")
// 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)
@@ -247,29 +210,6 @@ func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
}
}
func TestNotificationArtifactPathSafety(t *testing.T) {
root := t.TempDir()
os.WriteFile(filepath.Join(root, "safe.txt"), []byte("safe"), 0600)
os.WriteFile(filepath.Join(root, ".env"), []byte("secret"), 0600)
os.Symlink(filepath.Join(root, ".env"), filepath.Join(root, "alias.txt"))
outside := filepath.Join(t.TempDir(), "outside.txt")
os.WriteFile(outside, []byte("secret"), 0600)
os.Symlink(outside, filepath.Join(root, "external.txt"))
os.Mkdir(filepath.Join(root, "directory"), 0700)
os.WriteFile(filepath.Join(root, "large.bin"), []byte(strings.Repeat("x", (1<<20)+1)), 0600)
if err := syscall.Mkfifo(filepath.Join(root, "pipe"), 0600); err != nil {
t.Fatal(err)
}
for _, name := range []string{"../outside.txt", outside, ".env", "alias.txt", "external.txt", "directory", "large.bin", "pipe", "pipelines.db", "secret.key", "secrets/file.txt", "sub/../safe.txt"} {
if _, err := notificationArtifact(root, name); err == nil {
t.Fatal("unsafe artifact accepted", name)
}
}
if data, err := notificationArtifact(root, "safe.txt"); err != nil || string(data) != "safe" {
t.Fatal("safe artifact rejected", err)
}
}
func TestNotificationArtifactSelectionAndPreview(t *testing.T) {
root := t.TempDir()
public := filepath.Join(root, "9", "public")
@@ -332,11 +272,9 @@ func TestRunAttentionEventMapping(t *testing.T) {
}
// TestRunAttentionNotificationDelivery proves the operator-facing contract: the
// already-configured "system" destination and topic are used, the payload names
// the run and its pipeline, the click action opens the run, only waiting/failed
// publish, and a run that stays waiting is never republished.
// 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) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "attention.db"))
@@ -344,73 +282,46 @@ func TestRunAttentionNotificationDelivery(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
type delivered struct {
method, path, title, message, click, authorization, actions string
}
deliveries := make(chan delivered, 8)
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"))
deliveries <- delivered{r.Method, r.URL.Path, title, message, r.Header.Get("Click"), r.Header.Get("Authorization"), r.Header.Get("Actions")}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "attention-receipt", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
// A run that needs nobody publishes nothing.
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", "")
}
select {
case got := <-deliveries:
t.Fatalf("a run that needs nobody published: %+v", got)
default:
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("a run that needs nobody notified: %+v", got)
}
// A waiting run publishes once, with the destination, identity and click.
// 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 republished, on a later call or a re-request.
// 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" publishes once, with its diagnostic.
// A failed run marked "on" notifies once, with its diagnostic.
r.setNotifyMode(7, "on")
r.notifyRun(7, "release", "failed", 2, "deploy", "provider returned 500")
first := <-deliveries
if first.method != http.MethodPost || first.path != "/pipelines" {
t.Fatalf("wrong destination/topic: %+v", first)
got := recorder.recorded()
if len(got) != 3 {
t.Fatalf("notifications = %+v, want three genuine events", got)
}
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") {
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.actions != "view, Open in browser, https://pipelines.example.com/runs/7" {
t.Fatalf("waiting notification click does not open the run: %q", first.click)
if first.Click != "pipelines://run/7" || first.Kind != protocol.NotificationRunWaiting {
t.Fatalf("waiting notification click does not open the run: %+v", first)
}
if first.authorization != "" {
t.Fatalf("notification leaked an authorization header: %q", first.authorization)
}
second := <-deliveries
if second.title != "Run failed" || !strings.Contains(second.message, "Run #8") {
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 second.click != "pipelines://run/8" || second.actions != "view, Open in browser, https://pipelines.example.com/runs/8" {
t.Fatalf("failed notification click does not open the run: %q", second.click)
}
third := <-deliveries
if third.title != "Run failed" || !strings.Contains(third.message, "Run #7") {
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)
}
select {
case got := <-deliveries:
t.Fatalf("third notification delivered for two genuine events: %+v", got)
default:
}
}
// TestRunAttentionSuppressedByStagePolicy proves a stage's own notify policy and
@@ -428,29 +339,24 @@ func TestRunAttentionSuppressedByStagePolicy(t *testing.T) {
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")
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "suppressed", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
r.notifyRun(11, "release", "failed", 5, "deploy", "")
r.notifyRun(11, "release", protocol.RunStatusWaiting, 6, "approve", "")
if calls.Load() != 0 {
t.Fatalf("run-level default repeated a stage-policy event %d times", calls.Load())
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("run-level default repeated a stage-policy event: %+v", got)
}
}
// TestHumanRunAttentionNotification proves the run loop publishes the run-level
// 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's configured destination exactly
// once, with the run, pipeline and a run-opening click.
// 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()
@@ -459,17 +365,6 @@ func TestHumanRunAttentionNotification(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
type delivered struct{ title, message, click string }
deliveries := make(chan delivered, 4)
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"))
deliveries <- delivered{title, message, r.Header.Get("Click")}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "human-attention", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
if _, err := store.Submit(ctx, "human", humanPipelineSource); err != nil {
t.Fatal(err)
}
@@ -478,6 +373,8 @@ func TestHumanRunAttentionNotification(t *testing.T) {
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"}})
@@ -485,17 +382,20 @@ func TestHumanRunAttentionNotification(t *testing.T) {
t.Fatal(err)
}
r.wg.Wait()
got := <-deliveries
if got.title != "Run needs your decision" || !strings.Contains(got.message, fmt.Sprintf("Run #%d", run.ID)) || !strings.Contains(got.message, "human") {
t.Fatalf("run-level waiting notification wrong: %+v", got)
deadline := time.Now().Add(5 * time.Second)
for len(recorder.recorded()) == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if got.click != fmt.Sprintf("pipelines://run/%d", run.ID) {
t.Fatalf("run-level waiting notification click wrong: %q", got.click)
time.Sleep(50 * time.Millisecond)
got := recorder.recorded()
if len(got) != 1 {
t.Fatalf("waiting notifications = %+v, want exactly one", got)
}
select {
case extra := <-deliveries:
t.Fatalf("waiting run notified again: %+v", extra)
default:
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)
}
}
@@ -514,17 +414,12 @@ func TestRunAttentionNotifiesEachGenuineWait(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "wait", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
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 calls.Load() != 2 {
t.Fatalf("two genuine waits produced %d notifications, want 2", calls.Load())
if got := recorder.recorded(); len(got) != 2 {
t.Fatalf("two genuine waits produced %d notifications, want 2", len(got))
}
}
-68
View File
@@ -1,68 +0,0 @@
package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
)
func TestRunnerNtfyDeliveryIsAuditedAndIdempotent(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "ntfy.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
calls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
body, _ := io.ReadAll(r.Body)
if string(body) != "# Anime\nA report." {
t.Error("wrong markdown", string(body))
}
_, _ = w.Write([]byte(`{"id":"delivery123","event":"message","attachment":{"name":"digest.md","url":"https://ntfy.example.com/file/digest.md"}}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
source := "# stage notify\n```configs\ntype=ntfy\ndestination=anime\n```\n```edges\nsuccess -> #success\nerror -> #failure\n```\n"
if _, err := store.Submit(ctx, "notify", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, _ := newRunner(ctx, store)
for i, approved := range []bool{false, true} {
key := []string{"notify", "approved-notify"}[i]
request := protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: key, AllowTools: approved, Input: map[string]any{"prompt": "notify", "title": "Anime", "summary": "Your digest is ready", "markdown": "# Anime\nA report."}}
run, err := r.start(request)
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ := store.GetRun(ctx, run.ID)
if detail.Status != "succeeded" || len(detail.Steps) != 1 || detail.Steps[0].Output["delivery"] == nil || detail.Steps[0].SessionID != "" {
t.Fatal("native delivery not audited", detail)
}
if duplicate, err := r.start(request); err != nil || duplicate.ID != run.ID {
t.Fatal("repeat not idempotent", err)
}
}
if calls != 2 {
t.Fatal("duplicate publication", calls)
}
t.Setenv("PIPELINES_NTFY_ANIME_URL", "")
failed, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "failure", Input: map[string]any{"prompt": "notify", "title": "Anime", "summary": "Ready", "markdown": "# report"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ := store.GetRun(ctx, failed.ID)
if detail.Status != "failed" || detail.Steps[0].Outcome != "error" {
t.Fatal("delivery failure not routed", detail)
}
}
+5 -16
View File
@@ -4,13 +4,10 @@ import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -219,16 +216,8 @@ func TestReferenceWorkflowsLive(t *testing.T) {
t.Fatal(err)
}
defer func() { cancel(); runner.wg.Wait() }()
var alerts atomic.Int32
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
alerts.Add(1)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"reference-local-receipt","event":"message"}`)
}))
defer endpoint.Close()
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/reference")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
notes, recorder := newNoteCapture(t, store)
runner.notes = notes
type result struct {
Name string `json:"name"`
Verified bool `json:"verified"`
@@ -292,7 +281,7 @@ func TestReferenceWorkflowsLive(t *testing.T) {
pid = p.ID
}
}
priorAlerts := alerts.Load()
priorAlerts := len(recorder.recorded())
run, err := runner.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: c.name, Workspace: workspace, Input: map[string]any{"prompt": c.prompt}})
if err != nil {
row.Diagnostic = err.Error()
@@ -327,11 +316,11 @@ func TestReferenceWorkflowsLive(t *testing.T) {
t.Fatal("workspace capture absent")
}
}
wantAlerts := int32(0)
wantAlerts := 0
if c.name == "incident-handoff" || c.name == "missing-input-failure" {
wantAlerts = 1
}
if alerts.Load()-priorAlerts != wantAlerts {
if len(recorder.recorded())-priorAlerts != wantAlerts {
t.Fatal("unexpected notification count")
}
t.Logf("Verified %s: run #%d status=%s visits=%d", c.name, run.ID, run.Status, len(run.Steps))
+1 -1
View File
@@ -200,7 +200,7 @@ func scratchEnvironment(t *testing.T, realHome, home string) []string {
env = append(env, entry)
}
return append(env, "HOME="+home, "XDG_CONFIG_HOME="+config, "XDG_DATA_HOME="+data, "XDG_CACHE_HOME="+cache, "XDG_STATE_HOME="+filepath.Join(home, ".local", "state"),
"PIPELINES_OPENCODE="+opencodePath(), "PIPELINES_NTFY_URL=", "PIPELINES_MDNS=off")
"PIPELINES_OPENCODE="+opencodePath(), "PIPELINES_MDNS=off")
}
func copyProviderLogin(t *testing.T, real, scratch, provider string) {
+48 -117
View File
@@ -2,13 +2,9 @@ package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -18,30 +14,19 @@ import (
"git.a-wan.net/alan/pipelines/internal/summarise"
)
func TestRunNotificationPublisherFailureRetriesAfterReopen(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
// 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)
}
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got, actions := r.Header.Get("Click"), r.Header.Get("Actions"); got != "pipelines://run/7" || actions != "view, Open in browser, https://pipelines.example.com/runs/7" {
t.Errorf("wrong retry links: %q %q", got, actions)
}
if calls.Add(1) == 1 {
http.Error(w, "transient", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "ack", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s}
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.
@@ -61,17 +46,19 @@ func TestRunNotificationPublisherFailureRetriesAfterReopen(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
r = &runner{ctx: ctx, store: s}
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)
if err != nil || len(got) != 1 || got[0].Status != "sent" || got[0].Attempts != 2 || got[0].MessageID != "ack" || calls.Load() != 2 {
t.Fatalf("retry/dedupe: %+v calls=%d %v", got, calls.Load(), err)
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 TestTransactionalSuccessNotificationUsesWebLink(t *testing.T) {
func TestTransactionalSuccessNotificationUsesAppLink(t *testing.T) {
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "web-success.db"))
if err != nil {
@@ -93,28 +80,14 @@ func TestTransactionalSuccessNotificationUsesWebLink(t *testing.T) {
if err := s.FinishRun(ctx, id, "succeeded", "success", "", nil); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
if got, want := req.Header.Get("Click"), "pipelines://run/"+fmt.Sprint(id); got != want {
t.Errorf("click = %q, want %q", got, want)
}
if got, want := req.Header.Get("Actions"), "view, Open in browser, https://pipelines.example.com/runs/"+fmt.Sprint(id); got != want {
t.Errorf("actions = %q, want %q", got, want)
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "web-success", "event": "message"})
}))
defer endpoint.Close()
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s}
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)
if err != nil || len(got) != 1 || got[0].Status != "sent" || calls.Load() != 1 {
t.Fatalf("notification: %+v calls=%d err=%v", got, calls.Load(), err)
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)
}
}
@@ -142,16 +115,8 @@ func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "wrong-success", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s, events: newRunEventHub()}
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)
}
@@ -159,8 +124,8 @@ func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
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 calls.Load() != 0 {
t.Fatal("terminal stage success published before FinishRun")
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()
@@ -170,8 +135,8 @@ func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if got.Status != "running" || len(got.Notifications) != 0 || calls.Load() != 0 {
t.Fatalf("unpersisted success announced: %+v calls=%d", got, calls.Load())
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()
@@ -190,18 +155,6 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) == 1 && failFirst {
http.Error(w, "transient", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "waiting-ack", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
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)
@@ -215,6 +168,11 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
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)
@@ -225,12 +183,12 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
if err != nil {
t.Fatal(err)
}
wantCalls := int32(1)
wantCalls := 1
if failFirst {
wantCalls = 2
}
if calls.Load() != wantCalls || detail.Status != "waiting" || len(detail.Notifications) != 1 {
t.Fatalf("waiting hook duplicated/lost: calls=%d detail=%+v", calls.Load(), detail)
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" {
@@ -241,25 +199,16 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
}
func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "ack", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
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 int32
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 publishes for an
// 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},
} {
@@ -291,15 +240,16 @@ func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success"}, nil
}
before := calls.Load()
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 || calls.Load()-before != tc.want {
t.Fatalf("mode contract: %+v calls=%d %v", detail, calls.Load()-before, err)
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)
@@ -317,16 +267,9 @@ func TestRunNotificationAttentionModesAndRetryBound(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
http.Error(w, "unavailable", http.StatusServiceUnavailable)
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s}
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)
@@ -335,14 +278,14 @@ func TestRunNotificationAttentionModesAndRetryBound(t *testing.T) {
}
}
// auto and on waiting, plus auto and on failed; off never notifies.
if calls.Load() != 4 {
t.Fatalf("attention modes: %d calls, want 4", calls.Load())
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 calls.Load() != 12 {
t.Fatalf("retry bound: %d calls, want 12", calls.Load())
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)
@@ -379,32 +322,20 @@ func TestRunNotificationWorkerResumesPendingAfterRestart(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
delivered := make(chan struct{}, 2)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]string{"id": "recovered", "event": "message"})
delivered <- struct{}{}
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
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() }()
select {
case <-delivered:
case <-time.After(5 * time.Second):
t.Fatal("pending outbox was not recovered")
}
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" && got[0].MessageID == "recovered" {
if len(got) == 1 && got[0].Status == "sent" && appNotification(t, s, "run:7:1:failed") != nil {
break
}
if time.Now().After(deadline) {
+4 -5
View File
@@ -63,8 +63,7 @@ type runner struct {
// events pushes run state deltas to subscribed clients. When nil (tests that
// build a runner directly) emits are dropped, so nothing else changes.
events *runEventHub
// notes records and streams app notifications beside every ntfy
// publication. Nil (a runner built directly in a test) records nothing.
// notes records and streams app notifications. Nil (a runner built directly in a test) records nothing.
notes *appNotifier
// identMu guards idents: the pipeline identity and stored title (see
// runIdentity) that every emitted frame of a run carries, so a client with no
@@ -1032,7 +1031,7 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
return retryCheckpoint{}, fmt.Errorf("retry source %d has incompatible selected stage %q", sourceID, failed.Stage)
}
typ := stage.EffectiveType(declared.Type)
if typ == stage.HumanType || typ == stage.NtfyType {
if typ == stage.HumanType || typ == stage.RemovedNtfyType {
return retryCheckpoint{}, fmt.Errorf("retry source %d cannot replay completed external stage %s", sourceID, failed.Stage)
}
if typ == stage.ModelType {
@@ -1934,8 +1933,8 @@ func (r *runner) finishRunStateClass(id int64, name, workspace, status, outcome,
if detail.FinishedAt == "" {
return // Cleanup is not confirmed: never emit a false terminal event.
}
// Push the terminal delta before the attention notification, so a slow ntfy
// never delays the live update the app folds.
// Push the terminal delta before the attention notification, so a slow
// notification never delays the live update the app folds.
r.emitRun(protocol.RunEventFrame{
RunID: id,
Workspace: workspace,
+2 -9
View File
@@ -10,7 +10,6 @@ import (
"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 (r *runner) scheduleLoop() {
@@ -124,7 +123,7 @@ var scheduleBusyRetry = func() (every, limit time.Duration) {
return every, limit
}
// scheduleNoticePriority is ntfy's "low" priority.
// scheduleNoticePriority is the notification stream's "low" priority.
const scheduleNoticePriority = 2
// admitScheduled starts one claimed schedule's run and records the outcome in
@@ -203,7 +202,7 @@ func scheduleLabel(item protocol.SavedSchedule) string {
}
// scheduleNotice tells the operator, at low priority, through the app
// notification stream and (when enabled) ntfy, that a scheduled run was
// notification stream, that a scheduled run was
// delayed or skipped.
func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second)
@@ -212,10 +211,4 @@ func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, even
r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{
ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule,
Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}})
if !chatAttentionConfigured() || !ntfyEnabled(ctx, r.settingsStore()) {
return
}
if _, err := ntfyPublish(stage.WithNtfyPriority(ctx, scheduleNoticePriority), "system", title, message, "", nil, click); err != nil {
log.Printf("schedule id=%d %s notice: %v", item.ID, event, err)
}
}
@@ -41,15 +41,6 @@ func TestSessionExportLive(t *testing.T) {
if !ok || !stage.ValidModel(provider, id) {
t.Fatal("explicit valid PIPELINES_SESSION_EXPORT_MODEL required")
}
// Isolate notifications from the operator's real ntfy service.
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"session-export-live-receipt","event":"message"}`)
}))
defer endpoint.Close()
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/live")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Minute)
defer cancel()
-8
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
@@ -19,13 +18,6 @@ import (
// Exercise the real V2 CLI/poll path, runner, SQLite retention and websocket CLI
// against an isolated loopback server/database, never the configured deployment.
func TestStageDeadlineDiagnosticThroughCLIAndWebsocket(t *testing.T) {
ntfy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"id":"scratch-receipt","event":"message"}`))
}))
defer ntfy.Close()
t.Setenv("PIPELINES_NTFY_URL", ntfy.URL+"/scratch")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
for _, mode := range []string{"active", "http", "connection"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
+1 -75
View File
@@ -1,9 +1,6 @@
package server
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"net/url"
@@ -44,16 +41,6 @@ func networkAddresses() []protocol.NetworkAddress {
return result
}
func endpointPort(u *url.URL) string {
if port := u.Port(); port != "" {
return port
}
if u.Scheme == "https" || u.Scheme == "wss" {
return "443"
}
return "80"
}
func candidateURLs(addresses []protocol.NetworkAddress, scheme, port, path string) []string {
result := []string{}
for _, address := range addresses {
@@ -63,22 +50,9 @@ func candidateURLs(addresses []protocol.NetworkAddress, scheme, port, path strin
return result
}
func localEndpoint(u *url.URL, hostname string, addresses []protocol.NetworkAddress) bool {
host := u.Hostname()
if host == "localhost" || host == hostname || net.ParseIP(host).IsLoopback() {
return true
}
for _, address := range addresses {
if host == address.IP {
return true
}
}
return false
}
func systemStatus(r *http.Request, started time.Time, runErr error) *protocol.SystemStatus {
hostname, _ := os.Hostname()
s := &protocol.SystemStatus{Hostname: hostname, StartedAt: started.UTC().Format(time.RFC3339), Uptime: time.Since(started).Round(time.Second).String(), Addresses: networkAddresses(), Server: protocol.ServiceStatus{Health: "healthy"}, Ntfy: protocol.ServiceStatus{Health: "not configured"}, Note: "Addresses belong to the server computer (or container). Candidate URLs are not reachability checks; binding, firewalls, port mapping and TLS may differ."}
s := &protocol.SystemStatus{Hostname: hostname, StartedAt: started.UTC().Format(time.RFC3339), Uptime: time.Since(started).Round(time.Second).String(), Addresses: networkAddresses(), Server: protocol.ServiceStatus{Health: "healthy"}, Note: "Addresses belong to the server computer (or container). Candidate URLs are not reachability checks; binding, firewalls, port mapping and TLS may differ."}
if runErr != nil {
s.Server.Health = "execution unavailable"
}
@@ -104,53 +78,5 @@ func systemStatus(r *http.Request, started time.Time, runErr error) *protocol.Sy
s.Server.Candidates = []string{s.Server.URL}
}
}
endpoints := notificationEndpoints()
if len(endpoints) == 0 {
return s
}
s.Topic = endpoints[0].Topic
s.NtfyUser = os.Getenv("PIPELINES_NTFY_READER")
s.Ntfy.Health = "not checked"
// Only the validated public base is returned. Publishing URL and tokens
// never leave the server, even on probe failure.
s.Ntfy.URL = endpoints[0].ServerURL
if u, err := url.Parse(s.Ntfy.URL); err == nil && u.Host != "" {
s.Ntfy.Port = endpointPort(u)
if localEndpoint(u, hostname, s.Addresses) {
s.Ntfy.Candidates = candidateURLs(s.Addresses, u.Scheme, s.Ntfy.Port, "/"+s.Topic)
}
}
publish, err := url.Parse(os.Getenv("PIPELINES_NTFY_URL"))
if err != nil {
return s
}
if s.Ntfy.URL == "" && localEndpoint(publish, hostname, s.Addresses) {
s.Ntfy.Port = endpointPort(publish)
s.Ntfy.Candidates = candidateURLs(s.Addresses, publish.Scheme, s.Ntfy.Port, "/"+s.Topic)
}
publish.Path = "/v1/health"
publish.RawPath = ""
publish.RawQuery = ""
publish.Fragment = ""
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, publish.String(), nil)
if err != nil {
return s
}
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(req)
s.Ntfy.Health = "unreachable"
if err != nil {
return s
}
defer response.Body.Close()
s.Ntfy.Health = "unhealthy"
var health struct {
Healthy bool `json:"healthy"`
}
if response.StatusCode == http.StatusOK && json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&health) == nil && health.Healthy {
s.Ntfy.Health = "healthy"
}
return s
}
+9 -37
View File
@@ -5,25 +5,13 @@ import (
"encoding/json"
"git.a-wan.net/alan/pipelines/internal/client"
"git.a-wan.net/alan/pipelines/internal/protocol"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
func TestStatusRPCReportsServerAndNtfyWithoutSecrets(t *testing.T) {
ntfy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/health" {
t.Error("unexpected probe", r.URL.Path)
}
w.Write([]byte(`{"healthy":true}`))
}))
defer ntfy.Close()
t.Setenv("PIPELINES_NTFY_URL", ntfy.URL+"/phone")
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", ntfy.URL)
t.Setenv("PIPELINES_NTFY_TOKEN", "never-return-this-token")
func TestStatusRPCReportsServerWithoutNtfy(t *testing.T) {
srv := httptest.NewServer(Handler(context.Background()))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@@ -38,12 +26,14 @@ func TestStatusRPCReportsServerAndNtfyWithoutSecrets(t *testing.T) {
t.Fatal(err)
}
s := response.Status
if s == nil || s.Server.Health != "healthy" || s.Ntfy.Health != "healthy" || s.Ntfy.URL != ntfy.URL || s.Topic != "phone" || len(s.Addresses) == 0 || s.Hostname == "" || s.Server.Port == "" || s.Ntfy.Port == "" || s.StartedAt == "" || len(s.Ntfy.Candidates) == 0 {
if s == nil || s.Server.Health != "healthy" || len(s.Addresses) == 0 || s.Hostname == "" || s.Server.Port == "" || s.StartedAt == "" {
t.Fatal("incomplete status", s)
}
encoded, _ := json.Marshal(s)
if strings.Contains(string(encoded), "never-return") {
t.Fatal("credentials leaked", string(encoded))
for _, gone := range []string{`"ntfy"`, `"topic"`, `"ntfy_user"`} {
if strings.Contains(string(encoded), gone) {
t.Fatalf("status still reports %s: %s", gone, encoded)
}
}
if !strings.Contains(s.Server.URL, s.Server.Port) || !strings.Contains(s.Note, "not reachability checks") {
t.Fatal("ports or safety disclaimer missing", s)
@@ -78,28 +68,10 @@ func TestStatusReportsOpenCodeAttachment(t *testing.T) {
}
}
func TestStatusUnconfiguredUnhealthyAndIPv6Candidates(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "")
r := httptest.NewRequest("GET", "http://localhost/connect", nil)
if s := systemStatus(r, time.Now(), nil); s.Ntfy.Health != "not configured" {
t.Fatal(s)
}
for _, body := range []string{`{"healthy":false}`, `not-json`} {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(body)) }))
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/topic")
s := systemStatus(r, time.Now(), nil)
srv.Close()
if s.Ntfy.Health != "unhealthy" || s.Ntfy.URL != "" || s.Ntfy.Port == "" {
t.Fatal(s)
}
}
func TestStatusIPv6Candidates(t *testing.T) {
addresses := []protocol.NetworkAddress{{Interface: "test", IP: "::1"}, {Interface: "test", IP: "192.0.2.1"}}
urls := candidateURLs(addresses, "http", "8090", "/topic")
if urls[0] != "http://[::1]:8090/topic" || urls[1] != "http://192.0.2.1:8090/topic" {
urls := candidateURLs(addresses, "ws", "8080", "/connect")
if urls[0] != "ws://[::1]:8080/connect" || urls[1] != "ws://192.0.2.1:8080/connect" {
t.Fatal(urls)
}
if localEndpoint(&url.URL{Host: "remote.example:8090", Scheme: "http"}, "test", addresses) {
t.Fatal("remote endpoint guessed local")
}
}
+1 -5
View File
@@ -142,7 +142,6 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
// Prompts queued behind a running turn are durable and owned by their
// session; resume delivering any a previous process left queued.
hub.queueStore = stores[0]
hub.startChatNotificationOutbox(ctx, stores[0])
hub.liveStore = stores[0]
hub.turnDiffStore = stores[0]
}
@@ -256,7 +255,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
log.Printf("list pipelines: %v", err)
return
}
if err := write(protocol.Message{Type: protocol.PipelineList, Pipelines: items, NotificationEndpoints: notificationEndpoints()}); err != nil {
if err := write(protocol.Message{Type: protocol.PipelineList, Pipelines: items}); err != nil {
return
}
}
@@ -388,9 +387,6 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
continue
}
response := protocol.Message{Type: protocol.Pong, ID: request.ID}
if request.Type == protocol.List || request.Type == protocol.Submit {
response.NotificationEndpoints = notificationEndpoints()
}
if request.Type == protocol.GetStatus {
response.Type = protocol.Status
response.Status = systemStatus(r, started, runErr)