Files
pipelines/internal/server/chat_attention.go
T
alan 498c6f17a6 Add server notification settings with app checkboxes
Persist three global ntfy switches in server_settings: run_finished
(default on: auto-mode runs notify on success, read inside the
transition transaction; on/off modes unchanged), chat_needs_you
(default on: gates chat question/approval alerts) and
chat_reply_finished (default off: one alert per finished assistant
turn). Expose notification_settings / set_notification_settings over
the websocket protocol, add a Phone notifications section with
Material and Cupertino checkboxes in Settings, document the settings,
and keep the cli, tui, stage and pipeline test packages from
inheriting a real ntfy configuration.
2026-10-30 21:36:27 +00:00

172 lines
5.6 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
// reply marks a finished assistant turn (gated by chat_reply_finished)
// rather than a question/approval (gated by chat_needs_you).
reply 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
settingsStore := h.settings
h.attentionWG.Add(1)
go func() {
defer h.attentionWG.Done()
ctx, cancel := context.WithTimeout(base, 30*time.Second)
defer cancel()
// The operator's choice is read here, off the hub mutex, at publish time.
settings := chatNotificationSettings(ctx, settingsStore)
if (a.reply && !settings.ChatReplyFinished) || (!a.reply && !settings.ChatNeedsYou) {
return
}
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)
if a.reply {
title, body = chatReplyText(name, 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)
}