package server import ( "context" "log" "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 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 // id is the stable app notification id ("chat:::"). id string } // chatNotificationID is the app notification id for one chat attention item. func chatNotificationID(sessionID, what, id string) string { return "chat:" + sessionID + ":" + what + ":" + id } // 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 == "" || !h.attentionWanted() { return } form := frame.Form if !h.claimChatAttentionLocked("form\x00" + frame.SessionID + "\x00" + form.ID) { // An answered or cancelled question no longer needs the operator. if form.Resolved || form.Cancelled { h.clearChatAttention(frame.SessionID, chatNotificationID(frame.SessionID, "form", 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, id: chatNotificationID(frame.SessionID, "form", form.ID)}) } // 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 || !h.attentionWanted() { 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, 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. func (h *chatHub) attentionWanted() bool { return chatAttentionConfigured() || h.notes != nil } // clearChatAttention clears one chat app notification asynchronously, off the // hub mutex. func (h *chatHub) clearChatAttention(sessionID, id string) { if h.notes == nil { return } base := h.baseCtx if base == nil { base = context.Background() } notes := h.notes h.attentionWG.Add(1) go func() { defer h.attentionWG.Done() ctx, cancel := context.WithTimeout(base, 5*time.Second) defer cancel() notes.clearFor(ctx, pipeline.AppNotificationFilter{SessionID: sessionID, ID: id}) }() } // 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 notes := h.notes 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) kind := protocol.NotificationChatQuestion if a.reply { kind = protocol.NotificationChatReply } else if a.approval { kind = protocol.NotificationChatApproval } notes.record(ctx, pipeline.AppNotificationRecord{ AppNotification: protocol.AppNotification{ID: a.id, Kind: kind, Title: title, Message: body, Click: click, 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. if _, err := chatAttentionPublish(ctx, "system", title, truncateUTF8(singleLine(body), 2000), "", 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) }