Merge branch 'main' into pipelines/run-20261112-0138-sync-open-chats-across-devices-on-the-se-9f86
# Conflicts: # app/lib/features/chat/chat_screen_keys.dart # app/lib/features/chat/chat_screen_workspace.dart
This commit is contained in:
@@ -39,25 +39,37 @@ type appNotifier struct {
|
||||
}
|
||||
|
||||
type appNotificationSub struct {
|
||||
queue chan protocol.Message
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
ctx context.Context
|
||||
requestID string
|
||||
started time.Time
|
||||
queue chan protocol.Message
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
ended sync.Once
|
||||
}
|
||||
|
||||
func newAppNotifier(store appNotificationStore) *appNotifier {
|
||||
return &appNotifier{store: store, now: time.Now, subs: map[string]*appNotificationSub{}}
|
||||
}
|
||||
|
||||
func (s *appNotificationSub) stop() { s.once.Do(func() { close(s.done) }) }
|
||||
func (s *appNotificationSub) stop(reason string) {
|
||||
s.once.Do(func() { close(s.done) })
|
||||
s.ended.Do(func() {
|
||||
log.Printf("notification subscription ended request_id=%q duration=%s reason=%s", s.requestID, time.Since(s.started), reason)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *appNotificationSub) run(write func(protocol.Message) error) {
|
||||
for {
|
||||
select {
|
||||
case <-s.done:
|
||||
return
|
||||
case <-s.ctx.Done():
|
||||
s.stop("server stopping")
|
||||
return
|
||||
case msg := <-s.queue:
|
||||
if write(msg) != nil {
|
||||
s.stop()
|
||||
s.stop("write error")
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -77,7 +89,7 @@ func (a *appNotifier) enqueueLocked(msg protocol.Message, exclude string) {
|
||||
delete(a.subs, id)
|
||||
default:
|
||||
log.Printf("app notifications: dropping slow subscriber %s", id)
|
||||
sub.stop()
|
||||
sub.stop("write error")
|
||||
delete(a.subs, id)
|
||||
}
|
||||
}
|
||||
@@ -93,11 +105,15 @@ func (a *appNotifier) subscribe(ctx context.Context, clientID, requestID, after
|
||||
return err
|
||||
}
|
||||
if old := a.subs[clientID]; old != nil {
|
||||
old.stop()
|
||||
old.stop("client closed")
|
||||
}
|
||||
sub := &appNotificationSub{
|
||||
ctx: ctx, requestID: requestID, started: time.Now(),
|
||||
queue: make(chan protocol.Message, appNotificationQueue), done: make(chan struct{}),
|
||||
}
|
||||
sub := &appNotificationSub{queue: make(chan protocol.Message, appNotificationQueue), done: make(chan struct{})}
|
||||
sub.queue <- protocol.Message{Type: protocol.NotificationsSubscribed, ID: requestID, Notifications: active, IDs: cleared}
|
||||
a.subs[clientID] = sub
|
||||
log.Printf("notification subscription started request_id=%q cursor=%q", requestID, after)
|
||||
go sub.run(write)
|
||||
return nil
|
||||
}
|
||||
@@ -106,7 +122,11 @@ func (a *appNotifier) detach(clientID string) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if sub := a.subs[clientID]; sub != nil {
|
||||
sub.stop()
|
||||
reason := "client closed"
|
||||
if sub.ctx.Err() != nil {
|
||||
reason = "server stopping"
|
||||
}
|
||||
sub.stop(reason)
|
||||
delete(a.subs, clientID)
|
||||
}
|
||||
}
|
||||
@@ -290,6 +310,8 @@ func runNotificationKind(event string) string {
|
||||
return protocol.NotificationRunWaiting
|
||||
case "failed":
|
||||
return protocol.NotificationRunFailed
|
||||
case "interrupted":
|
||||
return protocol.NotificationRunFailed
|
||||
case "succeeded":
|
||||
return protocol.NotificationRunSucceeded
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -17,6 +20,30 @@ import (
|
||||
"git.a-wan.net/alan/pipelines/internal/summarise"
|
||||
)
|
||||
|
||||
func TestAppNotificationSubscriptionLogsLifecycle(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
f := newAppNotificationFixture(t, ctx)
|
||||
var output bytes.Buffer
|
||||
previous := log.Writer()
|
||||
log.SetOutput(&output)
|
||||
t.Cleanup(func() { log.SetOutput(previous) })
|
||||
|
||||
phone := dialAckClient(t, ctx, f.url)
|
||||
subscribeNotifications(t, ctx, phone, "cursor-1")
|
||||
if !strings.Contains(output.String(), `notification subscription started request_id="sub" cursor="cursor-1"`) {
|
||||
t.Fatalf("subscription start log = %q", output.String())
|
||||
}
|
||||
phone.CloseNow()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for !strings.Contains(output.String(), `notification subscription ended request_id="sub"`) && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if !strings.Contains(output.String(), `notification subscription ended request_id="sub"`) || !strings.Contains(output.String(), "reason=client closed") {
|
||||
t.Fatalf("subscription end log = %q", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
// appNotificationFixture is a handler over a temp store with one pipeline,
|
||||
// plus helpers to make a run end with a durable notification intent.
|
||||
type appNotificationFixture struct {
|
||||
@@ -50,6 +77,25 @@ func newAppNotificationFixture(t *testing.T, ctx context.Context) *appNotificati
|
||||
return &appNotificationFixture{t: t, ctx: ctx, store: store, runner: handler.(*runHandler).runner, url: srv.URL, def: def}
|
||||
}
|
||||
|
||||
func TestToolNotificationRecordsAppNotificationWhenNtfyDisabled(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newOperatorStore(t)
|
||||
if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: false}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hub := &chatHub{notes: newAppNotifier(store), settings: store}
|
||||
if ok, diagnostic := hub.publishToolNotification(ctx, "session-1", "Build failed", "Please inspect the run"); !ok || diagnostic != "" {
|
||||
t.Fatalf("tool notification result = %v, %q", ok, diagnostic)
|
||||
}
|
||||
active, _, err := store.ActiveAppNotifications(ctx, "", time.Now())
|
||||
if err != nil || len(active) != 1 {
|
||||
t.Fatalf("app notifications = %+v, %v", active, err)
|
||||
}
|
||||
if active[0].Kind != protocol.NotificationChatReply || active[0].Title != "Build failed" || active[0].Message != "Please inspect the run" {
|
||||
t.Fatalf("wrong tool notification: %+v", active[0])
|
||||
}
|
||||
}
|
||||
|
||||
// failRun creates a "Notify me" run and fails it, which commits a durable run
|
||||
// notification intent in the same transaction, then drains the outbox.
|
||||
func (f *appNotificationFixture) failRun(name string) int64 {
|
||||
|
||||
@@ -2,6 +2,8 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
@@ -12,6 +14,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
@@ -128,14 +131,20 @@ type chatToolNotifier func(ctx context.Context, sessionID, title, message string
|
||||
// ntfy destination (the one chat attention uses), honoring their ntfy switch.
|
||||
// Tapping it opens the chat (pipelines://chat/<id>).
|
||||
func (h *chatHub) publishToolNotification(ctx context.Context, sessionID, title, message string) (bool, string) {
|
||||
if !chatAttentionConfigured() {
|
||||
return false, "phone notifications (ntfy) are not configured on this Pipelines server"
|
||||
}
|
||||
if !chatNotificationSettings(ctx, h.settings).NtfyEnabled {
|
||||
return false, "the operator has turned phone notifications off"
|
||||
}
|
||||
title = truncateUTF8(title, 256)
|
||||
message = truncateUTF8(message, 2000)
|
||||
click, views := chatAttentionLinks(sessionID)
|
||||
if _, err := chatAttentionPublish(ctx, "system", truncateUTF8(title, 256), truncateUTF8(message, 2000), "", nil, click, views...); err != nil {
|
||||
digest := sha256.Sum256([]byte(title + "\x00" + message))
|
||||
if h.notes != nil {
|
||||
h.notes.record(ctx, pipeline.AppNotificationRecord{
|
||||
AppNotification: protocol.AppNotification{ID: "chat:" + sessionID + ":notify:" + hex.EncodeToString(digest[:8]), Kind: protocol.NotificationChatReply, Title: title, Message: message, Click: click, Priority: protocol.DefaultNotificationPriority, Tags: []string{}, Group: "chat:" + sessionID},
|
||||
SessionID: sessionID,
|
||||
})
|
||||
}
|
||||
if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled {
|
||||
return true, ""
|
||||
}
|
||||
if _, err := chatAttentionPublish(ctx, "system", title, message, "", nil, click, views...); err != nil {
|
||||
log.Printf("chat tool notification session=%s: %v", sessionID, err)
|
||||
return false, "the notification service refused it: " + err.Error()
|
||||
}
|
||||
|
||||
@@ -229,8 +229,8 @@ func runAttentionEvent(status string) string {
|
||||
switch strings.TrimSpace(strings.ToLower(status)) {
|
||||
case protocol.RunStatusWaiting:
|
||||
return protocol.NotifyWaiting
|
||||
case "failed":
|
||||
return "failed"
|
||||
case "failed", "interrupted":
|
||||
return strings.TrimSpace(strings.ToLower(status))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -375,9 +375,9 @@ func (r *runner) notifyRun(id int64, name, status string, sequence int, currentS
|
||||
if event == "" {
|
||||
return
|
||||
}
|
||||
// A run's end notifies only runs marked "on", unless the operator opted
|
||||
// into every run end (run_finished); waiting notifies any non-off run.
|
||||
if event != protocol.NotifyWaiting && r.notifyMode(id) != "on" {
|
||||
// Failed or interrupted runs always notify; successful runs notify only when
|
||||
// marked "on" or when the operator opted into every run end (run_finished).
|
||||
if event == "succeeded" || (event != protocol.NotifyWaiting && event != "failed" && event != "interrupted") {
|
||||
settings, err := r.store.NotificationSettings(r.ctx)
|
||||
if err != nil || !settings.RunFinished {
|
||||
return
|
||||
@@ -392,6 +392,10 @@ func (r *runner) notifyRun(id int64, name, status string, sequence int, currentS
|
||||
title = "Run failed"
|
||||
summary = fmt.Sprintf("Run #%d · %s · run failed", id, name)
|
||||
}
|
||||
if event == "interrupted" {
|
||||
title = "Run interrupted"
|
||||
summary = fmt.Sprintf("Run #%d · %s · run interrupted", id, name)
|
||||
}
|
||||
if event == "succeeded" {
|
||||
title = "Run succeeded"
|
||||
summary = fmt.Sprintf("Run #%d · %s · run succeeded", id, name)
|
||||
|
||||
@@ -105,8 +105,8 @@ func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Regress the terminal-path recipe from the authoring guide (research -> report
|
||||
// there) on the bundled two-stage example's draft -> check.
|
||||
// Regress the terminal-path recipe from the authoring guide on the bundled
|
||||
// research -> report starter.
|
||||
// A completion-alert request must not require native delivery or change run routing.
|
||||
func TestTerminalNotificationRecipe(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -118,15 +118,14 @@ func TestTerminalNotificationRecipe(t *testing.T) {
|
||||
defer store.Close()
|
||||
var source string
|
||||
for _, template := range examples.Catalog() {
|
||||
if template.Key == "two-stages" {
|
||||
if template.Key == "research" {
|
||||
source = template.Source
|
||||
}
|
||||
}
|
||||
if source == "" {
|
||||
t.Fatal("two-stages template missing")
|
||||
t.Fatal("research template missing")
|
||||
}
|
||||
source = strings.Replace(source, "# stage draft", "# stage draft\n```notify\non=failure\n```", 1)
|
||||
source = strings.Replace(source, "# stage check", "# stage check\n```notify\non=success,failure\n```", 1)
|
||||
source = strings.Replace(source, "# stage report", "# stage report\n```notify\non=success,failure\n```", 1)
|
||||
if _, err = store.Submit(ctx, "research notification recipe", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -160,12 +159,12 @@ func TestTerminalNotificationRecipe(t *testing.T) {
|
||||
name, stage, outcome, status string
|
||||
executionError, deliveryError bool
|
||||
}{
|
||||
{"success", "check", "success", "succeeded", false, false},
|
||||
{"draft blocked", "draft", "blocked", "failed", false, false},
|
||||
{"draft execution error", "draft", "error", "failed", true, false},
|
||||
{"check blocked", "check", "blocked", "failed", false, false},
|
||||
{"check execution error", "check", "error", "failed", true, false},
|
||||
{"delivery error preserves success", "check", "success", "succeeded", false, true},
|
||||
{"success", "report", "success", "succeeded", false, false},
|
||||
{"research blocked", "research", "blocked", "failed", false, false},
|
||||
{"research execution error", "research", "error", "failed", true, false},
|
||||
{"report blocked", "report", "blocked", "failed", false, false},
|
||||
{"report execution error", "report", "error", "failed", true, false},
|
||||
{"delivery error preserves success", "report", "success", "succeeded", false, true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
deliveryFailure.Store(test.deliveryError)
|
||||
@@ -278,7 +277,7 @@ func TestRunAttentionEventMapping(t *testing.T) {
|
||||
{"running", ""},
|
||||
{"succeeded", ""},
|
||||
{"canceled", ""},
|
||||
{"interrupted", ""},
|
||||
{"interrupted", "interrupted"},
|
||||
{"", ""},
|
||||
} {
|
||||
if got := runAttentionEvent(test.status); got != test.want {
|
||||
@@ -320,7 +319,7 @@ func TestRunAttentionNotificationDelivery(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A run that needs nobody publishes nothing.
|
||||
for _, status := range []string{"queued", "running", "succeeded", "canceled", "interrupted"} {
|
||||
for _, status := range []string{"queued", "running", "succeeded", "canceled"} {
|
||||
r.notifyRun(7, "release", status, 1, "build", "")
|
||||
}
|
||||
select {
|
||||
@@ -332,7 +331,7 @@ func TestRunAttentionNotificationDelivery(t *testing.T) {
|
||||
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
|
||||
// A run that stays waiting is never republished, on a later call or a re-request.
|
||||
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
|
||||
// An auto run's failure is silent: only runs marked "on" announce their end.
|
||||
// An auto run's failure announces its end.
|
||||
r.notifyRun(8, "release", "failed", 2, "deploy", "provider returned 500")
|
||||
// A failed run marked "on" publishes once, with its diagnostic.
|
||||
r.setNotifyMode(7, "on")
|
||||
@@ -352,12 +351,16 @@ func TestRunAttentionNotificationDelivery(t *testing.T) {
|
||||
t.Fatalf("notification leaked an authorization header: %q", first.authorization)
|
||||
}
|
||||
second := <-deliveries
|
||||
if second.title != "Run failed" || !strings.Contains(second.message, "Run #7") || !strings.Contains(second.message, "release") || !strings.Contains(second.message, "deploy") || !strings.Contains(second.message, "provider returned 500") {
|
||||
if second.title != "Run failed" || !strings.Contains(second.message, "Run #8") {
|
||||
t.Fatalf("failed notification is not actionable: %+v", second)
|
||||
}
|
||||
if second.click != "pipelines://run/7" || second.actions != "view, Open in browser, https://pipelines.example.com/runs/7" {
|
||||
if second.click != "pipelines://run/8" || second.actions != "view, Open in browser, https://pipelines.example.com/runs/8" {
|
||||
t.Fatalf("failed notification click does not open the run: %q", second.click)
|
||||
}
|
||||
third := <-deliveries
|
||||
if third.title != "Run failed" || !strings.Contains(third.message, "Run #7") {
|
||||
t.Fatalf("marked failed notification is not actionable: %+v", third)
|
||||
}
|
||||
select {
|
||||
case got := <-deliveries:
|
||||
t.Fatalf("third notification delivered for two genuine events: %+v", got)
|
||||
|
||||
@@ -334,16 +334,15 @@ func TestRunNotificationAttentionModesAndRetryBound(t *testing.T) {
|
||||
r.notifyRun(id, "test", status, sequence, "stage", "")
|
||||
}
|
||||
}
|
||||
// auto waiting, on waiting and on failed; an auto run's failure is silent
|
||||
// because run_finished defaults off.
|
||||
if calls.Load() != 3 {
|
||||
t.Fatalf("attention modes: %d calls, want 3", calls.Load())
|
||||
// auto and on waiting, plus auto and on failed; off never notifies.
|
||||
if calls.Load() != 4 {
|
||||
t.Fatalf("attention modes: %d calls, want 4", calls.Load())
|
||||
}
|
||||
r.deliverRunNotifications(time.Now().Add(time.Minute))
|
||||
r.deliverRunNotifications(time.Now().Add(2 * time.Minute))
|
||||
r.deliverRunNotifications(time.Now().Add(3 * time.Minute))
|
||||
if calls.Load() != 9 {
|
||||
t.Fatalf("retry bound: %d calls, want 9", calls.Load())
|
||||
if calls.Load() != 12 {
|
||||
t.Fatalf("retry bound: %d calls, want 12", calls.Load())
|
||||
}
|
||||
for _, id := range []int64{1, 2, 3} {
|
||||
got, err := s.RunNotifications(ctx, id)
|
||||
|
||||
Reference in New Issue
Block a user