Notify link=: review fixes
- ntfy uses the link only beside a web run view; otherwise it keeps the run click and the receipt says why (app click stays the link). - The outbox retry of a hook's failed publication re-resolves the stage's link=, so the ntfy and app tap targets keep it. - A valid link file is never the attached artifact. - Notification artifacts are read through os.OpenRoot with O_NOFOLLOW. - The link note is recorded once, on the first receipt, and never becomes the run-level failure reason. - Android: a recents relaunch does not reopen the link, and a run thread of several entries opens the run rather than the latest external page. - Docs and the protocol comment say "first non-empty line".
This commit is contained in:
@@ -51,10 +51,12 @@ class MainActivity : FlutterActivity() {
|
|||||||
/**
|
/**
|
||||||
* A notification whose click is an http(s) page (a stage's `link=`, such
|
* 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.
|
* 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?) {
|
private fun openExternalLink(intent: Intent?) {
|
||||||
val link = intent?.getStringExtra(NotificationPresenter.EXTRA_EXTERNAL_LINK) ?: return
|
val link = intent?.getStringExtra(NotificationPresenter.EXTRA_EXTERNAL_LINK) ?: return
|
||||||
intent.removeExtra(NotificationPresenter.EXTRA_EXTERNAL_LINK)
|
intent.removeExtra(NotificationPresenter.EXTRA_EXTERNAL_LINK)
|
||||||
|
if ((intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return
|
||||||
try {
|
try {
|
||||||
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)).addCategory(Intent.CATEGORY_BROWSABLE))
|
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)).addCategory(Intent.CATEGORY_BROWSABLE))
|
||||||
} catch (_: ActivityNotFoundException) {
|
} catch (_: ActivityNotFoundException) {
|
||||||
|
|||||||
+22
-5
@@ -156,7 +156,7 @@ class NotificationPresenter(private val context: Context) {
|
|||||||
.setAutoCancel(true)
|
.setAutoCancel(true)
|
||||||
.setWhen(latest.whenMillis)
|
.setWhen(latest.whenMillis)
|
||||||
.setShowWhen(true)
|
.setShowWhen(true)
|
||||||
.setContentIntent(openIntent(ids, latest.click, id))
|
.setContentIntent(openIntent(ids, threadClick(entries), id))
|
||||||
.apply { addRunAction(latest, id) }
|
.apply { addRunAction(latest, id) }
|
||||||
.setDeleteIntent(dismissIntent(ids, id))
|
.setDeleteIntent(dismissIntent(ids, id))
|
||||||
builder.setStyle(NotificationCompat.BigTextStyle().bigText(threadPreview(latest)))
|
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. */
|
/** Builds the deep-link portion of a tray tap without requiring Android Context. */
|
||||||
fun notificationIntent(ids: List<String>, click: String): NotificationIntentSpec {
|
fun notificationIntent(ids: List<String>, click: String): NotificationIntentSpec {
|
||||||
val link = notificationLink(click)
|
val link = notificationLink(click)
|
||||||
val scheme = link.substringBefore(":", "")
|
val appLink = link.substringBefore(":", "") == "pipelines"
|
||||||
val appLink = scheme == "pipelines"
|
|
||||||
val external = scheme.lowercase() in setOf("http", "https") && link.startsWith("$scheme://")
|
|
||||||
return NotificationIntentSpec(
|
return NotificationIntentSpec(
|
||||||
ids = ids.joinToString("\n"),
|
ids = ids.joinToString("\n"),
|
||||||
action = if (appLink) Intent.ACTION_VIEW else null,
|
action = if (appLink) Intent.ACTION_VIEW else null,
|
||||||
data = if (appLink) link 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<ThreadEntry>): 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? =
|
fun runActionLabel(runClick: String): String? =
|
||||||
if (runClick.isEmpty()) null else "Open run"
|
if (runClick.isEmpty()) null else "Open run"
|
||||||
|
|
||||||
|
|||||||
+18
@@ -61,6 +61,24 @@ class NotificationProtocolTest {
|
|||||||
assertNull(NotificationPresenter.notificationIntent(listOf("n-1"), "https:claude.ai").externalLink)
|
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
|
@Test
|
||||||
fun groupedNotificationUsesLatestArtifactPreviewAsExpandedText() {
|
fun groupedNotificationUsesLatestArtifactPreviewAsExpandedText() {
|
||||||
val entry = ThreadEntry(
|
val entry = ThreadEntry(
|
||||||
|
|||||||
@@ -236,4 +236,5 @@ The `notify` block accepts `on`, optional legacy `destination`, optional
|
|||||||
`artifacts=markdown|files`, optional `open=<relative-glob>` and optional
|
`artifacts=markdown|files`, optional `open=<relative-glob>` and optional
|
||||||
`link=<relative-glob>`. `open` selects an artifact in the run's shared `public/`;
|
`link=<relative-glob>`. `open` selects an artifact in the run's shared `public/`;
|
||||||
without it, one and only one regular file there is selected automatically.
|
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.
|
||||||
|
|||||||
@@ -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=`
|
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
|
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
|
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
|
run action (ntfy uses the link only when `PIPELINES_WEB_PUBLIC_URL` gives it a
|
||||||
URL keeps the usual tap target and is noted on the notification receipt:
|
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
|
```notify
|
||||||
on=success
|
on=success
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ type NotificationPolicy struct {
|
|||||||
Destination string `json:"destination"`
|
Destination string `json:"destination"`
|
||||||
Artifacts []string `json:"artifacts,omitempty"`
|
Artifacts []string `json:"artifacts,omitempty"`
|
||||||
Open string `json:"open,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"`
|
Link string `json:"link,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+47
-41
@@ -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 app stream gets one notification per step event, recorded before
|
||||||
// the first ntfy publication; artifacts stay ntfy attachments.
|
// the first ntfy publication; artifacts stay ntfy attachments.
|
||||||
appEvent, appKind := stageNotification(event, step.Target)
|
appEvent, appKind := stageNotification(event, step.Target)
|
||||||
appArtifact, appPreview := r.resolveNotificationArtifact(id, step.Sequence, policy.Open)
|
// A `link=` file decides the tap target; it is never the attached artifact.
|
||||||
// A `link=` file decides the tap target (ntfy and app alike); the run stays
|
link, linkFile, linkDiagnostic := r.resolveNotificationLink(id, policy.Link)
|
||||||
// reachable through the app's run action and ntfy's browser view.
|
appArtifact, appPreview := r.resolveNotificationArtifact(id, step.Sequence, policy.Open, linkFile)
|
||||||
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
|
recorded := false
|
||||||
ntfyOn := ntfyEnabled(ctx, r.settingsStore())
|
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) {
|
send := func(filename string, data []byte) {
|
||||||
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "sending", Filename: filename})
|
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "sending", Filename: filename})
|
||||||
if !persist() {
|
if !persist() {
|
||||||
@@ -99,25 +93,20 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
|
|||||||
receipt := &receipts[len(receipts)-1]
|
receipt := &receipts[len(receipts)-1]
|
||||||
if !recorded {
|
if !recorded {
|
||||||
recorded = true
|
recorded = true
|
||||||
record := runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview)
|
r.notes.record(ctx, withNotificationLink(runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview), link))
|
||||||
if link != "" {
|
|
||||||
record.Click, record.RunClick = link, runAttentionClick(id)
|
|
||||||
}
|
|
||||||
r.notes.record(ctx, record)
|
|
||||||
}
|
}
|
||||||
if !ntfyOn {
|
if !ntfyOn {
|
||||||
receipt.Status = "sent"
|
receipt.Status = "sent"
|
||||||
receipt.Diagnostic = note("ntfy disabled; delivered to app clients only")
|
receipt.Diagnostic = "ntfy disabled; delivered to app clients only"
|
||||||
persist()
|
persist()
|
||||||
return
|
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 {
|
if err != nil {
|
||||||
receipt.Status = "failed"
|
receipt.Status = "failed"
|
||||||
receipt.Diagnostic = note(err.Error())
|
receipt.Diagnostic = err.Error()
|
||||||
} else {
|
} else {
|
||||||
receipt.Status = "sent"
|
receipt.Status = "sent"
|
||||||
receipt.Diagnostic = note("")
|
|
||||||
receipt.MessageID, _ = result["message_id"].(string)
|
receipt.MessageID, _ = result["message_id"].(string)
|
||||||
receipt.AttachmentURL, _ = result["attachment_url"].(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 {
|
if !sentArtifact {
|
||||||
send("", nil)
|
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
|
// Only a successful publish covers the run alert. A failed stage publisher
|
||||||
// must not swallow the durable run-level fallback and its retries.
|
// must not swallow the durable run-level fallback and its retries.
|
||||||
for _, receipt := range receipts {
|
for _, receipt := range receipts {
|
||||||
@@ -194,11 +196,7 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if lease != nil {
|
if lease != nil {
|
||||||
diagnostic := "stage notification publication failed"
|
if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("%s", failure)); err != nil {
|
||||||
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 {
|
|
||||||
log.Printf("release stage notification run=%d: %v", id, err)
|
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.
|
// and the web origin is server configuration that can change.
|
||||||
n.Click = runAttentionClick(n.RunID)
|
n.Click = runAttentionClick(n.RunID)
|
||||||
ctx, cancel := context.WithTimeout(r.ctx, 30*time.Second)
|
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)
|
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 result stage.Values
|
||||||
var publishErr error
|
var publishErr error
|
||||||
if ntfyEnabled(ctx, r.settingsStore()) {
|
if ntfyEnabled(ctx, r.settingsStore()) {
|
||||||
// ntfy retains its existing run-level tap target; the richer artifact
|
// ntfy retains its existing run-level tap target (or the hook's link);
|
||||||
// target is carried by the app notification stream.
|
// 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)...)
|
views := runAttentionViews(n.RunID)
|
||||||
|
click, _ := ntfyLinkClick(n.RunID, link, views)
|
||||||
|
result, publishErr = ntfyPublish(ctx, n.Channel, n.Title, n.Body, "", nil, click, views...)
|
||||||
}
|
}
|
||||||
cancel()
|
cancel()
|
||||||
messageID, _ := result["message_id"].(string)
|
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/.
|
// resolveNotificationArtifact selects only files in the run's shared public/.
|
||||||
// It is deliberately independent of the ntfy attachment policy.
|
// It is deliberately independent of the ntfy attachment policy.
|
||||||
func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern string) (*protocol.NotificationArtifact, string) {
|
// The exclude file (a `link=` file) is never selected.
|
||||||
selected := r.publicNotificationFile(runID, pattern)
|
func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern, exclude string) (*protocol.NotificationArtifact, string) {
|
||||||
|
selected := r.publicNotificationFile(runID, pattern, exclude)
|
||||||
if selected == "" {
|
if selected == "" {
|
||||||
return nil, ""
|
return nil, ""
|
||||||
}
|
}
|
||||||
full := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public", filepath.FromSlash(selected))
|
file, _, err := openPublicFile(filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public"), selected)
|
||||||
file, err := os.Open(full)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, ""
|
return nil, ""
|
||||||
}
|
}
|
||||||
@@ -604,10 +606,11 @@ func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern
|
|||||||
return a, notificationPreview(data, media, filepath.Ext(selected))
|
return a, notificationPreview(data, media, filepath.Ext(selected))
|
||||||
}
|
}
|
||||||
|
|
||||||
// publicNotificationFile picks a regular, non-hidden, non-symlinked file in the
|
// publicNotificationFile picks a regular, non-hidden, non-symlinked file other
|
||||||
// run's shared public/ as a slash path: the most recently modified match of
|
// than exclude in the run's shared public/ as a slash path: the most recently
|
||||||
// pattern, or without a pattern the only file there. "" when none qualifies.
|
// modified match of pattern, or without a pattern the only such file there.
|
||||||
func (r *runner) publicNotificationFile(runID int64, pattern string) string {
|
// "" when none qualifies.
|
||||||
|
func (r *runner) publicNotificationFile(runID int64, pattern, exclude string) string {
|
||||||
root := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public")
|
root := filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public")
|
||||||
type candidate struct {
|
type candidate struct {
|
||||||
path string
|
path string
|
||||||
@@ -641,6 +644,9 @@ func (r *runner) publicNotificationFile(runID int64, pattern string) string {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
rel = filepath.ToSlash(rel)
|
rel = filepath.ToSlash(rel)
|
||||||
|
if rel == exclude {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
if pattern != "" {
|
if pattern != "" {
|
||||||
ok, _ := path.Match(pattern, rel)
|
ok, _ := path.Match(pattern, rel)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
@@ -2,11 +2,14 @@ package server
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"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"
|
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||||
"io"
|
"io"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
@@ -17,46 +20,60 @@ const notificationLinkLimit = 4 << 10
|
|||||||
// resolveNotificationLink reads the tap target a stage's `link=` pattern names
|
// 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
|
// 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 an absolute http(s) URL ntfy accepts as a click.
|
||||||
// Otherwise it returns no link and the reason for the notification receipt.
|
// It returns the link and its public/ file, or no link and the reason for the
|
||||||
func (r *runner) resolveNotificationLink(runID int64, pattern string) (string, string) {
|
// notification receipt.
|
||||||
|
func (r *runner) resolveNotificationLink(runID int64, pattern string) (string, string, string) {
|
||||||
if pattern == "" {
|
if pattern == "" {
|
||||||
return "", ""
|
return "", "", ""
|
||||||
}
|
}
|
||||||
rel := r.publicNotificationFile(runID, pattern)
|
rel := r.publicNotificationFile(runID, pattern, "")
|
||||||
if rel == "" {
|
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)
|
data, err := readNotificationLink(filepath.Join(r.artifactsRoot, fmt.Sprint(runID), "public"), rel)
|
||||||
if err != nil {
|
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") {
|
for _, line := range strings.Split(string(data), "\n") {
|
||||||
if line = strings.TrimSpace(line); line == "" {
|
if line = strings.TrimSpace(line); line == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if !validNotificationLink(line) {
|
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
|
// openPublicFile opens a regular file below root without following a symlink
|
||||||
// following a symlink out of it.
|
// out of it or blocking on a special file.
|
||||||
func readNotificationLink(root, rel string) ([]byte, error) {
|
func openPublicFile(root, rel string) (*os.File, os.FileInfo, error) {
|
||||||
scoped, err := os.OpenRoot(root)
|
scoped, err := os.OpenRoot(root)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("is unreadable")
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
defer scoped.Close()
|
defer scoped.Close()
|
||||||
file, err := scoped.OpenFile(filepath.FromSlash(rel), os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
|
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 {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("is unreadable")
|
return nil, fmt.Errorf("is unreadable")
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
info, err := file.Stat()
|
if info.Size() > notificationLinkLimit {
|
||||||
if err != nil || !info.Mode().IsRegular() || info.Size() > notificationLinkLimit {
|
|
||||||
return nil, fmt.Errorf("must be a regular file of at most 4 KiB")
|
return nil, fmt.Errorf("must be a regular file of at most 4 KiB")
|
||||||
}
|
}
|
||||||
data, err := io.ReadAll(io.LimitReader(file, notificationLinkLimit+1))
|
data, err := io.ReadAll(io.LimitReader(file, notificationLinkLimit+1))
|
||||||
@@ -72,3 +89,50 @@ func validNotificationLink(link string) bool {
|
|||||||
u, err := url.Parse(link)
|
u, err := url.Parse(link)
|
||||||
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && stage.ValidNtfyClick(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 "", ""
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,21 +2,58 @@ package server
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"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
|
// 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
|
// first non-empty line is an http(s) URL, keeping the run one action away and
|
||||||
// falls back to the run link and says why on the receipt.
|
// 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) {
|
func TestStageHookLinkClick(t *testing.T) {
|
||||||
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
|
|
||||||
captured := newNtfyCapture(t)
|
captured := newNtfyCapture(t)
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -31,18 +68,23 @@ func TestStageHookLinkClick(t *testing.T) {
|
|||||||
d, _ := store.Get(ctx, items[0].ID, 0)
|
d, _ := store.Get(ctx, items[0].ID, 0)
|
||||||
artifacts := t.TempDir()
|
artifacts := t.TempDir()
|
||||||
r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store), artifactsRoot: artifacts}
|
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 {
|
for _, test := range []struct {
|
||||||
name, link, open string
|
name, link, open string
|
||||||
files map[string]string
|
files map[string]string
|
||||||
click bool // the doc URL is the tap target
|
noWeb bool // no web origin: ntfy has no run view
|
||||||
artifact string // the attached artifact path, by today's open= rules
|
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
|
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", 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, artifact: "standup-link.txt"},
|
{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", 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-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: "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: "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: "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: "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", 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: "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) {
|
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 {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
public := filepath.Join(artifacts, fmt.Sprint(id), "public")
|
writePublic(t, artifacts, id, test.files)
|
||||||
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 {
|
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{}}
|
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 {
|
if err := store.FinishStep(ctx, id, step); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
before := len(captured())
|
before := len(captured())
|
||||||
policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Link: test.link, Open: test.open}
|
r.notifyStep(id, d.Name, workspace, policy, step)
|
||||||
r.notifyStep(id, d.Name, t.TempDir(), policy, step)
|
|
||||||
|
|
||||||
// Without a usable link everything is as before: ntfy taps open the
|
// ntfy opens the link only beside a web run view; the app opens the
|
||||||
// run, the app opens the attached artifact (else the run).
|
// link (else the attached artifact, else the run).
|
||||||
runClick := fmt.Sprintf("pipelines://run/%d", id)
|
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 != "" {
|
if test.artifact != "" {
|
||||||
wantClick, wantRunClick = fmt.Sprintf("pipelines://artifact/%d/1/%s", id, test.artifact), runClick
|
wantClick, wantRunClick = fmt.Sprintf("pipelines://artifact/%d/1/%s", id, test.artifact), runClick
|
||||||
}
|
}
|
||||||
if test.click {
|
if test.click {
|
||||||
wantNtfy, wantClick, wantRunClick = doc, doc, runClick
|
wantClick, wantRunClick = doc, runClick
|
||||||
}
|
}
|
||||||
got := captured()
|
got := captured()[before:]
|
||||||
if len(got) != before+1 {
|
if len(got) != publications {
|
||||||
t.Fatalf("ntfy publications = %+v", got[before:])
|
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) {
|
for _, publication := range got {
|
||||||
t.Fatalf("ntfy click/actions = %q %q, want %q", got[before].Click, got[before].Actions, wantNtfy)
|
if publication.Click != wantNtfy || publication.Actions != wantActions {
|
||||||
}
|
t.Fatalf("ntfy click/actions = %q %q, want %q %q", publication.Click, publication.Actions, wantNtfy, wantActions)
|
||||||
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]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
n := appNotification(t, store, fmt.Sprintf("run:%d:1:success", id))
|
||||||
if n == nil || n.Click != wantClick || n.RunClick != wantRunClick {
|
if n == nil || n.Click != wantClick || n.RunClick != wantRunClick {
|
||||||
t.Fatalf("app notification = %+v, want click %q run %q", n, wantClick, 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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
receipts := detail.Steps[0].Notifications
|
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 == "") {
|
if len(receipts) != publications {
|
||||||
t.Fatalf("receipts = %+v, want diagnostic %q", receipts, test.diagnostic)
|
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()
|
||||||
|
}
|
||||||
|
|||||||
@@ -289,7 +289,7 @@ func TestNotificationArtifactSelectionAndPreview(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
r := &runner{artifactsRoot: root}
|
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" {
|
if a == nil || a.Path != "reports/new.md" || a.URL != "/artifacts/9/3/public/reports/new.md" {
|
||||||
t.Fatalf("wrong selected artifact: %+v", a)
|
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" {
|
if got := notificationClick(9, 3, a); got != "pipelines://artifact/9/3/reports/new.md" {
|
||||||
t.Fatal(got)
|
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")
|
t.Fatal("multiple files selected automatically")
|
||||||
}
|
}
|
||||||
if err := os.Remove(old); err != nil {
|
if err := os.Remove(old); err != nil {
|
||||||
t.Fatal(err)
|
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")
|
t.Fatal("single artifact not selected automatically")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user