Remove ntfy: notifications go only through the app notification stream

Server: drop ntfy publishing (stage hooks, run outbox, chat attention, chat
tool notify, auto-switch and schedule notices), the chat push outbox (its
table is dropped at startup), ntfy status/endpoints and PIPELINES_NTFY_*.
The app_notifications stream, subscribe/clear and kinds are unchanged.
Notification settings keep run_finished/chat_needs_you/chat_reply_finished;
ntfy_enabled is accepted and ignored and its stored row is never read.

Stage type=ntfy is rejected: "ntfy stages were removed; notifications go to
the Pipelines apps — use the stage notify hook". The notify hook remains.

Installer: no ntfy build, accounts, config or supervisor child; manifest
gets top-level "mode" (legacy ntfy.mode still read). Reinstall retires an
old ntfy (safe PID-file stop, deletes binary, config, data dir, token, log,
with a note in logs/install.log); uninstall cleans leftovers.

App: ntfy settings section replaced by "Notification events"; texts updated.
Docs: docs/ntfy.md folded into docs/notifications.md; install, docker, cli,
author skill references updated; security review M1 marked resolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 23:24:24 +00:00
parent 806b5eca46
commit fc7dbb0ac0
138 changed files with 1958 additions and 4651 deletions
+1 -1
View File
@@ -140,7 +140,7 @@ func TestSkillUpgradeAddsSelfContainedNotificationReference(t *testing.T) {
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"on=failure", "on=success,failure", "destination=system", "cancellation", "output.markdown"} {
for _, want := range []string{"on=failure", "on=success,failure", "cancellation", "link=", "type=ntfy"} {
if !strings.Contains(string(data), want) {
t.Fatal("missing local recipe", want)
}
+1 -1
View File
@@ -26,7 +26,7 @@ regenerate, or a file you rewrote.
| `show_run` | `run_id`, `title?`, `replace?` | A live card for a run: pipeline, title, status, current stage, duration; it updates as the run progresses and opens the run when tapped. |
| `schedule_followup` | `message`, and `at?` or `after_minutes?`, or `run_id?` with `on?` | Queue a prompt to yourself in this chat: 1 minute to 7 days ahead (`at` is RFC 3339), or when run `run_id` reaches `on`: `finished` (default; it ended) or `attention` (it waits on a human decision, or ended), delivered after 7 days at the latest with the run's state appended. A run that already meets `on` is refused (act on it now). It is a scheduled message from "Agent follow-up" the operator can remove; it does not hold the operator's own messages back, and is delivered when the chat is free. At most 3 pending per chat. The result names the follow-up id and lists the pending ones. Do not wait for it in the current turn. |
| `cancel_followup` | `id` | Remove one of this chat's undelivered follow-ups by the id `schedule_followup` returned; the result lists those still pending. |
| `notify` | `title`, `message`, `priority?` | A notification on every Pipelines app the operator is signed in to (web tabs, desktop, Android) and their phone (ntfy); a tap opens this chat. Opening the chat, or tapping or dismissing it on any device, clears it on all of them. Pipelines already notifies when the reply ends and for questions and approvals, so use it only for news mid-turn or after background work the turn does not wait for; a turn that notified sends no separate "replied" notification. 5 per minute per chat; the result says where it went, and undelivered sends report why. |
| `notify` | `title`, `message`, `priority?` | A notification on every Pipelines app the operator is signed in to (web tabs, desktop, Android, iOS); a tap opens this chat. Opening the chat, or tapping or dismissing it on any device, clears it on all of them. Pipelines already notifies when the reply ends and for questions and approvals, so use it only for news mid-turn or after background work the turn does not wait for; a turn that notified sends no separate "replied" notification. 5 per minute per chat; the result says where it went, and undelivered sends report why. |
`show_diff` lists at most 300 files; a file patch over 256 KiB or a total over
1 MiB is shown partially and says so; binaries have no patch; renames show as
+2 -1
View File
@@ -233,7 +233,8 @@ library (`pipelines skills list`), one per line: `name` loads the latest version
at run start, `name@N` pins version N. An empty or missing block loads none.
Drafts and publications are rejected for an unknown skill, a missing version,
`@0`/non-numeric versions, a skill listed twice (pinned or not) and a `skills`
block on a human or ntfy stage.
block on a human stage. `type=ntfy` stages were removed and are rejected; use
a stage `notify` hook instead.
```skills
review-checklist
@@ -1,7 +1,8 @@
# Notification authoring
Use the server's existing system phone connection. Never read, copy or request
tokens/passwords, edit server settings, or call curl to publish while authoring.
Notifications go to the operator's signed-in Pipelines apps (web, Android,
iOS, macOS) through the server's own notification stream; there is nothing to
configure. Never edit server settings or call curl to publish while authoring.
Validation is not delivery. Do not send a test notification or run the workflow
without explicit approval.
@@ -11,8 +12,8 @@ A fenced `notify` block belongs inside an existing stage. `on` accepts `success`
`failure`, or `success,failure` — not `error`. A failure means an execution error,
the `error` outcome, or a route to `#failure`; other completed outcomes are success.
Hooks send stage events, not a separate run-finished event. They leave the graph,
handoffs, tools, model and run verdict unchanged. Delivery failures are audited
separately and do not turn a successful stage into failure.
handoffs, tools, model and run verdict unchanged. A notification problem is
audited separately and does not turn a successful stage into failure.
For the common sequential workflow whose failure/blocked edges terminate:
@@ -45,35 +46,25 @@ can send repeated events. Inspect routing; explain these limits rather than prom
exactly one final notification for every possible termination. Do not reroute
failures through a successful publisher and accidentally turn failure into success.
## Attachments only when requested
## Opening an artifact or a link
Omit `artifacts` for an event-only alert. `artifacts=markdown` attaches a nonempty
string in `output.markdown`; a field named `report` is not automatically attached.
Only add/rename output fields and corresponding prompts if a report attachment is
requested, preserving downstream handoffs. If no attachment is produced (including
on execution error), an event-only notification is still attempted.
`artifacts=files` attaches the workspace-relative paths in `output.artifacts`;
`artifacts=markdown,files` selects both. Each file gets its own notification, so
attachments may mean more than one message. Files must be regular, nonsymlinked,
at most 1 MiB, with at most 10 listed. Absolute/traversal/hidden paths, `secrets/`,
database/key paths and `node_modules/` are rejected. This is not content scanning.
Do not promise phone reception from structural validation.
`artifacts=` (and `destination=`) lines in older definitions still parse but
do nothing: they configured ntfy attachments, and ntfy was removed. Do not add
them.
`open=<pattern>` attaches one artifact from the run's shared `public/` directory
to the app notification and makes its tap open that artifact. The pattern is a
relative glob with no absolute path, `..`, or hidden path segment; if several
files match, the most recently modified file wins. Without `open=`, exactly one
regular file in `public/` is attached automatically. Zero or multiple files
produce no attached artifact. This is separate from ntfy's `artifacts=` keys.
produce no attached artifact.
`link=<pattern>` makes a tap on the phone notification (ntfy and app) open a
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 (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
`link=<pattern>` makes a tap on the notification open a 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; 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
@@ -81,40 +72,16 @@ on=success
link=standup-link.txt
```
## Optional explicit delivery stage
## No delivery stage
Use native delivery only when the user needs delivery as an explicit routed stage
(e.g. delivery failure must fail the run), not for an ordinary completion alert.
The preceding stage must output nonempty UTF-8 strings `title`, `summary`, and
`markdown`. Title/summary are single-line, at most 256/2048 bytes; Markdown is at
most 1 MiB. The native stage does not accept model prompts or tools and does not
need an output block:
````markdown
# stage publish
```configs
type=ntfy
destination=system
```
```edges
success -> #success
error -> #failure
```
````
`destination=system` uses the server's existing system connection. Native delivery
adds retained delivery metadata on success and follows its error edge on failure.
Neither hooks nor native delivery automatically retry ambiguous publishes; a new
run or repeated visit can send again. An upstream execution error does not reliably
produce the required three strings, so adding this stage alone cannot cover it.
The former `type=ntfy` delivery stage was removed. Validation rejects it with
"ntfy stages were removed; notifications go to the Pipelines apps — use the
stage notify hook". Use a `notify` hook on the stage whose result matters.
## Automatic run-attention notifications
Independently of any `notify` block, the server publishes one run-level attention
notification to the same already-configured `system` destination when a run needs a
person: when it enters `waiting` (a human stage asked for a decision), or when it
Independently of any `notify` block, the server records one run-level attention
notification when a run needs a person: when it enters `waiting` (a human stage asked for a decision), or when it
has an unexpected failure or interruption. A deliberate route to `#failure` with
its reason is recorded as an expected failure: it remains in Runs but does not
notify or appear in Needs you. Explicit `run_finished`/`on` completion notifications
@@ -124,19 +91,13 @@ Runs marked `on` notify at completion, while `off` disables these notifications.
Queued and running runs send nothing. You do not author these; they are the operator
default, so a run you never wired still reaches the operator.
The payload names the run and its pipeline. When the operator configures
`PIPELINES_WEB_PUBLIC_URL` on the server, run notifications and stage hooks carry
the authenticated web link `<origin>/runs/<id>`. Native installs default this to
their advertised web address; custom/VPN domains require the operator's actual
phone-reachable URL. Never use the API listener or ntfy URL, nor put credentials
in the click link. Existing Android-only installations without that setting keep
`pipelines://run/<id>`. Invalid origins omit the link and log a warning. Existing
delivered alerts are not rewritten. Do not change service settings or send a test
notification merely to author a workflow. A run that stays waiting is not
The payload names the run and its pipeline; a tap opens the run in the app.
Do not change service settings or send a test notification merely to author a
workflow. A run that stays waiting is not
republished on a read or restart, and a
stage `notify` policy that already covers the same event (`on=waiting`, or a failure
hook) suppresses the run-level default, so one genuine event means one notification.
A delivery failure is logged, never fails the run, and is not retried.
A notification problem is logged and never fails the run.
The app shows the same information in one attention surface ordered by importance:
a run waiting for a decision, then a failed run, then a run that finished since the
@@ -4,7 +4,7 @@ Pipelines turns a reusable process into sequential stages with explicit handoffs
outcome routing and retained evidence. A Go CLI/TUI and the Pipelines app connect
to an execution server; the server owns execution and SQLite history, the stage's
harness (OpenCode, Claude Code or Pi) owns model/tool sessions, operator chats
run on OpenCode, Claude Code or Codex, and optional ntfy delivers notifications. It is technology-neutral, not a
run on OpenCode, Claude Code or Codex, and the server delivers notifications to the Pipelines apps. It is technology-neutral, not a
parallel/distributed task engine or a guarantee that model reports are correct.
## Lifecycle and location
@@ -54,8 +54,7 @@ inputs/outputs, status/errors, audit transcripts, session ownership/references,
reported per-stage model usage (tokens/cost), retry links, schedules/state,
notification receipts and file changes. Not everything
is in that database: drafts/settings are client files; complete OpenCode sessions
and credentials use OpenCode storage; repository artifacts are files; ntfy has its
own storage. A pipeline ZIP is not a full backup of these components.
and credentials use OpenCode storage; repository artifacts are files. A pipeline ZIP is not a full backup of these components.
Never merge or sync live SQLite files using generic file synchronization. Do not
delete databases, sessions, volumes or credentials to repair a workflow.
@@ -162,7 +161,7 @@ source-built test binaries, draft/publication/transfer and restart persistence w
inference, notifications or deployment. It is not a live-provider or phone test.
That is a developer test fixture, not the native installer. End-user installation
runs natively through `./install` by default (`scripts/setup-native.py`, with
`--native` equivalent); the Docker server + ntfy installation is explicit with
`--native` equivalent); the Docker server installation is explicit with
`./install --docker`.
## Retained stage file changes
+2 -2
View File
@@ -19,8 +19,8 @@ overwritten. A ZIP includes versioned manifest/checksums, names and pinned Markd
definitions. Exported version numbers are provenance, not portable database IDs.
**Definition transfer is not full backup or database synchronization.** No older
versions, run history/diffs, drafts, repository files, provider credentials or ntfy
storage/settings are included. Archives are private files, not encrypted; prompts
versions, run history/diffs, drafts, repository files, provider credentials or
notification settings are included. Archives are private files, not encrypted; prompts
can contain secrets. Limits are 1,000 definitions, 1 MiB each, 32 MiB total source.
## Import and existing-name conflicts
-3
View File
@@ -913,9 +913,6 @@ func (a App) Run(ctx context.Context, args []string) error {
}
case "connection":
fmt.Fprintln(a.Out, "Server:", o.url)
for _, n := range r.NotificationEndpoints {
fmt.Fprintf(a.Out, "ntfy: %s · topic %s\n", n.ServerURL, n.Topic)
}
if note := identityNote(r); note != "" {
fmt.Fprintln(a.Out, "Note:", note)
}
+4 -2
View File
@@ -62,17 +62,19 @@ func TestCLIHelpDoesNotNeedServer(t *testing.T) {
}
func TestCLIStatusAndStatistics(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
run, _, _ := setup(t)
output, err := run("status")
if err != nil {
t.Fatal(err)
}
for _, text := range []string{"Pipelines server", "ntfy", "not configured", "Port:"} {
for _, text := range []string{"Pipelines server", "Port:"} {
if !strings.Contains(output, text) {
t.Fatal("missing CLI status", text, output)
}
}
if strings.Contains(output, "ntfy") {
t.Fatal("CLI status still reports ntfy", output)
}
output, err = run("status", "--json")
if err != nil {
t.Fatal(err)
+2 -2
View File
@@ -32,7 +32,7 @@ func TestInstalledDockerDefaultAvoidsUnconfiguredServerAndHonorsOverrides(t *tes
if err := wsjson.Read(ctx, conn, &request); err != nil {
return
}
wsjson.Write(ctx, conn, protocol.Message{Type: protocol.Status, ID: request.ID, Status: &protocol.SystemStatus{Ntfy: protocol.ServiceStatus{Health: health}}})
wsjson.Write(ctx, conn, protocol.Message{Type: protocol.Status, ID: request.ID, Status: &protocol.SystemStatus{Hostname: health}})
}))
t.Cleanup(srv.Close)
return "ws" + strings.TrimPrefix(srv.URL, "http") + "/connect"
@@ -56,7 +56,7 @@ func TestInstalledDockerDefaultAvoidsUnconfiguredServerAndHonorsOverrides(t *tes
t.Fatal(err, stderr.String())
}
var status protocol.SystemStatus
if json.Unmarshal(out.Bytes(), &status) != nil || status.Ntfy.Health != want {
if json.Unmarshal(out.Bytes(), &status) != nil || status.Hostname != want {
t.Fatal("wrong server selected", out.String())
}
}
+3 -3
View File
@@ -48,8 +48,8 @@ var notes = map[string]string{
"repair-session-export": "Read-only native session readback for a settled run visit, using its exact recorded session/backend. Writes a versioned repair file and appends repair evidence, preserving originals and the run outcome. Empty/failed/partial repairs remain warnings; upstream session availability cannot be guaranteed.",
"version": "Identify the local CLI binary without connecting to a server. --version is an alias. Use ping --json to identify the running server separately.",
"ping": "Pong includes the running server's compiled build.version, build.commit and build.dirty (null when unknown). This identifies the server, not the client or runtime workspace. Older servers omit build. The client compares its own build/protocol against the server: a same-protocol build mismatch prints one warning to stderr, a server speaking a newer protocol fails the command, and a response carrying a field this client does not model prints a one-time unrecognized-field notice instead of dropping it silently.",
"connection": "Prints the server endpoint and phone notification endpoints. Like ping, it reports the client/server build relationship and warns or fails rather than silently proceeding against a mismatched server.",
"status": "Reports server, host and ntfy publishing health. The client compares its build/protocol against the server and warns once (or fails on a newer protocol) rather than proceeding silently.",
"connection": "Prints the server endpoint. Like ping, it reports the client/server build relationship and warns or fails rather than silently proceeding against a mismatched server.",
"status": "Reports server health, ports and the server computer's addresses. The client compares its build/protocol against the server and warns once (or fails on a newer protocol) rather than proceeding silently.",
"export": "Without a name, select pipelines with Space and save a ZIP in the current directory. --output writes a portable definition bundle; --all skips selection. One name without --output prints Markdown as before. No runs, credentials or old versions are exported.",
"import": "Select definitions from a ZIP. Identical existing definitions are skipped. For differing names, choose keep existing, keep both under a new name, or use imported as a new version (history retained). --on-conflict supplies an explicit automation policy; --yes only approves final publication. Schedules may activate; no run history is imported.",
"new": "Create an optional template copy or a single-stage starter. Opens the configured default harness; --harness opencode|pi|nvim overrides it. No submission is performed.",
@@ -80,7 +80,7 @@ var serviceHelp = map[string]string{
"skill": "pipelines skill install installs/updates the bundled workflow skill in OpenCode and detected Claude Code and Codex skill roots without changing login/config or user-modified skills. ./install includes this step.",
"service": "Configure per-user OS autostart: pipelines service enable. Runs use the directory you invoke pipelines run from. Use --print to preview, service status to inspect, and service disable before uninstalling. Linux uses systemd; macOS uses launchd. No sudo.",
"serve": "Run the native server in the foreground. Its flags are documented by pipelines serve --help. Installation never starts it automatically.",
"start": "Start the per-user native pipeline server and this installation's Docker ntfy together.",
"start": "Start the per-user native pipeline server and its authenticated web proxy.",
"stop": "Stop both services. Active execution is interrupted; file changes are not rolled back.",
"restart": "Stop, then start both services, retaining definitions, run history, and credentials.",
"doctor": "Check both health endpoints and host OpenCode API discovery; does not execute a model.",
+1 -1
View File
@@ -20,7 +20,7 @@ EXECUTE
chat-adopt <session-id> Adopt an existing OpenCode, Claude Code or Codex chat
draft-delete <draft.md> Delete a selected retained draft and its metadata
connection Server and public phone connection (no secrets)
status Server/ntfy health, ports and server computer IPs
status Server health, ports and server computer IPs
stats All-history usage, pipeline counts and daily activity
ping Check connection and identify the running server build
version Identify this CLI build without connecting (--version)
+4 -4
View File
@@ -5,11 +5,11 @@ import (
"testing"
)
// TestMain isolates the package from an operator's real notification setup:
// these tests run real servers and runs, a developer shell may export the
// installed server's ntfy configuration, and no test may publish to it.
// TestMain isolates the package from the operator's environment: a developer
// shell may export the installed server's web origin, which tests must not
// pick up.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
for _, name := range []string{"PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
+13 -2
View File
@@ -17,7 +17,12 @@ type Config struct {
OpenCode string `json:"opencode"`
OpenCodeEnv map[string]string `json:"opencode_env"`
Path string `json:"path"`
Ntfy struct {
// Mode is "native" for a native installation (the per-user supervisor)
// and "docker" or empty for Compose.
Mode string `json:"mode"`
// LegacyNtfy is read only for its mode: manifests written before ntfy was
// removed recorded a native installation as ntfy.mode "native".
LegacyNtfy struct {
Mode string `json:"mode"`
} `json:"ntfy"`
Web struct {
@@ -70,7 +75,7 @@ func Load(executable string) (*Config, error) {
if config.Format != 1 || config.Prefix != prefix || config.ServerPort < 1024 || config.ServerPort > 65535 {
return nil, fmt.Errorf("invalid managed installation manifest")
}
if inferred && config.Ntfy.Mode != "native" {
if inferred && !config.Native() {
return nil, nil
}
if inferred {
@@ -82,6 +87,12 @@ func Load(executable string) (*Config, error) {
return &config, nil
}
// Native reports whether the manifest describes a native installation, in the
// current form or the one written before ntfy was removed.
func (c Config) Native() bool {
return c.Mode == "native" || (c.Mode == "" && c.LegacyNtfy.Mode == "native")
}
func (c Config) Environment() error {
for key, value := range c.OpenCodeEnv {
switch key {
+29 -2
View File
@@ -84,7 +84,7 @@ func nativeFixture(t *testing.T) (string, string) {
t.Fatal(err)
}
config := Config{Format: 1, Prefix: root, ServerPort: 18080, Python: filepath.Join(root, "python3")}
config.Ntfy.Mode = "native"
config.Mode = "native"
data, _ := json.Marshal(config)
if err = os.WriteFile(filepath.Join(root, "pipelines-install.json"), data, 0600); err != nil {
t.Fatal(err)
@@ -156,7 +156,7 @@ func TestNativeDiscoveryRejectsSymlinkManifestAndMismatchedPrefix(t *testing.T)
os.Symlink(target, manifest)
} else {
config := Config{Format: 1, Prefix: "/another/prefix", ServerPort: 18080}
config.Ntfy.Mode = "native"
config.Mode = "native"
data, _ := json.Marshal(config)
os.WriteFile(manifest, data, 0600)
}
@@ -166,3 +166,30 @@ func TestNativeDiscoveryRejectsSymlinkManifestAndMismatchedPrefix(t *testing.T)
})
}
}
// A manifest written before ntfy was removed marks a native installation as
// ntfy.mode "native" (with the rest of the old ntfy block); it must still be
// selected until a reinstall rewrites it with the top-level mode.
func TestLegacyNtfyManifestStillSelectsNativeInstallation(t *testing.T) {
t.Setenv("PIPELINES_PREFIX", "")
root, binary := nativeFixture(t)
legacy := map[string]any{"format": 1, "prefix": root, "server_port": 18080, "python": filepath.Join(root, "python3"),
"ntfy_port": 8090, "topic": "pipelines", "username": "phone-reader",
"ntfy": map[string]any{"mode": "native", "bin": filepath.Join(root, "bin", "ntfy"), "config": filepath.Join(root, "data", "ntfy", "server.yml"), "version": "v2.38.1"}}
data, _ := json.Marshal(legacy)
if err := os.WriteFile(filepath.Join(root, "pipelines-install.json"), data, 0600); err != nil {
t.Fatal(err)
}
loaded, err := Load(binary)
if err != nil || loaded == nil || !loaded.Native() {
t.Fatal("legacy native manifest not selected", loaded, err)
}
docker := Config{Mode: "docker"}
docker.LegacyNtfy.Mode = "native"
if docker.Native() {
t.Fatal("explicit docker mode overridden by the legacy block")
}
if !(Config{Mode: "native"}).Native() || (Config{}).Native() {
t.Fatal("top-level mode not honoured")
}
}
+5 -8
View File
@@ -77,8 +77,8 @@ func (d serviceDefinition) render(platform string) (string, error) {
}
// Only explicitly supported settings are captured, never the complete environment
// or provider credentials. File-based notification credentials remain references.
var serviceEnvironmentKeys = []string{"PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_OPENCODE_ENDPOINT_USERNAME", "PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL", "PIPELINES_CLAUDE"}
// or provider credentials. File-based credentials remain references.
var serviceEnvironmentKeys = []string{"PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_OPENCODE_ENDPOINT_USERNAME", "PIPELINES_WEB_PUBLIC_URL", "PIPELINES_CLAUDE"}
func envValues(env map[string]string) []string {
var values []string
@@ -169,7 +169,7 @@ func ServiceCommand(ctx context.Context, executable string, args []string, out,
if err != nil {
return err
}
if config != nil && config.Ntfy.Mode == "native" {
if config != nil && config.Native() {
// Use an internal verb so an older manager fails instead of forwarding
// "service" back into this CLI recursively. Reinstall refreshes manage.py.
command := exec.CommandContext(ctx, config.Python, append([]string{filepath.Join(config.Prefix, "lib/manage.py"), "--prefix", config.Prefix, "native-service"}, args...)...)
@@ -182,7 +182,7 @@ func ServiceCommand(ctx context.Context, executable string, args []string, out,
if config == nil && os.Getenv("PIPELINES_PREFIX") != "" {
return fmt.Errorf("PIPELINES_PREFIX does not select an existing installation; refusing to configure a standalone service")
}
help := "Usage: pipelines service enable [--print]\n pipelines service disable | status\nNative installs manage the existing server/web/ntfy supervisor, selected by PIPELINES_PREFIX or the installed CLI path.\nAutostart is per-user, at login. enable starts now; --print only previews.\nStandalone developer binaries also support enable --db FILE --addr HOST:PORT.\nRuns use the directory you invoke pipelines run from.\n"
help := "Usage: pipelines service enable [--print]\n pipelines service disable | status\nNative installs manage the existing server/web supervisor, selected by PIPELINES_PREFIX or the installed CLI path.\nAutostart is per-user, at login. enable starts now; --print only previews.\nStandalone developer binaries also support enable --db FILE --addr HOST:PORT.\nRuns use the directory you invoke pipelines run from.\n"
if len(args) == 0 || args[0] == "--help" || args[0] == "help" {
_, err := io.WriteString(out, help)
return err
@@ -221,9 +221,6 @@ func ServiceCommand(ctx context.Context, executable string, args []string, out,
if len(f.Args()) != 0 {
return fmt.Errorf("service enable takes no positional arguments")
}
if os.Getenv("PIPELINES_NTFY_TOKEN") != "" {
return fmt.Errorf("use PIPELINES_NTFY_TOKEN_FILE for autostart; inline tokens are not saved")
}
binary, err := ServerExecutable(executable)
if err != nil {
return err
@@ -242,7 +239,7 @@ func ServiceCommand(ctx context.Context, executable string, args []string, out,
d.Environment[key] = value
}
}
for _, key := range []string{"PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_NTFY_TOKEN_FILE"} {
for _, key := range []string{"PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE"} {
if value := d.Environment[key]; value != "" && (key != "PIPELINES_OPENCODE" || strings.ContainsRune(value, filepath.Separator)) {
absolute, err := filepath.Abs(value)
if err != nil {
+1 -2
View File
@@ -41,7 +41,7 @@ func TestSystemdDefinitionAcceptedByNativeValidator(t *testing.T) {
}
func TestServiceDefinitionsQuotePathsAndKeepEnvironmentLimited(t *testing.T) {
d := serviceDefinition{Binary: `/some bin/server`, Directory: `/repo "quoted" 100% $USER`, Args: []string{"-db", `/repo "quoted" 100% $USER/data.db`}, Environment: map[string]string{"PATH": "/usr/bin:/custom bin", "PIPELINES_NTFY_TOKEN_FILE": "/secret & token", "PIPELINES_CLAUDE": "/custom bin/claude", "PROVIDER_SECRET": "must-not-export"}}
d := serviceDefinition{Binary: `/some bin/server`, Directory: `/repo "quoted" 100% $USER`, Args: []string{"-db", `/repo "quoted" 100% $USER/data.db`}, Environment: map[string]string{"PATH": "/usr/bin:/custom bin", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE": "/secret & token", "PIPELINES_CLAUDE": "/custom bin/claude", "PROVIDER_SECRET": "must-not-export"}}
for _, platform := range []string{"linux", "darwin"} {
text, err := d.render(platform)
if err != nil {
@@ -142,7 +142,6 @@ func TestServiceConfigurationPreviewAndLifecycleWithMockOSManager(t *testing.T)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config"))
t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data"))
t.Setenv("PATH", bin)
t.Setenv("PIPELINES_NTFY_TOKEN", "")
server := filepath.Join(bin, "pipelines-server")
if err := os.WriteFile(server, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil {
t.Fatal(err)
+3 -4
View File
@@ -13,8 +13,8 @@ import (
// Environment keys for the operator-supplied OpenCode endpoint. The endpoint
// itself is opt-in: when none of the flag, these variables or the recorded
// setting is present the server keeps today's spawned default. The password is
// accepted only through a private file reference (never inline), mirroring the
// ntfy token-file rule; an optional username overrides the detected default.
// accepted only through a private file reference (never inline); an optional
// username overrides the detected default.
const (
EndpointEnvKey = "PIPELINES_OPENCODE_ENDPOINT"
EndpointPasswordFileEnvKey = "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE"
@@ -56,8 +56,7 @@ func NormalizeEndpointURL(raw string) (string, error) {
}
// ReadEndpointCredentialFile reads the optional endpoint password from a private
// file reference, mirroring the ntfy token-file rule: a regular, single-owner
// 0600 file with a bounded read. An empty path yields no password, so an endpoint
// file reference: a regular, single-owner 0600 file with a bounded read. An empty path yields no password, so an endpoint
// that authenticates with the default user only keeps working.
func ReadEndpointCredentialFile(path string) (string, error) {
if strings.TrimSpace(path) == "" {
+7 -111
View File
@@ -1,115 +1,11 @@
package pipeline
import (
"context"
"database/sql"
"errors"
"time"
)
// ChatNotification is one chat phone push (ntfy) in the durable outbox. It
// follows the run notification outbox (run_notifications.go): a row is leased
// for a bounded attempt, a crash during a lease is recovered when the lease
// expires, and attempts are bounded. ID is the chat's app notification id, so
// an enqueue is idempotent and a notification the operator already cleared in
// the app is never published late.
type ChatNotification struct {
ID, SessionID, Title, Body, Click string
// SequenceID is the ntfy sequence id the push is published with (so a later
// clear dismisses it on the phone); "" publishes without one.
SequenceID string
Priority int
Attempts int
}
// ChatNotificationAttempts bounds publication attempts per chat push.
const ChatNotificationAttempts = 5
// chatNotificationLease is how long one claimed attempt owns its row.
const chatNotificationLease = 60
// chatNotificationRetention bounds how long settled rows are kept.
const chatNotificationRetention = 7 * 24 * time.Hour
func (s *Store) initChatNotifications() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_notifications (
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, click TEXT NOT NULL,
sequence_id TEXT NOT NULL DEFAULT '', priority INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
next_attempt INTEGER NOT NULL DEFAULT 0, diagnostic TEXT NOT NULL DEFAULT '', message_id TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS chat_notifications_due ON chat_notifications(status,next_attempt);`)
// dropChatNotifications removes the chat_notifications table, the durable
// outbox an earlier server used to retry chat pushes to ntfy. ntfy was removed:
// chat notifications are recorded once on the app notification stream
// (app_notifications), so the old rows have nowhere to go and nothing reads
// them.
func (s *Store) dropChatNotifications() error {
_, err := s.db.Exec(`DROP TABLE IF EXISTS chat_notifications`)
return err
}
// EnqueueChatNotification records one chat push once (by id) and prunes
// settled rows past retention.
func (s *Store) EnqueueChatNotification(ctx context.Context, n ChatNotification, now time.Time) error {
if _, err := s.db.ExecContext(ctx, `DELETE FROM chat_notifications WHERE created_at<? AND status NOT IN ('pending','sending')`, now.Add(-chatNotificationRetention).Unix()); err != nil {
return err
}
_, err := s.db.ExecContext(ctx, `INSERT INTO chat_notifications(id,session_id,title,body,click,sequence_id,priority,created_at)
VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING`, n.ID, n.SessionID, n.Title, n.Body, n.Click, n.SequenceID, n.Priority, now.Unix())
return err
}
// ClaimChatNotification atomically leases one due push. A push whose app
// notification was cleared before it went out (the operator already answered
// in the app) is settled as cleared instead of published.
func (s *Store) ClaimChatNotification(ctx context.Context, now int64) (*ChatNotification, error) {
if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='cleared',diagnostic='cleared in the app before publication'
WHERE status IN ('pending','sending') AND next_attempt<=? AND EXISTS(SELECT 1 FROM app_notifications a WHERE a.id=chat_notifications.id AND a.cleared_at<>0)`, now); err != nil {
return nil, err
}
if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='failed',diagnostic='publisher acknowledgement unknown after final lease expired'
WHERE status='sending' AND attempts>=? AND next_attempt<=?`, ChatNotificationAttempts, now); err != nil {
return nil, err
}
n := new(ChatNotification)
err := s.db.QueryRowContext(ctx, `UPDATE chat_notifications SET status='sending',attempts=attempts+1,next_attempt=?
WHERE rowid=(SELECT rowid FROM chat_notifications WHERE status IN ('pending','sending') AND attempts<? AND next_attempt<=? ORDER BY next_attempt,rowid LIMIT 1)
RETURNING id,session_id,title,body,click,sequence_id,priority,attempts`, now+chatNotificationLease, ChatNotificationAttempts, now).Scan(&n.ID, &n.SessionID, &n.Title, &n.Body, &n.Click, &n.SequenceID, &n.Priority, &n.Attempts)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return n, nil
}
// FinishChatNotification settles a claimed attempt: sent, or pending again
// after an exponential backoff (5 s, 10 s, 20 s, ...) until attempts run out.
func (s *Store) FinishChatNotification(ctx context.Context, n ChatNotification, now int64, messageID string, failure error) error {
status, diagnostic, next := "sent", "", now
if failure != nil {
status, diagnostic = "pending", failure.Error()
next = now + int64(5)<<min(n.Attempts-1, 8)
if n.Attempts >= ChatNotificationAttempts {
status = "failed"
}
}
_, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status=?,diagnostic=?,message_id=?,next_attempt=?
WHERE id=? AND status='sending' AND attempts=?`, status, diagnostic, messageID, next, n.ID, n.Attempts)
return err
}
// ChatNotificationStatus reports one push's outbox status ("" when absent)
// and attempts.
func (s *Store) ChatNotificationStatus(ctx context.Context, id string) (string, int, error) {
var status string
var attempts int
err := s.db.QueryRowContext(ctx, `SELECT status,attempts FROM chat_notifications WHERE id=?`, id).Scan(&status, &attempts)
if errors.Is(err, sql.ErrNoRows) {
return "", 0, nil
}
return status, attempts, err
}
// ChatNotificationCleared reports whether id's app notification has been
// cleared; a publication that raced a clear then clears the phone too.
func (s *Store) ChatNotificationCleared(ctx context.Context, id string) (bool, error) {
var cleared bool
err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM app_notifications WHERE id=? AND cleared_at<>0)`, id).Scan(&cleared)
return cleared, err
}
@@ -1,76 +0,0 @@
package pipeline
import (
"context"
"errors"
"path/filepath"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestChatNotificationOutboxRetriesAndSkipsCleared(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "chat-outbox.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
now := time.Unix(1000, 0)
n := ChatNotification{ID: "chat:ses_a:form:q1", SessionID: "ses_a", Title: "T", Body: "B", Click: "pipelines://chat/ses_a", SequenceID: "pl-1"}
for range 2 { // idempotent by id
if err := s.EnqueueChatNotification(ctx, n, now); err != nil {
t.Fatal(err)
}
}
first, err := s.ClaimChatNotification(ctx, 1000)
if err != nil || first == nil || first.Attempts != 1 || first.SequenceID != "pl-1" {
t.Fatalf("claim = %+v %v", first, err)
}
if again, err := s.ClaimChatNotification(ctx, 1000); err != nil || again != nil {
t.Fatalf("leased row claimed twice: %+v %v", again, err)
}
if err := s.FinishChatNotification(ctx, *first, 1000, "", errors.New("ntfy down")); err != nil {
t.Fatal(err)
}
if early, _ := s.ClaimChatNotification(ctx, 1004); early != nil {
t.Fatalf("retried before backoff: %+v", early)
}
second, err := s.ClaimChatNotification(ctx, 1005)
if err != nil || second == nil || second.Attempts != 2 {
t.Fatalf("retry claim = %+v %v", second, err)
}
if err := s.FinishChatNotification(ctx, *second, 1005, "m1", nil); err != nil {
t.Fatal(err)
}
if status, attempts, _ := s.ChatNotificationStatus(ctx, n.ID); status != "sent" || attempts != 2 {
t.Fatalf("status = %s/%d", status, attempts)
}
// A lease lost to a crash is reclaimed after it expires.
crashed := ChatNotification{ID: "chat:ses_a:form:q2", SessionID: "ses_a", Title: "T", Body: "B"}
_ = s.EnqueueChatNotification(ctx, crashed, now)
if c, _ := s.ClaimChatNotification(ctx, 2000); c == nil {
t.Fatal("no claim")
}
if c, _ := s.ClaimChatNotification(ctx, 2061); c == nil || c.Attempts != 2 {
t.Fatalf("expired lease not reclaimed: %+v", c)
} else if err := s.FinishChatNotification(ctx, *c, 2061, "m2", nil); err != nil {
t.Fatal(err)
}
// A push whose app notification was cleared first is never published.
cleared := ChatNotification{ID: "chat:ses_b:form:q3", SessionID: "ses_b", Title: "T", Body: "B"}
if _, _, err := s.RecordAppNotification(ctx, AppNotificationRecord{AppNotification: protocol.AppNotification{ID: cleared.ID, Kind: protocol.NotificationChatQuestion, Title: "T"}, SessionID: "ses_b"}, now); err != nil {
t.Fatal(err)
}
if _, err := s.ClearAppNotifications(ctx, []string{cleared.ID}, now); err != nil {
t.Fatal(err)
}
_ = s.EnqueueChatNotification(ctx, cleared, now)
if c, _ := s.ClaimChatNotification(ctx, 3000); c != nil {
t.Fatalf("cleared push claimed: %+v", c)
}
if status, _, _ := s.ChatNotificationStatus(ctx, cleared.ID); status != "cleared" {
t.Fatalf("cleared push status = %q", status)
}
}
+4 -4
View File
@@ -5,11 +5,11 @@ import (
"testing"
)
// TestMain isolates the package from an operator's real notification setup.
// The store only enqueues notifications, but a developer shell may export the
// installed server's ntfy configuration and no test may ever publish to it.
// TestMain isolates the package from the operator's environment: a developer
// shell may export the installed server's web origin, which tests must not
// pick up.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
for _, name := range []string{"PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
@@ -26,12 +26,12 @@ func TestNotificationSettingsDefaultPersistAndPartialUpdate(t *testing.T) {
t.Fatalf("default values changed: %+v", got)
}
got, err = s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true})
want := protocol.NotificationSettings{RunFinished: false, ChatNeedsYou: true, ChatReplyFinished: true, NtfyEnabled: true}
want := protocol.NotificationSettings{RunFinished: false, ChatNeedsYou: true, ChatReplyFinished: true}
if err != nil || got != want {
t.Fatalf("partial update = %+v, %v", got, err)
}
got, err = s.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyRunFinished: true, protocol.NotifyChatNeedsYou: false})
want = protocol.NotificationSettings{RunFinished: true, ChatNeedsYou: false, ChatReplyFinished: true, NtfyEnabled: true}
want = protocol.NotificationSettings{RunFinished: true, ChatNeedsYou: false, ChatReplyFinished: true}
if err != nil || got != want {
t.Fatalf("second update = %+v, %v", got, err)
}
@@ -144,3 +144,37 @@ func TestLegacyRunFinishedValueIsIgnored(t *testing.T) {
t.Fatalf("notifications = %+v, %v", got, err)
}
}
// ntfy was removed. A stored notify.ntfy_enabled row from an earlier server is
// never read, the other stored choices keep their meaning, and an older client
// that still sends the ntfy_enabled switch is accepted without changing
// anything.
func TestLegacyNtfySettingIsIgnored(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "legacy-ntfy.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
for key, value := range map[string]string{"notify.ntfy_enabled": "false", "notify.chat_reply_finished": "true", "notify.any_run_ended": "true"} {
if _, err := s.db.ExecContext(ctx, `INSERT INTO server_settings(key,value) VALUES(?,?)`, key, value); err != nil {
t.Fatal(err)
}
}
want := protocol.NotificationSettings{RunFinished: true, ChatNeedsYou: true, ChatReplyFinished: true}
if got, err := s.NotificationSettings(ctx); err != nil || got != want {
t.Fatalf("settings with a stored ntfy row = %+v, %v", got, err)
}
if _, present := want.Map()[protocol.LegacyNotifyNtfyEnabled]; present {
t.Fatal("the wire form still carries ntfy_enabled")
}
got, err := s.UpdateNotificationSettings(ctx, map[string]any{protocol.LegacyNotifyNtfyEnabled: true})
if err != nil || got != want {
t.Fatalf("ntfy-only update = %+v, %v", got, err)
}
got, err = s.UpdateNotificationSettings(ctx, map[string]any{protocol.LegacyNotifyNtfyEnabled: false, protocol.NotifyChatNeedsYou: false})
want.ChatNeedsYou = false
if err != nil || got != want {
t.Fatalf("mixed update = %+v, %v", got, err)
}
}
+7 -2
View File
@@ -39,7 +39,12 @@ func TestNotifyPolicyParsing(t *testing.T) {
t.Fatal("notify link not validated", err)
}
source = "# stage native\n```configs\ntype=ntfy\ndestination=anime\n```\n```notify\non=failure\ndestination=anime\n```\n```edges\nsuccess -> #success\nerror -> #failure\n```"
if _, err := Parse(source); err != nil {
t.Fatal("notify not supported on native stage", err)
// ntfy stages were removed: an old definition is refused with what to use
// instead, by the parser and by `pipelines validate`'s report parser.
if _, err := Parse(source); err == nil || !strings.Contains(err.Error(), "ntfy stages were removed; notifications go to the Pipelines apps — use the stage notify hook") {
t.Fatal("type=ntfy stage not rejected with guidance:", err)
}
if _, _, err := ParseDefinitionReport(source); err == nil || !strings.Contains(err.Error(), "use the stage notify hook") {
t.Fatal("validate report accepted a type=ntfy stage:", err)
}
}
+2 -2
View File
@@ -10,7 +10,7 @@ import (
func overrideGraph() protocol.Graph {
return protocol.Graph{Stages: []protocol.Stage{
{Key: "plan", Type: "model", Configs: map[string]string{"provider": "pinned", "model": "pinned-model"}},
{Key: "note", Type: "ntfy", Configs: map[string]string{}},
{Key: "note", Type: "human", Configs: map[string]string{}},
{Key: "review", Type: "model", Configs: map[string]string{"provider": "pinned2", "model": "pinned2-model"}},
}}
}
@@ -97,7 +97,7 @@ func TestEffectiveModelsRejectsBadInput(t *testing.T) {
t.Fatalf("non-model stage override error = %v, want a cannot-honour refusal", err)
}
// A whole-run override on a graph with no model stage is accepted and inert.
inert := protocol.Graph{Stages: []protocol.Stage{{Key: "note", Type: "ntfy", Configs: map[string]string{}}}}
inert := protocol.Graph{Stages: []protocol.Stage{{Key: "note", Type: "human", Configs: map[string]string{}}}}
got, err := EffectiveModels(inert, "acme/whole", nil)
if err != nil || len(got) != 0 {
t.Fatalf("whole-run override on a no-model graph = %+v, %v; want inert", got, err)
+1 -1
View File
@@ -77,7 +77,7 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU
db.Close()
return nil, err
}
if err := s.initChatNotifications(); err != nil {
if err := s.dropChatNotifications(); err != nil {
db.Close()
return nil, err
}
+2 -1
View File
@@ -81,7 +81,8 @@ type ChatShownItem struct {
// Detail says why a notification was not delivered (or not to the phone).
Detail string `json:"detail,omitempty"`
// Channels says where a delivered notification went: "apps" (the
// operator's signed-in Pipelines apps) and/or "phone" (ntfy).
// operator's signed-in Pipelines apps). Items recorded before ntfy was
// removed may also carry "phone".
Channels []string `json:"channels,omitempty"`
}
+49 -57
View File
@@ -67,13 +67,6 @@ type NotificationPolicy struct {
Link string `json:"link,omitempty"`
}
// Public phone setup only. Never include publishing endpoints or credentials.
type NotificationEndpoint struct {
Destination string `json:"destination"`
ServerURL string `json:"server_url,omitempty"`
Topic string `json:"topic"`
}
type Template struct {
Key string `json:"key"`
Name string `json:"name"`
@@ -142,56 +135,55 @@ type PipelineSummary struct {
// are optional so older peers ignore them. See search.go for the per-type payloads
// and the ranking/kind/bound vocabulary.
type Message struct {
SkillFiles []SkillFile `json:"skill_files,omitempty"`
SkillSummaries []SkillSummary `json:"skill_summaries,omitempty"`
SkillVersion *SkillVersion `json:"skill_version,omitempty"`
Storage *StorageOverview `json:"storage,omitempty"`
StoragePolicy *StoragePolicy `json:"storage_policy,omitempty"`
StorageCleanup *StorageCleanupResult `json:"storage_cleanup,omitempty"`
StorageCleanupToken string `json:"storage_cleanup_token,omitempty"`
Schedule *SavedSchedule `json:"schedule,omitempty"`
Schedules []SavedSchedule `json:"schedules,omitempty"`
ScheduleID int64 `json:"schedule_id,omitempty"`
ExpectedRevision int64 `json:"expected_revision,omitempty"`
DefaultHarness string `json:"default_harness,omitempty"`
Build *buildinfo.Info `json:"build,omitempty"`
Protocol int `json:"protocol,omitempty"`
DefaultModel string `json:"default_model,omitempty"`
Evidence []SessionEvidence `json:"evidence,omitempty"`
Usage *UsageStats `json:"usage,omitempty"`
Status *SystemStatus `json:"status,omitempty"`
Graph *Graph `json:"graph,omitempty"`
ExpectedVersion int `json:"expected_version,omitempty"`
Templates []Template `json:"templates,omitempty"`
CreateOnly bool `json:"create_only,omitempty"`
IncludeArchived bool `json:"include_archived,omitempty"`
NotificationEndpoints []NotificationEndpoint `json:"notification_endpoints,omitempty"`
Type string `json:"type"`
ID string `json:"id,omitempty"`
Time string `json:"time,omitempty"`
Error string `json:"error,omitempty"`
Warnings []string `json:"warnings,omitempty"` // non-blocking authoring lint for validate/submit
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Digest string `json:"digest,omitempty"`
SourcePath string `json:"source_path,omitempty"`
Source string `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Version int `json:"version,omitempty"`
Pipelines []PipelineSummary `json:"pipelines,omitempty"`
PipelineID int64 `json:"pipeline_id,omitempty"`
Detail *PipelineDetail `json:"detail,omitempty"`
RunID int64 `json:"run_id,omitempty"`
RunDetail *RunDetail `json:"run_detail,omitempty"`
Runs []RunSummary `json:"runs,omitempty"`
Stage string `json:"stage,omitempty"`
Option string `json:"option,omitempty"`
Feedback string `json:"feedback,omitempty"`
Input map[string]any `json:"input,omitempty"`
AllowTools bool `json:"allow_tools,omitempty"`
WritePaths []string `json:"write_paths,omitempty"`
RequestKey string `json:"request_key,omitempty"`
Workspace string `json:"workspace,omitempty"`
SkillFiles []SkillFile `json:"skill_files,omitempty"`
SkillSummaries []SkillSummary `json:"skill_summaries,omitempty"`
SkillVersion *SkillVersion `json:"skill_version,omitempty"`
Storage *StorageOverview `json:"storage,omitempty"`
StoragePolicy *StoragePolicy `json:"storage_policy,omitempty"`
StorageCleanup *StorageCleanupResult `json:"storage_cleanup,omitempty"`
StorageCleanupToken string `json:"storage_cleanup_token,omitempty"`
Schedule *SavedSchedule `json:"schedule,omitempty"`
Schedules []SavedSchedule `json:"schedules,omitempty"`
ScheduleID int64 `json:"schedule_id,omitempty"`
ExpectedRevision int64 `json:"expected_revision,omitempty"`
DefaultHarness string `json:"default_harness,omitempty"`
Build *buildinfo.Info `json:"build,omitempty"`
Protocol int `json:"protocol,omitempty"`
DefaultModel string `json:"default_model,omitempty"`
Evidence []SessionEvidence `json:"evidence,omitempty"`
Usage *UsageStats `json:"usage,omitempty"`
Status *SystemStatus `json:"status,omitempty"`
Graph *Graph `json:"graph,omitempty"`
ExpectedVersion int `json:"expected_version,omitempty"`
Templates []Template `json:"templates,omitempty"`
CreateOnly bool `json:"create_only,omitempty"`
IncludeArchived bool `json:"include_archived,omitempty"`
Type string `json:"type"`
ID string `json:"id,omitempty"`
Time string `json:"time,omitempty"`
Error string `json:"error,omitempty"`
Warnings []string `json:"warnings,omitempty"` // non-blocking authoring lint for validate/submit
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Digest string `json:"digest,omitempty"`
SourcePath string `json:"source_path,omitempty"`
Source string `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Version int `json:"version,omitempty"`
Pipelines []PipelineSummary `json:"pipelines,omitempty"`
PipelineID int64 `json:"pipeline_id,omitempty"`
Detail *PipelineDetail `json:"detail,omitempty"`
RunID int64 `json:"run_id,omitempty"`
RunDetail *RunDetail `json:"run_detail,omitempty"`
Runs []RunSummary `json:"runs,omitempty"`
Stage string `json:"stage,omitempty"`
Option string `json:"option,omitempty"`
Feedback string `json:"feedback,omitempty"`
Input map[string]any `json:"input,omitempty"`
AllowTools bool `json:"allow_tools,omitempty"`
WritePaths []string `json:"write_paths,omitempty"`
RequestKey string `json:"request_key,omitempty"`
Workspace string `json:"workspace,omitempty"`
// Model and StageModels are the launch-time model overrides: Model applies to
// every model stage of the run and StageModels overrides individual stages by
// key (per-stage wins over whole-run). Both are optional so older peers ignore
+16 -14
View File
@@ -6,12 +6,14 @@ import (
)
// Notification settings are the operator's global choices about which events
// publish through the server's ntfy connection. A client reads them with
// are recorded on the app notification stream (subscribe_notifications), and
// so reach every signed-in Pipelines app. A client reads them with
// {"type":"notification_settings"} and changes them with
// {"type":"set_notification_settings","notification_settings":{"<key>":bool}};
// a set may name any subset of keys, and unknown keys or non-boolean values
// are refused. Both replies have type "notification_settings" and carry every
// key with its stored value.
// are refused (the removed ntfy_enabled key is accepted and ignored, so an
// older client's switch does not fail). Both replies have type
// "notification_settings" and carry every key with its stored value.
const (
GetNotificationSettings = "notification_settings"
SetNotificationSettings = "set_notification_settings"
@@ -23,7 +25,10 @@ const (
NotifyRunFinished = "run_finished"
NotifyChatNeedsYou = "chat_needs_you"
NotifyChatReplyFinished = "chat_reply_finished"
NotifyNtfyEnabled = "ntfy_enabled"
// LegacyNotifyNtfyEnabled is the removed "also send to ntfy" switch. A set
// that names it is accepted and the key ignored; a stored value is never
// read.
LegacyNotifyNtfyEnabled = "ntfy_enabled"
)
// NotificationSettings is the typed form of the global notification choices.
@@ -36,18 +41,14 @@ type NotificationSettings struct {
ChatNeedsYou bool
// ChatReplyFinished notifies when an assistant turn in a chat ends.
ChatReplyFinished bool
// NtfyEnabled publishes notifications to ntfy. On by default; when off the
// server still records and streams every notification to app clients
// (subscribe_notifications) but stops publishing to ntfy.
NtfyEnabled bool
}
// NotificationSettingKeys lists every setting key in a stable order.
var NotificationSettingKeys = []string{NotifyRunFinished, NotifyChatNeedsYou, NotifyChatReplyFinished, NotifyNtfyEnabled}
var NotificationSettingKeys = []string{NotifyRunFinished, NotifyChatNeedsYou, NotifyChatReplyFinished}
// DefaultNotificationSettings are the values before the operator changes any.
func DefaultNotificationSettings() NotificationSettings {
return NotificationSettings{RunFinished: false, ChatNeedsYou: true, ChatReplyFinished: false, NtfyEnabled: true}
return NotificationSettings{RunFinished: false, ChatNeedsYou: true, ChatReplyFinished: false}
}
// Map returns the wire form with every key present.
@@ -56,7 +57,6 @@ func (s NotificationSettings) Map() map[string]any {
NotifyRunFinished: s.RunFinished,
NotifyChatNeedsYou: s.ChatNeedsYou,
NotifyChatReplyFinished: s.ChatReplyFinished,
NotifyNtfyEnabled: s.NtfyEnabled,
}
}
@@ -69,14 +69,13 @@ func (s *NotificationSettings) Field(key string) *bool {
return &s.ChatNeedsYou
case NotifyChatReplyFinished:
return &s.ChatReplyFinished
case NotifyNtfyEnabled:
return &s.NtfyEnabled
}
return nil
}
// ValidateNotificationSettingsUpdate checks a partial update: at least one key,
// every key known and every value a boolean.
// every key known and every value a boolean. The legacy ntfy_enabled key is
// dropped from the result, so an update naming only it changes nothing.
func ValidateNotificationSettingsUpdate(update map[string]any) (map[string]bool, error) {
if len(update) == 0 {
return nil, fmt.Errorf("notification_settings must name at least one setting")
@@ -89,6 +88,9 @@ func ValidateNotificationSettingsUpdate(update map[string]any) (map[string]bool,
result := make(map[string]bool, len(update))
var probe NotificationSettings
for _, key := range keys {
if key == LegacyNotifyNtfyEnabled {
continue
}
if probe.Field(key) == nil {
return nil, fmt.Errorf("unknown notification setting %q", key)
}
+6 -9
View File
@@ -2,12 +2,10 @@ package protocol
import "fmt"
// App notifications are the same operator notifications the server publishes
// to ntfy, streamed over /connect so the Pipelines app can post them itself
// without the ntfy app. Every publication point records one notification
// (persisted, with a stable id) before it publishes to ntfy, so the stream
// carries exactly the set ntfy gets, governed by the same notification
// settings; notify.ntfy_enabled=false stops only the ntfy publish.
// App notifications are the operator's notifications, streamed over /connect
// so every Pipelines app can post them itself. Every notification point records
// one notification (persisted, with a stable id), governed by the notification
// settings.
//
// → {"type":"subscribe_notifications","id":"1","after":"run:7:3:waiting"}
// ← {"type":"notifications_subscribed","id":"1","notifications":[{...}],"ids":["chat:ses_x:form:f1"]}
@@ -58,8 +56,7 @@ const (
NotificationSchedule = "schedule"
)
// DefaultNotificationPriority is ntfy's default priority, which every ntfy
// publication uses today (the server sends no Priority header).
// DefaultNotificationPriority is the default of the 1-5 notification priority.
const DefaultNotificationPriority = 3
// MaxReplayedNotifications bounds a subscribe reply and MaxClearNotificationIDs
@@ -78,7 +75,7 @@ type AppNotification struct {
Kind string `json:"kind"`
Title string `json:"title"`
Message string `json:"message"`
// Click is the app tap target (normally the same run deep link ntfy gets).
// Click is the app tap target (normally the run or chat deep link).
Click string `json:"click"`
RunClick string `json:"run_click,omitempty"`
Artifact *NotificationArtifact `json:"artifact,omitempty"`
-3
View File
@@ -21,7 +21,6 @@ type SystemStatus struct {
Uptime string `json:"uptime"`
Addresses []NetworkAddress `json:"addresses"`
Server ServiceStatus `json:"server"`
Ntfy ServiceStatus `json:"ntfy"`
// OpenCode reports how brokered chat is attached to OpenCode. Health is
// "endpoint" when attached to the operator's configured endpoint,
// "fallback" when that endpoint could not be attached and chat fell back to
@@ -29,7 +28,5 @@ type SystemStatus struct {
// "unavailable" when chat is disabled. URL is the configured endpoint, if
// any. It never carries a credential.
OpenCode ServiceStatus `json:"opencode"`
Topic string `json:"topic,omitempty"`
NtfyUser string `json:"ntfy_user,omitempty"`
Note string `json:"note"`
}
+3 -3
View File
@@ -26,7 +26,7 @@ go test ./... # ~1 min for everything; `gofmt -l .` must print
- `internal/server/chat_*.go` — the chat broker: `chat_sessions`, claims, the stream, permissions,
session registry.
- `internal/stage/` — one client per harness and stage type: `opencode.go` (native sessions),
`pi.go` (RPC), `model.go`, `agent.go`, `human.go` (decision stages), `ntfy.go` (notifications),
`pi.go` (RPC), `model.go`, `agent.go`, `human.go` (decision stages),
`model_prompt.go` (file-based turn prompt), `budget.go` (usage accounting). Model stages return
markdown for `output.md`; only its `# outcome` section is parsed (`internal/turn`).
- `internal/pipeline/` — the store: definitions and immutable versions, runs and steps, the
@@ -40,11 +40,11 @@ go test ./... # ~1 min for everything; `gofmt -l .` must print
`scripts/run-local-server.sh` starts a scratch server, and the binary takes `-addr` and `-db`, so a
live check runs against a **scratch database and a free loopback port**. The operator's deployment is
`~/.local/share/pipelines` with the service on `0.0.0.0:8080` and ntfy on `8090`.
`~/.local/share/pipelines` with the service on `0.0.0.0:8080`.
## Hard rules
- **Never restart, rebuild or redeploy the deployed server, ntfy or a running run** to test a change:
- **Never restart, rebuild or redeploy the deployed server or a running run** to test a change:
a restart kills every run in flight. Deploying is the operator's step.
- Commit locally only, never push.
- One run per workspace at a time — the server refuses a second one rather than sharing a tree.
+3 -35
View File
@@ -11,7 +11,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// appNotificationStore persists the app notification outbox.
@@ -27,8 +26,8 @@ type appNotificationStore interface {
// that falls this far behind is dropped; it recovers with a resubscribe.
const appNotificationQueue = 512
// appNotifier records every operator notification (the same ones published to
// ntfy) and streams them to subscribed connections. One mutex orders store
// appNotifier records every operator notification and streams it to
// subscribed connections. One mutex orders store
// writes with fan-out, so each subscriber sees its snapshot reply and then
// every later push exactly in commit order.
type appNotifier struct {
@@ -133,7 +132,7 @@ func (a *appNotifier) detach(clientID string) {
// record persists n and pushes it when it is new, and reports whether it is
// recorded. Failures are logged only: recording must never block or fail the
// ntfy publication beside it.
// event that raised it.
func (a *appNotifier) record(ctx context.Context, n pipeline.AppNotificationRecord) bool {
if a == nil {
return false
@@ -162,7 +161,6 @@ func (a *appNotifier) clear(ctx context.Context, ids []string, exclude string) (
}
if len(changed) > 0 {
a.enqueueLocked(protocol.Message{Type: protocol.NotificationsCleared, IDs: recordIDs(changed)}, exclude)
clearChatNtfy(recordIDs(changed))
}
return changed, nil
}
@@ -182,7 +180,6 @@ func (a *appNotifier) clearFor(ctx context.Context, filter pipeline.AppNotificat
}
if len(ids) > 0 {
a.enqueueLocked(protocol.Message{Type: protocol.NotificationsCleared, IDs: ids}, "")
clearChatNtfy(ids)
}
}
@@ -286,27 +283,6 @@ func handleAppNotifications(ctx context.Context, request protocol.Message, notes
return true
}
// ntfyEnabled reads notify.ntfy_enabled. Without a store, or when the read
// fails, ntfy stays enabled (the default) so a transient error never silences
// the operator.
func ntfyEnabled(ctx context.Context, store notificationSettingsStore) bool {
if store == nil {
return true
}
settings, err := store.NotificationSettings(ctx)
if err != nil {
log.Printf("read notification settings: %v", err)
return true
}
return settings.NtfyEnabled
}
// ntfyDisabledResult is what a publication reports when ntfy is turned off:
// the notification reached app clients only.
func ntfyDisabledResult() stage.Values {
return stage.Values{"destination": "system", "message_id": "", "ntfy": "disabled"}
}
// runNotificationKind maps a run outbox event to its app notification kind.
func runNotificationKind(event string) string {
switch event {
@@ -356,11 +332,3 @@ func runNotificationRecord(runID int64, sequence int, event, kind, title, messag
RunID: runID,
}
}
// settingsStore returns the runner's store as a settings reader, or nil.
func (r *runner) settingsStore() notificationSettingsStore {
if r.store == nil {
return nil
}
return r.store
}
+66 -87
View File
@@ -16,7 +16,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/summarise"
)
@@ -78,16 +77,12 @@ func newAppNotificationFixture(t *testing.T, ctx context.Context) *appNotificati
return &appNotificationFixture{t: t, ctx: ctx, store: store, runner: handler.(*runHandler).runner, hub: handler.(*runHandler).hub, url: srv.URL, def: def}
}
func TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
func TestToolNotificationRecordsAppNotification(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
hub := &chatHub{notes: newAppNotifier(store), settings: store}
got := hub.publishToolNotification(ctx, "session-1", chatToolNotice{ID: "shown_1", Title: "Build failed", Message: "Please inspect the run", Priority: "low"})
if !got.App || got.Phone || got.Detail != "phone notifications (ntfy) are turned off" {
if !got.App || got.Detail != "" {
t.Fatalf("tool notification result = %+v", got)
}
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
@@ -98,13 +93,15 @@ func TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
n.Message != "Please inspect the run" || n.Priority != 2 || n.Group != "chat:session-1" || n.Click != "pipelines://chat/session-1" {
t.Fatalf("wrong tool notification: %+v", n)
}
// Without the app stream there is nowhere to deliver: the agent is told.
if got := (&chatHub{}).publishToolNotification(ctx, "session-1", chatToolNotice{ID: "shown_2", Title: "t", Message: "m"}); got.App || got.Detail == "" {
t.Fatalf("store-less delivery = %+v", got)
}
}
// An agent's notify reaches every connected app, not only the clients watching
// that chat, and a client that connects later replays the ones still active.
func TestToolNotificationBroadcastsAndReplaysToReconnectingClients(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
f := newAppNotificationFixture(t, ctx)
@@ -114,7 +111,7 @@ func TestToolNotificationBroadcastsAndReplaysToReconnectingClients(t *testing.T)
subscribeNotifications(t, ctx, desktop, "")
notice := chatToolNotice{ID: "shown_a", Title: "Done", Message: "Build finished", Priority: "high"}
if got := hub.publishToolNotification(ctx, "ses_x", notice); !got.App || got.Phone || got.Detail == "" {
if got := hub.publishToolNotification(ctx, "ses_x", notice); !got.App || got.Detail != "" {
t.Fatalf("delivery = %+v", got)
}
for name, conn := range map[string]*websocket.Conn{"web": web, "desktop": desktop} {
@@ -226,11 +223,9 @@ func subscribeNotifications(t *testing.T, ctx context.Context, conn *websocket.C
return reply
}
func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
func TestAppNotificationStreamCarriesRunFailure(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
captured := newNtfyCapture(t)
f := newAppNotificationFixture(t, ctx)
phone := dialAckClient(t, ctx, f.url)
initial := subscribeNotifications(t, ctx, phone, "")
@@ -239,13 +234,9 @@ func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
}
run := f.failRun("stream")
push := readFrame(t, ctx, phone, protocol.NotificationPush)
got := captured()
if len(got) != 1 {
t.Fatalf("ntfy deliveries = %+v", got)
}
n := push.Notification
if n == nil || n.Title != got[0].Title || n.Message != got[0].Message || n.Click != got[0].Click {
t.Fatalf("stream %+v differs from ntfy %+v", n, got[0])
if n == nil || n.Title != "Run failed" || !strings.Contains(n.Message, fmt.Sprintf("Run #%d", run)) {
t.Fatalf("stream notification = %+v", n)
}
if n.ID != fmt.Sprintf("run:%d:0:failed", run) || n.Kind != protocol.NotificationRunFailed || n.Group != fmt.Sprintf("run:%d", run) ||
n.Priority != 3 || n.Tags == nil || len(n.Tags) != 0 || n.Click != fmt.Sprintf("pipelines://run/%d", run) {
@@ -264,7 +255,7 @@ func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
t.Fatalf("notification wire lacks %q: %s", key, raw)
}
}
// A retried publication of the same event is not streamed twice.
// A retried delivery of the same event is not streamed twice.
f.runner.deliverRunNotifications(time.Now().Add(time.Hour))
reply := subscribeNotifications(t, ctx, phone, "")
if len(reply.Notifications) != 1 || reply.Notifications[0].ID != n.ID || reply.Notifications[0].CreatedAt != n.CreatedAt {
@@ -273,11 +264,10 @@ func TestAppNotificationStreamMatchesNtfy(t *testing.T) {
}
func TestAppNotificationReplayAfterCursorAndCrossDeviceClear(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
f := newAppNotificationFixture(t, ctx)
// Offline: two runs fail with no app connected (ntfy unconfigured too).
// Offline: two runs fail with no app connected.
first := f.failRun("first")
second := f.failRun("second")
firstID, secondID := fmt.Sprintf("run:%d:0:failed", first), fmt.Sprintf("run:%d:0:failed", second)
@@ -357,42 +347,41 @@ func TestAppNotificationReplayAfterCursorAndCrossDeviceClear(t *testing.T) {
}
}
func TestNtfyDisabledStillStreams(t *testing.T) {
// An older app may still send the removed ntfy_enabled switch: the server
// accepts it without changing anything, replies with exactly the three
// notification settings, and keeps streaming.
func TestLegacyNtfySwitchIsIgnoredAndRunsStillStream(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
captured := newNtfyCapture(t)
f := newAppNotificationFixture(t, ctx)
phone := dialAckClient(t, ctx, f.url)
set := ackExchange(t, ctx, phone, protocol.Message{Type: protocol.SetNotificationSettings, ID: "off", NotificationSettings: map[string]any{protocol.NotifyNtfyEnabled: false}})
if set.Type != protocol.NotificationSettingsReply || set.NotificationSettings[protocol.NotifyNtfyEnabled] != false {
set := ackExchange(t, ctx, phone, protocol.Message{Type: protocol.SetNotificationSettings, ID: "off", NotificationSettings: map[string]any{protocol.LegacyNotifyNtfyEnabled: false}})
want := protocol.DefaultNotificationSettings().Map()
if set.Type != protocol.NotificationSettingsReply || len(set.NotificationSettings) != 3 {
t.Fatalf("settings reply = %+v", set)
}
for key, value := range want {
if set.NotificationSettings[key] != value {
t.Fatalf("settings reply %s = %v, want %v: %+v", key, set.NotificationSettings[key], value, set)
}
}
if _, present := set.NotificationSettings[protocol.LegacyNotifyNtfyEnabled]; present {
t.Fatalf("reply still carries ntfy_enabled: %+v", set)
}
subscribeNotifications(t, ctx, phone, "")
run := f.failRun("quiet")
push := readFrame(t, ctx, phone, protocol.NotificationPush)
if push.Notification == nil || push.Notification.ID != fmt.Sprintf("run:%d:0:failed", run) || push.Notification.Title != "Run failed" {
t.Fatalf("push = %+v", push)
}
if got := captured(); len(got) != 0 {
t.Fatalf("ntfy published while disabled: %+v", got)
}
// The outbox is settled, not retried against ntfy.
// The outbox is settled once the app notification is recorded.
rows, err := f.store.RunNotifications(ctx, run)
if err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("outbox = %+v %v", rows, err)
}
}
func TestChatAppNotificationsRespectNtfyEnabledAndClearOnAnswer(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
var published []ntfyCapture
original := chatAttentionPublish
chatAttentionPublish = func(_ context.Context, _, title, message, _ string, _ []byte, click string, _ ...stage.NtfyView) (stage.Values, error) {
published = append(published, ntfyCapture{Title: title, Message: message, Click: click})
return stage.Values{}, nil
}
defer func() { chatAttentionPublish = original }()
func TestChatAppNotificationsClearOnAnswer(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
h := chatAttentionHub(t, "ses_a")
@@ -402,13 +391,13 @@ func TestChatAppNotificationsRespectNtfyEnabledAndClearOnAnswer(t *testing.T) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_a", Kind: protocol.ChatEventForm, Form: &form})
h.attentionWG.Wait()
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(published) != 1 || len(active) != 1 {
t.Fatalf("published=%+v active=%+v err=%v", published, active, err)
if err != nil || len(active) != 1 {
t.Fatalf("active=%+v err=%v", active, err)
}
n := active[0]
if n.ID != "chat:ses_a:form:que_1" || n.Kind != protocol.NotificationChatQuestion || n.Group != "chat:ses_a" ||
n.Title != published[0].Title || n.Message != published[0].Message || n.Click != published[0].Click {
t.Fatalf("chat notification %+v vs ntfy %+v", n, published[0])
n.Message != "Ship it?" || n.Click != "pipelines://chat/ses_a" {
t.Fatalf("chat notification %+v", n)
}
// Answering the question clears it.
form.Resolved = true
@@ -417,15 +406,11 @@ func TestChatAppNotificationsRespectNtfyEnabledAndClearOnAnswer(t *testing.T) {
if active, _, _ := store.ActiveAppNotifications(ctx, "", time.Now()); len(active) != 0 {
t.Fatalf("answered question still active: %+v", active)
}
// With ntfy off, the approval is streamed but not published.
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil {
t.Fatal(err)
}
h.pushPermission("ses_a", protocol.ChatPermissionFrame{SessionID: "ses_a", RequestID: "per_1", Message: "Allow rm?"})
h.attentionWG.Wait()
active, _, _ = store.ActiveAppNotifications(ctx, "", time.Now())
if len(published) != 1 || len(active) != 1 || active[0].Kind != protocol.NotificationChatApproval || active[0].ID != "chat:ses_a:permission:per_1" {
t.Fatalf("published=%+v active=%+v", published, active)
if len(active) != 1 || active[0].Kind != protocol.NotificationChatApproval || active[0].ID != "chat:ses_a:permission:per_1" {
t.Fatalf("active=%+v", active)
}
h.confirmPermission("ses_a", "per_1", "phone", "once")
h.attentionWG.Wait()
@@ -452,12 +437,9 @@ func TestRunLeavingWaitingClearsWaitingNotification(t *testing.T) {
}
}
// A stage notify hook streams one notification per step event (artifacts stay
// ntfy attachments) with the hook's title and summary, and with ntfy disabled
// it still streams while publishing nothing.
// A stage notify hook streams one notification per step event with the hook's
// title and summary, and audits the delivery as an app receipt.
func TestStageHookAppNotification(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
captured := newNtfyCapture(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
@@ -468,38 +450,35 @@ func TestStageHookAppNotification(t *testing.T) {
d, _ := store.Get(ctx, items[0].ID, 0)
workspace := t.TempDir()
r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store)}
// artifacts= is a legacy setting (it used to attach files to ntfy) and is
// accepted without effect.
policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Artifacts: []string{"markdown"}}
for i, ntfyOn := range []bool{true, false} {
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: ntfyOn}); err != nil {
t.Fatal(err)
}
id, _, err := store.CreateRun(ctx, d, fmt.Sprintf("hook%d", i), workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
t.Fatal(err)
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{"markdown": "# Digest"}}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := len(captured())
r.notifyStep(id, d.Name, workspace, policy, step)
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != i+1 {
t.Fatalf("active = %+v %v", active, err)
}
n := active[i]
if n.ID != fmt.Sprintf("run:%d:1:success", id) || n.Kind != protocol.NotificationStageSucceeded || n.Click != fmt.Sprintf("pipelines://run/%d", id) {
t.Fatalf("hook notification = %+v", n)
}
got := captured()
if ntfyOn && (len(got) != before+1 || got[before].Title != n.Title || got[before].Message != n.Message || got[before].Click != n.Click) {
t.Fatalf("ntfy %+v vs stream %+v", got, n)
}
if !ntfyOn && len(got) != before {
t.Fatalf("ntfy published while disabled: %+v", got)
}
id, _, err := store.CreateRun(ctx, d, "hook", workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
t.Fatal(err)
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{"markdown": "# Digest"}}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
r.notifyStep(id, d.Name, workspace, policy, step)
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != 1 {
t.Fatalf("active = %+v %v", active, err)
}
n := active[0]
if n.ID != fmt.Sprintf("run:%d:1:success", id) || n.Kind != protocol.NotificationStageSucceeded || n.Click != fmt.Sprintf("pipelines://run/%d", id) ||
n.Title != "Pipeline stage success" || !strings.Contains(n.Message, "stage one") {
t.Fatalf("hook notification = %+v", n)
}
detail, err := store.GetRun(ctx, id)
if err != nil || len(detail.Steps) != 1 || len(detail.Steps[0].Notifications) != 1 {
t.Fatalf("receipts = %+v %v", detail.Steps, err)
}
if receipt := detail.Steps[0].Notifications[0]; receipt.Destination != "app" || receipt.Status != "sent" || receipt.Filename != "" {
t.Fatalf("receipt = %+v", receipt)
}
}
-2
View File
@@ -58,7 +58,6 @@ func listActivity(t *testing.T, ctx context.Context, conn *websocket.Conn) *prot
// last one exits.
func TestChatActivityReachesEveryConnection(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, listedObservedChat{broker}, store)
@@ -113,7 +112,6 @@ func TestChatActivityReachesEveryConnection(t *testing.T) {
// invent completion. A terminal event releases it and clears list activity.
func TestChatBackgroundTaskWaitsForExitBeyondObserverTTL(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
limit := chatUnattendedTurnLimit
chatUnattendedTurnLimit = 300 * time.Millisecond
t.Cleanup(func() { chatUnattendedTurnLimit = limit })
+11 -27
View File
@@ -3,22 +3,17 @@ package server
import (
"context"
"net/url"
"os"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// chatAttentionRetainedLimit bounds the hub-wide set of form/permission ids that
// already produced (or never deserve) an attention notification.
const chatAttentionRetainedLimit = 1024
// chatAttentionPublish is the publisher; tests may replace it.
var chatAttentionPublish = stage.PublishNtfy
// chatAttention is one pending operator-attention notification for a chat.
type chatAttention struct {
sessionID string
@@ -115,14 +110,10 @@ func (h *chatHub) notePermissionAttentionLocked(frame protocol.ChatPermissionFra
h.startChatAttention(chatAttention{sessionID: frame.SessionID, approval: true, body: body, id: chatNotificationID(frame.SessionID, "permission", frame.RequestID)})
}
func chatAttentionConfigured() bool {
return os.Getenv("PIPELINES_NTFY_URL") != ""
}
// attentionWanted reports whether a chat attention item has anywhere to go:
// the ntfy connection or the app notification stream.
// the app notification stream.
func (h *chatHub) attentionWanted() bool {
return chatAttentionConfigured() || h.notes != nil
return h.notes != nil
}
// clearChatAttention clears one chat app notification asynchronously, off the
@@ -145,9 +136,8 @@ func (h *chatHub) clearChatAttention(sessionID, id string) {
}()
}
// startChatAttention publishes asynchronously within the 30-second notification
// budget. It never blocks or fails chat handling; the phone push goes through
// the durable outbox, which retries a failed attempt.
// startChatAttention records the app notification asynchronously within the
// 30-second notification budget. It never blocks or fails chat handling.
func (h *chatHub) startChatAttention(a chatAttention) {
base := h.baseCtx
if base == nil {
@@ -176,7 +166,7 @@ func (h *chatHub) startChatAttention(a chatAttention) {
if a.reply {
title, body = chatReplyText(name, a.body)
}
click, _ := chatAttentionLinks(a.sessionID)
click := chatAttentionClick(a.sessionID)
kind := protocol.NotificationChatQuestion
if a.reply {
kind = protocol.NotificationChatReply
@@ -188,16 +178,11 @@ func (h *chatHub) startChatAttention(a chatAttention) {
Priority: protocol.DefaultNotificationPriority, Tags: []string{}, Group: "chat:" + a.sessionID},
SessionID: a.sessionID,
})
if !chatAttentionConfigured() || !settings.NtfyEnabled {
return
}
// ntfy takes a single-line message of at most 2048 bytes.
h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: a.id, SessionID: a.sessionID, Title: title, Body: truncateUTF8(singleLine(body), 2000), Click: click, SequenceID: chatNtfySequence(a.id)})
}()
}
// chatAttentionText builds a single-line ntfy title/body within PublishNtfy's
// limits.
// chatAttentionText builds a single-line notification title/body of bounded
// length.
func chatAttentionText(name string, approval bool, body string) (string, string) {
name = singleLine(name)
if name == "" {
@@ -215,9 +200,8 @@ func singleLine(text string) string {
return strings.Join(strings.Fields(strings.ReplaceAll(text, "\x00", "")), " ")
}
// chatAttentionLinks opens the chat in the app; the web origin, when
// configured, is offered as an "Open in browser" action.
func chatAttentionLinks(sessionID string) (string, []stage.NtfyView) {
escaped := url.PathEscape(sessionID)
return "pipelines://chat/" + escaped, webAttentionViews("/chat/" + escaped)
// chatAttentionClick is the notification tap target that opens the chat in
// the app.
func chatAttentionClick(sessionID string) string {
return "pipelines://chat/" + url.PathEscape(sessionID)
}
@@ -17,7 +17,6 @@ import (
// switch to.
func autoContinueServer(t *testing.T) (*refusingChat, *queueServer, *pipeline.Store) {
t.Helper()
capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
broker.quiet = true
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) {
+3 -7
View File
@@ -32,7 +32,7 @@ const (
chatAutoContinuePrefix = "auto-continue-"
// chatAutoSwitchClient is the sender label of the continue prompt.
chatAutoSwitchClient = "Pipelines (automatic)"
// chatAutoSwitchPriority is ntfy's "low" priority.
// chatAutoSwitchPriority is the notification stream's "low" priority.
chatAutoSwitchPriority = 2
// chatAutoSwitchRemembered bounds the refusals remembered as handled.
chatAutoSwitchRemembered = 256
@@ -280,7 +280,7 @@ func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sess
}
// publishAutoSwitchNotice tells the operator, at low priority, through the
// app notification stream and (when enabled) ntfy.
// app notification stream.
func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.UsageRefusal, name, email string) {
name = singleLine(name)
if name == "" {
@@ -288,7 +288,7 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us
}
title := truncateUTF8("Switched "+name+" to "+singleLine(email)+" and continued", 256)
message := "Claude usage ran out, so Pipelines switched the account and asked the agent to check it is on track before continuing."
click, _ := chatAttentionLinks(refusal.SessionID)
click := chatAttentionClick(refusal.SessionID)
id := "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal)
if h.notes != nil {
h.notes.record(ctx, pipeline.AppNotificationRecord{
@@ -297,8 +297,4 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us
SessionID: refusal.SessionID,
})
}
if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled {
return
}
h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: id, SessionID: refusal.SessionID, Title: title, Body: message, Click: click, Priority: chatAutoSwitchPriority})
}
+14 -19
View File
@@ -12,7 +12,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// refusingChat is a channelChat that reports usage refusals and switches
@@ -69,24 +68,21 @@ type publishedNotice struct {
priority int
}
func capturePublications(t *testing.T) func() []publishedNotice {
// autoSwitchNotices returns the auto-switch notices recorded on the app
// notification stream.
func autoSwitchNotices(t *testing.T, store *pipeline.Store) []publishedNotice {
t.Helper()
t.Setenv("PIPELINES_NTFY_URL", "https://ntfy.invalid/pipelines")
var mu sync.Mutex
active, _, err := store.ActiveAppNotifications(context.Background(), "", time.Now())
if err != nil {
t.Fatal(err)
}
var got []publishedNotice
previous := chatAttentionPublish
chatAttentionPublish = func(ctx context.Context, _, title, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
mu.Lock()
got = append(got, publishedNotice{title, stage.NtfyPriority(ctx)})
mu.Unlock()
return stage.Values{}, nil
}
t.Cleanup(func() { chatAttentionPublish = previous })
return func() []publishedNotice {
mu.Lock()
defer mu.Unlock()
return append([]publishedNotice(nil), got...)
for _, n := range active {
if strings.Contains(n.ID, ":auto-switch:") {
got = append(got, publishedNotice{n.Title, n.Priority})
}
}
return got
}
func autoSwitchServer(t *testing.T, sessions ...string) (*refusingChat, *queueServer, *pipeline.Store) {
@@ -109,8 +105,8 @@ func autoSwitchServer(t *testing.T, sessions ...string) (*refusingChat, *queueSe
// for the refusal is taken out, and a late one is refused. The operator is
// told at low priority.
func TestUsageRefusalSwitchesAccountAndQueuesAGuardedContinue(t *testing.T) {
published := capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
published := func() []publishedNotice { return autoSwitchNotices(t, store) }
conn := dialChatConn(t, server.ctx, server.srv)
if ack := sendPrompt(t, server.ctx, conn, "p1", "work", "op-1"); ack.ChatQueued {
t.Fatalf("first prompt queued: %+v", ack)
@@ -170,8 +166,8 @@ func TestUsageRefusalSwitchesAccountAndQueuesAGuardedContinue(t *testing.T) {
func TestUsageRefusalWithoutASwitchLeavesTheChat(t *testing.T) {
for _, failure := range []error{claude.ErrNoAccountLeft, claude.ErrAutoSwitchOff} {
t.Run(failure.Error(), func(t *testing.T) {
published := capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
published := func() []publishedNotice { return autoSwitchNotices(t, store) }
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) { return claude.AutoSwitch{}, failure }
conn := dialChatConn(t, server.ctx, server.srv)
if ack := sendScheduled(t, server.ctx, conn, "p1", "continue", "auto-continue-refusal-1", time.Now().Add(time.Hour)); !ack.ChatQueued {
@@ -191,7 +187,6 @@ func TestUsageRefusalWithoutASwitchLeavesTheChat(t *testing.T) {
// Chats refused together each get their own continue prompt; a chat that is
// not the operator's is left alone.
func TestConcurrentUsageRefusalsContinueEveryChat(t *testing.T) {
capturePublications(t)
broker, _, _ := autoSwitchServer(t, "ses_1", "ses_2")
broker.quiet = true
var once sync.Once
-1
View File
@@ -78,7 +78,6 @@ func restartChatDB(t *testing.T) string {
func fastReattach(t *testing.T) {
t.Helper()
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
poll := chatReattachPoll
chatReattachPoll = 20 * time.Millisecond
t.Cleanup(func() { chatReattachPoll = poll })
+2 -5
View File
@@ -46,14 +46,11 @@ type chatHub struct {
// to the other clients, so each retained user message has a stable id.
userSeq int
// attentionSeen/attentionOrder are the bounded hub-wide record of forms and
// approval requests already considered for an ntfy attention notification;
// attentionWG tracks in-flight publications.
// approval requests already considered for an attention notification;
// attentionWG tracks in-flight recordings.
attentionSeen map[string]struct{}
attentionOrder []string
attentionWG sync.WaitGroup
// outbox makes chat phone pushes durable and retried (chat_ntfy_outbox.go);
// nil publishes each push once, directly.
outbox chatNotificationOutbox
// notifiedTurns holds the chats whose current turn already sent an agent
// notify, so that turn's end is not announced again (one turn, one ping).
notifiedTurns map[string]struct{}
+1 -1
View File
@@ -26,7 +26,7 @@ import (
// pipeline stage session (created as a raw OpenCode session and recorded in
// run_steps/run_session_owners exactly as a run does) never appears in
// chat_sessions. It is opt-in (real inference) and never touches the deployed
// server, ntfy or any lane; it runs on a t.TempDir workspace.
// server or any lane; it runs on a t.TempDir workspace.
func TestChatLiveEndToEnd(t *testing.T) {
if os.Getenv("PIPELINES_TEST_OPENCODE_CHAT_LIVE") != "1" {
t.Skip("set PIPELINES_TEST_OPENCODE_CHAT_LIVE=1 to run the live OpenCode chat end-to-end check")
-1
View File
@@ -47,7 +47,6 @@ func (c *reportingChat) setRunning(running bool) {
func TestChatRunnerEndsItsTurnWhoseEndFrameWasLost(t *testing.T) {
fastUnattended(t)
fastStaleTurnSettle(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := &reportingChat{observedChat: newObservedChat()}
server := startQueueServer(t, broker, store)
+21 -58
View File
@@ -2,22 +2,18 @@ package server
import (
"context"
"sync"
"testing"
"time"
"github.com/coder/websocket"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// One turn, one ping: a turn that already sent an agent notify does not also
// announce its end, while a later turn without one does, and a notify sent
// after a turn ended (background work) does not silence the next turn.
func TestAgentNotifySuppressesThatTurnsReplyNotification(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
captured := newNtfyCapture(t)
store := newOperatorStore(t)
ctx := context.Background()
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
@@ -33,63 +29,50 @@ func TestAgentNotifySuppressesThatTurnsReplyNotification(t *testing.T) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
h.attentionWG.Wait()
}
kinds := func() []string {
t.Helper()
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil {
t.Fatal(err)
}
var got []string
for _, n := range active {
got = append(got, n.Kind+":"+n.Title)
}
return got
}
start("turn_1")
if got := h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n1", Title: "Halfway", Message: "Tests pass"}); !got.App || !got.Phone {
if got := h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n1", Title: "Halfway", Message: "Tests pass"}); !got.App {
t.Fatalf("delivery = %+v", got)
}
end("turn_1")
if got := captured(); len(got) != 1 || got[0].Title != "Halfway" {
t.Fatalf("turn with a notify published %+v", got)
}
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
if err != nil || len(active) != 1 || active[0].Kind != protocol.NotificationChatNotify {
t.Fatalf("app notifications = %+v, %v", active, err)
if got := kinds(); len(got) != 1 || got[0] != protocol.NotificationChatNotify+":Halfway" {
t.Fatalf("turn with a notify recorded %+v", got)
}
// Background work notifies after the turn; the next turn still announces.
h.publishToolNotification(ctx, "ses_n", chatToolNotice{ID: "n2", Title: "Deploy done", Message: "Live"})
start("turn_2")
end("turn_2")
got := captured()
if len(got) != 3 || got[2].Title != "Chat replied" {
got := kinds()
if len(got) != 3 || got[2] != protocol.NotificationChatReply+":Chat replied" {
t.Fatalf("later deliveries = %+v", got)
}
}
// Every chat ntfy message carries a sequence id derived from its app id, and
// clearing the app notification (here: on another device) clears it in ntfy
// and pushes the clear to every other connected client.
func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
// Clearing a chat app notification on one device pushes the clear to every
// other connected client.
func TestClearingAChatNotificationClearsEveryClient(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var mu sync.Mutex
var published []string
originalPublish, originalClear := chatAttentionPublish, chatAttentionClear
chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
mu.Lock()
published = append(published, stage.NtfySequence(ctx))
mu.Unlock()
return stage.Values{"message_id": "m"}, nil
}
cleared := make(chan string, 8)
chatAttentionClear = func(_ context.Context, destination, sequence string) error {
if destination == "system" {
cleared <- sequence
}
return nil
}
defer func() { chatAttentionPublish, chatAttentionClear = originalPublish, originalClear }()
f := newAppNotificationFixture(t, ctx)
hub := f.handlerHub()
web, desktop, phone := dialAckClient(t, ctx, f.url), dialAckClient(t, ctx, f.url), dialAckClient(t, ctx, f.url)
subscribeNotifications(t, ctx, web, "")
subscribeNotifications(t, ctx, desktop, "")
subscribeNotifications(t, ctx, phone, "")
if got := hub.publishToolNotification(ctx, "ses_c", chatToolNotice{ID: "shown_c", Title: "Look", Message: "Now"}); !got.App || !got.Phone {
if got := hub.publishToolNotification(ctx, "ses_c", chatToolNotice{ID: "shown_c", Title: "Look", Message: "Now"}); !got.App {
t.Fatalf("delivery = %+v", got)
}
id := "chat:ses_c:notify:shown_c"
@@ -98,11 +81,6 @@ func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
t.Fatalf("push = %+v", push)
}
}
mu.Lock()
if len(published) != 1 || published[0] != chatNtfySequence(id) {
t.Fatalf("published sequences = %v", published)
}
mu.Unlock()
// Tapped on the phone: the phone gets the reply, every other client a push.
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ClearNotifications, ID: "tap", IDs: []string{id}})
@@ -114,19 +92,4 @@ func TestClearingAChatNotificationClearsEveryClientAndNtfy(t *testing.T) {
t.Fatalf("%s cleared push = %+v", name, push)
}
}
select {
case sequence := <-cleared:
if sequence != chatNtfySequence(id) {
t.Fatalf("ntfy cleared %q", sequence)
}
case <-ctx.Done():
t.Fatal("ntfy was not cleared")
}
}
func TestChatNtfySequenceIsAValidStableNtfyID(t *testing.T) {
a, b := chatNtfySequence("chat:ses_x:notify:abc"), chatNtfySequence("chat:ses_x:notify:abd")
if a != chatNtfySequence("chat:ses_x:notify:abc") || a == b || len(a) != 27 {
t.Fatalf("sequences %q %q", a, b)
}
}
-54
View File
@@ -1,54 +0,0 @@
package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"log"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// chatAttentionClear dismisses one ntfy message by sequence id; tests may
// replace it.
var chatAttentionClear = stage.ClearNtfy
// chatNtfySequence is the ntfy sequence id a chat notification (app id
// "chat:<session>:<what>:<id>") is published with, so clearing the app
// notification can also clear it in the ntfy app. It is derived from the app
// id, so nothing extra is stored and a restart still clears it.
func chatNtfySequence(id string) string {
digest := sha256.Sum256([]byte(id))
return "pl-" + hex.EncodeToString(digest[:12])
}
// clearChatNtfy asks ntfy to clear the chat notifications among ids (every
// app notification id that was cleared), off the caller's goroutine. ntfy
// emits message_clear and its clients dismiss the notification. Run
// notifications are published without a sequence id and are left alone.
func clearChatNtfy(ids []string) {
if !chatAttentionConfigured() {
return
}
var sequences []string
for _, id := range ids {
if strings.HasPrefix(id, "chat:") {
sequences = append(sequences, chatNtfySequence(id))
}
}
if len(sequences) == 0 {
return
}
clear := chatAttentionClear
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
for _, sequence := range sequences {
if err := clear(ctx, "system", sequence); err != nil {
log.Printf("clear ntfy notification %s: %v", sequence, err)
}
}
}()
}
-128
View File
@@ -1,128 +0,0 @@
package server
import (
"context"
"log"
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// Chat phone pushes (attention items and Claude auto-switch notices) go
// through a durable outbox like run notifications: the push is recorded first,
// one attempt is made at once, and a background worker retries a failed or
// interrupted attempt with backoff, also after a restart. A push whose app
// notification the operator already cleared is never published late, and a
// publication that raced a clear is cleared on the phone again, so the ntfy
// sequence-id/clear behaviour (chat_ntfy_clear.go) holds.
// chatNotificationOutbox is the durable chat push outbox; *pipeline.Store
// implements it.
type chatNotificationOutbox interface {
EnqueueChatNotification(ctx context.Context, n pipeline.ChatNotification, now time.Time) error
ClaimChatNotification(ctx context.Context, now int64) (*pipeline.ChatNotification, error)
FinishChatNotification(ctx context.Context, n pipeline.ChatNotification, now int64, messageID string, failure error) error
ChatNotificationCleared(ctx context.Context, id string) (bool, error)
Done() <-chan struct{}
}
// chatOutboxInterval is how often the worker looks for due retries.
var chatOutboxInterval = time.Second
// chatOutboxSkew shifts the outbox clock; tests move it past a backoff.
var chatOutboxSkew atomic.Int64
func chatOutboxNow() time.Time { return time.Now().Add(time.Duration(chatOutboxSkew.Load())) }
// startChatNotificationOutbox wires the durable outbox and starts its retry
// worker for the life of ctx.
func (h *chatHub) startChatNotificationOutbox(ctx context.Context, outbox chatNotificationOutbox) {
h.outbox = outbox
go func() {
ticker := time.NewTicker(chatOutboxInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-outbox.Done():
return
case <-ticker.C:
h.deliverChatNotifications(ctx, 16)
}
}
}()
}
// pushChatNtfy publishes one chat phone push. With an outbox it is recorded
// durably and attempted at once; without one (a store-less hub) it is a single
// direct attempt, as before.
func (h *chatHub) pushChatNtfy(ctx context.Context, n pipeline.ChatNotification) {
if h.outbox != nil {
err := h.outbox.EnqueueChatNotification(ctx, n, chatOutboxNow())
if err == nil {
h.deliverChatNotifications(ctx, 1)
return
}
log.Printf("enqueue chat notification %s: %v; publishing directly", n.ID, err)
}
if _, err := chatAttentionPublish(chatNtfyContext(ctx, n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(n)...); err != nil {
log.Printf("chat notification session=%s: %v", n.SessionID, err)
}
}
func chatNtfyContext(ctx context.Context, n pipeline.ChatNotification) context.Context {
if n.SequenceID != "" {
ctx = stage.WithNtfySequenceID(ctx, n.SequenceID)
}
if n.Priority > 0 {
ctx = stage.WithNtfyPriority(ctx, n.Priority)
}
return ctx
}
// chatNtfyViews derives the push's actions at delivery, so a changed web
// origin applies to a retried push.
func chatNtfyViews(n pipeline.ChatNotification) []stage.NtfyView {
_, views := chatAttentionLinks(n.SessionID)
return views
}
// deliverChatNotifications attempts up to limit due pushes.
func (h *chatHub) deliverChatNotifications(ctx context.Context, limit int) {
outbox := h.outbox
if outbox == nil {
return
}
for i := 0; i < limit && ctx.Err() == nil; i++ {
n, err := outbox.ClaimChatNotification(ctx, chatOutboxNow().Unix())
if err != nil {
log.Printf("claim chat notification: %v", err)
return
}
if n == nil {
return
}
publish, cancel := context.WithTimeout(ctx, 30*time.Second)
result, publishErr := chatAttentionPublish(chatNtfyContext(publish, *n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(*n)...)
cancel()
if publishErr != nil {
log.Printf("chat notification session=%s attempt=%d: %v", n.SessionID, n.Attempts, publishErr)
}
messageID, _ := result["message_id"].(string)
save, done := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
if err := outbox.FinishChatNotification(save, *n, chatOutboxNow().Unix(), messageID, publishErr); err != nil {
log.Printf("save chat notification %s: %v", n.ID, err)
}
// The operator may have cleared it in the app while it was being
// published, after the clear went to ntfy: clear it there again.
if publishErr == nil && n.SequenceID != "" {
if cleared, err := outbox.ChatNotificationCleared(save, n.ID); err == nil && cleared {
clearChatNtfy([]string{n.ID})
}
}
done()
}
}
-61
View File
@@ -1,61 +0,0 @@
package server
import (
"context"
"errors"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// A chat attention push that ntfy refuses is kept in the durable outbox and
// retried by the worker with its sequence id, not lost after one attempt.
func TestChatAttentionPushIsRetriedFromTheOutbox(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
interval := chatOutboxInterval
chatOutboxInterval = 20 * time.Millisecond
defer func() { chatOutboxInterval = interval }()
var mu sync.Mutex
var sequences []string
original := chatAttentionPublish
chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
mu.Lock()
defer mu.Unlock()
sequences = append(sequences, stage.NtfySequence(ctx))
if len(sequences) == 1 {
return nil, errors.New("ntfy unavailable")
}
return stage.Values{"message_id": "m1"}, nil
}
defer func() { chatAttentionPublish = original }()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
h := chatAttentionHub(t, "ses_a")
h.settings = store
h.notes = newAppNotifier(store)
h.startChatNotificationOutbox(ctx, store)
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_a", Kind: "question", Title: "Ship it?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_a", Kind: protocol.ChatEventForm, Form: &form})
h.attentionWG.Wait()
id := "chat:ses_a:form:que_1"
if status, attempts, err := store.ChatNotificationStatus(ctx, id); err != nil || status != "pending" || attempts != 1 {
t.Fatalf("after a refused attempt: %s/%d %v", status, attempts, err)
}
// The first backoff is 5 s; move the outbox clock past it.
chatOutboxSkew.Store(int64(10 * time.Second))
defer chatOutboxSkew.Store(0)
waitFor(t, "retried push sent", func() bool {
status, _, _ := store.ChatNotificationStatus(ctx, id)
return status == "sent"
})
mu.Lock()
defer mu.Unlock()
if len(sequences) != 2 || sequences[0] != chatNtfySequence(id) || sequences[1] != sequences[0] {
t.Fatalf("sequence ids = %v", sequences)
}
}
-1
View File
@@ -89,7 +89,6 @@ func TestChatPromptBehindAnUnqueuedScheduledHeadRunsAfterRestart(t *testing.T) {
func TestChatQueueEndsAStaleObservedTurnOnceTheHarnessIsIdle(t *testing.T) {
fastUnattended(t)
fastStaleTurnSettle(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := newObservedChat()
server := startQueueServer(t, broker, store)
+1 -2
View File
@@ -130,8 +130,7 @@ func truncateRunes(text string, limit int) string {
}
// chatReplyText builds a finished reply's title and body. The body keeps the
// reply's paragraph breaks for the app's notifications; ntfy gets it on one
// line (see chatAttentionPublishBody).
// reply's paragraph breaks for the app's notifications.
func chatReplyText(name, body string) (string, string) {
name = singleLine(name)
if name == "" {
@@ -15,10 +15,6 @@ func TestReplyNotificationKeepsParagraphs(t *testing.T) {
if body != "One\n\nTwo" {
t.Fatalf("app body should keep paragraph breaks, got %q", body)
}
// ntfy gets the same text on one line.
if flat := singleLine(body); strings.Contains(flat, "\n") || flat != "One Two" {
t.Fatalf("ntfy body = %q", flat)
}
long := truncateRunes(strings.Repeat("a", 1500), chatReplyBodyRunes)
if n := utf8.RuneCountInString(long); n != chatReplyBodyRunes+1 || chatReplyBodyRunes != 1000 {
t.Fatalf("excerpt is %d runes (limit %d)", n, chatReplyBodyRunes)
+11 -24
View File
@@ -6,7 +6,6 @@ import (
"encoding/hex"
"errors"
"io"
"log"
"mime"
"net/http"
"net/url"
@@ -16,7 +15,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// shownFile is a resolved file inside the operator's home.
@@ -135,19 +133,17 @@ type chatToolNotice struct {
// chatToolDelivery reports where a chat tool notification went: App when it
// was recorded on the app notification stream (every connected Pipelines app
// receives it and a reconnecting one replays it), Phone when ntfy accepted it.
// Detail explains a phone delivery that was skipped or refused.
// receives it and a reconnecting one replays it). Detail explains a failure.
type chatToolDelivery struct {
App bool
Phone bool
Detail string
}
// chatToolNotifier delivers one model-requested notification for a chat.
type chatToolNotifier func(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery
// chatNotifyPriority maps the tool's priority word to the app stream's
// ntfy-style 1-5 priority.
// chatNotifyPriority maps the tool's priority word to the app stream's 1-5
// priority (3 is the default).
func chatNotifyPriority(priority string) int {
switch priority {
case "low":
@@ -160,14 +156,12 @@ func chatNotifyPriority(priority string) int {
// publishToolNotification records the notification on the app notification
// stream (kind chat_notify), which is pushed to every subscribed client and
// replayed to one that reconnects while it is still active, then publishes it
// through the operator's existing "system" ntfy destination (the one chat
// attention uses), honoring their ntfy switch. Tapping it opens the chat
// (pipelines://chat/<id>).
// replayed to one that reconnects while it is still active. Tapping it opens
// the chat (pipelines://chat/<id>).
func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
title := truncateUTF8(notice.Title, 256)
message := truncateUTF8(notice.Message, 2000)
click, views := chatAttentionLinks(sessionID)
click := chatAttentionClick(sessionID)
id := notice.ID
if id == "" {
digest := sha256.Sum256([]byte(title + "\x00" + message))
@@ -182,19 +176,12 @@ func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string,
})
}
switch {
case !chatAttentionConfigured():
delivery.Detail = "phone notifications (ntfy) are not configured"
case !chatNotificationSettings(ctx, h.settings).NtfyEnabled:
delivery.Detail = "phone notifications (ntfy) are turned off"
default:
if _, err := chatAttentionPublish(stage.WithNtfySequenceID(ctx, chatNtfySequence(appID)), "system", title, message, "", nil, click, views...); err != nil {
log.Printf("chat tool notification session=%s: %v", sessionID, err)
delivery.Detail = "the phone notification service refused it: " + err.Error()
} else {
delivery.Phone = true
}
case h.notes == nil:
delivery.Detail = "the app notification stream is not available"
case !delivery.App:
delivery.Detail = "the notification could not be recorded"
}
if delivery.App || delivery.Phone {
if delivery.App {
// This turn has pinged the operator; its end is not announced again.
h.markTurnNotified(sessionID)
}
+2 -12
View File
@@ -169,20 +169,10 @@ func (s *chatToolService) runNotify(ctx context.Context, sessionID, title, messa
}
id := newChatShownID()
delivery := s.notify(ctx, sessionID, chatToolNotice{ID: id, Title: title, Message: message, Priority: priority})
item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App || delivery.Phone, Detail: delivery.Detail}
item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App, Detail: delivery.Detail}
if delivery.App {
item.Channels = append(item.Channels, "apps")
}
if delivery.Phone {
item.Channels = append(item.Channels, "phone")
}
switch {
case delivery.App && delivery.Phone:
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps and phone notifications."}
case delivery.App:
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps; " + delivery.Detail + "."}
case delivery.Phone:
return &item, chattools.Result{Text: "Delivered to the operator's phone notifications."}
return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps."}
}
return &item, chattools.Result{Text: "Not delivered: " + delivery.Detail + ".", IsError: true}
}
+9 -9
View File
@@ -38,7 +38,7 @@ func newChatToolFixture(t *testing.T) *chatToolFixture {
}
f.service.notify = func(_ context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
f.notified = append(f.notified, sessionID+": "+notice.Title)
return chatToolDelivery{App: true, Phone: true}
return chatToolDelivery{App: true}
}
return f
}
@@ -240,7 +240,7 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
f.service.now = func() time.Time { return now }
for i := range 5 {
if r := f.call(a, "notify", `{"title":"Done","message":"Build finished","priority":"high"}`); r.IsError ||
r.Text != "Delivered to the operator's Pipelines apps and phone notifications." {
r.Text != "Delivered to the operator's Pipelines apps." {
t.Fatalf("notification %d: %v", i, r)
}
}
@@ -261,30 +261,30 @@ func TestNotifyIsRateLimitedPerChat(t *testing.T) {
t.Fatalf("notified = %v", f.notified)
}
got := f.items(t, "ses_n1")
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" || strings.Join(got[0].Channels, ",") != "apps,phone" {
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" || strings.Join(got[0].Channels, ",") != "apps" {
t.Fatalf("items = %+v", got)
}
f.service.notify = func(context.Context, string, chatToolNotice) chatToolDelivery {
return chatToolDelivery{Detail: "ntfy is not configured"}
return chatToolDelivery{Detail: "the notification could not be recorded"}
}
r := f.call(b, "notify", `{"title":"Fails","message":"x"}`)
if !r.IsError || !strings.Contains(r.Text, "ntfy is not configured") {
if !r.IsError || !strings.Contains(r.Text, "the notification could not be recorded") {
t.Fatalf("an undelivered notification is reported: %v", r)
}
if last := f.items(t, "ses_n2"); len(last) != 2 || last[1].Delivered || last[1].Detail != "ntfy is not configured" {
if last := f.items(t, "ses_n2"); len(last) != 2 || last[1].Delivered || last[1].Detail != "the notification could not be recorded" {
t.Fatalf("the undelivered entry is recorded: %+v", last)
}
// Apps only (ntfy off): the agent is told where it went.
// Delivered: the agent is told where it went.
f.service.notify = func(_ context.Context, _ string, notice chatToolNotice) chatToolDelivery {
if !strings.HasPrefix(notice.ID, "shown_") || notice.Priority != "low" {
t.Errorf("notice = %+v", notice)
}
return chatToolDelivery{App: true, Detail: "phone notifications (ntfy) are turned off"}
return chatToolDelivery{App: true}
}
r = f.call(b, "notify", `{"title":"Apps","message":"x","priority":"low"}`)
if r.IsError || r.Text != "Delivered to the operator's Pipelines apps; phone notifications (ntfy) are turned off." {
if r.IsError || r.Text != "Delivered to the operator's Pipelines apps." {
t.Fatalf("apps-only result: %v", r)
}
if last := f.items(t, "ses_n2"); len(last) != 3 || !last[2].Delivered || !strings.HasPrefix(last[2].ID, "shown_") || strings.Join(last[2].Channels, ",") != "apps" {
+28 -14
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"path/filepath"
"strings"
"sync"
"testing"
"time"
@@ -105,6 +106,28 @@ func chatNotes(t *testing.T, store *pipeline.Store, kind string) []protocol.AppN
return out
}
// chatNoteTotal counts every chat notification ever recorded, active or
// cleared.
func chatNoteTotal(t *testing.T, store *pipeline.Store) int {
t.Helper()
active, cleared, err := store.ActiveAppNotifications(context.Background(), "", time.Now())
if err != nil {
t.Fatal(err)
}
total := 0
for _, n := range active {
if strings.HasPrefix(n.ID, "chat:") {
total++
}
}
for _, id := range cleared {
if strings.HasPrefix(id, "chat:") {
total++
}
}
return total
}
func stepFrameFor(status, turn string) protocol.ChatEventFrame {
return protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: status, TurnID: turn}}
}
@@ -114,11 +137,10 @@ func textFrame(text string) protocol.ChatEventFrame {
}
// A turn started from the app keeps being observed after the app closes, so
// its finished reply is recorded (app stream) and published (ntfy) once, and
// its finished reply is recorded on the app stream once, and
// the observer is torn down when the turn ends.
func TestChatReplyNotifiesAfterLastClientLeaves(t *testing.T) {
fastUnattended(t)
captured := newNtfyCapture(t)
store := unattendedStore(t, true)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -135,11 +157,10 @@ func TestChatReplyNotifiesAfterLastClientLeaves(t *testing.T) {
broker.push(stepFrameFor(protocol.ChatStepEnded, "turn_1"))
waitFor(t, "reply notification", func() bool { return len(chatNotes(t, store, protocol.NotificationChatReply)) == 1 })
waitFor(t, "observer torn down", func() bool { active, _ := broker.streams(); return active == 0 })
waitFor(t, "ntfy publish", func() bool { return len(captured()) == 1 })
time.Sleep(50 * time.Millisecond)
notes := chatNotes(t, store, protocol.NotificationChatReply)
if got := captured(); len(notes) != 1 || len(got) != 1 || got[0].Title != "Release prep replied" || got[0].Message != "The build is green." {
t.Fatalf("notes=%+v ntfy=%+v", notes, got)
if len(notes) != 1 || notes[0].Title != "Release prep replied" || chatNoteTotal(t, store) != 1 {
t.Fatalf("notes=%+v", notes)
}
if notes[0].Message != "The build is green." || notes[0].Click != "pipelines://chat/ses_1" {
t.Fatalf("note = %+v", notes[0])
@@ -150,7 +171,6 @@ func TestChatReplyNotifiesAfterLastClientLeaves(t *testing.T) {
// nothing, even though the unattended turn is observed.
func TestChatUnattendedReplyRespectsSetting(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -170,7 +190,6 @@ func TestChatUnattendedReplyRespectsSetting(t *testing.T) {
// A question the agent asks while no client is attached notifies.
func TestChatQuestionNotifiesWithNoClient(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -196,7 +215,6 @@ func TestChatQuestionNotifiesWithNoClient(t *testing.T) {
// announced exactly once and the client sees the turn end.
func TestChatReattachMidTurnDoesNotDuplicate(t *testing.T) {
fastUnattended(t)
captured := newNtfyCapture(t)
store := unattendedStore(t, true)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -227,8 +245,8 @@ func TestChatReattachMidTurnDoesNotDuplicate(t *testing.T) {
}
waitFor(t, "reply notification", func() bool { return len(chatNotes(t, store, protocol.NotificationChatReply)) == 1 })
time.Sleep(100 * time.Millisecond)
if got := captured(); len(got) != 2 {
t.Fatalf("ntfy deliveries = %+v, want one question and one reply", got)
if got := chatNoteTotal(t, store); got != 2 {
t.Fatalf("recorded notifications = %d, want one question and one reply", got)
}
if n := len(chatNotes(t, store, protocol.NotificationChatQuestion)) + len(chatNotes(t, store, protocol.NotificationChatReply)); n > 2 {
t.Fatalf("duplicate notifications: %d", n)
@@ -242,7 +260,6 @@ func TestChatReattachMidTurnDoesNotDuplicate(t *testing.T) {
// start does not observe sessions whose harness reports no running turn.
func TestChatIdleSessionWithNoClientIsNotObserved(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, true)
broker := newObservedChat()
server := startQueueServer(t, broker, store)
@@ -266,7 +283,6 @@ func TestChatIdleSessionWithNoClientIsNotObserved(t *testing.T) {
// with no client, so its reply still notifies; then the observer goes away.
func TestChatRunningTurnObservedAfterRestart(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, true)
broker := newObservedChat()
broker.probe["ses_1"] = true
@@ -284,7 +300,6 @@ func TestChatRunningTurnObservedAfterRestart(t *testing.T) {
// a later authoritative idle result releases it.
func TestChatRecoveredBusySessionWaitsForAuthoritativeIdle(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, true)
broker := newObservedChat()
broker.probe["ses_1"] = true
@@ -303,7 +318,6 @@ func TestChatRecoveredBusySessionWaitsForAuthoritativeIdle(t *testing.T) {
// A turn that never reports its end does not hold an observer forever.
func TestChatStuckUnattendedTurnIsReleased(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
limit := chatUnattendedTurnLimit
chatUnattendedTurnLimit = 300 * time.Millisecond
t.Cleanup(func() { chatUnattendedTurnLimit = limit })
+4 -19
View File
@@ -2,14 +2,10 @@ package server
import (
"context"
"encoding/json"
"fmt"
"mime"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -386,19 +382,6 @@ func TestHumanStageWaitingNotification(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
filename, _ := new(mime.WordDecoder).DecodeHeader(r.Header.Get("Filename"))
ack := map[string]any{"id": "msg1", "event": "message"}
if filename != "" {
ack["attachment"] = map[string]string{"name": filename, "url": "https://ntfy.example.com/file/" + filename}
}
_ = json.NewEncoder(w).Encode(ack)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
source := strings.Replace(humanPipelineSource, "```configs\ntype=human\n```", "```notify\non=waiting\n```\n\n```configs\ntype=human\n```", 1)
if _, err := store.Submit(ctx, "human-notify", source); err != nil {
t.Fatal(err)
@@ -414,14 +397,16 @@ func TestHumanStageWaitingNotification(t *testing.T) {
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
defer r.wg.Wait()
run, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "human-notify", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if calls.Load() != 1 {
t.Fatalf("waiting notification fired %d times", calls.Load())
if got := recorder.recorded(); len(got) != 1 || got[0].Kind != protocol.NotificationRunWaiting {
t.Fatalf("waiting notification fired %d times: %+v", len(got), got)
}
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
+4 -4
View File
@@ -5,11 +5,11 @@ import (
"testing"
)
// TestMain isolates the package from an operator's real notification setup:
// a developer shell may export the installed server's ntfy configuration, and
// no test may publish to it. Tests that need ntfy point it at an httptest server.
// TestMain isolates the package from the operator's environment: a developer
// shell may export the installed server's web origin, which tests must not
// pick up.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
for _, name := range []string{"PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
+40 -10
View File
@@ -89,8 +89,34 @@ func TestNotificationSettingsProtocol(t *testing.T) {
wantSettings(t, replies[0], updated)
}
// ntfy was removed. An older app may still send its "also send to ntfy"
// switch, alone or beside a real setting: the key is accepted and ignored,
// and every reply carries exactly the three notification settings.
func TestLegacyNtfySettingIsAcceptedAndIgnored(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
store := newOperatorStore(t)
replies := notificationSettingsRoundTrip(t, ctx, store,
protocol.Message{Type: protocol.SetNotificationSettings, ID: "ntfy", NotificationSettings: map[string]any{protocol.LegacyNotifyNtfyEnabled: false}},
protocol.Message{Type: protocol.SetNotificationSettings, ID: "mixed", NotificationSettings: map[string]any{protocol.LegacyNotifyNtfyEnabled: true, protocol.NotifyRunFinished: true}},
protocol.Message{Type: protocol.GetNotificationSettings, ID: "get"},
)
want := protocol.DefaultNotificationSettings()
wantSettings(t, replies[0], want)
want.RunFinished = true
wantSettings(t, replies[1], want)
wantSettings(t, replies[2], want)
for _, reply := range replies {
if len(reply.NotificationSettings) != 3 {
t.Fatalf("reply carries %d settings: %+v", len(reply.NotificationSettings), reply)
}
if _, present := reply.NotificationSettings[protocol.LegacyNotifyNtfyEnabled]; present {
t.Fatalf("reply still carries ntfy_enabled: %+v", reply)
}
}
}
func TestChatNeedsYouSettingSuppressesQuestionsAndApprovals(t *testing.T) {
captured := newNtfyCapture(t)
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatNeedsYou: false}); err != nil {
t.Fatal(err)
@@ -98,6 +124,9 @@ func TestChatNeedsYouSettingSuppressesQuestionsAndApprovals(t *testing.T) {
h := chatAttentionHub(t, "ses_quiet")
h.registry = store
h.settings = store
notes, recorder := newNoteCapture(t, store)
h.notes = notes
captured := recorder.recorded
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_quiet", Kind: "question", Title: "Ship?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_quiet", Kind: protocol.ChatEventForm, Form: &form})
h.pushPermission("ses_quiet", protocol.ChatPermissionFrame{SessionID: "ses_quiet", RequestID: "per_1", Message: "Allow?"})
@@ -127,8 +156,6 @@ func replyTurn(h *chatHub, session, turnID, messageID, text string) {
}
func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
captured := newNtfyCapture(t)
store := newOperatorStore(t)
ctx := context.Background()
if err := store.RecordOperatorSession(ctx, "ses_done", t.TempDir(), "Release prep", protocol.ChatSessionTagOperator); err != nil {
@@ -137,6 +164,9 @@ func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
h := chatAttentionHub(t, "ses_done", "ses_bare")
h.registry = store
h.settings = store
notes, recorder := newNoteCapture(t, store)
h.notes = notes
captured := recorder.recorded
// Off by default: a finished turn is silent.
replyTurn(h, "ses_done", "turn_0", "msg_0", "Quiet reply")
h.attentionWG.Wait()
@@ -162,10 +192,9 @@ func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
if len(got) != 1 {
t.Fatalf("deliveries = %+v", got)
}
wantBody := truncateRunes("The build is green. "+strings.Repeat("x", 300), chatReplyBodyRunes)
want := ntfyCapture{Title: "Release prep replied", Message: wantBody, Click: "pipelines://chat/ses_done", Actions: "view, Open in browser, https://pipelines.example.com/chat/ses_done"}
if got[0] != want {
t.Fatalf("got %+v, want %+v", got[0], want)
if n := got[0]; n.Title != "Release prep replied" || n.Click != "pipelines://chat/ses_done" || n.Kind != protocol.NotificationChatReply ||
!strings.HasPrefix(n.Message, "The build\nis green. xxx") {
t.Fatalf("got %+v", n)
}
// The next genuine turn notifies again; a turn without text (and a
// session without a title or native turn ids) uses the fallback text.
@@ -186,8 +215,9 @@ func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) {
}
}
func TestChatReplyFinishedNeedsNtfyConfiguration(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
// Without the app notification stream a finished turn has nowhere to go and
// is not even considered.
func TestChatReplyFinishedNeedsTheAppStream(t *testing.T) {
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil {
t.Fatal(err)
@@ -199,6 +229,6 @@ func TestChatReplyFinishedNeedsNtfyConfiguration(t *testing.T) {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.attentionSeen) != 0 {
t.Fatalf("unconfigured ntfy still considered a publication: %v", h.attentionSeen)
t.Fatalf("a stream-less hub still considered a notification: %v", h.attentionSeen)
}
}
-31
View File
@@ -1,31 +0,0 @@
package server
import (
"git.a-wan.net/alan/pipelines/internal/protocol"
"net/url"
"os"
"regexp"
"strings"
)
var notificationTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
func publicNtfyBase(text string) string {
u, err := url.Parse(text)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
return ""
}
return strings.TrimRight(u.String(), "/")
}
func notificationEndpoints() []protocol.NotificationEndpoint {
u, err := url.Parse(os.Getenv("PIPELINES_NTFY_URL"))
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.RawPath != "" {
return nil
}
topic := strings.TrimPrefix(u.Path, "/")
if !notificationTopic.MatchString(topic) {
return nil
}
return []protocol.NotificationEndpoint{{Destination: "system", ServerURL: publicNtfyBase(os.Getenv("PIPELINES_NTFY_PUBLIC_URL")), Topic: topic}}
}
@@ -1,34 +0,0 @@
package server
import (
"testing"
)
func TestPublicNotificationSetup(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "private-token")
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "http://10.0.0.249:8090")
found := false
for _, endpoint := range notificationEndpoints() {
if endpoint.Destination == "system" {
found = true
if endpoint.ServerURL != "http://10.0.0.249:8090" || endpoint.Topic != "pipelines" {
t.Fatal(endpoint)
}
}
}
if !found {
t.Fatal("missing destination")
}
for _, value := range []string{"http://user:secret@example.com", "http://example.com?token=secret", "file:///tmp/secret", "http://example.com/topic"} {
if publicNtfyBase(value) != "" {
t.Fatal("unsafe public URL accepted", value)
}
}
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "")
for _, endpoint := range notificationEndpoints() {
if endpoint.ServerURL != "" {
t.Fatal("internal URL exposed", endpoint)
}
}
}
+116 -143
View File
@@ -2,136 +2,117 @@ package server
import (
"context"
"encoding/json"
"mime"
"net/http"
"net/http/httptest"
"errors"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func TestRunNotificationAppClickAndWebAction(t *testing.T) {
for _, tc := range []struct{ base, view string }{
{"https://pipelines.example.com", "https://pipelines.example.com/runs/20"},
{"http://10.0.0.75:8095/", "http://10.0.0.75:8095/runs/20"},
{"", ""}, // No web origin: the app link alone.
{"javascript:alert(1)", ""},
{"https://user:password@example.com", ""},
{"https://example.com?token=secret", ""},
{"https://example.com/#fragment", ""},
{"https://example.com/subpath", ""}, // Web app uses origin-root routes.
{"/runs", ""},
{"https://example.com\r\nClick:bad", ""},
} {
t.Run(tc.base, func(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", tc.base)
if got := runAttentionClick(20); got != "pipelines://run/20" {
t.Fatalf("click = %q", got)
}
views := runAttentionViews(20)
if tc.view == "" {
if len(views) != 0 {
t.Fatalf("unexpected views %+v", views)
}
return
}
if len(views) != 1 || views[0].Label != "Open in browser" || views[0].URL != tc.view {
t.Fatalf("views = %+v, want %q", views, tc.view)
}
})
func TestRunNotificationAppClick(t *testing.T) {
if got := runAttentionClick(20); got != "pipelines://run/20" {
t.Fatalf("click = %q", got)
}
if got := chatAttentionClick("ses/x"); got != "pipelines://chat/ses%2Fx" {
t.Fatalf("chat click = %q", got)
}
}
type ntfyCapture struct {
Title, Message, Click, Actions string
// recordingNotes wraps an app notification store and keeps every newly
// recorded notification, in order, so a test sees exactly what the app stream
// was given (also after a clear). fail makes every record fail, failNext the
// next few; calls counts every attempt, failed or not.
type recordingNotes struct {
appNotificationStore
mu sync.Mutex
got []protocol.AppNotification
fail bool
failNext int
calls int
}
// newNtfyCapture points the system destination at a mock ntfy endpoint.
func newNtfyCapture(t *testing.T) func() []ntfyCapture {
func (r *recordingNotes) RecordAppNotification(ctx context.Context, n pipeline.AppNotificationRecord, now time.Time) (protocol.AppNotification, bool, error) {
r.mu.Lock()
r.calls++
fail := r.fail || r.failNext > 0
if r.failNext > 0 {
r.failNext--
}
r.mu.Unlock()
if fail {
return protocol.AppNotification{}, false, errors.New("record refused")
}
stored, fresh, err := r.appNotificationStore.RecordAppNotification(ctx, n, now)
if err == nil && fresh {
r.mu.Lock()
r.got = append(r.got, stored)
r.mu.Unlock()
}
return stored, fresh, err
}
func (r *recordingNotes) attempts() int {
r.mu.Lock()
defer r.mu.Unlock()
return r.calls
}
func (r *recordingNotes) recorded() []protocol.AppNotification {
r.mu.Lock()
defer r.mu.Unlock()
return append([]protocol.AppNotification(nil), r.got...)
}
// newNoteCapture returns an app notifier over store (a scratch store when
// nil) and a reader of everything it recorded.
func newNoteCapture(t *testing.T, store *pipeline.Store) (*appNotifier, *recordingNotes) {
t.Helper()
var mu sync.Mutex
var got []ntfyCapture
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/clear") {
// A cleared chat notification's ntfy clear, not a delivery.
_ = json.NewEncoder(w).Encode(map[string]string{"id": "clr", "event": "message_clear"})
return
}
decoder := new(mime.WordDecoder)
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
mu.Lock()
got = append(got, ntfyCapture{title, message, r.Header.Get("Click"), r.Header.Get("Actions")})
mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]string{"id": "msg", "event": "message"})
}))
t.Cleanup(srv.Close)
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
return func() []ntfyCapture {
mu.Lock()
defer mu.Unlock()
return append([]ntfyCapture(nil), got...)
if store == nil {
store = newOperatorStore(t)
}
recorder := &recordingNotes{appNotificationStore: store}
return newAppNotifier(recorder), recorder
}
// Rows queued by older servers hold a web URL, the old placeholder deep link or
// an empty click (an invalid web origin). Each delivers with the app link and
// the current web action.
// an empty click (an invalid web origin). Each is recorded with the app link.
func TestQueuedLegacyRunNotificationsUseAppLink(t *testing.T) {
for _, web := range []string{"https://pipelines.example.com", ""} {
t.Run("web="+web, func(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", web)
captured := newNtfyCapture(t)
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "legacy.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
clicks := map[int64]string{7: "https://pipelines.example.com/runs/7", 8: "pipelines://run/8", 9: ""}
for id, click := range clicks {
if err := s.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "failed", Channel: "system", Title: "Run failed", Body: "Run failed", Click: click}); err != nil {
t.Fatal(err)
}
}
r := &runner{ctx: ctx, store: s}
r.deliverRunNotifications(time.Now())
got := captured()
if len(got) != 3 {
t.Fatalf("deliveries = %+v", got)
}
seen := map[string]bool{}
for _, n := range got {
seen[n.Click] = true
want := ""
if web != "" {
want = "view, Open in browser, " + web + "/runs/" + n.Click[len("pipelines://run/"):]
}
if n.Actions != want {
t.Fatalf("actions = %q, want %q", n.Actions, want)
}
}
for _, click := range []string{"pipelines://run/7", "pipelines://run/8", "pipelines://run/9"} {
if !seen[click] {
t.Fatalf("missing %s in %+v", click, got)
}
}
for id := range clicks {
rows, err := s.RunNotifications(ctx, id)
if err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("run %d rows = %+v %v", id, rows, err)
}
}
})
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "legacy.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
clicks := map[int64]string{7: "https://pipelines.example.com/runs/7", 8: "pipelines://run/8", 9: ""}
for id, click := range clicks {
if err := s.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "failed", Channel: "system", Title: "Run failed", Body: "Run failed", Click: click}); err != nil {
t.Fatal(err)
}
}
notes, recorder := newNoteCapture(t, s)
r := &runner{ctx: ctx, store: s, notes: notes}
r.deliverRunNotifications(time.Now())
got := recorder.recorded()
if len(got) != 3 {
t.Fatalf("deliveries = %+v", got)
}
seen := map[string]bool{}
for _, n := range got {
seen[n.Click] = true
}
for _, click := range []string{"pipelines://run/7", "pipelines://run/8", "pipelines://run/9"} {
if !seen[click] {
t.Fatalf("missing %s in %+v", click, got)
}
}
for id := range clicks {
rows, err := s.RunNotifications(ctx, id)
if err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("run %d rows = %+v %v", id, rows, err)
}
}
}
@@ -145,14 +126,14 @@ func chatAttentionHub(t *testing.T, sessions ...string) *chatHub {
}
func TestChatQuestionNotifiesOnceWithAppLink(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
captured := newNtfyCapture(t)
store := newOperatorStore(t)
if err := store.RecordOperatorSession(context.Background(), "ses_q", t.TempDir(), "Release prep", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
h := chatAttentionHub(t, "ses_q")
h.registry = store
notes, recorder := newNoteCapture(t, store)
h.notes = notes
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_q", Kind: "question", Title: "Which branch\nshould ship?"}
frame := protocol.ChatEventFrame{SessionID: "ses_q", Kind: protocol.ChatEventForm, Form: &form}
h.emit(frame)
@@ -163,27 +144,27 @@ func TestChatQuestionNotifiesOnceWithAppLink(t *testing.T) {
h.mu.Unlock()
h.emit(frame)
h.attentionWG.Wait()
got := captured()
got := recorder.recorded()
if len(got) != 1 {
t.Fatalf("deliveries = %+v", got)
}
want := ntfyCapture{Title: "Release prep needs your answer", Message: "Which branch should ship?", Click: "pipelines://chat/ses_q", Actions: "view, Open in browser, https://pipelines.example.com/chat/ses_q"}
if got[0] != want {
t.Fatalf("got %+v, want %+v", got[0], want)
if n := got[0]; n.Title != "Release prep needs your answer" || n.Message != "Which branch should ship?" || n.Click != "pipelines://chat/ses_q" {
t.Fatalf("got %+v", n)
}
// Resolution and a later stale copy publish nothing more.
// Resolution and a later stale copy record nothing more.
resolved := form
resolved.Resolved = true
h.emit(protocol.ChatEventFrame{SessionID: "ses_q", Kind: protocol.ChatEventForm, Form: &resolved})
h.attentionWG.Wait()
if n := len(captured()); n != 1 {
t.Fatalf("resolution republished: %d", n)
if n := len(recorder.recorded()); n != 1 {
t.Fatalf("resolution re-recorded: %d", n)
}
}
func TestChatResolvedOrReplayedFormsDoNotNotify(t *testing.T) {
captured := newNtfyCapture(t)
h := chatAttentionHub(t, "ses_r")
notes, recorder := newNoteCapture(t, nil)
h.notes = notes
resolved := protocol.ChatForm{ID: "que_old", SessionID: "ses_r", Kind: "question", Title: "Old?", Resolved: true}
cancelled := protocol.ChatForm{ID: "que_gone", SessionID: "ses_r", Kind: "question", Title: "Gone?", Cancelled: true}
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventForm, Form: &resolved})
@@ -196,14 +177,15 @@ func TestChatResolvedOrReplayedFormsDoNotNotify(t *testing.T) {
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventText, MessageID: "msg_1", Part: &protocol.ChatPart{ID: "p1"}, Delta: "done"})
h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}})
h.attentionWG.Wait()
if got := captured(); len(got) != 0 {
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("unexpected deliveries %+v", got)
}
}
func TestChatPermissionNotifiesOnce(t *testing.T) {
captured := newNtfyCapture(t) // No web origin: no browser action.
h := chatAttentionHub(t, "ses_p")
notes, recorder := newNoteCapture(t, nil)
h.notes = notes
frame := protocol.ChatPermissionFrame{SessionID: "ses_p", RequestID: "per_1", Action: "bash", Message: "Run rm -rf build?"}
h.pushPermission("ses_p", frame)
h.pushPermission("ses_p", frame)
@@ -215,40 +197,31 @@ func TestChatPermissionNotifiesOnce(t *testing.T) {
resolved := protocol.ChatPermissionFrame{SessionID: "ses_p", RequestID: "per_2", Message: "Already answered", Resolved: true}
h.pushPermission("ses_p", resolved)
h.attentionWG.Wait()
got := captured()
want := ntfyCapture{Title: "Chat needs your approval", Message: "Run rm -rf build?", Click: "pipelines://chat/ses_p"}
if len(got) != 1 || got[0] != want {
t.Fatalf("deliveries = %+v, want one %+v", got, want)
got := recorder.recorded()
if len(got) != 1 || got[0].Title != "Chat needs your approval" || got[0].Message != "Run rm -rf build?" || got[0].Click != "pipelines://chat/ses_p" {
t.Fatalf("deliveries = %+v", got)
}
}
func TestChatAttentionNeedsNtfyConfiguration(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
calls := 0
original := chatAttentionPublish
chatAttentionPublish = func(context.Context, string, string, string, string, []byte, string, ...stage.NtfyView) (stage.Values, error) {
calls++
return nil, nil
}
defer func() { chatAttentionPublish = original }()
// Without the app notification stream a chat attention item has nowhere to
// go, so it is not even claimed.
func TestChatAttentionNeedsTheAppStream(t *testing.T) {
h := chatAttentionHub(t, "ses_n")
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_n", Kind: "question", Title: "Ready?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventForm, Form: &form})
h.pushPermission("ses_n", protocol.ChatPermissionFrame{SessionID: "ses_n", RequestID: "per_1", Message: "Allow?"})
h.attentionWG.Wait()
if calls != 0 {
t.Fatalf("published %d without ntfy configuration", calls)
if len(h.attentionSeen) != 0 {
t.Fatalf("claimed without a notification stream: %v", h.attentionSeen)
}
}
// A failing ntfy endpoint never blocks or fails chat handling.
// A failing notification store never blocks or fails chat handling.
func TestChatAttentionFailureIsOnlyLogged(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusServiceUnavailable)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
h := chatAttentionHub(t, "ses_f")
notes, recorder := newNoteCapture(t, nil)
recorder.fail = true
h.notes = notes
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_f", Kind: "question", Title: "Ready?"}
h.emit(protocol.ChatEventFrame{SessionID: "ses_f", Kind: protocol.ChatEventForm, Form: &form})
h.attentionWG.Wait()
+31 -218
View File
@@ -5,7 +5,6 @@ import (
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"log"
"mime"
@@ -16,7 +15,6 @@ import (
"path/filepath"
"regexp"
"strings"
"syscall"
"time"
"unicode/utf8"
)
@@ -62,149 +60,41 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
summary := stageNotificationSummary(name, id, step.Stage, event, step.Outcome)
summary = truncateUTF8(summary, 1800)
title := fmt.Sprintf("Pipeline stage %s", event)
receipts := []protocol.NotificationReceipt{}
persist := func() bool {
save, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := r.store.SaveNotifications(save, id, step.Sequence, receipts); err != nil {
log.Printf("notification audit run=%d step=%d: %v", id, step.Sequence, err)
return false
}
return true
}
// The app stream gets one notification per step event, recorded before
// the first ntfy publication; artifacts stay ntfy attachments.
// The app stream gets one notification per step event.
appEvent, appKind := stageNotification(event, step.Target)
// A `link=` file decides the tap target; it is never the attached artifact.
link, linkFile, linkDiagnostic := r.resolveNotificationLink(id, policy.Link)
appArtifact, appPreview := r.resolveNotificationArtifact(id, step.Sequence, policy.Open, linkFile)
recorded := false
ntfyOn := ntfyEnabled(ctx, r.settingsStore())
views := runAttentionViews(id)
ntfyClick, linkNote := ntfyLinkClick(id, link, views)
if ntfyOn && linkDiagnostic == "" {
linkDiagnostic = linkNote
}
send := func(filename string, data []byte) {
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "sending", Filename: filename})
if !persist() {
return
receipt := protocol.NotificationReceipt{Destination: "app", Status: "sent", Diagnostic: linkDiagnostic}
if !r.notes.record(ctx, withNotificationLink(runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview), link)) {
receipt.Status = "failed"
if receipt.Diagnostic != "" {
receipt.Diagnostic += "; "
}
receipt := &receipts[len(receipts)-1]
if !recorded {
recorded = true
r.notes.record(ctx, withNotificationLink(runNotificationRecord(id, step.Sequence, appEvent, appKind, title, summary, appArtifact, appPreview), link))
}
if !ntfyOn {
receipt.Status = "sent"
receipt.Diagnostic = "ntfy disabled; delivered to app clients only"
persist()
return
}
result, err := ntfyPublish(ctx, "system", title, summary, filename, data, ntfyClick, views...)
if err != nil {
receipt.Status = "failed"
receipt.Diagnostic = err.Error()
} else {
receipt.Status = "sent"
receipt.MessageID, _ = result["message_id"].(string)
receipt.AttachmentURL, _ = result["attachment_url"].(string)
}
persist()
}
reject := func(filename, diagnostic string) {
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "failed", Filename: filename, Diagnostic: diagnostic})
persist()
}
sentArtifact := false
for _, kind := range policy.Artifacts {
switch kind {
case "markdown":
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
sentArtifact = true
send("digest.md", []byte(markdown))
}
case "files":
raw, exists := step.Output["artifacts"]
if !exists {
continue
}
var names []string
switch files := raw.(type) {
case []string:
names = files
case []any:
for _, value := range files {
name, ok := value.(string)
if !ok {
reject("", "output.artifacts must be an array of relative file paths")
names = nil
break
}
names = append(names, name)
}
default:
reject("", "output.artifacts must be an array of relative file paths")
}
if len(names) > 10 {
reject("", "at most 10 file artifacts can be notified")
continue
}
seen := map[string]bool{}
for _, name := range names {
if seen[name] {
continue
}
seen[name] = true
data, err := notificationArtifact(workspace, name)
if err != nil {
reject(name, err.Error())
continue
}
sentArtifact = true
send(filepath.Base(name), data)
}
}
}
// No produced artifacts still merits an event, especially on failures.
if !sentArtifact {
send("", nil)
}
// The link note is recorded once, never as the run-level failure reason.
failure := "stage notification publication failed"
if len(receipts) > 0 && receipts[0].Diagnostic != "" {
failure = receipts[0].Diagnostic
}
if linkDiagnostic != "" && len(receipts) > 0 {
first := &receipts[0]
if first.Diagnostic != "" {
first.Diagnostic += "; "
}
first.Diagnostic += linkDiagnostic
persist()
}
// Only a successful publish covers the run alert. A failed stage publisher
// must not swallow the durable run-level fallback and its retries.
for _, receipt := range receipts {
if receipt.Status == "sent" {
covered := stageAttentionEvent(event)
if event == "success" && step.Target == protocol.SuccessEnd {
covered = "succeeded"
}
r.markAttentionSent(id, step.Sequence, covered)
return
receipt.Diagnostic += "the app notification was not recorded"
}
save, done := context.WithTimeout(context.Background(), 5*time.Second)
if err := r.store.SaveNotifications(save, id, step.Sequence, []protocol.NotificationReceipt{receipt}); err != nil {
log.Printf("notification audit run=%d step=%d: %v", id, step.Sequence, err)
}
done()
if receipt.Status == "sent" {
covered := stageAttentionEvent(event)
if event == "success" && step.Target == protocol.SuccessEnd {
covered = "succeeded"
}
r.markAttentionSent(id, step.Sequence, covered)
return
}
// A hook that recorded nothing must not swallow the durable run-level
// fallback and its retries.
if lease != nil {
if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("%s", failure)); err != nil {
if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("stage notification was not recorded")); err != nil {
log.Printf("release stage notification run=%d: %v", id, err)
}
}
}
// ntfyPublish is the run notification publisher; tests may replace it.
var ntfyPublish = stage.PublishNtfy
// stageNotification maps a stage hook event to the app notification event
// (the id suffix, shared with the run outbox for the same run event so the
// two never both appear) and kind.
@@ -360,35 +250,11 @@ func runAttentionClick(id int64) string {
return fmt.Sprintf("pipelines://run/%d", id)
}
// runAttentionViews is the optional "Open in browser" action for a run.
func runAttentionViews(id int64) []stage.NtfyView {
return webAttentionViews(fmt.Sprintf("/runs/%d", id))
}
// webAttentionViews returns an "Open in browser" ntfy action for path on the
// operator's authenticated web origin, or nothing when none is configured.
// Never infer a public address from a request Host, the unauthenticated API
// listener or the ntfy server URL.
func webAttentionViews(path string) []stage.NtfyView {
raw := os.Getenv("PIPELINES_WEB_PUBLIC_URL")
if raw == "" {
return nil
}
base := publicNtfyBase(raw)
if base == "" {
log.Printf("notification web link unavailable: PIPELINES_WEB_PUBLIC_URL must be an HTTP(S) origin without credentials, query or fragment")
return nil
}
return []stage.NtfyView{{Label: "Open in browser", URL: base + path}}
}
// notifyRun publishes one run-level attention notification to the operator's
// already-configured "system" destination. It is the run counterpart of
// notifyStep and reuses the same PublishNtfy machinery, destination and token
// handling, so no second publisher, topic or service is introduced. The run id
// and pipeline name identify the run and the click action opens it in the app.
// Attempts are persisted before publication. Publisher acknowledgement is not
// proof of device reception; a crash in that acknowledgement window can repeat.
// notifyRun records one run-level attention notification on the app
// notification stream. It is the run counterpart of notifyStep. The run id and
// pipeline name identify the run and the click action opens it in the app.
// The event goes through the durable run notification outbox, so a crash
// before it is recorded is recovered after a restart.
func (r *runner) notifyRun(id int64, name, status string, sequence int, currentStage, diagnostic string) {
if r.notifyMode(id) == "off" {
return
@@ -488,20 +354,13 @@ func (r *runner) deliverRunNotificationBatch(now time.Time, limit int) {
link, linkFile := r.stageHookLink(*n)
artifact, preview := r.resolveNotificationArtifact(n.RunID, n.Sequence, "", linkFile)
n.Click = notificationClick(n.RunID, n.Sequence, artifact)
r.notes.record(ctx, withNotificationLink(runNotificationRecord(n.RunID, n.Sequence, n.Event, runNotificationKind(n.Event), n.Title, n.Body, artifact, preview), link))
var result stage.Values
var publishErr error
if ntfyEnabled(ctx, r.settingsStore()) {
// ntfy retains its existing run-level tap target (or the hook's link);
// the richer artifact target is carried by the app notification stream.
views := runAttentionViews(n.RunID)
click, _ := ntfyLinkClick(n.RunID, link, views)
result, publishErr = ntfyPublish(ctx, n.Channel, n.Title, n.Body, "", nil, click, views...)
var recordErr error
if r.notes != nil && !r.notes.record(ctx, withNotificationLink(runNotificationRecord(n.RunID, n.Sequence, n.Event, runNotificationKind(n.Event), n.Title, n.Body, artifact, preview), link)) {
recordErr = fmt.Errorf("app notification was not recorded")
}
cancel()
messageID, _ := result["message_id"].(string)
save, done := context.WithTimeout(context.Background(), 5*time.Second)
err = r.store.FinishRunNotification(save, *n, now.Add(time.Since(started)).Unix(), messageID, publishErr)
err = r.store.FinishRunNotification(save, *n, now.Add(time.Since(started)).Unix(), "", recordErr)
done()
if err != nil {
log.Printf("save run notification run=%d: %v", n.RunID, err)
@@ -521,51 +380,6 @@ func truncateUTF8(text string, max int) string {
return text
}
func notificationArtifact(workspace, name string) ([]byte, error) {
if name == "" || filepath.IsAbs(name) || filepath.Clean(name) != name || strings.ContainsAny(name, "\\\x00\r\n") {
return nil, fmt.Errorf("artifact must be a clean workspace-relative file path")
}
for _, part := range strings.Split(filepath.ToSlash(name), "/") {
lower := strings.ToLower(part)
if strings.HasPrefix(part, ".") || lower == "secrets" || lower == "node_modules" || strings.HasSuffix(lower, ".pem") || strings.HasSuffix(lower, ".key") || strings.HasSuffix(lower, ".db") || strings.HasSuffix(lower, ".db-wal") || strings.HasSuffix(lower, ".db-shm") || strings.HasSuffix(lower, ".sqlite") || strings.HasSuffix(lower, ".sqlite3") {
return nil, fmt.Errorf("artifact path is protected")
}
}
root, err := filepath.EvalSymlinks(workspace)
if err != nil {
return nil, fmt.Errorf("artifact workspace unavailable")
}
// os.Root prevents symlink traversal outside the workspace; disallow symlinks
// altogether so aliases cannot bypass protected path names within it either.
current := root
for _, part := range strings.Split(name, string(os.PathSeparator)) {
current = filepath.Join(current, part)
info, err := os.Lstat(current)
if err != nil || info.Mode()&os.ModeSymlink != 0 {
return nil, fmt.Errorf("artifact is missing or uses a symlink")
}
}
scoped, err := os.OpenRoot(root)
if err != nil {
return nil, fmt.Errorf("artifact workspace unavailable")
}
defer scoped.Close()
file, err := scoped.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
if err != nil {
return nil, fmt.Errorf("cannot read artifact")
}
defer file.Close()
info, err := file.Stat()
if err != nil || !info.Mode().IsRegular() || info.Size() > 1<<20 {
return nil, fmt.Errorf("artifact must be a regular file at most 1 MiB")
}
data, err := io.ReadAll(io.LimitReader(file, (1<<20)+1))
if err != nil || len(data) > 1<<20 {
return nil, fmt.Errorf("cannot read artifact within size limit")
}
return data, nil
}
func notificationClick(runID int64, sequence int, artifact *protocol.NotificationArtifact) string {
if artifact == nil {
return runAttentionClick(runID)
@@ -578,7 +392,6 @@ func notificationClick(runID int64, sequence int, artifact *protocol.Notificatio
}
// resolveNotificationArtifact selects only files in the run's shared public/.
// It is deliberately independent of the ntfy attachment policy.
// The exclude file (a `link=` file) is never selected.
func (r *runner) resolveNotificationArtifact(runID int64, sequence int, pattern, exclude string) (*protocol.NotificationArtifact, string) {
selected := r.publicNotificationFile(runID, pattern, exclude)
+12 -18
View File
@@ -4,7 +4,6 @@ import (
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"net/url"
"os"
@@ -12,6 +11,7 @@ import (
"slices"
"strings"
"syscall"
"unicode/utf8"
)
// notificationLinkLimit bounds a `link=` file: it holds one URL, not a document.
@@ -19,7 +19,7 @@ const notificationLinkLimit = 4 << 10
// resolveNotificationLink reads the tap target a stage's `link=` pattern names
// in the run's shared public/: the first non-empty line of the most recently
// modified match, when it is an absolute http(s) URL ntfy accepts as a click.
// modified match, when it is a valid absolute http(s) URL.
// It returns the link and its public/ file, or no link and the reason for the
// notification receipt.
func (r *runner) resolveNotificationLink(runID int64, pattern string) (string, string, string) {
@@ -83,23 +83,16 @@ func readNotificationLink(root, rel string) ([]byte, error) {
return data, nil
}
// validNotificationLink accepts only an absolute http(s) URL with a host that
// also passes the ntfy click rules (no credentials, no fragment, bounded).
// validNotificationLink accepts only an absolute http(s) URL with a host, no
// credentials, no fragment, no whitespace or control characters and a bounded
// length. The value is an operator-visible link, never a place to smuggle a
// token.
func validNotificationLink(link string) bool {
if len(link) > 2048 || !utf8.ValidString(link) || strings.ContainsAny(link, "\r\n\t\x00 ") {
return false
}
u, err := url.Parse(link)
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && stage.ValidNtfyClick(link)
}
// ntfyLinkClick is the ntfy tap target: the link only while the run stays
// reachable through a web run view, else the run itself with a note saying so.
func ntfyLinkClick(runID int64, link string, views []stage.NtfyView) (string, string) {
if link == "" {
return runAttentionClick(runID), ""
}
if len(views) == 0 {
return runAttentionClick(runID), "notify link: ntfy keeps the run tap target without a web run view (PIPELINES_WEB_PUBLIC_URL)"
}
return link, ""
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && u.User == nil && u.Fragment == ""
}
// withNotificationLink makes link the app notification's tap target, keeping
@@ -112,7 +105,8 @@ func withNotificationLink(record pipeline.AppNotificationRecord, link string) pi
}
// stageHookLink re-resolves the `link=` of the stage hook behind a queued run
// event, so the durable retry of the hook's failed publication keeps its link.
// event, so the durable retry of the hook's unrecorded notification keeps its
// link.
// It returns the link and its public/ file, or nothing.
func (r *runner) stageHookLink(n pipeline.RunNotification) (string, string) {
event := map[string]string{protocol.NotifyWaiting: protocol.NotifyWaiting, "failed": "failure", "succeeded": "success"}[n.Event]
+24 -96
View File
@@ -2,17 +2,12 @@ package server
import (
"context"
"encoding/json"
"fmt"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
@@ -49,18 +44,14 @@ func appNotification(t *testing.T, store *pipeline.Store, id string) *protocol.A
return nil
}
// A stage hook's `link=` file decides the ntfy and app tap target when its
// first non-empty line is an http(s) URL, keeping the run one action away and
// never attaching the link file; anything else falls back to the run link and
// says why on the first receipt.
// A stage hook's `link=` file decides the app tap target when its first
// non-empty line is an http(s) URL, keeping the run one action away and never
// attaching the link file; anything else falls back to the attached artifact
// or the run link and says why on the receipt.
func TestStageHookLinkClick(t *testing.T) {
captured := newNtfyCapture(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: true}); err != nil {
t.Fatal(err)
}
if _, err := store.Submit(ctx, "standup", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
@@ -72,8 +63,6 @@ func TestStageHookLinkClick(t *testing.T) {
for _, test := range []struct {
name, link, open string
files map[string]string
noWeb bool // no web origin: ntfy has no run view
attach bool // markdown and a workspace file are also attached
click bool // the doc URL is the app tap target
artifact string // the attached artifact path
diagnostic string
@@ -81,13 +70,12 @@ func TestStageHookLinkClick(t *testing.T) {
{name: "valid", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "\n " + doc + " \r\nnotes\n", "notes.txt": "n", "more.txt": "m"}, click: true},
{name: "valid-only-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, click: true},
{name: "valid-other-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup"}, click: true, artifact: "standup.md"},
{name: "valid-no-web", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, noWeb: true, click: true, diagnostic: "notify link: ntfy keeps the run tap target"},
{name: "missing", link: "standup-link.txt", diagnostic: "notify link: no public file matches standup-link.txt"},
{name: "missing-other-file", link: "standup-link.txt", files: map[string]string{"report.md": "# Report"}, artifact: "report.md", diagnostic: "notify link: no public file matches standup-link.txt"},
{name: "missing-attachments", link: "standup-link.txt", attach: true, diagnostic: "notify link: no public file matches standup-link.txt"},
{name: "relative", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "standup.html\n" + doc}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt does not start with an absolute http(s) URL"},
{name: "scheme", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "javascript:alert(1)"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"},
{name: "fragment", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "#top"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"},
{name: "credentials", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "https://user:pw@example.com/doc"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"},
{name: "empty", link: "standup-link.txt", files: map[string]string{"standup-link.txt": " \n\n"}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt is empty"},
{name: "large", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "\n" + strings.Repeat("x", 4<<10)}, artifact: "standup-link.txt", diagnostic: "at most 4 KiB"},
{name: "absent", files: map[string]string{"standup-link.txt": doc, "notes.txt": "n"}},
@@ -95,15 +83,7 @@ func TestStageHookLinkClick(t *testing.T) {
{name: "with-open", link: "*-link.txt", open: "*", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup"}, click: true, artifact: "standup.md"},
} {
t.Run(test.name, func(t *testing.T) {
web := "https://pipelines.example.com"
if test.noWeb {
web = ""
}
t.Setenv("PIPELINES_WEB_PUBLIC_URL", web)
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "report.txt"), []byte("report"), 0600); err != nil {
t.Fatal(err)
}
id, _, err := store.CreateRun(ctx, d, test.name, workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
@@ -114,28 +94,13 @@ func TestStageHookLinkClick(t *testing.T) {
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{}}
policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Link: test.link, Open: test.open}
publications := 1
if test.attach {
step.Output = map[string]any{"markdown": "# Standup", "artifacts": []any{"report.txt"}}
policy.Artifacts = []string{"markdown", "files"}
publications = 2
}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := len(captured())
r.notifyStep(id, d.Name, workspace, policy, step)
// ntfy opens the link only beside a web run view; the app opens the
// link (else the attached artifact, else the run).
// The app opens the link, else the attached artifact, else the run.
runClick := fmt.Sprintf("pipelines://run/%d", id)
wantNtfy, wantActions := runClick, ""
if !test.noWeb {
wantActions = fmt.Sprintf("view, Open in browser, https://pipelines.example.com/runs/%d", id)
if test.click {
wantNtfy = doc
}
}
wantClick, wantRunClick := runClick, ""
if test.artifact != "" {
wantClick, wantRunClick = fmt.Sprintf("pipelines://artifact/%d/1/%s", id, test.artifact), runClick
@@ -143,15 +108,6 @@ func TestStageHookLinkClick(t *testing.T) {
if test.click {
wantClick, wantRunClick = doc, runClick
}
got := captured()[before:]
if len(got) != publications {
t.Fatalf("ntfy publications = %+v", got)
}
for _, publication := range got {
if publication.Click != wantNtfy || publication.Actions != wantActions {
t.Fatalf("ntfy click/actions = %q %q, want %q %q", publication.Click, publication.Actions, wantNtfy, wantActions)
}
}
n := appNotification(t, store, fmt.Sprintf("run:%d:1:success", id))
if n == nil || n.Click != wantClick || n.RunClick != wantRunClick {
t.Fatalf("app notification = %+v, want click %q run %q", n, wantClick, wantRunClick)
@@ -164,52 +120,23 @@ func TestStageHookLinkClick(t *testing.T) {
t.Fatal(err)
}
receipts := detail.Steps[0].Notifications
if len(receipts) != publications {
if len(receipts) != 1 || receipts[0].Status != "sent" || receipts[0].Destination != "app" {
t.Fatalf("receipts = %+v", receipts)
}
// The reason is recorded once, on the first receipt. (The capture
// acknowledges no attachment, so attachment receipts fail.)
for i, receipt := range receipts {
noted := strings.Contains(receipt.Diagnostic, "notify link")
if i == 0 && test.diagnostic != "" {
noted = !strings.Contains(receipt.Diagnostic, test.diagnostic)
}
if noted || (!test.attach && (receipt.Status != "sent" || (test.diagnostic == "") != (receipt.Diagnostic == ""))) {
t.Fatalf("receipts = %+v, want diagnostic %q on the first only", receipts, test.diagnostic)
}
if got := receipts[0].Diagnostic; (test.diagnostic == "") != (got == "") || !strings.Contains(got, test.diagnostic) {
t.Fatalf("receipt diagnostic = %q, want %q", got, test.diagnostic)
}
})
}
}
// A terminal stage hook whose publication fails hands the run event back to
// the durable outbox; the retry keeps the hook's link, and the run-level
// failure reason never carries the link note.
// A terminal stage hook whose notification is not recorded hands the run
// event back to the durable outbox; the retry keeps the hook's link, and the
// run-level failure reason never carries the link note.
func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
var mu sync.Mutex
var clicks []string
var fail atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
clicks = append(clicks, r.Header.Get("Click"))
mu.Unlock()
if fail.Swap(false) {
http.Error(w, "transient", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "msg", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := newOperatorStore(t)
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: true}); err != nil {
t.Fatal(err)
}
source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\nlink=standup-link.txt\n```", 1)
if _, err := store.Submit(ctx, "standup", source); err != nil {
t.Fatal(err)
@@ -221,11 +148,12 @@ func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) {
t.Fatalf("stage policy = %+v", policy)
}
artifacts := t.TempDir()
r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store), artifactsRoot: artifacts}
notes, recorder := newNoteCapture(t, store)
r := &runner{ctx: ctx, store: store, notes: notes, artifactsRoot: artifacts}
for _, test := range []struct {
name string
files map[string]string
retry string // the retry's ntfy click; "" means the run
retry string // the retry's tap target; "" means the run
}{
{name: "valid", files: map[string]string{"standup-link.txt": standupDoc}, retry: standupDoc},
{name: "missing"},
@@ -247,25 +175,25 @@ func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) {
if err := store.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "succeeded", Channel: "system", Title: "Run succeeded", Body: "Run succeeded", Click: runAttentionClick(id)}); err != nil {
t.Fatal(err)
}
mu.Lock()
clicks = nil
mu.Unlock()
fail.Store(true)
recorder.mu.Lock()
recorder.fail, recorder.got = true, nil
recorder.mu.Unlock()
r.notifyStep(id, d.Name, t.TempDir(), policy, step)
rows, err := store.RunNotifications(ctx, id)
if err != nil || len(rows) != 1 || rows[0].Status != "pending" || rows[0].Diagnostic == "" || strings.Contains(rows[0].Diagnostic, "notify link") {
t.Fatalf("released run notification = %+v %v", rows, err)
}
recorder.mu.Lock()
recorder.fail = false
recorder.mu.Unlock()
r.deliverRunNotifications(time.Now().Add(time.Minute))
want := test.retry
if want == "" {
want = runAttentionClick(id)
}
mu.Lock()
got := append([]string(nil), clicks...)
mu.Unlock()
if len(got) != 2 || got[0] != want || got[1] != want {
t.Fatalf("hook and retry clicks = %q, want %q twice", got, want)
got := recorder.recorded()
if len(got) != 1 || got[0].Click != want || got[0].ID != fmt.Sprintf("run:%d:1:succeeded", id) {
t.Fatalf("retried notification = %+v, want click %q", got, want)
}
if rows, err = store.RunNotifications(ctx, id); err != nil || len(rows) != 1 || rows[0].Status != "sent" {
t.Fatalf("retried run notification = %+v %v", rows, err)
+80 -185
View File
@@ -2,28 +2,22 @@ package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"git.a-wan.net/alan/pipelines/examples"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"io"
"mime"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"syscall"
"testing"
"time"
)
func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com/")
// A stage notify hook records one app notification per matching step event
// and audits it as one app receipt; a non-matching event records nothing.
func TestStageNotificationEvents(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "notify.db"))
@@ -32,46 +26,22 @@ func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
}
defer store.Close()
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "report.txt"), []byte("created file"), 0600); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count := calls.Add(1)
if click, actions := r.Header.Get("Click"), r.Header.Get("Actions"); !strings.HasPrefix(click, "pipelines://run/") || actions != "view, Open in browser, https://pipelines.example.com/runs/"+strings.TrimPrefix(click, "pipelines://run/") {
t.Errorf("stage notification lacks app click/web action: %q %q", click, actions)
}
filename, _ := new(mime.WordDecoder).DecodeHeader(r.Header.Get("Filename"))
body, _ := io.ReadAll(r.Body)
if filename == "report.txt" && string(body) != "created file" {
t.Error("wrong file content")
}
if filename == "digest.md" && string(body) != "# Digest" {
t.Error("wrong markdown")
}
ack := map[string]any{"id": fmt.Sprintf("msg%d", count), "event": "message"}
if filename != "" {
ack["attachment"] = map[string]string{"name": filename, "url": "https://ntfy.example.com/file/" + filename}
}
_ = json.NewEncoder(w).Encode(ack)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
if _, err := store.Submit(ctx, "notifications", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
d, _ := store.Get(ctx, items[0].ID, 0)
r, _ := newRunner(ctx, store)
notes, recorder := newNoteCapture(t, store)
r.notes = notes
for i, test := range []struct {
status, outcome, target, on string
attachments bool
expected int32
kind string
}{
{"completed", "success", protocol.SuccessEnd, "success", true, 2},
{"completed", "blocked", protocol.FailureEnd, "failure", false, 1},
{"failed", "error", protocol.FailureEnd, "failure", false, 1},
{"completed", "error", protocol.FailureEnd, "success", false, 0},
{"completed", "success", protocol.SuccessEnd, "success", protocol.NotificationRunSucceeded},
{"completed", "blocked", protocol.FailureEnd, "failure", protocol.NotificationRunFailed},
{"failed", "error", protocol.FailureEnd, "failure", protocol.NotificationRunFailed},
{"completed", "error", protocol.FailureEnd, "success", ""},
} {
id, _, err := store.CreateRun(ctx, d, fmt.Sprintf("case%d", i), workspace, false, nil, map[string]any{"prompt": "task"})
if err != nil {
@@ -82,26 +52,27 @@ func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
}
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: test.status, Outcome: test.outcome, Target: test.target, Output: map[string]any{}}
policy := &protocol.NotificationPolicy{On: []string{test.on}, Destination: "anime"}
if test.attachments {
policy.Artifacts = []string{"markdown", "files"}
step.Output = map[string]any{"markdown": "# Digest", "artifacts": []any{"report.txt"}}
}
if err := store.FinishStep(ctx, id, step); err != nil {
t.Fatal(err)
}
before := calls.Load()
before := len(recorder.recorded())
r.notifyStep(id, d.Name, workspace, policy, step)
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if calls.Load()-before != test.expected || len(detail.Steps[0].Notifications) != int(test.expected) {
t.Fatal("event/attachments mismatch", detail, calls.Load()-before)
}
for _, receipt := range detail.Steps[0].Notifications {
if receipt.Status != "sent" || receipt.MessageID == "" {
t.Fatal("notification receipt not persisted", receipt)
got := recorder.recorded()[before:]
if test.kind == "" {
if len(got) != 0 || len(detail.Steps[0].Notifications) != 0 {
t.Fatal("a non-matching event notified", got, detail.Steps[0].Notifications)
}
continue
}
if len(got) != 1 || got[0].Kind != test.kind || got[0].Click != fmt.Sprintf("pipelines://run/%d", id) || len(detail.Steps[0].Notifications) != 1 {
t.Fatal("event mismatch", got, detail.Steps[0].Notifications)
}
if receipt := detail.Steps[0].Notifications[0]; receipt.Status != "sent" || receipt.Destination != "app" {
t.Fatal("notification receipt not persisted", receipt)
}
}
}
@@ -135,27 +106,12 @@ func TestTerminalNotificationRecipe(t *testing.T) {
t.Fatal("recipe missing", err)
}
id := items[0].ID
var calls atomic.Int32
var deliveryFailure atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
if req.Header.Get("Filename") != "" {
t.Error("event alert unexpectedly changed output to add attachments")
}
if deliveryFailure.Load() {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "recipe-receipt", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
for index, test := range []struct {
name, stage, outcome, status string
executionError, deliveryError bool
@@ -169,7 +125,9 @@ func TestTerminalNotificationRecipe(t *testing.T) {
{"delivery error preserves success", "report", "success", "succeeded", false, true, true},
} {
t.Run(test.name, func(t *testing.T) {
deliveryFailure.Store(test.deliveryError)
recorder.mu.Lock()
recorder.fail = test.deliveryError
recorder.mu.Unlock()
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == test.stage {
if test.executionError {
@@ -179,7 +137,7 @@ func TestTerminalNotificationRecipe(t *testing.T) {
}
return stage.Result{Outcome: "success", Output: stage.Values{"question": "topic", "evidence": []any{"source fact"}}}, nil
}
before := calls.Load()
before := len(recorder.recorded())
run, err := r.start(protocol.Message{PipelineID: id, Version: 1, RequestKey: fmt.Sprintf("recipe-%d", index), Workspace: t.TempDir(), Input: map[string]any{"prompt": "research a topic"}})
if err != nil {
t.Fatal(err)
@@ -189,8 +147,9 @@ func TestTerminalNotificationRecipe(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if detail.Status != test.status || (calls.Load()-before == 1) != test.notify {
t.Fatal("wrong verdict or duplicate/missing terminal alert", detail.Status, calls.Load()-before)
recorded := len(recorder.recorded()) - before
if detail.Status != test.status || (!test.deliveryError && (recorded == 1) != test.notify) || (test.deliveryError && recorded != 0) {
t.Fatal("wrong verdict or duplicate/missing terminal alert", detail.Status, recorded)
}
last := detail.Steps[len(detail.Steps)-1]
if last.Stage != test.stage || (len(last.Notifications) == 1) != test.notify {
@@ -226,6 +185,7 @@ func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
// artifacts= is a legacy (ntfy attachment) setting, still accepted.
source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\ndestination=anime\nartifacts=markdown\n```", 1)
if _, err := store.Submit(ctx, "test", source); err != nil {
t.Fatal(err)
@@ -235,7 +195,10 @@ func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Result"}}, nil
}
t.Setenv("PIPELINES_NTFY_URL", "")
// The app stream refuses the notification.
notes, recorder := newNoteCapture(t, store)
recorder.fail = true
r.notes = notes
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "once", Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
@@ -247,29 +210,6 @@ func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
}
}
func TestNotificationArtifactPathSafety(t *testing.T) {
root := t.TempDir()
os.WriteFile(filepath.Join(root, "safe.txt"), []byte("safe"), 0600)
os.WriteFile(filepath.Join(root, ".env"), []byte("secret"), 0600)
os.Symlink(filepath.Join(root, ".env"), filepath.Join(root, "alias.txt"))
outside := filepath.Join(t.TempDir(), "outside.txt")
os.WriteFile(outside, []byte("secret"), 0600)
os.Symlink(outside, filepath.Join(root, "external.txt"))
os.Mkdir(filepath.Join(root, "directory"), 0700)
os.WriteFile(filepath.Join(root, "large.bin"), []byte(strings.Repeat("x", (1<<20)+1)), 0600)
if err := syscall.Mkfifo(filepath.Join(root, "pipe"), 0600); err != nil {
t.Fatal(err)
}
for _, name := range []string{"../outside.txt", outside, ".env", "alias.txt", "external.txt", "directory", "large.bin", "pipe", "pipelines.db", "secret.key", "secrets/file.txt", "sub/../safe.txt"} {
if _, err := notificationArtifact(root, name); err == nil {
t.Fatal("unsafe artifact accepted", name)
}
}
if data, err := notificationArtifact(root, "safe.txt"); err != nil || string(data) != "safe" {
t.Fatal("safe artifact rejected", err)
}
}
func TestNotificationArtifactSelectionAndPreview(t *testing.T) {
root := t.TempDir()
public := filepath.Join(root, "9", "public")
@@ -332,11 +272,9 @@ func TestRunAttentionEventMapping(t *testing.T) {
}
// TestRunAttentionNotificationDelivery proves the operator-facing contract: the
// already-configured "system" destination and topic are used, the payload names
// the run and its pipeline, the click action opens the run, only waiting/failed
// publish, and a run that stays waiting is never republished.
// notification names the run and its pipeline, the click action opens the run,
// only waiting/failed notify, and a run that stays waiting is never repeated.
func TestRunAttentionNotificationDelivery(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "attention.db"))
@@ -344,73 +282,46 @@ func TestRunAttentionNotificationDelivery(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
type delivered struct {
method, path, title, message, click, authorization, actions string
}
deliveries := make(chan delivered, 8)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
decoder := new(mime.WordDecoder)
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
deliveries <- delivered{r.Method, r.URL.Path, title, message, r.Header.Get("Click"), r.Header.Get("Authorization"), r.Header.Get("Actions")}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "attention-receipt", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
// A run that needs nobody publishes nothing.
notes, recorder := newNoteCapture(t, store)
r.notes = notes
// A run that needs nobody notifies nothing.
for _, status := range []string{"queued", "running", "succeeded", "canceled"} {
r.notifyRun(7, "release", status, 1, "build", "")
}
select {
case got := <-deliveries:
t.Fatalf("a run that needs nobody published: %+v", got)
default:
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("a run that needs nobody notified: %+v", got)
}
// A waiting run publishes once, with the destination, identity and click.
// A waiting run notifies once, with the identity and click.
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
// A run that stays waiting is never republished, on a later call or a re-request.
// A run that stays waiting is never repeated, on a later call or a re-request.
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
// An auto run's failure announces its end.
r.notifyRun(8, "release", "failed", 2, "deploy", "provider returned 500")
// A failed run marked "on" publishes once, with its diagnostic.
// A failed run marked "on" notifies once, with its diagnostic.
r.setNotifyMode(7, "on")
r.notifyRun(7, "release", "failed", 2, "deploy", "provider returned 500")
first := <-deliveries
if first.method != http.MethodPost || first.path != "/pipelines" {
t.Fatalf("wrong destination/topic: %+v", first)
got := recorder.recorded()
if len(got) != 3 {
t.Fatalf("notifications = %+v, want three genuine events", got)
}
if first.title != "Run needs your decision" || !strings.Contains(first.message, "Run #7") || !strings.Contains(first.message, "release") || !strings.Contains(first.message, "decision") || !strings.Contains(first.message, "approve") {
first := got[0]
if first.Title != "Run needs your decision" || !strings.Contains(first.Message, "Run #7") || !strings.Contains(first.Message, "release") || !strings.Contains(first.Message, "decision") || !strings.Contains(first.Message, "approve") {
t.Fatalf("waiting notification does not identify the run/pipeline/need: %+v", first)
}
if first.click != "pipelines://run/7" || first.actions != "view, Open in browser, https://pipelines.example.com/runs/7" {
t.Fatalf("waiting notification click does not open the run: %q", first.click)
if first.Click != "pipelines://run/7" || first.Kind != protocol.NotificationRunWaiting {
t.Fatalf("waiting notification click does not open the run: %+v", first)
}
if first.authorization != "" {
t.Fatalf("notification leaked an authorization header: %q", first.authorization)
}
second := <-deliveries
if second.title != "Run failed" || !strings.Contains(second.message, "Run #8") {
if second := got[1]; second.Title != "Run failed" || !strings.Contains(second.Message, "Run #8") || second.Click != "pipelines://run/8" {
t.Fatalf("failed notification is not actionable: %+v", second)
}
if second.click != "pipelines://run/8" || second.actions != "view, Open in browser, https://pipelines.example.com/runs/8" {
t.Fatalf("failed notification click does not open the run: %q", second.click)
}
third := <-deliveries
if third.title != "Run failed" || !strings.Contains(third.message, "Run #7") {
if third := got[2]; third.Title != "Run failed" || !strings.Contains(third.Message, "Run #7") || !strings.Contains(third.Message, "provider returned 500") {
t.Fatalf("marked failed notification is not actionable: %+v", third)
}
select {
case got := <-deliveries:
t.Fatalf("third notification delivered for two genuine events: %+v", got)
default:
}
}
// TestRunAttentionSuppressedByStagePolicy proves a stage's own notify policy and
@@ -428,29 +339,24 @@ func TestRunAttentionSuppressedByStagePolicy(t *testing.T) {
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
r.markAttentionSent(11, 5, "failed")
r.markAttentionSent(11, 6, "waiting")
if !r.attentionAlready(11, 5, "failed") || !r.attentionAlready(11, 6, "waiting") {
t.Fatal("stage-policy coverage not recorded")
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "suppressed", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
r.notifyRun(11, "release", "failed", 5, "deploy", "")
r.notifyRun(11, "release", protocol.RunStatusWaiting, 6, "approve", "")
if calls.Load() != 0 {
t.Fatalf("run-level default repeated a stage-policy event %d times", calls.Load())
if got := recorder.recorded(); len(got) != 0 {
t.Fatalf("run-level default repeated a stage-policy event: %+v", got)
}
}
// TestHumanRunAttentionNotification proves the run loop publishes the run-level
// TestHumanRunAttentionNotification proves the run loop records the run-level
// attention notification itself when the pipeline declares no notify policy: the
// transition to waiting reaches the operator's configured destination exactly
// once, with the run, pipeline and a run-opening click.
// transition to waiting reaches the operator exactly once, with the run,
// pipeline and a run-opening click.
func TestHumanRunAttentionNotification(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -459,17 +365,6 @@ func TestHumanRunAttentionNotification(t *testing.T) {
t.Fatal(err)
}
defer store.Close()
type delivered struct{ title, message, click string }
deliveries := make(chan delivered, 4)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
decoder := new(mime.WordDecoder)
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
deliveries <- delivered{title, message, r.Header.Get("Click")}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "human-attention", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
if _, err := store.Submit(ctx, "human", humanPipelineSource); err != nil {
t.Fatal(err)
}
@@ -478,6 +373,8 @@ func TestHumanRunAttentionNotification(t *testing.T) {
if err != nil {
t.Fatal(err)
}
notes, recorder := newNoteCapture(t, store)
r.notes = notes
defer r.wg.Wait()
r.execute = successExecute
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "human-attention", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
@@ -485,17 +382,20 @@ func TestHumanRunAttentionNotification(t *testing.T) {
t.Fatal(err)
}
r.wg.Wait()
got := <-deliveries
if got.title != "Run needs your decision" || !strings.Contains(got.message, fmt.Sprintf("Run #%d", run.ID)) || !strings.Contains(got.message, "human") {
t.Fatalf("run-level waiting notification wrong: %+v", got)
deadline := time.Now().Add(5 * time.Second)
for len(recorder.recorded()) == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if got.click != fmt.Sprintf("pipelines://run/%d", run.ID) {
t.Fatalf("run-level waiting notification click wrong: %q", got.click)
time.Sleep(50 * time.Millisecond)
got := recorder.recorded()
if len(got) != 1 {
t.Fatalf("waiting notifications = %+v, want exactly one", got)
}
select {
case extra := <-deliveries:
t.Fatalf("waiting run notified again: %+v", extra)
default:
if got[0].Title != "Run needs your decision" || !strings.Contains(got[0].Message, fmt.Sprintf("Run #%d", run.ID)) || !strings.Contains(got[0].Message, "human") {
t.Fatalf("run-level waiting notification wrong: %+v", got[0])
}
if got[0].Click != fmt.Sprintf("pipelines://run/%d", run.ID) {
t.Fatalf("run-level waiting notification click wrong: %q", got[0].Click)
}
}
@@ -514,17 +414,12 @@ func TestRunAttentionNotifiesEachGenuineWait(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "wait", "event": "message"})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
notes, recorder := newNoteCapture(t, store)
r.notes = notes
r.notifyRun(1, "release", protocol.RunStatusWaiting, 1, "gate", "")
r.notifyRun(1, "release", protocol.RunStatusWaiting, 1, "gate", "")
r.notifyRun(1, "release", protocol.RunStatusWaiting, 5, "gate-again", "")
if calls.Load() != 2 {
t.Fatalf("two genuine waits produced %d notifications, want 2", calls.Load())
if got := recorder.recorded(); len(got) != 2 {
t.Fatalf("two genuine waits produced %d notifications, want 2", len(got))
}
}
-68
View File
@@ -1,68 +0,0 @@
package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
)
func TestRunnerNtfyDeliveryIsAuditedAndIdempotent(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "ntfy.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
calls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
body, _ := io.ReadAll(r.Body)
if string(body) != "# Anime\nA report." {
t.Error("wrong markdown", string(body))
}
_, _ = w.Write([]byte(`{"id":"delivery123","event":"message","attachment":{"name":"digest.md","url":"https://ntfy.example.com/file/digest.md"}}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
source := "# stage notify\n```configs\ntype=ntfy\ndestination=anime\n```\n```edges\nsuccess -> #success\nerror -> #failure\n```\n"
if _, err := store.Submit(ctx, "notify", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, _ := newRunner(ctx, store)
for i, approved := range []bool{false, true} {
key := []string{"notify", "approved-notify"}[i]
request := protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: key, AllowTools: approved, Input: map[string]any{"prompt": "notify", "title": "Anime", "summary": "Your digest is ready", "markdown": "# Anime\nA report."}}
run, err := r.start(request)
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ := store.GetRun(ctx, run.ID)
if detail.Status != "succeeded" || len(detail.Steps) != 1 || detail.Steps[0].Output["delivery"] == nil || detail.Steps[0].SessionID != "" {
t.Fatal("native delivery not audited", detail)
}
if duplicate, err := r.start(request); err != nil || duplicate.ID != run.ID {
t.Fatal("repeat not idempotent", err)
}
}
if calls != 2 {
t.Fatal("duplicate publication", calls)
}
t.Setenv("PIPELINES_NTFY_ANIME_URL", "")
failed, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "failure", Input: map[string]any{"prompt": "notify", "title": "Anime", "summary": "Ready", "markdown": "# report"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, _ := store.GetRun(ctx, failed.ID)
if detail.Status != "failed" || detail.Steps[0].Outcome != "error" {
t.Fatal("delivery failure not routed", detail)
}
}
+5 -16
View File
@@ -4,13 +4,10 @@ import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -219,16 +216,8 @@ func TestReferenceWorkflowsLive(t *testing.T) {
t.Fatal(err)
}
defer func() { cancel(); runner.wg.Wait() }()
var alerts atomic.Int32
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
alerts.Add(1)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"reference-local-receipt","event":"message"}`)
}))
defer endpoint.Close()
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/reference")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
notes, recorder := newNoteCapture(t, store)
runner.notes = notes
type result struct {
Name string `json:"name"`
Verified bool `json:"verified"`
@@ -292,7 +281,7 @@ func TestReferenceWorkflowsLive(t *testing.T) {
pid = p.ID
}
}
priorAlerts := alerts.Load()
priorAlerts := len(recorder.recorded())
run, err := runner.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: c.name, Workspace: workspace, Input: map[string]any{"prompt": c.prompt}})
if err != nil {
row.Diagnostic = err.Error()
@@ -327,11 +316,11 @@ func TestReferenceWorkflowsLive(t *testing.T) {
t.Fatal("workspace capture absent")
}
}
wantAlerts := int32(0)
wantAlerts := 0
if c.name == "incident-handoff" || c.name == "missing-input-failure" {
wantAlerts = 1
}
if alerts.Load()-priorAlerts != wantAlerts {
if len(recorder.recorded())-priorAlerts != wantAlerts {
t.Fatal("unexpected notification count")
}
t.Logf("Verified %s: run #%d status=%s visits=%d", c.name, run.ID, run.Status, len(run.Steps))
+1 -1
View File
@@ -200,7 +200,7 @@ func scratchEnvironment(t *testing.T, realHome, home string) []string {
env = append(env, entry)
}
return append(env, "HOME="+home, "XDG_CONFIG_HOME="+config, "XDG_DATA_HOME="+data, "XDG_CACHE_HOME="+cache, "XDG_STATE_HOME="+filepath.Join(home, ".local", "state"),
"PIPELINES_OPENCODE="+opencodePath(), "PIPELINES_NTFY_URL=", "PIPELINES_MDNS=off")
"PIPELINES_OPENCODE="+opencodePath(), "PIPELINES_MDNS=off")
}
func copyProviderLogin(t *testing.T, real, scratch, provider string) {
+48 -117
View File
@@ -2,13 +2,9 @@ package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -18,30 +14,19 @@ import (
"git.a-wan.net/alan/pipelines/internal/summarise"
)
func TestRunNotificationPublisherFailureRetriesAfterReopen(t *testing.T) {
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
// An app notification that could not be recorded stays pending in the run
// outbox and is retried after the store is reopened; a repeated request is
// deduplicated.
func TestRunNotificationRecordFailureRetriesAfterReopen(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "retry.db")
s, err := pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got, actions := r.Header.Get("Click"), r.Header.Get("Actions"); got != "pipelines://run/7" || actions != "view, Open in browser, https://pipelines.example.com/runs/7" {
t.Errorf("wrong retry links: %q %q", got, actions)
}
if calls.Add(1) == 1 {
http.Error(w, "transient", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "ack", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s}
notes, recorder := newNoteCapture(t, s)
recorder.fail = true
r := &runner{ctx: ctx, store: s, notes: notes}
// The run was started with "Notify me", so its failure is announced.
r.setNotifyMode(7, "on")
// Emulate a durable transition intent saved before the runner callback.
@@ -61,17 +46,19 @@ func TestRunNotificationPublisherFailureRetriesAfterReopen(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
r = &runner{ctx: ctx, store: s}
notes, recorder = newNoteCapture(t, s)
r = &runner{ctx: ctx, store: s, notes: notes}
r.setNotifyMode(7, "on")
r.deliverRunNotifications(time.Now().Add(time.Minute))
r.notifyRun(7, "test", "failed", 1, "stage", "")
got, err = s.RunNotifications(ctx, 7)
if err != nil || len(got) != 1 || got[0].Status != "sent" || got[0].Attempts != 2 || got[0].MessageID != "ack" || calls.Load() != 2 {
t.Fatalf("retry/dedupe: %+v calls=%d %v", got, calls.Load(), err)
recorded := recorder.recorded()
if err != nil || len(got) != 1 || got[0].Status != "sent" || got[0].Attempts != 2 || recorder.attempts() != 1 || len(recorded) != 1 || recorded[0].Click != "pipelines://run/7" {
t.Fatalf("retry/dedupe: %+v recorded=%+v %v", got, recorded, err)
}
}
func TestTransactionalSuccessNotificationUsesWebLink(t *testing.T) {
func TestTransactionalSuccessNotificationUsesAppLink(t *testing.T) {
ctx := context.Background()
s, err := pipeline.Open(filepath.Join(t.TempDir(), "web-success.db"))
if err != nil {
@@ -93,28 +80,14 @@ func TestTransactionalSuccessNotificationUsesWebLink(t *testing.T) {
if err := s.FinishRun(ctx, id, "succeeded", "success", "", nil); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
if got, want := req.Header.Get("Click"), "pipelines://run/"+fmt.Sprint(id); got != want {
t.Errorf("click = %q, want %q", got, want)
}
if got, want := req.Header.Get("Actions"), "view, Open in browser, https://pipelines.example.com/runs/"+fmt.Sprint(id); got != want {
t.Errorf("actions = %q, want %q", got, want)
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "web-success", "event": "message"})
}))
defer endpoint.Close()
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com")
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s}
notes, recorder := newNoteCapture(t, s)
r := &runner{ctx: ctx, store: s, notes: notes}
r.notifyRun(id, "test", "succeeded", 0, "", "")
r.deliverRunNotifications(time.Now())
got, err := s.RunNotifications(ctx, id)
if err != nil || len(got) != 1 || got[0].Status != "sent" || calls.Load() != 1 {
t.Fatalf("notification: %+v calls=%d err=%v", got, calls.Load(), err)
recorded := recorder.recorded()
if err != nil || len(got) != 1 || got[0].Status != "sent" || len(recorded) != 1 || recorded[0].Click != fmt.Sprintf("pipelines://run/%d", id) || recorded[0].Kind != protocol.NotificationRunSucceeded {
t.Fatalf("notification: %+v recorded=%+v err=%v", got, recorded, err)
}
}
@@ -142,16 +115,8 @@ func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "wrong-success", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s, events: newRunEventHub()}
notes, recorder := newNoteCapture(t, s)
r := &runner{ctx: ctx, store: s, events: newRunEventHub(), notes: notes}
if err := s.BeginStep(ctx, id, 1, "one", nil); err != nil {
t.Fatal(err)
}
@@ -159,8 +124,8 @@ func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
if _, _, _, _, err := r.finishStage(id, "test", "workspace", d.Graph.Stages[0], state, protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: protocol.SuccessEnd, Output: map[string]any{"markdown": "result"}}); err != nil {
t.Fatal(err)
}
if calls.Load() != 0 {
t.Fatal("terminal stage success published before FinishRun")
if recorder.attempts() != 0 {
t.Fatal("terminal stage success announced before FinishRun")
}
sub := r.events.subscribe("test", "workspace", nil, func(protocol.Message) error { return nil })
defer sub.close()
@@ -170,8 +135,8 @@ func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if got.Status != "running" || len(got.Notifications) != 0 || calls.Load() != 0 {
t.Fatalf("unpersisted success announced: %+v calls=%d", got, calls.Load())
if got.Status != "running" || len(got.Notifications) != 0 || recorder.attempts() != 0 {
t.Fatalf("unpersisted success announced: %+v attempts=%d", got, recorder.attempts())
}
sub.mu.Lock()
defer sub.mu.Unlock()
@@ -190,18 +155,6 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) == 1 && failFirst {
http.Error(w, "transient", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": "waiting-ack", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
source := strings.Replace(humanPipelineSource, "# stage gate", "# stage gate\n```notify\non=waiting\n```", 1)
if _, err := s.Submit(ctx, "waiting", source); err != nil {
t.Fatal(err)
@@ -215,6 +168,11 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
t.Fatal(err)
}
defer func() { cancel(); r.schedulerWG.Wait() }()
notes, recorder := newNoteCapture(t, s)
if failFirst {
recorder.failNext = 1
}
r.notes = notes
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "waiting-hook", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
@@ -225,12 +183,12 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
if err != nil {
t.Fatal(err)
}
wantCalls := int32(1)
wantCalls := 1
if failFirst {
wantCalls = 2
}
if calls.Load() != wantCalls || detail.Status != "waiting" || len(detail.Notifications) != 1 {
t.Fatalf("waiting hook duplicated/lost: calls=%d detail=%+v", calls.Load(), detail)
if recorder.attempts() != wantCalls || len(recorder.recorded()) != 1 || detail.Status != "waiting" || len(detail.Notifications) != 1 {
t.Fatalf("waiting hook duplicated/lost: attempts=%d recorded=%+v detail=%+v", recorder.attempts(), recorder.recorded(), detail)
}
status := detail.Notifications[0].Status
if status != "sent" && status != "covered" {
@@ -241,25 +199,16 @@ func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
}
func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"id": "ack", "event": "message"})
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
for _, tc := range []struct {
mode string
hook bool
// any turns the global run_finished setting on (it defaults off), so
// every run end notifies, not only runs marked "on".
any bool
want int32
want int
}{
{"on", false, false, 1}, {"auto", false, false, 0}, {"auto", false, true, 1}, {"on", false, true, 1}, {"off", false, false, 0}, {"off", false, true, 0},
// A stage hook is the pipeline's own opt-in: it still publishes for an
// A stage hook is the pipeline's own opt-in: it still notifies for an
// auto run, and never doubles up with the run alert.
{"on", true, false, 1}, {"auto", true, false, 1}, {"auto", true, true, 1}, {"off", true, false, 0},
} {
@@ -291,15 +240,16 @@ func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success"}, nil
}
before := calls.Load()
notes, recorder := newNoteCapture(t, s)
r.notes = notes
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "mode", NotifyMode: tc.mode, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := s.GetRun(ctx, run.ID)
if err != nil || detail.Status != "succeeded" || detail.NotifyMode != tc.mode || calls.Load()-before != tc.want {
t.Fatalf("mode contract: %+v calls=%d %v", detail, calls.Load()-before, err)
if err != nil || detail.Status != "succeeded" || detail.NotifyMode != tc.mode || len(recorder.recorded()) != tc.want {
t.Fatalf("mode contract: %+v recorded=%+v %v", detail, recorder.recorded(), err)
}
if tc.want == 1 && !(tc.hook && tc.mode == "auto" && !tc.any) && (len(detail.Notifications) != 1 || (detail.Notifications[0].Status != "sent" && detail.Notifications[0].Status != "covered")) {
t.Fatalf("missing final audit: %+v", detail.Notifications)
@@ -317,16 +267,9 @@ func TestRunNotificationAttentionModesAndRetryBound(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
http.Error(w, "unavailable", http.StatusServiceUnavailable)
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r := &runner{ctx: ctx, store: s}
notes, recorder := newNoteCapture(t, s)
recorder.fail = true
r := &runner{ctx: ctx, store: s, notes: notes}
for i, mode := range []string{"auto", "on", "off"} {
id := int64(i + 1)
r.setNotifyMode(id, mode)
@@ -335,14 +278,14 @@ func TestRunNotificationAttentionModesAndRetryBound(t *testing.T) {
}
}
// auto and on waiting, plus auto and on failed; off never notifies.
if calls.Load() != 4 {
t.Fatalf("attention modes: %d calls, want 4", calls.Load())
if recorder.attempts() != 4 {
t.Fatalf("attention modes: %d attempts, want 4", recorder.attempts())
}
r.deliverRunNotifications(time.Now().Add(time.Minute))
r.deliverRunNotifications(time.Now().Add(2 * time.Minute))
r.deliverRunNotifications(time.Now().Add(3 * time.Minute))
if calls.Load() != 12 {
t.Fatalf("retry bound: %d calls, want 12", calls.Load())
if recorder.attempts() != 12 {
t.Fatalf("retry bound: %d attempts, want 12", recorder.attempts())
}
for _, id := range []int64{1, 2, 3} {
got, err := s.RunNotifications(ctx, id)
@@ -379,32 +322,20 @@ func TestRunNotificationWorkerResumesPendingAfterRestart(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
delivered := make(chan struct{}, 2)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]string{"id": "recovered", "event": "message"})
delivered <- struct{}{}
}))
defer server.Close()
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
r, err := newRunner(ctx, s)
if err != nil {
t.Fatal(err)
}
// As the handler does, before the worker's first tick.
r.notes = newAppNotifier(s)
defer func() { cancel(); r.schedulerWG.Wait() }()
select {
case <-delivered:
case <-time.After(5 * time.Second):
t.Fatal("pending outbox was not recovered")
}
deadline := time.Now().Add(5 * time.Second)
for {
got, err := s.RunNotifications(ctx, 7)
if err != nil {
t.Fatal(err)
}
if len(got) == 1 && got[0].Status == "sent" && got[0].MessageID == "recovered" {
if len(got) == 1 && got[0].Status == "sent" && appNotification(t, s, "run:7:1:failed") != nil {
break
}
if time.Now().After(deadline) {
+4 -5
View File
@@ -63,8 +63,7 @@ type runner struct {
// events pushes run state deltas to subscribed clients. When nil (tests that
// build a runner directly) emits are dropped, so nothing else changes.
events *runEventHub
// notes records and streams app notifications beside every ntfy
// publication. Nil (a runner built directly in a test) records nothing.
// notes records and streams app notifications. Nil (a runner built directly in a test) records nothing.
notes *appNotifier
// identMu guards idents: the pipeline identity and stored title (see
// runIdentity) that every emitted frame of a run carries, so a client with no
@@ -1032,7 +1031,7 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
return retryCheckpoint{}, fmt.Errorf("retry source %d has incompatible selected stage %q", sourceID, failed.Stage)
}
typ := stage.EffectiveType(declared.Type)
if typ == stage.HumanType || typ == stage.NtfyType {
if typ == stage.HumanType || typ == stage.RemovedNtfyType {
return retryCheckpoint{}, fmt.Errorf("retry source %d cannot replay completed external stage %s", sourceID, failed.Stage)
}
if typ == stage.ModelType {
@@ -1934,8 +1933,8 @@ func (r *runner) finishRunStateClass(id int64, name, workspace, status, outcome,
if detail.FinishedAt == "" {
return // Cleanup is not confirmed: never emit a false terminal event.
}
// Push the terminal delta before the attention notification, so a slow ntfy
// never delays the live update the app folds.
// Push the terminal delta before the attention notification, so a slow
// notification never delays the live update the app folds.
r.emitRun(protocol.RunEventFrame{
RunID: id,
Workspace: workspace,
+2 -9
View File
@@ -10,7 +10,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func (r *runner) scheduleLoop() {
@@ -124,7 +123,7 @@ var scheduleBusyRetry = func() (every, limit time.Duration) {
return every, limit
}
// scheduleNoticePriority is ntfy's "low" priority.
// scheduleNoticePriority is the notification stream's "low" priority.
const scheduleNoticePriority = 2
// admitScheduled starts one claimed schedule's run and records the outcome in
@@ -203,7 +202,7 @@ func scheduleLabel(item protocol.SavedSchedule) string {
}
// scheduleNotice tells the operator, at low priority, through the app
// notification stream and (when enabled) ntfy, that a scheduled run was
// notification stream, that a scheduled run was
// delayed or skipped.
func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second)
@@ -212,10 +211,4 @@ func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, even
r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{
ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule,
Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}})
if !chatAttentionConfigured() || !ntfyEnabled(ctx, r.settingsStore()) {
return
}
if _, err := ntfyPublish(stage.WithNtfyPriority(ctx, scheduleNoticePriority), "system", title, message, "", nil, click); err != nil {
log.Printf("schedule id=%d %s notice: %v", item.ID, event, err)
}
}
@@ -41,15 +41,6 @@ func TestSessionExportLive(t *testing.T) {
if !ok || !stage.ValidModel(provider, id) {
t.Fatal("explicit valid PIPELINES_SESSION_EXPORT_MODEL required")
}
// Isolate notifications from the operator's real ntfy service.
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"session-export-live-receipt","event":"message"}`)
}))
defer endpoint.Close()
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/live")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Minute)
defer cancel()
-8
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
@@ -19,13 +18,6 @@ import (
// Exercise the real V2 CLI/poll path, runner, SQLite retention and websocket CLI
// against an isolated loopback server/database, never the configured deployment.
func TestStageDeadlineDiagnosticThroughCLIAndWebsocket(t *testing.T) {
ntfy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"id":"scratch-receipt","event":"message"}`))
}))
defer ntfy.Close()
t.Setenv("PIPELINES_NTFY_URL", ntfy.URL+"/scratch")
t.Setenv("PIPELINES_NTFY_TOKEN", "")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
for _, mode := range []string{"active", "http", "connection"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
+1 -75
View File
@@ -1,9 +1,6 @@
package server
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"net/url"
@@ -44,16 +41,6 @@ func networkAddresses() []protocol.NetworkAddress {
return result
}
func endpointPort(u *url.URL) string {
if port := u.Port(); port != "" {
return port
}
if u.Scheme == "https" || u.Scheme == "wss" {
return "443"
}
return "80"
}
func candidateURLs(addresses []protocol.NetworkAddress, scheme, port, path string) []string {
result := []string{}
for _, address := range addresses {
@@ -63,22 +50,9 @@ func candidateURLs(addresses []protocol.NetworkAddress, scheme, port, path strin
return result
}
func localEndpoint(u *url.URL, hostname string, addresses []protocol.NetworkAddress) bool {
host := u.Hostname()
if host == "localhost" || host == hostname || net.ParseIP(host).IsLoopback() {
return true
}
for _, address := range addresses {
if host == address.IP {
return true
}
}
return false
}
func systemStatus(r *http.Request, started time.Time, runErr error) *protocol.SystemStatus {
hostname, _ := os.Hostname()
s := &protocol.SystemStatus{Hostname: hostname, StartedAt: started.UTC().Format(time.RFC3339), Uptime: time.Since(started).Round(time.Second).String(), Addresses: networkAddresses(), Server: protocol.ServiceStatus{Health: "healthy"}, Ntfy: protocol.ServiceStatus{Health: "not configured"}, Note: "Addresses belong to the server computer (or container). Candidate URLs are not reachability checks; binding, firewalls, port mapping and TLS may differ."}
s := &protocol.SystemStatus{Hostname: hostname, StartedAt: started.UTC().Format(time.RFC3339), Uptime: time.Since(started).Round(time.Second).String(), Addresses: networkAddresses(), Server: protocol.ServiceStatus{Health: "healthy"}, Note: "Addresses belong to the server computer (or container). Candidate URLs are not reachability checks; binding, firewalls, port mapping and TLS may differ."}
if runErr != nil {
s.Server.Health = "execution unavailable"
}
@@ -104,53 +78,5 @@ func systemStatus(r *http.Request, started time.Time, runErr error) *protocol.Sy
s.Server.Candidates = []string{s.Server.URL}
}
}
endpoints := notificationEndpoints()
if len(endpoints) == 0 {
return s
}
s.Topic = endpoints[0].Topic
s.NtfyUser = os.Getenv("PIPELINES_NTFY_READER")
s.Ntfy.Health = "not checked"
// Only the validated public base is returned. Publishing URL and tokens
// never leave the server, even on probe failure.
s.Ntfy.URL = endpoints[0].ServerURL
if u, err := url.Parse(s.Ntfy.URL); err == nil && u.Host != "" {
s.Ntfy.Port = endpointPort(u)
if localEndpoint(u, hostname, s.Addresses) {
s.Ntfy.Candidates = candidateURLs(s.Addresses, u.Scheme, s.Ntfy.Port, "/"+s.Topic)
}
}
publish, err := url.Parse(os.Getenv("PIPELINES_NTFY_URL"))
if err != nil {
return s
}
if s.Ntfy.URL == "" && localEndpoint(publish, hostname, s.Addresses) {
s.Ntfy.Port = endpointPort(publish)
s.Ntfy.Candidates = candidateURLs(s.Addresses, publish.Scheme, s.Ntfy.Port, "/"+s.Topic)
}
publish.Path = "/v1/health"
publish.RawPath = ""
publish.RawQuery = ""
publish.Fragment = ""
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, publish.String(), nil)
if err != nil {
return s
}
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(req)
s.Ntfy.Health = "unreachable"
if err != nil {
return s
}
defer response.Body.Close()
s.Ntfy.Health = "unhealthy"
var health struct {
Healthy bool `json:"healthy"`
}
if response.StatusCode == http.StatusOK && json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&health) == nil && health.Healthy {
s.Ntfy.Health = "healthy"
}
return s
}
+9 -37
View File
@@ -5,25 +5,13 @@ import (
"encoding/json"
"git.a-wan.net/alan/pipelines/internal/client"
"git.a-wan.net/alan/pipelines/internal/protocol"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
func TestStatusRPCReportsServerAndNtfyWithoutSecrets(t *testing.T) {
ntfy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/health" {
t.Error("unexpected probe", r.URL.Path)
}
w.Write([]byte(`{"healthy":true}`))
}))
defer ntfy.Close()
t.Setenv("PIPELINES_NTFY_URL", ntfy.URL+"/phone")
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", ntfy.URL)
t.Setenv("PIPELINES_NTFY_TOKEN", "never-return-this-token")
func TestStatusRPCReportsServerWithoutNtfy(t *testing.T) {
srv := httptest.NewServer(Handler(context.Background()))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@@ -38,12 +26,14 @@ func TestStatusRPCReportsServerAndNtfyWithoutSecrets(t *testing.T) {
t.Fatal(err)
}
s := response.Status
if s == nil || s.Server.Health != "healthy" || s.Ntfy.Health != "healthy" || s.Ntfy.URL != ntfy.URL || s.Topic != "phone" || len(s.Addresses) == 0 || s.Hostname == "" || s.Server.Port == "" || s.Ntfy.Port == "" || s.StartedAt == "" || len(s.Ntfy.Candidates) == 0 {
if s == nil || s.Server.Health != "healthy" || len(s.Addresses) == 0 || s.Hostname == "" || s.Server.Port == "" || s.StartedAt == "" {
t.Fatal("incomplete status", s)
}
encoded, _ := json.Marshal(s)
if strings.Contains(string(encoded), "never-return") {
t.Fatal("credentials leaked", string(encoded))
for _, gone := range []string{`"ntfy"`, `"topic"`, `"ntfy_user"`} {
if strings.Contains(string(encoded), gone) {
t.Fatalf("status still reports %s: %s", gone, encoded)
}
}
if !strings.Contains(s.Server.URL, s.Server.Port) || !strings.Contains(s.Note, "not reachability checks") {
t.Fatal("ports or safety disclaimer missing", s)
@@ -78,28 +68,10 @@ func TestStatusReportsOpenCodeAttachment(t *testing.T) {
}
}
func TestStatusUnconfiguredUnhealthyAndIPv6Candidates(t *testing.T) {
t.Setenv("PIPELINES_NTFY_URL", "")
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "")
r := httptest.NewRequest("GET", "http://localhost/connect", nil)
if s := systemStatus(r, time.Now(), nil); s.Ntfy.Health != "not configured" {
t.Fatal(s)
}
for _, body := range []string{`{"healthy":false}`, `not-json`} {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(body)) }))
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/topic")
s := systemStatus(r, time.Now(), nil)
srv.Close()
if s.Ntfy.Health != "unhealthy" || s.Ntfy.URL != "" || s.Ntfy.Port == "" {
t.Fatal(s)
}
}
func TestStatusIPv6Candidates(t *testing.T) {
addresses := []protocol.NetworkAddress{{Interface: "test", IP: "::1"}, {Interface: "test", IP: "192.0.2.1"}}
urls := candidateURLs(addresses, "http", "8090", "/topic")
if urls[0] != "http://[::1]:8090/topic" || urls[1] != "http://192.0.2.1:8090/topic" {
urls := candidateURLs(addresses, "ws", "8080", "/connect")
if urls[0] != "ws://[::1]:8080/connect" || urls[1] != "ws://192.0.2.1:8080/connect" {
t.Fatal(urls)
}
if localEndpoint(&url.URL{Host: "remote.example:8090", Scheme: "http"}, "test", addresses) {
t.Fatal("remote endpoint guessed local")
}
}
+1 -5
View File
@@ -142,7 +142,6 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
// Prompts queued behind a running turn are durable and owned by their
// session; resume delivering any a previous process left queued.
hub.queueStore = stores[0]
hub.startChatNotificationOutbox(ctx, stores[0])
hub.liveStore = stores[0]
hub.turnDiffStore = stores[0]
}
@@ -256,7 +255,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
log.Printf("list pipelines: %v", err)
return
}
if err := write(protocol.Message{Type: protocol.PipelineList, Pipelines: items, NotificationEndpoints: notificationEndpoints()}); err != nil {
if err := write(protocol.Message{Type: protocol.PipelineList, Pipelines: items}); err != nil {
return
}
}
@@ -388,9 +387,6 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
continue
}
response := protocol.Message{Type: protocol.Pong, ID: request.ID}
if request.Type == protocol.List || request.Type == protocol.Submit {
response.NotificationEndpoints = notificationEndpoints()
}
if request.Type == protocol.GetStatus {
response.Type = protocol.Status
response.Status = systemStatus(r, started, runErr)
-16
View File
@@ -1,16 +0,0 @@
package stage
import (
"os"
"testing"
)
// TestMain isolates the package from an operator's real notification setup: a
// developer shell may export the installed server's ntfy configuration, and no
// test may publish to it. Tests that need ntfy point it at an httptest server.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
}
-350
View File
@@ -1,350 +0,0 @@
package stage
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"maps"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
)
const NtfyType = "ntfy"
var destinationName = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
var ntfyMessageID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)
var ntfyTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
var ntfyTokenValue = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
// NtfyStage publishes to an operator-configured destination. Tokens never enter
// stage prompts, definitions, output maps, or diagnostics. No automatic retries:
// an ambiguous network failure may already have delivered the notification.
type NtfyStage struct{}
func (NtfyStage) Validate(def Definition) error {
if def.Type != NtfyType {
return fmt.Errorf("expected ntfy stage")
}
for name := range def.Blocks {
switch name {
case "configs", "edges", "output":
case "skills":
return errSkillsModelOnly("ntfy")
default:
return fmt.Errorf("unexpected block %q for ntfy stage", name)
}
}
for key := range def.Configs {
if key != "destination" && key != "timeout" {
return fmt.Errorf("unknown ntfy config %q", key)
}
}
if _, err := StageTimeout(def); err != nil {
return err
}
if !destinationName.MatchString(def.Configs["destination"]) {
return fmt.Errorf("ntfy destination must be a lowercase name containing letters, digits, or underscores")
}
if def.Edges["success"] == "" {
return fmt.Errorf("ntfy stage requires a success outcome")
}
return nil
}
func (NtfyStage) Run(ctx context.Context, def Definition, input Values) (Result, error) {
if err := (NtfyStage{}).Validate(def); err != nil {
return Result{}, err
}
timeout, _ := StageTimeout(def)
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
title, _ := input["title"].(string)
summary, _ := input["summary"].(string)
markdown, _ := input["markdown"].(string)
for name, text := range map[string]string{"title": title, "summary": summary, "markdown": markdown} {
if strings.TrimSpace(text) == "" || !utf8.ValidString(text) || strings.ContainsRune(text, '\x00') {
return Result{}, fmt.Errorf("ntfy input.%s must be a nonempty UTF-8 string", name)
}
}
if len(title) > 256 || len(summary) > 2048 || len(markdown) > 1<<20 {
return Result{}, fmt.Errorf("ntfy input exceeds limits (title 256 bytes, summary 2048 bytes, markdown 1 MiB)")
}
if strings.ContainsAny(title, "\r\n") || strings.ContainsAny(summary, "\r\n") {
return Result{}, fmt.Errorf("ntfy title and summary must be single-line strings")
}
delivery, err := PublishNtfy(ctx, def.Configs["destination"], title, summary, "digest.md", []byte(markdown), "")
if err != nil {
return Result{}, err
}
output := maps.Clone(input)
output["delivery"] = delivery
return Result{Outcome: "success", Output: output}, nil
}
type ntfyPriorityKey struct{}
// WithNtfyPriority makes PublishNtfy calls under ctx send ntfy priority
// (1 min to 5 max); without it ntfy uses its default, 3.
func WithNtfyPriority(ctx context.Context, priority int) context.Context {
return context.WithValue(ctx, ntfyPriorityKey{}, priority)
}
// NtfyPriority is the priority WithNtfyPriority set on ctx, 0 when none.
func NtfyPriority(ctx context.Context) int {
priority, _ := ctx.Value(ntfyPriorityKey{}).(int)
return priority
}
type ntfySequenceKey struct{}
// ntfySequenceID is the form of a sequence id this package sends: ntfy
// accepts the same characters as a topic name.
var ntfySequenceID = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
// WithNtfySequenceID makes PublishNtfy calls under ctx publish with ntfy
// sequence id sequence (X-Sequence-ID), so ClearNtfy can later dismiss the
// message on every subscribed client. An invalid id is ignored.
func WithNtfySequenceID(ctx context.Context, sequence string) context.Context {
return context.WithValue(ctx, ntfySequenceKey{}, sequence)
}
// NtfySequence is the sequence id WithNtfySequenceID set on ctx, "" when none.
func NtfySequence(ctx context.Context) string {
sequence, _ := ctx.Value(ntfySequenceKey{}).(string)
return sequence
}
// ClearNtfy marks the messages published with sequence id sequence on
// destination as read: ntfy (v2.15+) emits a message_clear event and its
// Android and web clients dismiss the notification. Clearing an unknown
// sequence id is harmless (ntfy still answers 200).
func ClearNtfy(ctx context.Context, destination, sequence string) error {
if !destinationName.MatchString(destination) || !ntfySequenceID.MatchString(sequence) {
return fmt.Errorf("invalid ntfy clear request")
}
endpoint, token, err := ntfyConnection(destination)
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPut, strings.TrimSuffix(endpoint, "/")+"/"+sequence+"/clear", nil)
if err != nil {
return fmt.Errorf("cannot create ntfy request")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(request)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("ntfy clear unconfirmed")
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64<<10))
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("ntfy clear returned HTTP %d", response.StatusCode)
}
return nil
}
// PublishNtfy is shared by native delivery stages and stage notification hooks.
// An empty filename publishes an event without an attachment. A non-empty click
// is an optional ntfy Click action (an absolute URL) so a tap on the notification
// opens the destination the operator should act on; it is validated here and
// never carries credentials. Optional views add ntfy "view" action buttons (for
// example "Open in browser"); each is validated as strictly as the click.
func PublishNtfy(ctx context.Context, destination, title, summary, filename string, data []byte, click string, views ...NtfyView) (Values, error) {
if !destinationName.MatchString(destination) || strings.TrimSpace(title) == "" || strings.TrimSpace(summary) == "" || len(title) > 256 || len(summary) > 2048 || !utf8.ValidString(title) || !utf8.ValidString(summary) || strings.ContainsAny(title+summary, "\r\n\x00") {
return nil, fmt.Errorf("invalid ntfy notification metadata")
}
if !ValidNtfyClick(click) {
return nil, fmt.Errorf("invalid ntfy click action")
}
actions, err := ntfyViewActions(views)
if err != nil {
return nil, err
}
if len(data) > 1<<20 || (filename != "" && (filename != filepath.Base(filename) || filename == "." || strings.ContainsAny(filename, "/\\\r\n\x00") || len(filename) > 200)) {
return nil, fmt.Errorf("invalid ntfy attachment")
}
endpoint, token, err := ntfyConnection(destination)
if err != nil {
return nil, err
}
method := http.MethodPut
if filename == "" {
method = http.MethodPost
data = []byte(summary)
}
request, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("cannot create ntfy request")
}
request.Header.Set("Content-Type", "application/octet-stream")
if filename == "" {
request.Header.Set("Content-Type", "text/plain; charset=utf-8")
} else if strings.HasSuffix(filename, ".md") {
request.Header.Set("Content-Type", "text/markdown; charset=utf-8")
}
request.Header.Set("Title", mime.BEncoding.Encode("utf-8", title))
request.Header.Set("Message", mime.BEncoding.Encode("utf-8", summary))
if click != "" {
request.Header.Set("Click", click)
}
if priority, ok := ctx.Value(ntfyPriorityKey{}).(int); ok && priority >= 1 && priority <= 5 {
request.Header.Set("Priority", strconv.Itoa(priority))
}
if sequence, ok := ctx.Value(ntfySequenceKey{}).(string); ok && ntfySequenceID.MatchString(sequence) {
request.Header.Set("X-Sequence-ID", sequence)
}
if actions != "" {
request.Header.Set("Actions", actions)
}
if filename != "" {
request.Header.Set("Filename", mime.BEncoding.Encode("utf-8", filename))
}
if strings.HasSuffix(filename, ".md") {
request.Header.Set("Markdown", "yes")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(request)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, fmt.Errorf("ntfy delivery unconfirmed; inspect destination before retrying")
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode >= 300 {
return nil, fmt.Errorf("ntfy publish returned HTTP %d; delivery not confirmed", response.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(response.Body, (64<<10)+1))
if err != nil || len(body) > 64<<10 {
return nil, fmt.Errorf("ntfy acknowledgment unreadable; inspect destination before retrying")
}
var ack struct {
ID string `json:"id"`
Event string `json:"event"`
Attachment struct {
URL string `json:"url"`
Name string `json:"name"`
} `json:"attachment"`
}
if json.Unmarshal(body, &ack) != nil || !ntfyMessageID.MatchString(ack.ID) || ack.Event != "message" || (filename != "" && ack.Attachment.Name != filename) {
return nil, fmt.Errorf("ntfy acknowledgment invalid or missing attachment; inspect destination before retrying")
}
if filename != "" {
attachment, err := url.Parse(ack.Attachment.URL)
if err != nil || attachment.Hostname() == "" || (attachment.Scheme != "http" && attachment.Scheme != "https") || attachment.User != nil {
return nil, fmt.Errorf("ntfy acknowledgment has no valid attachment URL; inspect destination before retrying")
}
}
return Values{"destination": destination, "message_id": ack.ID, "attachment_url": ack.Attachment.URL, "filename": filename}, nil
}
// ntfyConnection resolves destination's topic URL and token from the
// environment ("system" reads PIPELINES_NTFY_URL and its token).
func ntfyConnection(destination string) (string, string, error) {
prefix := "PIPELINES_NTFY_" + strings.ToUpper(destination)
if destination == "system" {
prefix = "PIPELINES_NTFY"
}
endpoint := os.Getenv(prefix + "_URL")
token := os.Getenv(prefix + "_TOKEN")
if path := os.Getenv(prefix + "_TOKEN_FILE"); path != "" {
if token != "" {
return "", "", fmt.Errorf("configure only one ntfy token source")
}
file, err := os.Open(path)
if err != nil {
return "", "", fmt.Errorf("cannot read ntfy token file")
}
contents, err := io.ReadAll(io.LimitReader(file, 4097))
file.Close()
if err != nil || len(contents) > 4096 {
return "", "", fmt.Errorf("invalid ntfy token file")
}
token = strings.TrimSpace(string(contents))
if token == "" {
return "", "", fmt.Errorf("ntfy token file is empty")
}
}
u, err := url.Parse(endpoint)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || !ntfyTopic.MatchString(strings.TrimPrefix(u.Path, "/")) || u.RawPath != "" {
return "", "", fmt.Errorf("configure %s_URL with an HTTP(S) ntfy topic URL (no credentials or query)", prefix)
}
if token != "" && (len(token) > 4096 || !ntfyTokenValue.MatchString(token)) {
return "", "", fmt.Errorf("invalid ntfy token configuration")
}
return endpoint, token, nil
}
// ValidNtfyClick accepts an empty click or an absolute URL the ntfy server will
// hand to the operating system on tap: a scheme, no credentials, no fragment,
// no control characters and a bounded length. The value is an operator-visible
// deep link, never a place to smuggle a token.
func ValidNtfyClick(click string) bool {
if click == "" {
return true
}
if len(click) > 2048 || !utf8.ValidString(click) || strings.ContainsAny(click, "\r\n\t\x00 ") {
return false
}
u, err := url.Parse(click)
return err == nil && u.Scheme != "" && u.User == nil && u.Fragment == ""
}
// NtfyView is one ntfy "view" action button: a tap opens URL. Label is short
// printable ASCII and URL is an absolute HTTP(S) address without credentials.
type NtfyView struct {
Label string
URL string
}
// ntfyViewActions renders views in ntfy's simple Actions header format
// ("view, <label>, <url>", separated by "; "). Commas, semicolons and quotes are
// rejected rather than escaped, so a value can never split into another action.
func ntfyViewActions(views []NtfyView) (string, error) {
if len(views) > 3 { // ntfy allows at most three actions.
return "", fmt.Errorf("at most 3 ntfy actions")
}
parts := make([]string, 0, len(views))
for _, view := range views {
label := strings.TrimSpace(view.Label)
if label == "" || len(label) > 64 || strings.ContainsAny(label, ",;\"'\\=") || !printableASCII(label) {
return "", fmt.Errorf("invalid ntfy action label")
}
if view.URL == "" || !ValidNtfyClick(view.URL) || strings.ContainsAny(view.URL, ",;\"'\\") || !printableASCII(view.URL) {
return "", fmt.Errorf("invalid ntfy action URL")
}
if u, err := url.Parse(view.URL); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" {
return "", fmt.Errorf("invalid ntfy action URL")
}
parts = append(parts, "view, "+label+", "+view.URL)
}
return strings.Join(parts, "; "), nil
}
func printableASCII(text string) bool {
for i := 0; i < len(text); i++ {
if text[i] < 0x20 || text[i] > 0x7e {
return false
}
}
return true
}
-274
View File
@@ -1,274 +0,0 @@
package stage
import (
"context"
"encoding/json"
"io"
"mime"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func ntfyDefinition() Definition {
return Definition{Type: NtfyType, Configs: map[string]string{"destination": "anime"}, Blocks: map[string]string{"configs": "destination=anime", "edges": "success -> #success"}, Edges: map[string]string{"success": "#success", "error": "#failure"}}
}
func TestNtfyTokenFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "token")
if err := os.WriteFile(path, []byte("secret-file-token\n"), 0600); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer secret-file-token" {
t.Error("token file not used")
}
_, _ = w.Write([]byte(`{"id":"msg","event":"message"}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN_FILE", path)
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, ""); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "other-token")
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, ""); err == nil {
t.Fatal("ambiguous token sources accepted")
}
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "")
os.WriteFile(path, nil, 0600)
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, ""); err == nil {
t.Fatal("empty token accepted")
}
}
func ntfyInput() Values {
return Values{"title": "Anime digest 🎬", "summary": "New episodes and announcements", "markdown": "# Anime digest\n\n- [Example](https://example.com)\n"}
}
func TestNtfyPublishesMarkdownAttachment(t *testing.T) {
calls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
body, _ := io.ReadAll(r.Body)
if r.Method != "PUT" || r.URL.Path != "/anime" || string(body) != ntfyInput()["markdown"] || r.Header.Get("Authorization") != "Bearer secret-token" || r.Header.Get("Filename") != "digest.md" || r.Header.Get("Markdown") != "yes" {
t.Error("invalid publication", r.Method, r.URL.Path, r.Header, string(body))
}
decoder := new(mime.WordDecoder)
title, err := decoder.DecodeHeader(r.Header.Get("Title"))
if err != nil || title != ntfyInput()["title"] {
t.Error("unicode title corrupted", title, err)
}
summary, _ := decoder.DecodeHeader(r.Header.Get("Message"))
if summary != ntfyInput()["summary"] {
t.Error("summary missing")
}
_ = json.NewEncoder(w).Encode(map[string]any{"id": "msg123", "event": "message", "attachment": map[string]string{"name": "digest.md", "url": "https://ntfy.example.com/file/msg123.md"}})
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "secret-token")
input := ntfyInput()
result, err := (NtfyStage{}).Run(context.Background(), ntfyDefinition(), input)
if err != nil || result.Outcome != "success" || calls != 1 {
t.Fatal("publish failed", result, err, calls)
}
delivery := result.Output["delivery"].(Values)
if delivery["message_id"] != "msg123" || result.Output["markdown"] != input["markdown"] {
t.Fatal("missing delivery/content")
}
if _, exists := input["delivery"]; exists {
t.Fatal("input mutated")
}
encoded, _ := json.Marshal(result)
if strings.Contains(string(encoded), "secret-token") {
t.Fatal("token leaked")
}
}
func TestNtfyRejectsInvalidDefinitions(t *testing.T) {
for _, key := range []string{"token", "url", "topic", "retries"} {
def := ntfyDefinition()
def.Configs[key] = "secret"
if err := (NtfyStage{}).Validate(def); err == nil {
t.Fatal("inline config accepted", key)
}
}
for _, block := range []string{"prompt", "tools", "input"} {
def := ntfyDefinition()
def.Blocks[block] = "anything"
if err := (NtfyStage{}).Validate(def); err == nil {
t.Fatal("unexpected block accepted", block)
}
}
for _, name := range []string{"", "Anime", "anime-news", "../secret", "*"} {
def := ntfyDefinition()
def.Configs["destination"] = name
if err := (NtfyStage{}).Validate(def); err == nil {
t.Fatal("unsafe destination accepted", name)
}
}
}
func TestNtfyInputAndConfigurationValidation(t *testing.T) {
t.Setenv("PIPELINES_NTFY_ANIME_URL", "http://127.0.0.1:1/anime")
for _, key := range []string{"title", "summary", "markdown"} {
input := ntfyInput()
delete(input, key)
if _, err := (NtfyStage{}).Run(context.Background(), ntfyDefinition(), input); err == nil || !strings.Contains(err.Error(), "input."+key) {
t.Fatal("missing field accepted", key, err)
}
}
for _, test := range []struct{ key, value string }{{"title", "inject\r\nAuthorization: evil"}, {"summary", "multi\nline"}, {"markdown", strings.Repeat("a", (1<<20)+1)}} {
input := ntfyInput()
input[test.key] = test.value
if _, err := (NtfyStage{}).Run(context.Background(), ntfyDefinition(), input); err == nil {
t.Fatal("unsafe input accepted", test.key)
}
}
for _, endpoint := range []string{"", "file:///foo", "https://user:pass@example.com/topic", "https://example.com/topic?token=secret", "https://example.com/a/b", "https://example.com/topic#fragment"} {
t.Setenv("PIPELINES_NTFY_ANIME_URL", endpoint)
if _, err := (NtfyStage{}).Run(context.Background(), ntfyDefinition(), ntfyInput()); err == nil || strings.Contains(err.Error(), "user:pass") {
t.Fatal("unsafe URL accepted/leaked", err)
}
}
}
func TestNtfyDoesNotRedirectOrRetryAndRedactsErrors(t *testing.T) {
for _, code := range []int{302, 401, 429, 500} {
calls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
w.Header().Set("Location", "/other")
w.WriteHeader(code)
_, _ = w.Write([]byte("secret-token"))
}))
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "secret-token")
_, err := (NtfyStage{}).Run(context.Background(), ntfyDefinition(), ntfyInput())
if err == nil || calls != 1 || strings.Contains(err.Error(), "secret-token") || strings.Contains(err.Error(), srv.URL) {
t.Fatal("retry/redirect/secret leak", calls, err)
}
srv.Close()
}
for _, body := range []string{`{}`, `{"id":"msg","event":"message"}`, `{"id":"msg","event":"message","attachment":{"name":"digest.md","url":"file:///bad"}}`, strings.Repeat("x", (64<<10)+1)} {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(body)) }))
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
if _, err := (NtfyStage{}).Run(context.Background(), ntfyDefinition(), ntfyInput()); err == nil {
t.Fatal("invalid acknowledgment accepted")
}
srv.Close()
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := (NtfyStage{}).Run(ctx, ntfyDefinition(), ntfyInput()); err == nil {
t.Fatal("cancellation ignored")
}
}
func TestNtfyPriorityFromContext(t *testing.T) {
var priorities []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
priorities = append(priorities, r.Header.Get("Priority"))
_, _ = w.Write([]byte(`{"id":"msg","event":"message"}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN_FILE", "")
for _, ctx := range []context.Context{context.Background(), WithNtfyPriority(context.Background(), 2), WithNtfyPriority(context.Background(), 9)} {
if _, err := PublishNtfy(ctx, "anime", "Title", "Summary", "", nil, ""); err != nil {
t.Fatal(err)
}
}
if strings.Join(priorities, ",") != ",2," {
t.Fatalf("priorities = %q", priorities)
}
}
func TestNtfyClickAndViewActions(t *testing.T) {
var click, actions []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
click = append(click, r.Header.Get("Click"))
actions = append(actions, r.Header.Get("Actions"))
_, _ = w.Write([]byte(`{"id":"msg","event":"message"}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN_FILE", "")
view := NtfyView{Label: "Open in browser", URL: "https://pipelines.example.com/runs/7"}
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, "pipelines://run/7", view); err != nil {
t.Fatal(err)
}
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, "pipelines://chat/ses_1"); err != nil {
t.Fatal(err)
}
if len(click) != 2 || click[0] != "pipelines://run/7" || actions[0] != "view, Open in browser, https://pipelines.example.com/runs/7" || click[1] != "pipelines://chat/ses_1" || actions[1] != "" {
t.Fatalf("click=%q actions=%q", click, actions)
}
for _, bad := range []NtfyView{
{Label: "", URL: "https://example.com/runs/1"},
{Label: "Open, now", URL: "https://example.com/runs/1"},
{Label: "Open\r\nX: y", URL: "https://example.com/runs/1"},
{Label: "Open", URL: ""},
{Label: "Open", URL: "pipelines://run/1"},
{Label: "Open", URL: "javascript:alert(1)"},
{Label: "Open", URL: "https://user:pass@example.com/runs/1"},
{Label: "Open", URL: "https://example.com/runs/1\r\nAuthorization: x"},
{Label: "Open", URL: "https://example.com/a,b"},
{Label: "Open", URL: "https://example.com/a;view, x, https://evil.example"},
{Label: "Open", URL: "/runs/1"},
} {
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, "", bad); err == nil {
t.Fatalf("unsafe action accepted: %+v", bad)
}
}
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, "", view, view, view, view); err == nil {
t.Fatal("more than three actions accepted")
}
if len(click) != 2 {
t.Fatalf("invalid actions still published: %d", len(click))
}
}
func TestNtfySequenceIDPublishAndClear(t *testing.T) {
var requests []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests = append(requests, r.Method+" "+r.URL.Path+" seq="+r.Header.Get("X-Sequence-ID")+" auth="+r.Header.Get("Authorization"))
if r.Method == http.MethodPost {
_, _ = w.Write([]byte(`{"id":"m1","event":"message","sequence_id":"pl-abc"}`))
return
}
_, _ = w.Write([]byte(`{"id":"m2","event":"message_clear","sequence_id":"pl-abc"}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
t.Setenv("PIPELINES_NTFY_TOKEN", "tok")
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
ctx := WithNtfySequenceID(context.Background(), "pl-abc")
if _, err := PublishNtfy(ctx, "system", "Title", "Body", "", nil, ""); err != nil {
t.Fatal(err)
}
if err := ClearNtfy(context.Background(), "system", "pl-abc"); err != nil {
t.Fatal(err)
}
if err := ClearNtfy(context.Background(), "system", "bad/id"); err == nil {
t.Fatal("invalid sequence id accepted")
}
// An invalid sequence id on publish is dropped rather than sent.
if _, err := PublishNtfy(WithNtfySequenceID(context.Background(), "a:b"), "system", "Title", "Body", "", nil, ""); err != nil {
t.Fatal(err)
}
want := []string{
"POST /pipelines seq=pl-abc auth=Bearer tok",
"PUT /pipelines/pl-abc/clear seq= auth=Bearer tok",
"POST /pipelines seq= auth=Bearer tok",
}
if strings.Join(requests, "\n") != strings.Join(want, "\n") {
t.Fatalf("requests:\n%s", strings.Join(requests, "\n"))
}
}
+9
View File
@@ -0,0 +1,9 @@
package stage
// RemovedNtfyType is the former `type=ntfy` stage, which published Markdown to
// an ntfy server. ntfy was removed from Pipelines; a definition that still
// uses the type is rejected with RemovedNtfyMessage.
const RemovedNtfyType = "ntfy"
// RemovedNtfyMessage tells an author what replaces a `type=ntfy` stage.
const RemovedNtfyMessage = "ntfy stages were removed; notifications go to the Pipelines apps — use the stage notify hook"
+21
View File
@@ -0,0 +1,21 @@
package stage
import (
"context"
"strings"
"testing"
)
func TestRemovedNtfyStageIsRejectedWithGuidance(t *testing.T) {
def := Definition{Key: "tell", Type: RemovedNtfyType, Configs: map[string]string{"destination": "system"}, Edges: map[string]string{"success": "#success"}}
registry := DefaultRegistry()
_, runErr := registry.Run(context.Background(), def, Values{})
for name, err := range map[string]error{"validate": registry.Validate(def), "run": runErr} {
if err == nil || !strings.Contains(err.Error(), RemovedNtfyMessage) {
t.Fatalf("%s: %v", name, err)
}
}
if !strings.Contains(RemovedNtfyMessage, "ntfy stages were removed; notifications go to the Pipelines apps — use the stage notify hook") {
t.Fatal(RemovedNtfyMessage)
}
}
-4
View File
@@ -76,10 +76,6 @@ func TestSkillsBlockValidationByStageTypeAndHarness(t *testing.T) {
if err := (HumanStage{}).Validate(human); err == nil || !strings.Contains(err.Error(), "only on model stages") {
t.Fatal("human:", err)
}
ntfy := Definition{Key: "tell", Type: NtfyType, Blocks: map[string]string{"skills": "review"}, Configs: map[string]string{"destination": "phone"}, Edges: map[string]string{"success": "#success", "error": "#failure"}}
if err := (NtfyStage{}).Validate(ntfy); err == nil || !strings.Contains(err.Error(), "only on model stages") {
t.Fatal("ntfy:", err)
}
}
func testSkillSet(t *testing.T) *SkillSet {
+4 -1
View File
@@ -75,7 +75,7 @@ func NewRegistry(types map[string]Stage) *Registry {
}
func DefaultRegistry() *Registry {
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}, FindingsType: FindingsStage{}})
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}, FindingsType: FindingsStage{}})
}
func EffectiveType(name string) string {
@@ -92,6 +92,9 @@ func (r *Registry) Resolve(name string) (Stage, error) {
return implementation, nil
}
}
if name == RemovedNtfyType {
return nil, fmt.Errorf("unsupported stage type %q: %s", name, RemovedNtfyMessage)
}
return nil, fmt.Errorf("unsupported stage type %q", name)
}
+3 -26
View File
@@ -8,7 +8,7 @@ import (
)
func Offline(endpoint string) *protocol.SystemStatus {
s := &protocol.SystemStatus{Server: protocol.ServiceStatus{Health: "unreachable"}, Ntfy: protocol.ServiceStatus{Health: "unknown (server unavailable)"}}
s := &protocol.SystemStatus{Server: protocol.ServiceStatus{Health: "unreachable"}}
if u, err := url.Parse(endpoint); err == nil {
s.Server.Port = u.Port()
}
@@ -41,30 +41,7 @@ func ServerLines(s *protocol.SystemStatus) []string {
return lines
}
func NtfyLines(s *protocol.SystemStatus) []string {
if s == nil {
return []string{"Checking ntfy…"}
}
lines := []string{"Status: " + s.Ntfy.Health}
if s.Ntfy.URL != "" {
lines = append(lines, "Server: "+s.Ntfy.URL)
}
if s.Topic != "" {
lines = append(lines, "Topic: "+s.Topic)
}
if s.NtfyUser != "" {
lines = append(lines, "Login: "+s.NtfyUser, "Use the password set during installation.")
}
if s.Ntfy.Health == "not configured" {
lines = append(lines, "The connected Pipelines server has no ntfy publishing configuration.", "For Docker: check docker compose port pipelines 8080.", "Connect the TUI to that port; check --url / PIPELINES_URL.", "If this is the intended server: run ./install there.")
} else if s.Ntfy.Health == "unreachable" || s.Ntfy.Health == "unhealthy" {
lines = append(lines, "On the server: docker compose logs ntfy")
}
return lines
}
// The human view has exactly two focused sections. --json retains full data.
// The human view is one focused section. --json retains full data.
func Lines(s *protocol.SystemStatus) []string {
lines := append([]string{"Pipelines server"}, ServerLines(s)...)
return append(append(lines, "", "ntfy"), NtfyLines(s)...)
return append([]string{"Pipelines server"}, ServerLines(s)...)
}
+4 -11
View File
@@ -1,12 +1,11 @@
package statusview
import (
"git.a-wan.net/alan/pipelines/internal/protocol"
"strings"
"testing"
)
func TestOfflineStatusIncludesBothServicesAndRedactsURLCredentials(t *testing.T) {
func TestOfflineStatusShowsTheServerAndRedactsURLCredentials(t *testing.T) {
s := Offline("ws://user:password@localhost:8080/connect?token=secret#secret")
text := strings.Join(Lines(s), "\n")
for _, secret := range []string{"password", "token=", "secret", "user:"} {
@@ -14,18 +13,12 @@ func TestOfflineStatusIncludesBothServicesAndRedactsURLCredentials(t *testing.T)
t.Fatal("credentials exposed", text)
}
}
for _, expected := range []string{"Pipelines server", "unreachable", "ntfy", "unknown (server unavailable)", "8080"} {
for _, expected := range []string{"Pipelines server", "unreachable", "8080"} {
if !strings.Contains(text, expected) {
t.Fatal("missing offline information", expected, text)
}
}
}
func TestUnconfiguredNtfyExplainsConnectedServerAndEndpointMismatch(t *testing.T) {
text := strings.Join(NtfyLines(&protocol.SystemStatus{Ntfy: protocol.ServiceStatus{Health: "not configured"}}), "\n")
for _, want := range []string{"connected Pipelines server", "docker compose port pipelines 8080", "--url / PIPELINES_URL"} {
if !strings.Contains(text, want) {
t.Fatal("missing endpoint diagnosis", want, text)
}
if strings.Contains(strings.ToLower(text), "ntfy") {
t.Fatal("status still describes ntfy", text)
}
}
+1 -1
View File
@@ -42,5 +42,5 @@ say why is a review finding.
you checked.
- Terminal width matters: verify at a narrow width as well as a wide one, and never assume colour
support (`plain-nocolor-*` exists for a reason).
- Do not restart the deployed server or ntfy to test a TUI change: run the binary against a
- Do not restart the deployed server to test a TUI change: run the binary against a
scratch server or use the fixtures.
+4 -4
View File
@@ -5,11 +5,11 @@ import (
"testing"
)
// TestMain isolates the package from an operator's real notification setup:
// these tests run real servers and runs, a developer shell may export the
// installed server's ntfy configuration, and no test may publish to it.
// TestMain isolates the package from the operator's environment: a developer
// shell may export the installed server's web origin, which tests must not
// pick up.
func TestMain(m *testing.M) {
for _, name := range []string{"PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"} {
for _, name := range []string{"PIPELINES_WEB_PUBLIC_URL"} {
os.Unsetenv(name)
}
os.Exit(m.Run())
-3
View File
@@ -123,7 +123,6 @@ type Model struct {
keys keyMap
pipelines []protocol.PipelineSummary
loaded bool
notificationEndpoints []protocol.NotificationEndpoint
logSeen []bool
unread int
logOpen bool
@@ -333,7 +332,6 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.markVisibleLogs()
}
case connectedMsg:
m.notificationEndpoints = nil
if m.conn != nil && m.conn != msg.conn {
m.conn.CloseNow()
}
@@ -391,7 +389,6 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, m.read()
}
if msg.Type == protocol.PipelineList || msg.Type == protocol.Submitted {
m.notificationEndpoints = msg.NotificationEndpoints
if msg.DefaultModel != "" {
m.defaultModel = msg.DefaultModel
}
-39
View File
@@ -1,39 +0,0 @@
package tui
import (
"context"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/charmbracelet/x/ansi"
"strings"
"testing"
)
func TestInfrastructureRetainedWithoutClutteringPageHeaders(t *testing.T) {
m := New(context.Background(), "ws://localhost/connect")
m.width = 120
m.height = 40
updated, _ := m.Update(receivedMsg(protocol.Message{Type: protocol.PipelineList, NotificationEndpoints: []protocol.NotificationEndpoint{{Destination: "system", ServerURL: "http://10.0.0.249:8090", Topic: "pipelines"}}}))
m = updated.(Model)
view := ansi.Strip(m.View())
header := strings.Split(view, "\n")[0]
for _, text := range []string{"ntfy", "http://10.0.0.249:8090", "topic pipelines"} {
if strings.Contains(header, text) {
t.Fatal("infrastructure cluttered the result page header", text, view)
}
}
if strings.Contains(strings.Join(m.homeLines(), "\n"), "Phone notifications") {
t.Fatal("notification setup still occupies home panel")
}
m.runOpen = true
if strings.Contains(strings.Split(ansi.Strip(m.View()), "\n")[0], "topic pipelines") || len(m.notificationEndpoints) != 1 || m.notificationEndpoints[0].Topic != "pipelines" {
t.Fatal("notification information lost or leaked into run header")
}
for _, width := range []int{1, 12, 40, 80, 120} {
m.width = width
for _, line := range strings.Split(m.View(), "\n") {
if ansi.StringWidth(line) > width {
t.Fatalf("header/layout overflows at width %d", width)
}
}
}
}
+2 -9
View File
@@ -161,7 +161,7 @@ func (m Model) runHasMutationTools() bool {
}
if m.detail != nil {
for _, s := range m.detail.Graph.Stages {
if _, explicit := s.Blocks["tools"]; !explicit && s.Type != "ntfy" {
if _, explicit := s.Blocks["tools"]; !explicit {
return true
}
for _, tool := range strings.Fields(s.Blocks["tools"]) {
@@ -190,13 +190,9 @@ func (m Model) runScopeLabel() string {
if m.detail == nil {
return "Scope: defined by the selected pipeline"
}
var tools, notifications []string
var tools []string
seen := map[string]bool{}
for _, s := range m.detail.Graph.Stages {
if s.Type == "ntfy" {
notifications = append(notifications, "publish Markdown to ntfy destination "+s.Configs["destination"])
continue
}
declared, explicit := s.Blocks["tools"]
if !explicit {
declared = "read glob grep edit shell"
@@ -212,9 +208,6 @@ func (m Model) runScopeLabel() string {
if len(tools) > 0 {
label = "Stage tools: " + strings.Join(tools, ", ")
}
if len(notifications) > 0 {
label += " · " + strings.Join(notifications, "; ")
}
return label
}
+1 -21
View File
@@ -55,26 +55,6 @@ func TestRunComposerShowsStageScopedTools(t *testing.T) {
}
}
func TestNativeNtfyStagePresentation(t *testing.T) {
m := panelModel(t)
s := &m.detail.Graph.Stages[0]
s.Type = "ntfy"
s.Prompt = ""
s.Configs = map[string]string{"destination": "anime"}
s.Blocks = nil
header, lines := m.stageColumns(116)
view := header + "\n" + strings.Join(lines, "\n")
if strings.Contains(header, "PROMPT") || !strings.Contains(view, "ntfy") || !strings.Contains(view, "anime") {
t.Fatal("native stage displayed as model", view)
}
m.runForm = 1
m.runInput = newInput()
view = m.runFormView(40)
if !strings.Contains(view, "publish Markdown to ntfy destination anime") {
t.Fatal("delivery side effect not shown", view)
}
}
func TestNotifyPolicyAndReceiptsVisible(t *testing.T) {
m := panelModel(t)
m.detail.Graph.Stages[0].Notify = &protocol.NotificationPolicy{On: []string{"success", "failure"}, Destination: "anime", Artifacts: []string{"markdown", "files"}}
@@ -88,7 +68,7 @@ func TestNotifyPolicyAndReceiptsVisible(t *testing.T) {
run := runInspectionModel()
run.runStepIndex = 1
run.toggleRunSection(4)
run.runDetail.Steps[0].Notifications = []protocol.NotificationReceipt{{Destination: "anime", Status: "sent", Filename: "report.txt", MessageID: "message123", AttachmentURL: "https://ntfy.example.com/file/report.txt"}, {Destination: "anime", Status: "failed", Diagnostic: "HTTP 401"}}
run.runDetail.Steps[0].Notifications = []protocol.NotificationReceipt{{Destination: "anime", Status: "sent", Filename: "report.txt", MessageID: "message123", AttachmentURL: "https://files.example.com/report.txt"}, {Destination: "anime", Status: "failed", Diagnostic: "HTTP 401"}}
view = strings.Join(run.runSectionLines(116), "\n")
for _, text := range []string{"Notification: anime", "report.txt", "message123", "HTTP 401"} {
if !strings.Contains(view, text) {
+5 -20
View File
@@ -5,7 +5,6 @@ import (
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/statusview"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"strings"
)
@@ -49,13 +48,10 @@ func (m Model) updateStatus(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
func (m Model) statusLines() []string {
lines := []string{}
if m.statusRequest != "" {
lines = append(lines, m.loading("Checking server and ntfy…"))
lines = append(lines, m.loading("Checking server…"))
}
if m.statusError != "" {
lines = append(lines, m.statusError)
if m.systemStatus == nil {
lines = append(lines, "ntfy: unknown (server information unavailable)")
}
}
if m.systemStatus != nil {
lines = append(lines, " ")
@@ -64,10 +60,9 @@ func (m Model) statusLines() []string {
return lines
}
func (m Model) statusContent() []string {
server, ntfy := statusview.ServerLines(m.systemStatus), statusview.NtfyLines(m.systemStatus)
server := statusview.ServerLines(m.systemStatus)
if m.systemStatus == nil && m.statusError != "" {
s := statusview.Offline(m.url)
server, ntfy = statusview.ServerLines(s), statusview.NtfyLines(s)
server = statusview.ServerLines(statusview.Offline(m.url))
}
if m.statusError != "" {
server = append([]string{m.statusError}, server...)
@@ -83,18 +78,8 @@ func (m Model) statusContent() []string {
}
return rows
}
if width >= 100 {
w := (width - 2) / 2
server, ntfy = wrap(server, w-4), wrap(ntfy, width-w-6)
cardHeight := max(len(server), len(ntfy)) + 4
left := panel(w, cardHeight, []string{"Pipelines server"}, server, "", false)
right := panel(width-w-2, cardHeight, []string{"ntfy · phone connection"}, ntfy, "", false)
return strings.Split(lipgloss.JoinHorizontal(lipgloss.Top, left, " ", right), "\n")
}
server, ntfy = wrap(server, width-4), wrap(ntfy, width-4)
left := panel(width, len(server)+4, []string{"Pipelines server"}, server, "", false)
right := panel(width, len(ntfy)+4, []string{"ntfy · phone connection"}, ntfy, "", false)
return strings.Split(left+"\n\n"+right, "\n")
server = wrap(server, width-4)
return strings.Split(panel(width, len(server)+4, []string{"Pipelines server"}, server, "", false), "\n")
}
func (m Model) statusView(height int) string {
+2 -2
View File
@@ -23,10 +23,10 @@ func TestStatusPalettePopupAndClosePreservesUnderlyingPage(t *testing.T) {
t.Fatal("status unavailable off Home", m.View())
}
m.statusRequest = "status-1"
updated, _ := m.Update(receivedMsg(protocol.Message{Type: protocol.Status, ID: "status-1", Status: &protocol.SystemStatus{Hostname: "test-machine", Server: protocol.ServiceStatus{Health: "healthy", Port: "8080"}, Ntfy: protocol.ServiceStatus{Health: "healthy", URL: "http://192.0.2.2:8090", Port: "8090"}, Addresses: []protocol.NetworkAddress{{Interface: "en0", IP: "192.0.2.2"}}}}))
updated, _ := m.Update(receivedMsg(protocol.Message{Type: protocol.Status, ID: "status-1", Status: &protocol.SystemStatus{Hostname: "test-machine", Server: protocol.ServiceStatus{Health: "healthy", Port: "8080"}, Addresses: []protocol.NetworkAddress{{Interface: "en0", IP: "192.0.2.2"}}}}))
m = updated.(Model)
view := ansi.Strip(m.View())
for _, text := range []string{"Pipelines server", "ntfy", "8080", "8090", "192.0.2.2"} {
for _, text := range []string{"Pipelines server", "8080", "192.0.2.2"} {
if !strings.Contains(view, text) {
t.Fatal("missing status info", text, view)
}
-16
View File
@@ -154,22 +154,6 @@ func TestTerminalErrorsReplaceLoadingAndKeepRecoveryInstructions(t *testing.T) {
}
}
func TestNarrowStatusActuallyScrollsToPhoneConnection(t *testing.T) {
m := New(context.Background(), "ws://localhost/connect")
m.width, m.height = 40, 16
m.statusOpen = true
m.statusError = "Connection unavailable"
var views []string
for i := 0; i < 60; i++ {
views = append(views, ansi.Strip(m.statusView(12)))
updated, _ := m.updateStatus(keyMessage("j"))
m = updated.(Model)
}
if !strings.Contains(strings.Join(views, "\n"), "ntfy · phone connection") || m.statusTop == 0 {
t.Fatal("phone connection remains unreachable")
}
}
func TestNarrowRunShowsActualResultAndEssentialControls(t *testing.T) {
m := runInspectionModel()
m.width, m.height = 40, 16
-1
View File
@@ -35,7 +35,6 @@ func TestUIUXReviewSnapshots(t *testing.T) {
m.height = 36
m.loaded = true
m.status = "127.0.0.1:8080"
m.notificationEndpoints = []protocol.NotificationEndpoint{{Destination: "system", ServerURL: "http://100.85.25.33:8090", Topic: "pipelines"}}
m.pipelines = []protocol.PipelineSummary{{ID: 8, Name: "Implement, review and land", Version: 1, Stages: 4, CreatedAt: "2026-10-08T20:00:00Z", UpdatedAt: "2026-10-08T20:00:00Z"}}
save := func(name string) {
t.Helper()