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) }