Notifications: agent notify reaches every device and clears everywhere

- Server: chat ntfy messages carry a sequence id derived from their app id;
  clearing a chat app notification also clears it in ntfy (PUT
  /<topic>/<seq>/clear, verified on ntfy v2.38.1).
- Server: a turn that sent an agent notify does not also send chat_reply.
- notify tool and MCP instructions: Pipelines already notifies at reply end
  and for questions/approvals; notify is for mid-turn or background news.
- Shown notify items carry channels (apps/phone); the transcript row says
  where it went.
- App: NotificationBridge.close(tag); web closes tracked Notifications and
  tells other tabs over a BroadcastChannel; native bridge cancels by tag and
  now supports macOS. AgentNotices closes on notifications_cleared and on
  resubscribe cleared ids, and a tap sends clear_notifications.
- Docs: skill, chat reference, ntfy/notifications docs, app note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 19:43:55 +00:00
parent c441400f36
commit b91ef04ab0
32 changed files with 743 additions and 73 deletions
+97 -30
View File
@@ -105,6 +105,60 @@ func NtfyPriority(ctx context.Context) 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
@@ -125,36 +179,9 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
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")
}
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 nil, fmt.Errorf("configure only one ntfy token source")
}
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("cannot read ntfy token file")
}
contents, err := io.ReadAll(io.LimitReader(file, 4097))
file.Close()
if err != nil || len(contents) > 4096 {
return nil, fmt.Errorf("invalid ntfy token file")
}
token = strings.TrimSpace(string(contents))
if token == "" {
return nil, 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 nil, 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 nil, fmt.Errorf("invalid ntfy token configuration")
endpoint, token, err := ntfyConnection(destination)
if err != nil {
return nil, err
}
method := http.MethodPut
if filename == "" {
@@ -179,6 +206,9 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
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)
}
@@ -227,6 +257,43 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
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
+38
View File
@@ -234,3 +234,41 @@ func TestNtfyClickAndViewActions(t *testing.T) {
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"))
}
}