diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/MainActivity.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/MainActivity.kt index ff6d5f59..7937bb2f 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/MainActivity.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/MainActivity.kt @@ -51,10 +51,12 @@ class MainActivity : FlutterActivity() { /** * A notification whose click is an http(s) page (a stage's `link=`, such * as a published doc) opens it in the browser rather than as an app route. + * A relaunch from recents replays the original intent; it opens nothing. */ private fun openExternalLink(intent: Intent?) { val link = intent?.getStringExtra(NotificationPresenter.EXTRA_EXTERNAL_LINK) ?: return intent.removeExtra(NotificationPresenter.EXTRA_EXTERNAL_LINK) + if ((intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)).addCategory(Intent.CATEGORY_BROWSABLE)) } catch (_: ActivityNotFoundException) { diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt index 044a9045..55cef433 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt @@ -156,7 +156,7 @@ class NotificationPresenter(private val context: Context) { .setAutoCancel(true) .setWhen(latest.whenMillis) .setShowWhen(true) - .setContentIntent(openIntent(ids, latest.click, id)) + .setContentIntent(openIntent(ids, threadClick(entries), id)) .apply { addRunAction(latest, id) } .setDeleteIntent(dismissIntent(ids, id)) builder.setStyle(NotificationCompat.BigTextStyle().bigText(threadPreview(latest))) @@ -285,17 +285,34 @@ class NotificationPresenter(private val context: Context) { /** Builds the deep-link portion of a tray tap without requiring Android Context. */ fun notificationIntent(ids: List, click: String): NotificationIntentSpec { val link = notificationLink(click) - val scheme = link.substringBefore(":", "") - val appLink = scheme == "pipelines" - val external = scheme.lowercase() in setOf("http", "https") && link.startsWith("$scheme://") + val appLink = link.substringBefore(":", "") == "pipelines" return NotificationIntentSpec( ids = ids.joinToString("\n"), action = if (appLink) Intent.ACTION_VIEW else null, data = if (appLink) link else null, - externalLink = if (external) link else null, + externalLink = if (isExternalLink(link)) link else null, ) } + /** An http(s) page (a stage's `link=`), opened in the browser. */ + fun isExternalLink(click: String): Boolean { + val scheme = click.substringBefore(":", "") + return scheme.lowercase() in setOf("http", "https") && click.startsWith("$scheme://") + } + + /** + * A thread's tap target: its latest click, except that a thread of + * several entries opens the run rather than one entry's external page. + */ + fun threadClick(entries: List): String { + val latest = entries.last() + return if (entries.size > 1 && isExternalLink(latest.click) && latest.runClick.isNotEmpty()) { + latest.runClick + } else { + latest.click + } + } + fun runActionLabel(runClick: String): String? = if (runClick.isEmpty()) null else "Open run" diff --git a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt index 069b3c3e..5e332c07 100644 --- a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt +++ b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt @@ -61,6 +61,24 @@ class NotificationProtocolTest { assertNull(NotificationPresenter.notificationIntent(listOf("n-1"), "https:claude.ai").externalLink) } + @Test + fun threadOfSeveralEntriesOpensTheRunInsteadOfAnExternalPage() { + val doc = ThreadEntry( + id = "n-2", + kind = "stage_succeeded", + priority = 3, + sender = "Run 7", + text = "Standup ready", + click = "https://claude.ai/public/artifacts/0f3c-standup", + whenMillis = 2L, + runClick = "pipelines://run/7", + ) + val earlier = doc.copy(id = "n-1", click = "pipelines://run/7", runClick = "", whenMillis = 1L) + assertEquals(doc.click, NotificationPresenter.threadClick(listOf(doc))) + assertEquals("pipelines://run/7", NotificationPresenter.threadClick(listOf(earlier, doc))) + assertEquals("pipelines://run/7", NotificationPresenter.threadClick(listOf(doc, earlier))) + } + @Test fun groupedNotificationUsesLatestArtifactPreviewAsExpandedText() { val entry = ThreadEntry( diff --git a/internal/author/skill/references/format.md b/internal/author/skill/references/format.md index 9ab29d9b..ed7ae534 100644 --- a/internal/author/skill/references/format.md +++ b/internal/author/skill/references/format.md @@ -236,4 +236,5 @@ The `notify` block accepts `on`, optional legacy `destination`, optional `artifacts=markdown|files`, optional `open=` and optional `link=`. `open` selects an artifact in the run's shared `public/`; without it, one and only one regular file there is selected automatically. -`link` selects a `public/` file whose first line is the http(s) tap target. +`link` selects a `public/` file whose first non-empty line is the http(s) tap +target; that file is never the attached artifact. diff --git a/internal/author/skill/references/notifications.md b/internal/author/skill/references/notifications.md index a536de34..8ce5713c 100644 --- a/internal/author/skill/references/notifications.md +++ b/internal/author/skill/references/notifications.md @@ -71,8 +71,10 @@ produce no attached artifact. This is separate from ntfy's `artifacts=` keys. URL the stage produced, such as a published doc. The pattern follows the `open=` rules; the matched file's first non-empty line must be an absolute http(s) URL without credentials or fragment. The run stays reachable from the notification's -run action, and `open=` still attaches its artifact. A missing file or invalid -URL keeps the usual tap target and is noted on the notification receipt: +run action (ntfy uses the link only when `PIPELINES_WEB_PUBLIC_URL` gives it a +browser run view), and `open=` still attaches its artifact; the link file itself +is never attached. A missing file or invalid URL keeps the usual tap target and +is noted on the notification receipt: ```notify on=success diff --git a/internal/protocol/message.go b/internal/protocol/message.go index d49ab897..6ab0d983 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -57,7 +57,7 @@ type NotificationPolicy struct { Destination string `json:"destination"` Artifacts []string `json:"artifacts,omitempty"` Open string `json:"open,omitempty"` - // Link names a public/ file whose first line is the http(s) tap target. + // Link names a public/ file whose first non-empty line is the http(s) tap target. Link string `json:"link,omitempty"` } diff --git a/internal/server/notify.go b/internal/server/notify.go index 36d911dd..14ce11f5 100644 --- a/internal/server/notify.go +++ b/internal/server/notify.go @@ -75,22 +75,16 @@ 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) - // A `link=` file decides the tap target (ntfy and app alike); the run stays - // reachable through the app's run action and ntfy's browser view. - click := runAttentionClick(id) - link, linkDiagnostic := r.resolveNotificationLink(id, policy.Link) - if link != "" { - click = link - } - note := func(diagnostic string) string { - if linkDiagnostic == "" || diagnostic == "" { - return diagnostic + linkDiagnostic - } - return diagnostic + "; " + linkDiagnostic - } + // 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() { @@ -99,25 +93,20 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N receipt := &receipts[len(receipts)-1] if !recorded { recorded = true - record := runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview) - if link != "" { - record.Click, record.RunClick = link, runAttentionClick(id) - } - r.notes.record(ctx, record) + r.notes.record(ctx, withNotificationLink(runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview), link)) } if !ntfyOn { receipt.Status = "sent" - receipt.Diagnostic = note("ntfy disabled; delivered to app clients only") + receipt.Diagnostic = "ntfy disabled; delivered to app clients only" persist() return } - result, err := ntfyPublish(ctx, "system", title, summary, filename, data, click, runAttentionViews(id)...) + result, err := ntfyPublish(ctx, "system", title, summary, filename, data, ntfyClick, views...) if err != nil { receipt.Status = "failed" - receipt.Diagnostic = note(err.Error()) + receipt.Diagnostic = err.Error() } else { receipt.Status = "sent" - receipt.Diagnostic = note("") receipt.MessageID, _ = result["message_id"].(string) receipt.AttachmentURL, _ = result["attachment_url"].(string) } @@ -181,6 +170,19 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N 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 { @@ -194,11 +196,7 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N } } if lease != nil { - diagnostic := "stage notification publication failed" - if len(receipts) > 0 && receipts[0].Diagnostic != "" { - diagnostic = receipts[0].Diagnostic - } - if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("%s", diagnostic)); err != nil { + if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("%s", failure)); err != nil { log.Printf("release stage notification run=%d: %v", id, err) } } @@ -486,15 +484,19 @@ 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) - artifact, preview := r.resolveNotificationArtifact(n.RunID, n.Sequence, "") + // A retry of a stage hook's failed publication keeps the hook's link. + 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, runNotificationRecord(n.RunID, n.Sequence, n.Event, runNotificationKind(n.Event), n.Title, n.Body, artifact, preview)) + 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; 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)...) + // 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...) } cancel() messageID, _ := result["message_id"].(string) @@ -577,13 +579,13 @@ 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. -func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern string) (*protocol.NotificationArtifact, string) { - selected := r.publicNotificationFile(runID, pattern) +// 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) if selected == "" { return nil, "" } - full := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public", filepath.FromSlash(selected)) - file, err := os.Open(full) + file, _, err := openPublicFile(filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public"), selected) if err != nil { return nil, "" } @@ -604,10 +606,11 @@ func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern return a, notificationPreview(data, media, filepath.Ext(selected)) } -// publicNotificationFile picks a regular, non-hidden, non-symlinked file in the -// run's shared public/ as a slash path: the most recently modified match of -// pattern, or without a pattern the only file there. "" when none qualifies. -func (r *runner) publicNotificationFile(runID int64, pattern string) string { +// publicNotificationFile picks a regular, non-hidden, non-symlinked file other +// than exclude in the run's shared public/ as a slash path: the most recently +// modified match of pattern, or without a pattern the only such file there. +// "" when none qualifies. +func (r *runner) publicNotificationFile(runID int64, pattern, exclude string) string { root := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public") type candidate struct { path string @@ -641,6 +644,9 @@ func (r *runner) publicNotificationFile(runID int64, pattern string) string { return nil } rel = filepath.ToSlash(rel) + if rel == exclude { + return nil + } if pattern != "" { ok, _ := path.Match(pattern, rel) if !ok { diff --git a/internal/server/notify_link.go b/internal/server/notify_link.go index 33f95086..c7659171 100644 --- a/internal/server/notify_link.go +++ b/internal/server/notify_link.go @@ -2,11 +2,14 @@ package server 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" "path/filepath" + "slices" "strings" "syscall" ) @@ -17,46 +20,60 @@ 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. -// Otherwise it returns no link and the reason for the notification receipt. -func (r *runner) resolveNotificationLink(runID int64, pattern string) (string, string) { +// 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) { if pattern == "" { - return "", "" + return "", "", "" } - rel := r.publicNotificationFile(runID, pattern) + rel := r.publicNotificationFile(runID, pattern, "") if rel == "" { - return "", fmt.Sprintf("notify link: no public file matches %s", pattern) + return "", "", fmt.Sprintf("notify link: no public file matches %s", pattern) } data, err := readNotificationLink(filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public"), rel) if err != nil { - return "", fmt.Sprintf("notify link: public/%s %v", rel, err) + return "", "", fmt.Sprintf("notify link: public/%s %v", rel, err) } for _, line := range strings.Split(string(data), "\n") { if line = strings.TrimSpace(line); line == "" { continue } if !validNotificationLink(line) { - return "", fmt.Sprintf("notify link: public/%s does not start with an absolute http(s) URL", rel) + return "", "", fmt.Sprintf("notify link: public/%s does not start with an absolute http(s) URL", rel) } - return line, "" + return line, rel, "" } - return "", fmt.Sprintf("notify link: public/%s is empty", rel) + return "", "", fmt.Sprintf("notify link: public/%s is empty", rel) } -// readNotificationLink reads one small regular file below root without -// following a symlink out of it. -func readNotificationLink(root, rel string) ([]byte, error) { +// openPublicFile opens a regular file below root without following a symlink +// out of it or blocking on a special file. +func openPublicFile(root, rel string) (*os.File, os.FileInfo, error) { scoped, err := os.OpenRoot(root) if err != nil { - return nil, fmt.Errorf("is unreadable") + return nil, nil, err } defer scoped.Close() file, err := scoped.OpenFile(filepath.FromSlash(rel), os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0) + if err != nil { + return nil, nil, err + } + info, err := file.Stat() + if err != nil || !info.Mode().IsRegular() { + file.Close() + return nil, nil, fmt.Errorf("not a regular file") + } + return file, info, nil +} + +// readNotificationLink reads one small regular file below root. +func readNotificationLink(root, rel string) ([]byte, error) { + file, info, err := openPublicFile(root, rel) if err != nil { return nil, fmt.Errorf("is unreadable") } defer file.Close() - info, err := file.Stat() - if err != nil || !info.Mode().IsRegular() || info.Size() > notificationLinkLimit { + if info.Size() > notificationLinkLimit { return nil, fmt.Errorf("must be a regular file of at most 4 KiB") } data, err := io.ReadAll(io.LimitReader(file, notificationLinkLimit+1)) @@ -72,3 +89,50 @@ func validNotificationLink(link string) bool { 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, "" +} + +// withNotificationLink makes link the app notification's tap target, keeping +// the run as its run action. +func withNotificationLink(record pipeline.AppNotificationRecord, link string) pipeline.AppNotificationRecord { + if link != "" { + record.Click, record.RunClick = link, runAttentionClick(record.RunID) + } + return record +} + +// 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. +// 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] + if event == "" || r.store == nil { + return "", "" + } + detail, err := r.store.GetRun(r.ctx, n.RunID) + if err != nil { + return "", "" + } + for _, step := range detail.Steps { + if step.Sequence != n.Sequence { + continue + } + for _, definition := range detail.Graph.Stages { + if definition.Key == step.Stage && definition.Notify != nil && slices.Contains(definition.Notify.On, event) { + link, file, _ := r.resolveNotificationLink(n.RunID, definition.Notify.Link) + return link, file + } + } + } + return "", "" +} diff --git a/internal/server/notify_link_test.go b/internal/server/notify_link_test.go index ebcf4669..56883fc4 100644 --- a/internal/server/notify_link_test.go +++ b/internal/server/notify_link_test.go @@ -2,21 +2,58 @@ 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" ) +const standupDoc = "https://claude.ai/public/artifacts/0f3c-standup" + +// writePublic writes files into run id's shared public/ directory. +func writePublic(t *testing.T, artifacts string, id int64, files map[string]string) { + t.Helper() + public := filepath.Join(artifacts, fmt.Sprint(id), "public") + if err := os.MkdirAll(public, 0700); err != nil { + t.Fatal(err) + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(public, name), []byte(content), 0600); err != nil { + t.Fatal(err) + } + } +} + +// appNotification returns the app notification with id, or nil. +func appNotification(t *testing.T, store *pipeline.Store, id string) *protocol.AppNotification { + t.Helper() + active, _, err := store.ActiveAppNotifications(context.Background(), "", time.Now()) + if err != nil { + t.Fatal(err) + } + for i := range active { + if active[i].ID == id { + return &active[i] + } + } + return nil +} + // A stage hook's `link=` file decides the ntfy and app tap target when its -// first line is an http(s) URL, keeping the run one action away; anything else -// falls back to the run link and says why on the receipt. +// 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. func TestStageHookLinkClick(t *testing.T) { - t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com") captured := newNtfyCapture(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -31,18 +68,23 @@ func TestStageHookLinkClick(t *testing.T) { d, _ := store.Get(ctx, items[0].ID, 0) artifacts := t.TempDir() r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store), artifactsRoot: artifacts} - const doc = "https://claude.ai/public/artifacts/0f3c-standup" + const doc = standupDoc for _, test := range []struct { name, link, open string files map[string]string - click bool // the doc URL is the tap target - artifact string // the attached artifact path, by today's open= rules + 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 }{ - {name: "valid", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "\n " + doc + " \r\nnotes\n", "notes.txt": "n"}, click: true}, - {name: "valid-only-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, click: true, artifact: "standup-link.txt"}, + {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"}, @@ -50,60 +92,67 @@ func TestStageHookLinkClick(t *testing.T) { {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"}}, {name: "absent-only-file", files: map[string]string{"standup-link.txt": doc}, artifact: "standup-link.txt"}, - {name: "with-open", link: "*-link.txt", open: "*.md", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup", "notes.txt": "n"}, click: true, artifact: "standup.md"}, + {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) { - id, _, err := store.CreateRun(ctx, d, test.name, t.TempDir(), false, nil, map[string]any{"prompt": "task"}) + 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) } - public := filepath.Join(artifacts, fmt.Sprint(id), "public") - if err := os.MkdirAll(public, 0700); err != nil { - t.Fatal(err) - } - for name, content := range test.files { - if err := os.WriteFile(filepath.Join(public, name), []byte(content), 0600); err != nil { - t.Fatal(err) - } - } + writePublic(t, artifacts, id, test.files) 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{}} + 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()) - policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Link: test.link, Open: test.open} - r.notifyStep(id, d.Name, t.TempDir(), policy, step) + r.notifyStep(id, d.Name, workspace, policy, step) - // Without a usable link everything is as before: ntfy taps open the - // run, the app opens the attached artifact (else the run). + // ntfy opens the link only beside a web run view; the app opens the + // link (else the attached artifact, else the run). runClick := fmt.Sprintf("pipelines://run/%d", id) - wantNtfy, wantClick, wantRunClick := runClick, runClick, "" + 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 } if test.click { - wantNtfy, wantClick, wantRunClick = doc, doc, runClick + wantClick, wantRunClick = doc, runClick } - got := captured() - if len(got) != before+1 { - t.Fatalf("ntfy publications = %+v", got[before:]) + got := captured()[before:] + if len(got) != publications { + t.Fatalf("ntfy publications = %+v", got) } - if got[before].Click != wantNtfy || got[before].Actions != fmt.Sprintf("view, Open in browser, https://pipelines.example.com/runs/%d", id) { - t.Fatalf("ntfy click/actions = %q %q, want %q", got[before].Click, got[before].Actions, wantNtfy) - } - active, _, err := store.ActiveAppNotifications(ctx, "", time.Now()) - if err != nil { - t.Fatal(err) - } - var n *protocol.AppNotification - for i := range active { - if active[i].ID == fmt.Sprintf("run:%d:1:success", id) { - n = &active[i] + 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) } @@ -115,9 +164,142 @@ func TestStageHookLinkClick(t *testing.T) { t.Fatal(err) } receipts := detail.Steps[0].Notifications - if len(receipts) != 1 || receipts[0].Status != "sent" || !strings.Contains(receipts[0].Diagnostic, test.diagnostic) || (test.diagnostic == "") != (receipts[0].Diagnostic == "") { - t.Fatalf("receipts = %+v, want diagnostic %q", receipts, test.diagnostic) + if len(receipts) != publications { + 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) + } } }) } } + +// 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. +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) + } + items, _ := store.List(ctx) + d, _ := store.Get(ctx, items[0].ID, 0) + policy := d.Graph.Stages[0].Notify + if policy == nil || policy.Link != "standup-link.txt" { + t.Fatalf("stage policy = %+v", policy) + } + artifacts := t.TempDir() + r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store), artifactsRoot: artifacts} + for _, test := range []struct { + name string + files map[string]string + retry string // the retry's ntfy click; "" means the run + }{ + {name: "valid", files: map[string]string{"standup-link.txt": standupDoc}, retry: standupDoc}, + {name: "missing"}, + } { + t.Run(test.name, func(t *testing.T) { + id, _, err := store.CreateRun(ctx, d, test.name, t.TempDir(), false, nil, map[string]any{"prompt": "task"}) + if err != nil { + t.Fatal(err) + } + writePublic(t, artifacts, id, test.files) + 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: protocol.SuccessEnd, Output: map[string]any{}} + if err := store.FinishStep(ctx, id, step); err != nil { + t.Fatal(err) + } + // The run's transactional success intent the hook arbitrates against. + 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) + 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) + } + 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) + } + 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) + } + }) + } +} + +// Notification files in public/ are read without following a symlink (a swap +// after selection) or blocking on a special file. +func TestOpenPublicFileRefusesSymlinksAndSpecialFiles(t *testing.T) { + root := t.TempDir() + outside := filepath.Join(t.TempDir(), "secret.txt") + if err := os.WriteFile(outside, []byte("secret"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "report.md"), []byte("# Report"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(root, "alias.md")); err != nil { + t.Fatal(err) + } + if err := syscall.Mkfifo(filepath.Join(root, "pipe.md"), 0600); err != nil { + t.Fatal(err) + } + for _, name := range []string{"alias.md", "pipe.md", "../secret.txt"} { + if file, _, err := openPublicFile(root, name); err == nil { + file.Close() + t.Fatal("unsafe public file opened", name) + } + } + file, _, err := openPublicFile(root, "report.md") + if err != nil { + t.Fatal(err) + } + file.Close() +} diff --git a/internal/server/notify_test.go b/internal/server/notify_test.go index 4f6ff03e..3c4af31c 100644 --- a/internal/server/notify_test.go +++ b/internal/server/notify_test.go @@ -289,7 +289,7 @@ func TestNotificationArtifactSelectionAndPreview(t *testing.T) { t.Fatal(err) } r := &runner{artifactsRoot: root} - a, preview := r.resolveNotificationArtifact(9, 3, "reports/*.md") + 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) } @@ -299,13 +299,13 @@ func TestNotificationArtifactSelectionAndPreview(t *testing.T) { 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 { + 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" { + if got, _ := r.resolveNotificationArtifact(9, 3, "", ""); got == nil || got.Path != "reports/new.md" { t.Fatal("single artifact not selected automatically") } }