package server import ( "context" "errors" "path/filepath" "sync" "testing" "time" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" ) func TestRunNotificationAppClick(t *testing.T) { if got := runAttentionClick(20); got != "pipelines://run/20" { t.Fatalf("click = %q", got) } if got := chatAttentionClick("ses/x"); got != "pipelines://chat/ses%2Fx" { t.Fatalf("chat click = %q", got) } } // recordingNotes wraps an app notification store and keeps every newly // recorded notification, in order, so a test sees exactly what the app stream // was given (also after a clear). fail makes every record fail, failNext the // next few; calls counts every attempt, failed or not. type recordingNotes struct { appNotificationStore mu sync.Mutex got []protocol.AppNotification fail bool failNext int calls int } func (r *recordingNotes) RecordAppNotification(ctx context.Context, n pipeline.AppNotificationRecord, now time.Time) (protocol.AppNotification, bool, error) { r.mu.Lock() r.calls++ fail := r.fail || r.failNext > 0 if r.failNext > 0 { r.failNext-- } r.mu.Unlock() if fail { return protocol.AppNotification{}, false, errors.New("record refused") } stored, fresh, err := r.appNotificationStore.RecordAppNotification(ctx, n, now) if err == nil && fresh { r.mu.Lock() r.got = append(r.got, stored) r.mu.Unlock() } return stored, fresh, err } func (r *recordingNotes) attempts() int { r.mu.Lock() defer r.mu.Unlock() return r.calls } func (r *recordingNotes) recorded() []protocol.AppNotification { r.mu.Lock() defer r.mu.Unlock() return append([]protocol.AppNotification(nil), r.got...) } // newNoteCapture returns an app notifier over store (a scratch store when // nil) and a reader of everything it recorded. func newNoteCapture(t *testing.T, store *pipeline.Store) (*appNotifier, *recordingNotes) { t.Helper() if store == nil { store = newOperatorStore(t) } recorder := &recordingNotes{appNotificationStore: store} return newAppNotifier(recorder), recorder } // Rows queued by older servers hold a web URL, the old placeholder deep link or // an empty click (an invalid web origin). Each is recorded with the app link. func TestQueuedLegacyRunNotificationsUseAppLink(t *testing.T) { ctx := context.Background() s, err := pipeline.Open(filepath.Join(t.TempDir(), "legacy.db")) if err != nil { t.Fatal(err) } defer s.Close() clicks := map[int64]string{7: "https://pipelines.example.com/runs/7", 8: "pipelines://run/8", 9: ""} for id, click := range clicks { if err := s.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "failed", Channel: "system", Title: "Run failed", Body: "Run failed", Click: click}); err != nil { t.Fatal(err) } } notes, recorder := newNoteCapture(t, s) r := &runner{ctx: ctx, store: s, notes: notes} r.deliverRunNotifications(time.Now()) got := recorder.recorded() if len(got) != 3 { t.Fatalf("deliveries = %+v", got) } seen := map[string]bool{} for _, n := range got { seen[n.Click] = true } for _, click := range []string{"pipelines://run/7", "pipelines://run/8", "pipelines://run/9"} { if !seen[click] { t.Fatalf("missing %s in %+v", click, got) } } for id := range clicks { rows, err := s.RunNotifications(ctx, id) if err != nil || len(rows) != 1 || rows[0].Status != "sent" { t.Fatalf("run %d rows = %+v %v", id, rows, err) } } } func chatAttentionHub(t *testing.T, sessions ...string) *chatHub { t.Helper() h := newChatHub() for _, id := range sessions { h.rooms[id] = newChatRoom(context.Background(), id) } return h } func TestChatQuestionNotifiesOnceWithAppLink(t *testing.T) { store := newOperatorStore(t) if err := store.RecordOperatorSession(context.Background(), "ses_q", t.TempDir(), "Release prep", protocol.ChatSessionTagOperator); err != nil { t.Fatal(err) } h := chatAttentionHub(t, "ses_q") h.registry = store notes, recorder := newNoteCapture(t, store) h.notes = notes form := protocol.ChatForm{ID: "que_1", SessionID: "ses_q", Kind: "question", Title: "Which branch\nshould ship?"} frame := protocol.ChatEventFrame{SessionID: "ses_q", Kind: protocol.ChatEventForm, Form: &form} h.emit(frame) h.emit(frame) // duplicate live event // A reconnect builds a new room whose readback re-emits the pending form. h.mu.Lock() h.rooms["ses_q"] = newChatRoom(context.Background(), "ses_q") h.mu.Unlock() h.emit(frame) h.attentionWG.Wait() got := recorder.recorded() if len(got) != 1 { t.Fatalf("deliveries = %+v", got) } if n := got[0]; n.Title != "Release prep needs your answer" || n.Message != "Which branch should ship?" || n.Click != "pipelines://chat/ses_q" { t.Fatalf("got %+v", n) } // Resolution and a later stale copy record nothing more. resolved := form resolved.Resolved = true h.emit(protocol.ChatEventFrame{SessionID: "ses_q", Kind: protocol.ChatEventForm, Form: &resolved}) h.attentionWG.Wait() if n := len(recorder.recorded()); n != 1 { t.Fatalf("resolution re-recorded: %d", n) } } func TestChatResolvedOrReplayedFormsDoNotNotify(t *testing.T) { h := chatAttentionHub(t, "ses_r") notes, recorder := newNoteCapture(t, nil) h.notes = notes resolved := protocol.ChatForm{ID: "que_old", SessionID: "ses_r", Kind: "question", Title: "Old?", Resolved: true} cancelled := protocol.ChatForm{ID: "que_gone", SessionID: "ses_r", Kind: "question", Title: "Gone?", Cancelled: true} h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventForm, Form: &resolved}) h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventForm, Form: &cancelled}) // A stale unresolved copy of an already-resolved form is not announced. stale := resolved stale.Resolved = false h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventForm, Form: &stale}) // Ordinary reply frames never notify. h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventText, MessageID: "msg_1", Part: &protocol.ChatPart{ID: "p1"}, Delta: "done"}) h.emit(protocol.ChatEventFrame{SessionID: "ses_r", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}}) h.attentionWG.Wait() if got := recorder.recorded(); len(got) != 0 { t.Fatalf("unexpected deliveries %+v", got) } } func TestChatPermissionNotifiesOnce(t *testing.T) { h := chatAttentionHub(t, "ses_p") notes, recorder := newNoteCapture(t, nil) h.notes = notes frame := protocol.ChatPermissionFrame{SessionID: "ses_p", RequestID: "per_1", Action: "bash", Message: "Run rm -rf build?"} h.pushPermission("ses_p", frame) h.pushPermission("ses_p", frame) // The last subscriber left; a reconnect replays the pending request. h.mu.Lock() h.rooms["ses_p"] = newChatRoom(context.Background(), "ses_p") h.mu.Unlock() h.pushPermission("ses_p", frame) resolved := protocol.ChatPermissionFrame{SessionID: "ses_p", RequestID: "per_2", Message: "Already answered", Resolved: true} h.pushPermission("ses_p", resolved) h.attentionWG.Wait() got := recorder.recorded() if len(got) != 1 || got[0].Title != "Chat needs your approval" || got[0].Message != "Run rm -rf build?" || got[0].Click != "pipelines://chat/ses_p" { t.Fatalf("deliveries = %+v", got) } } // Without the app notification stream a chat attention item has nowhere to // go, so it is not even claimed. func TestChatAttentionNeedsTheAppStream(t *testing.T) { h := chatAttentionHub(t, "ses_n") form := protocol.ChatForm{ID: "que_1", SessionID: "ses_n", Kind: "question", Title: "Ready?"} h.emit(protocol.ChatEventFrame{SessionID: "ses_n", Kind: protocol.ChatEventForm, Form: &form}) h.pushPermission("ses_n", protocol.ChatPermissionFrame{SessionID: "ses_n", RequestID: "per_1", Message: "Allow?"}) h.attentionWG.Wait() if len(h.attentionSeen) != 0 { t.Fatalf("claimed without a notification stream: %v", h.attentionSeen) } } // A failing notification store never blocks or fails chat handling. func TestChatAttentionFailureIsOnlyLogged(t *testing.T) { h := chatAttentionHub(t, "ses_f") notes, recorder := newNoteCapture(t, nil) recorder.fail = true h.notes = notes form := protocol.ChatForm{ID: "que_1", SessionID: "ses_f", Kind: "question", Title: "Ready?"} h.emit(protocol.ChatEventFrame{SessionID: "ses_f", Kind: protocol.ChatEventForm, Form: &form}) h.attentionWG.Wait() if forms := h.pendingForms("ses_f"); len(forms) != 1 || forms[0].ID != "que_1" { t.Fatalf("chat state disturbed: %+v", forms) } }