Attach run artifacts to app notifications

This commit is contained in:
2026-11-12 18:39:03 +00:00
parent f102ff94ea
commit d42d7a3534
10 changed files with 266 additions and 18 deletions
+19 -2
View File
@@ -320,14 +320,31 @@ func runNotificationKind(event string) string {
// runNotificationRecord builds the app notification for one run event:
// identity "run:<run>:<step>:<event>", deep link and group from the run id.
func runNotificationRecord(runID int64, sequence int, event, kind, title, message string) pipeline.AppNotificationRecord {
func runNotificationRecord(runID int64, sequence int, event, kind, title, message string, extras ...interface{}) pipeline.AppNotificationRecord {
var artifact *protocol.NotificationArtifact
var preview string
if len(extras) > 0 {
artifact, _ = extras[0].(*protocol.NotificationArtifact)
}
if len(extras) > 1 {
preview, _ = extras[1].(string)
}
click := runAttentionClick(runID)
runClick := ""
if artifact != nil {
click = notificationClick(runID, sequence, artifact)
runClick = runAttentionClick(runID)
}
return pipeline.AppNotificationRecord{
AppNotification: protocol.AppNotification{
ID: fmt.Sprintf("run:%d:%d:%s", runID, sequence, event),
Kind: kind,
Title: title,
Message: message,
Click: runAttentionClick(runID),
Click: click,
RunClick: runClick,
Artifact: artifact,
Preview: preview,
Priority: protocol.DefaultNotificationPriority,
Tags: []string{},
Group: fmt.Sprintf("run:%d", runID),
+125 -3
View File
@@ -8,8 +8,13 @@ import (
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"log"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"syscall"
"time"
@@ -70,6 +75,7 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
// The app stream gets one notification per step event, recorded before
// the first ntfy publication; artifacts stay ntfy attachments.
appEvent, appKind := stageNotification(event, step.Target)
appArtifact, appPreview := r.resolveNotificationArtifact(id, step.Sequence, policy.Open)
recorded := false
ntfyOn := ntfyEnabled(ctx, r.settingsStore())
send := func(filename string, data []byte) {
@@ -80,7 +86,7 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
receipt := &receipts[len(receipts)-1]
if !recorded {
recorded = true
r.notes.record(ctx, runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary))
r.notes.record(ctx, runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview))
}
if !ntfyOn {
receipt.Status = "sent"
@@ -462,11 +468,15 @@ func (r *runner) deliverRunNotificationBatch(now time.Time, limit int) {
// and the web origin is server configuration that can change.
n.Click = runAttentionClick(n.RunID)
ctx, cancel := context.WithTimeout(r.ctx, 30*time.Second)
r.notes.record(ctx, runNotificationRecord(n.RunID, n.Sequence, n.Event, runNotificationKind(n.Event), n.Title, n.Body))
artifact, preview := r.resolveNotificationArtifact(n.RunID, n.Sequence, "")
n.Click = notificationClick(n.RunID, n.Sequence, artifact)
r.notes.record(ctx, runNotificationRecord(n.RunID, n.Sequence, n.Event, runNotificationKind(n.Event), n.Title, n.Body, artifact, preview))
var result stage.Values
var publishErr error
if ntfyEnabled(ctx, r.settingsStore()) {
result, publishErr = ntfyPublish(ctx, n.Channel, n.Title, n.Body, "", nil, n.Click, runAttentionViews(n.RunID)...)
// ntfy retains its existing run-level tap target; the richer artifact
// target is carried by the app notification stream.
result, publishErr = ntfyPublish(ctx, n.Channel, n.Title, n.Body, "", nil, runAttentionClick(n.RunID), runAttentionViews(n.RunID)...)
}
cancel()
messageID, _ := result["message_id"].(string)
@@ -536,6 +546,118 @@ func notificationArtifact(workspace, name string) ([]byte, error) {
return data, nil
}
func notificationClick(runID int64, sequence int, artifact *protocol.NotificationArtifact) string {
if artifact == nil {
return runAttentionClick(runID)
}
parts := strings.Split(artifact.Path, "/")
for i, part := range parts {
parts[i] = url.PathEscape(part)
}
return fmt.Sprintf("pipelines://artifact/%d/%d/%s", runID, sequence, strings.Join(parts, "/"))
}
// resolveNotificationArtifact selects only files in the run's shared public/.
// It is deliberately independent of the ntfy attachment policy.
func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern string) (*protocol.NotificationArtifact, string) {
root := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public")
type candidate struct {
path string
info os.FileInfo
}
var candidates []candidate
_ = filepath.Walk(root, func(name string, info os.FileInfo, err error) error {
if err != nil || info == nil {
return nil
}
rel, _ := filepath.Rel(root, name)
if rel == "." {
return nil
}
parts := strings.Split(filepath.ToSlash(rel), "/")
for _, part := range parts {
if strings.HasPrefix(part, ".") {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
}
if info.Mode()&os.ModeSymlink != 0 {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if !info.Mode().IsRegular() {
return nil
}
rel = filepath.ToSlash(rel)
if pattern != "" {
ok, _ := path.Match(pattern, rel)
if !ok {
return nil
}
}
candidates = append(candidates, candidate{rel, info})
return nil
})
if pattern == "" && len(candidates) != 1 {
return nil, ""
}
if len(candidates) == 0 {
return nil, ""
}
selected := candidates[0]
for _, c := range candidates[1:] {
if c.info.ModTime().After(selected.info.ModTime()) {
selected = c
}
}
full := filepath.Join(root, filepath.FromSlash(selected.path))
file, err := os.Open(full)
if err != nil {
return nil, ""
}
defer file.Close()
data, err := io.ReadAll(io.LimitReader(file, 64<<10))
if err != nil {
return nil, ""
}
media := mime.TypeByExtension(filepath.Ext(selected.path))
if media == "" {
sample := data
if len(sample) > 512 {
sample = sample[:512]
}
media = http.DetectContentType(sample)
}
a := &protocol.NotificationArtifact{RunID: runID, Sequence: sequence, Path: selected.path, Name: filepath.Base(selected.path), URL: artifactURL(runID, sequence, "public/"+selected.path), MediaType: media}
return a, notificationPreview(data, media, filepath.Ext(selected.path))
}
var markdownSyntax = regexp.MustCompile(`[*_` + "`" + `>#\[\]()]`)
func notificationPreview(data []byte, media, ext string) string {
if !(strings.HasPrefix(media, "text/") || ext == ".md" || ext == ".markdown") {
return ""
}
text := strings.ReplaceAll(string(data), "\r\n", "\n")
lines := strings.Split(text, "\n")
for i, line := range lines {
lines[i] = strings.Join(strings.Fields(markdownSyntax.ReplaceAllString(line, "")), " ")
}
text = strings.TrimSpace(strings.Join(lines, "\n"))
if len([]rune(text)) <= 600 {
return text
}
runes := []rune(strings.TrimRight(text, " \n"))
if len(runes) > 599 {
runes = runes[:599]
}
return strings.TrimRight(string(runes), " \n") + "…"
}
// stageNotificationSummary is a stage notification's one-line body. The
// outcome is shown only when the stage recorded one (a waiting human stage has
// none yet), and a waiting stage says what it waits for.
+41
View File
@@ -19,6 +19,7 @@ import (
"sync/atomic"
"syscall"
"testing"
"time"
)
func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
@@ -269,6 +270,46 @@ func TestNotificationArtifactPathSafety(t *testing.T) {
}
}
func TestNotificationArtifactSelectionAndPreview(t *testing.T) {
root := t.TempDir()
public := filepath.Join(root, "9", "public")
if err := os.MkdirAll(filepath.Join(public, "reports"), 0700); err != nil {
t.Fatal(err)
}
old := filepath.Join(public, "reports", "old.md")
newer := filepath.Join(public, "reports", "new.md")
if err := os.WriteFile(old, []byte("old"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(newer, []byte("# Hello world\n\n"+strings.Repeat("word ", 200)), 0600); err != nil {
t.Fatal(err)
}
oldTime := time.Now().Add(-time.Hour)
if err := os.Chtimes(old, oldTime, oldTime); err != nil {
t.Fatal(err)
}
r := &runner{artifactsRoot: root}
a, preview := r.resolveNotificationArtifact(9, 3, "reports/*.md")
if a == nil || a.Path != "reports/new.md" || a.URL != "/artifacts/9/3/public/reports/new.md" {
t.Fatalf("wrong selected artifact: %+v", a)
}
if len([]rune(preview)) > 600 || !strings.HasPrefix(preview, "Hello world") || !strings.HasSuffix(preview, "…") {
t.Fatalf("wrong preview: %q", preview)
}
if got := notificationClick(9, 3, a); got != "pipelines://artifact/9/3/reports/new.md" {
t.Fatal(got)
}
if got, _ := r.resolveNotificationArtifact(9, 3, ""); got != nil {
t.Fatal("multiple files selected automatically")
}
if err := os.Remove(old); err != nil {
t.Fatal(err)
}
if got, _ := r.resolveNotificationArtifact(9, 3, ""); got == nil || got.Path != "reports/new.md" {
t.Fatal("single artifact not selected automatically")
}
}
// TestRunAttentionEventMapping pins the single decision of whether a run needs
// the operator: a run parked on a person (waiting) or a failed run, and nothing
// else. A queued, running, succeeded, canceled or interrupted run never notifies.