package server import ( "context" "net/http/httptest" "strings" "testing" "time" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" "github.com/coder/websocket" "github.com/coder/websocket/wsjson" ) func notificationSettingsRoundTrip(t *testing.T, ctx context.Context, store *pipeline.Store, requests ...protocol.Message) []protocol.Message { t.Helper() handlerCtx, cancel := context.WithCancel(ctx) handler := Handler(handlerCtx, store) defer func() { cancel(); WaitRuns(handler) }() srv := httptest.NewServer(handler) defer srv.Close() conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil) if err != nil { t.Fatal(err) } defer conn.CloseNow() var welcome protocol.Message if err := wsjson.Read(ctx, conn, &welcome); err != nil { t.Fatal(err) } var replies []protocol.Message for _, request := range requests { if err := wsjson.Write(ctx, conn, request); err != nil { t.Fatal(err) } var reply protocol.Message if err := wsjson.Read(ctx, conn, &reply); err != nil { t.Fatal(err) } replies = append(replies, reply) } return replies } func wantSettings(t *testing.T, reply protocol.Message, want protocol.NotificationSettings) { t.Helper() if reply.Type != protocol.NotificationSettingsReply || len(reply.NotificationSettings) != len(protocol.NotificationSettingKeys) { t.Fatalf("reply = %+v", reply) } for key, value := range want.Map() { if reply.NotificationSettings[key] != value { t.Fatalf("%s = %v, want %v (reply %+v)", key, reply.NotificationSettings[key], value, reply.NotificationSettings) } } } func TestNotificationSettingsProtocol(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() store := newOperatorStore(t) replies := notificationSettingsRoundTrip(t, ctx, store, protocol.Message{Type: protocol.GetNotificationSettings, ID: "get"}, protocol.Message{Type: protocol.SetNotificationSettings, ID: "set", NotificationSettings: map[string]any{protocol.NotifyChatReplyFinished: true}}, protocol.Message{Type: protocol.SetNotificationSettings, ID: "unknown", NotificationSettings: map[string]any{protocol.NotifyRunFinished: false, "run_started": true}}, protocol.Message{Type: protocol.SetNotificationSettings, ID: "string", NotificationSettings: map[string]any{protocol.NotifyRunFinished: "no"}}, protocol.Message{Type: protocol.SetNotificationSettings, ID: "empty"}, protocol.Message{Type: protocol.GetNotificationSettings, ID: "again"}, ) defaults := protocol.DefaultNotificationSettings() wantSettings(t, replies[0], defaults) if replies[0].ID != "get" || replies[1].ID != "set" { t.Fatalf("ids not echoed: %+v", replies) } updated := defaults updated.ChatReplyFinished = true wantSettings(t, replies[1], updated) for _, reply := range replies[2:5] { if reply.Type != protocol.Error || reply.Error == "" || reply.NotificationSettings != nil { t.Fatalf("invalid update not refused: %+v", reply) } } if !strings.Contains(replies[2].Error, "run_started") { t.Fatalf("unknown key error = %q", replies[2].Error) } wantSettings(t, replies[5], updated) // A new server on the same database (a restart) reads the stored choice. replies = notificationSettingsRoundTrip(t, ctx, store, protocol.Message{Type: protocol.GetNotificationSettings, ID: "restart"}) wantSettings(t, replies[0], updated) } func TestChatNeedsYouSettingSuppressesQuestionsAndApprovals(t *testing.T) { captured := newNtfyCapture(t) store := newOperatorStore(t) if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatNeedsYou: false}); err != nil { t.Fatal(err) } h := chatAttentionHub(t, "ses_quiet") h.registry = store h.settings = store form := protocol.ChatForm{ID: "que_1", SessionID: "ses_quiet", Kind: "question", Title: "Ship?"} h.emit(protocol.ChatEventFrame{SessionID: "ses_quiet", Kind: protocol.ChatEventForm, Form: &form}) h.pushPermission("ses_quiet", protocol.ChatPermissionFrame{SessionID: "ses_quiet", RequestID: "per_1", Message: "Allow?"}) h.attentionWG.Wait() if got := captured(); len(got) != 0 { t.Fatalf("disabled chat_needs_you published %+v", got) } // Turning it back on announces new requests again. if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatNeedsYou: true}); err != nil { t.Fatal(err) } h.pushPermission("ses_quiet", protocol.ChatPermissionFrame{SessionID: "ses_quiet", RequestID: "per_2", Message: "Allow now?"}) h.attentionWG.Wait() if got := captured(); len(got) != 1 || got[0].Title != "Chat needs your approval" { t.Fatalf("re-enabled chat_needs_you = %+v", got) } } func replyTurn(h *chatHub, session, turnID, messageID, text string) { h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turnID}}) if text != "" { h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventText, MessageID: messageID, Part: &protocol.ChatPart{ID: messageID + "_p"}, Delta: text}) } // A provider step boundary inside the turn is not the end of the reply. h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turnID, Intermediate: true}}) h.emit(protocol.ChatEventFrame{SessionID: session, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turnID}}) } func TestChatReplyFinishedNotifiesOncePerTurn(t *testing.T) { t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com") captured := newNtfyCapture(t) store := newOperatorStore(t) ctx := context.Background() if err := store.RecordOperatorSession(ctx, "ses_done", t.TempDir(), "Release prep", protocol.ChatSessionTagOperator); err != nil { t.Fatal(err) } h := chatAttentionHub(t, "ses_done", "ses_bare") h.registry = store h.settings = store // Off by default: a finished turn is silent. replyTurn(h, "ses_done", "turn_0", "msg_0", "Quiet reply") h.attentionWG.Wait() if got := captured(); len(got) != 0 { t.Fatalf("default published %+v", got) } if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil { t.Fatal(err) } long := "The build\nis green. " + strings.Repeat("x", 300) replyTurn(h, "ses_done", "turn_1", "msg_1", long) // Duplicate and replayed ends of the same turn, including after a // reconnect builds a new room, publish nothing more. ended := protocol.ChatEventFrame{SessionID: "ses_done", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}} h.emit(ended) h.mu.Lock() h.rooms["ses_done"] = newChatRoom(context.Background(), "ses_done") h.mu.Unlock() h.emit(ended) h.emit(protocol.ChatEventFrame{SessionID: "ses_done", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}}) h.attentionWG.Wait() got := captured() if len(got) != 1 { t.Fatalf("deliveries = %+v", got) } wantBody := truncateRunes("The build is green. "+strings.Repeat("x", 300), chatReplyBodyRunes) want := ntfyCapture{Title: "Release prep replied", Message: wantBody, Click: "pipelines://chat/ses_done", Actions: "view, Open in browser, https://pipelines.example.com/chat/ses_done"} if got[0] != want { t.Fatalf("got %+v, want %+v", got[0], want) } // The next genuine turn notifies again; a turn without text (and a // session without a title or native turn ids) uses the fallback text. replyTurn(h, "ses_done", "turn_2", "msg_2", "Second answer") h.emit(protocol.ChatEventFrame{SessionID: "ses_bare", Kind: protocol.ChatEventUser, MessageID: "usr_1", Part: &protocol.ChatPart{ID: "u1", Text: "do it"}}) replyTurn(h, "ses_bare", "", "", "") h.attentionWG.Wait() got = captured() if len(got) != 3 { t.Fatalf("deliveries = %+v", got) } bodies := map[string]string{} for _, n := range got[1:] { bodies[n.Title] = n.Message } if bodies["Release prep replied"] != "Second answer" || bodies["Chat replied"] != chatReplyFallbackBody { t.Fatalf("later deliveries = %+v", got[1:]) } } func TestChatReplyFinishedNeedsNtfyConfiguration(t *testing.T) { t.Setenv("PIPELINES_NTFY_URL", "") store := newOperatorStore(t) if _, err := store.UpdateNotificationSettings(context.Background(), map[string]any{protocol.NotifyChatReplyFinished: true}); err != nil { t.Fatal(err) } h := chatAttentionHub(t, "ses_off") h.settings = store replyTurn(h, "ses_off", "turn_1", "msg_1", "hello") h.attentionWG.Wait() h.mu.Lock() defer h.mu.Unlock() if len(h.attentionSeen) != 0 { t.Fatalf("unconfigured ntfy still considered a publication: %v", h.attentionSeen) } }