Files
pipelines/internal/server/chat_attention.go
T
alan 40ba2ac117 Open ntfy notifications in the app and notify chats that need the operator
Run notifications now always click through to pipelines://run/<id>; a valid
PIPELINES_WEB_PUBLIC_URL adds an "Open in browser" ntfy view action instead
of replacing the click. Queued rows derive links from the run id at delivery,
so legacy rows holding a web URL still open the app.

Unresolved chat questions/forms and permission requests publish one async,
bounded notification to the system destination (pipelines://chat/<id> plus the
browser action), deduplicated per form/request id across reconnects and
replays. stage.PublishNtfy gains optional, strictly validated view actions.
Server tests now clear the operator's real ntfy environment.
2026-10-30 20:40:06 +00:00

160 lines
5.1 KiB
Go

package server
import (
"context"
"log"
"net/url"
"os"
"strings"
"time"
"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
approval bool
body string
}
// claimChatAttentionLocked records key in the hub-wide dedupe set and reports
// whether it was new. Unlike the per-room sets it survives reconnects and room
// teardown, so a replayed pending form or approval is not announced twice.
// Callers must hold h.mu.
func (h *chatHub) claimChatAttentionLocked(key string) bool {
if h.attentionSeen == nil {
h.attentionSeen = map[string]struct{}{}
}
if _, ok := h.attentionSeen[key]; ok {
return false
}
h.attentionSeen[key] = struct{}{}
h.attentionOrder = append(h.attentionOrder, key)
if len(h.attentionOrder) > chatAttentionRetainedLimit {
delete(h.attentionSeen, h.attentionOrder[0])
h.attentionOrder = h.attentionOrder[1:]
}
return true
}
// noteFormAttentionLocked notifies the operator once about an unresolved
// question/form. A form first seen resolved or cancelled is only recorded, so a
// later stale copy cannot announce it. Callers must hold h.mu.
func (h *chatHub) noteFormAttentionLocked(frame protocol.ChatEventFrame) {
if frame.Kind != protocol.ChatEventForm || frame.Form == nil || frame.Form.ID == "" || frame.SessionID == "" || !chatAttentionConfigured() {
return
}
form := frame.Form
if !h.claimChatAttentionLocked("form\x00" + frame.SessionID + "\x00" + form.ID) {
return
}
if form.Resolved || form.Cancelled {
return
}
body := form.Title
if len(form.Fields) > 0 {
question := form.Fields[0].Title
if question == "" {
question = form.Fields[0].Description
}
if body == "" {
body = question
} else if question != "" && question != body {
body += ": " + question
}
}
if strings.TrimSpace(body) == "" {
body = "The agent asked a question"
}
kind := strings.ToLower(form.Kind)
h.startChatAttention(chatAttention{sessionID: frame.SessionID, approval: strings.Contains(kind, "permission") || strings.Contains(kind, "approval"), body: body})
}
// notePermissionAttentionLocked notifies the operator once about a pending
// approval request. Callers must hold h.mu.
func (h *chatHub) notePermissionAttentionLocked(frame protocol.ChatPermissionFrame) {
if frame.RequestID == "" || frame.SessionID == "" || frame.Resolved || !chatAttentionConfigured() {
return
}
if !h.claimChatAttentionLocked("permission\x00" + frame.SessionID + "\x00" + frame.RequestID) {
return
}
body := frame.Message
if strings.TrimSpace(body) == "" && frame.Action != "" {
body = "Allow " + frame.Action
if len(frame.Resources) > 0 {
body += " " + frame.Resources[0]
}
}
if strings.TrimSpace(body) == "" {
body = "The agent asked for permission"
}
h.startChatAttention(chatAttention{sessionID: frame.SessionID, approval: true, body: body})
}
func chatAttentionConfigured() bool {
return os.Getenv("PIPELINES_NTFY_URL") != ""
}
// startChatAttention publishes asynchronously within the 30-second notification
// budget. It never blocks or fails chat handling; failures are only logged.
func (h *chatHub) startChatAttention(a chatAttention) {
base := h.baseCtx
if base == nil {
base = context.Background()
}
registry := h.registry
h.attentionWG.Add(1)
go func() {
defer h.attentionWG.Done()
ctx, cancel := context.WithTimeout(base, 30*time.Second)
defer cancel()
name := ""
if registry != nil {
if session, found, err := registry.OperatorSession(ctx, a.sessionID); err == nil && found {
name = session.Title
}
}
title, body := chatAttentionText(name, a.approval, a.body)
click, views := chatAttentionLinks(a.sessionID)
if _, err := chatAttentionPublish(ctx, "system", title, body, "", nil, click, views...); err != nil {
log.Printf("chat attention notification session=%s: %v", a.sessionID, err)
}
}()
}
// chatAttentionText builds a single-line ntfy title/body within PublishNtfy's
// limits.
func chatAttentionText(name string, approval bool, body string) (string, string) {
name = singleLine(name)
if name == "" {
name = "Chat"
}
suffix := " needs your answer"
if approval {
suffix = " needs your approval"
}
return truncateUTF8(name, 256-len(suffix)) + suffix, truncateUTF8(singleLine(body), 2000)
}
// singleLine folds whitespace (including CR/LF) to single spaces and drops NULs.
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)
}