Notify link=: a stage's public/ file sets the phone tap target

A stage's notify block may name `link=<pattern>` (validated like `open=`).
When the hook fires, the newest public/ match is read (at most 4 KiB); its
first non-empty line, if an absolute http(s) URL ntfy accepts as a click,
becomes the ntfy Click and the app notification click, with the run kept
as the app's run action and ntfy's browser view. A missing file or invalid
URL keeps today's tap target and is noted on the receipt diagnostic.

Android opens such an http(s) click in the browser (after clearing the
notification) instead of handing it to Flutter as a route.
This commit is contained in:
2026-12-02 12:20:22 +00:00
parent 26b1c00094
commit f5f31b7bcd
12 changed files with 355 additions and 55 deletions
+55 -29
View File
@@ -76,6 +76,19 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
// 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
}
recorded := false
ntfyOn := ntfyEnabled(ctx, r.settingsStore())
send := func(filename string, data []byte) {
@@ -86,20 +99,25 @@ 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, appArtifact, appPreview))
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)
}
if !ntfyOn {
receipt.Status = "sent"
receipt.Diagnostic = "ntfy disabled; delivered to app clients only"
receipt.Diagnostic = note("ntfy disabled; delivered to app clients only")
persist()
return
}
result, err := ntfyPublish(ctx, "system", title, summary, filename, data, runAttentionClick(id), runAttentionViews(id)...)
result, err := ntfyPublish(ctx, "system", title, summary, filename, data, click, runAttentionViews(id)...)
if err != nil {
receipt.Status = "failed"
receipt.Diagnostic = err.Error()
receipt.Diagnostic = note(err.Error())
} else {
receipt.Status = "sent"
receipt.Diagnostic = note("")
receipt.MessageID, _ = result["message_id"].(string)
receipt.AttachmentURL, _ = result["attachment_url"].(string)
}
@@ -560,6 +578,36 @@ 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)
if selected == "" {
return nil, ""
}
full := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public", filepath.FromSlash(selected))
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))
if media == "" {
sample := data
if len(sample) > 512 {
sample = sample[:512]
}
media = http.DetectContentType(sample)
}
a := &protocol.NotificationArtifact{RunID: runID, Sequence: sequence, Path: selected, Name: filepath.Base(selected), URL: artifactURL(runID, sequence, "public/"+selected), MediaType: media}
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 {
root := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public")
type candidate struct {
path string
@@ -602,11 +650,8 @@ func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern
candidates = append(candidates, candidate{rel, info})
return nil
})
if pattern == "" && len(candidates) != 1 {
return nil, ""
}
if len(candidates) == 0 {
return nil, ""
if (pattern == "" && len(candidates) != 1) || len(candidates) == 0 {
return ""
}
selected := candidates[0]
for _, c := range candidates[1:] {
@@ -614,26 +659,7 @@ func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern
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))
return selected.path
}
var markdownSyntax = regexp.MustCompile(`[*_` + "`" + `>#\[\]()]`)
+74
View File
@@ -0,0 +1,74 @@
package server
import (
"fmt"
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"net/url"
"os"
"path/filepath"
"strings"
"syscall"
)
// notificationLinkLimit bounds a `link=` file: it holds one URL, not a document.
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) {
if pattern == "" {
return "", ""
}
rel := r.publicNotificationFile(runID, pattern)
if rel == "" {
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)
}
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 line, ""
}
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) {
scoped, err := os.OpenRoot(root)
if err != nil {
return nil, fmt.Errorf("is unreadable")
}
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, fmt.Errorf("is unreadable")
}
defer file.Close()
info, err := file.Stat()
if err != nil || !info.Mode().IsRegular() || 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))
if err != nil || len(data) > notificationLinkLimit {
return nil, fmt.Errorf("must be a regular file of at most 4 KiB")
}
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).
func validNotificationLink(link string) bool {
u, err := url.Parse(link)
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && stage.ValidNtfyClick(link)
}
+123
View File
@@ -0,0 +1,123 @@
package server
import (
"context"
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// 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.
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()
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)
}
items, _ := store.List(ctx)
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"
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
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: "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: "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: "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"}},
{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"},
} {
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)
}
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)
}
}
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{}}
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)
// Without a usable link everything is as before: ntfy taps open the
// run, the app opens the attached artifact (else the run).
runClick := fmt.Sprintf("pipelines://run/%d", id)
wantNtfy, wantClick, wantRunClick := runClick, 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
}
got := captured()
if len(got) != before+1 {
t.Fatalf("ntfy publications = %+v", got[before:])
}
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]
}
}
if n == nil || n.Click != wantClick || n.RunClick != wantRunClick {
t.Fatalf("app notification = %+v, want click %q run %q", n, wantClick, wantRunClick)
}
if (n.Artifact == nil) != (test.artifact == "") || (n.Artifact != nil && n.Artifact.Path != test.artifact) {
t.Fatalf("app artifact = %+v, want %q", n.Artifact, test.artifact)
}
detail, err := store.GetRun(ctx, id)
if err != nil {
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)
}
})
}
}