package server import ( "context" "strings" "sync" "testing" "time" "git.a-wan.net/alan/pipelines/internal/chattools" "git.a-wan.net/alan/pipelines/internal/protocol" ) // lockedRuns is a run store a test can change while the service reads it. type lockedRuns struct { mu sync.Mutex runs map[int64]protocol.RunSummary } func (l *lockedRuns) RunSummaryByID(_ context.Context, id int64) (protocol.RunSummary, bool, error) { l.mu.Lock() defer l.mu.Unlock() run, ok := l.runs[id] return run, ok, nil } func (l *lockedRuns) set(run protocol.RunSummary) { l.mu.Lock() defer l.mu.Unlock() l.runs[run.ID] = run } func followupID(t *testing.T, r chattools.Result) string { t.Helper() _, rest, ok := strings.Cut(r.Text, "Scheduled follow-up ") if r.IsError || !ok { t.Fatalf("the result names the follow-up id: %v", r) } return strings.TrimSuffix(strings.Fields(rest)[0], ":") } func newFollowupFixture(t *testing.T) (*chatToolFixture, *lockedRuns) { t.Helper() f := newChatToolFixture(t) runs := &lockedRuns{runs: map[int64]protocol.RunSummary{}} f.service.runs = runs f.service.broker = newChannelChat() return f, runs } // awaitReleased waits until sessionID's follow-up was delivered to the broker // with want in its text, or requeued as due now with it. func awaitReleased(t *testing.T, f *chatToolFixture, sessionID, want string) { t.Helper() broker := f.service.broker.(*channelChat) deadline := time.Now().Add(5 * time.Second) for { for _, text := range broker.promptTexts() { if strings.Contains(text, want) { return } } for _, p := range f.service.pendingFollowups(sessionID) { if p.SendAt == 0 && strings.Contains(p.Text, want) { return } } if time.Now().After(deadline) { t.Fatalf("the follow-up was not released with %q: prompts %v, queue %+v", want, broker.promptTexts(), f.service.pendingFollowups(sessionID)) } time.Sleep(10 * time.Millisecond) } } // The schedule result names the id and lists what is pending; cancel_followup // removes exactly that follow-up. func TestScheduleFollowupReturnsTheIDAndCancelRemovesIt(t *testing.T) { f, _ := newFollowupFixture(t) token := f.token(t, chatToolSessionScope+"ses_c") first := f.call(token, "schedule_followup", `{"message":"one","after_minutes":30}`) id := followupID(t, first) if !strings.HasPrefix(id, chatFollowupPrefix) || !strings.Contains(first.Text, "Pending follow-ups (1 of 3): "+id+" (at ") { t.Fatalf("schedule result = %v", first) } second := followupID(t, f.call(token, "schedule_followup", `{"message":"two","after_minutes":60}`)) r := f.call(token, "cancel_followup", `{"id":"`+id+`"}`) if r.IsError || !strings.Contains(r.Text, "Canceled follow-up "+id) || !strings.Contains(r.Text, "(1 of 3): "+second) { t.Fatalf("cancel = %v", r) } if r := f.call(token, "cancel_followup", `{"id":"`+id+`"}`); !r.IsError || !strings.Contains(r.Text, "no pending follow-up") { t.Fatalf("a second cancel is refused: %v", r) } if r := f.call(token, "cancel_followup", `{"id":"op-1"}`); !r.IsError || !strings.Contains(r.Text, "not a follow-up id") { t.Fatalf("an operator prompt cannot be canceled: %v", r) } other := f.token(t, chatToolSessionScope+"ses_other") if r := f.call(other, "cancel_followup", `{"id":"`+second+`"}`); !r.IsError { t.Fatalf("another chat cannot cancel this chat's follow-up: %v", r) } if pending := f.service.pendingFollowups("ses_c"); len(pending) != 1 || pending[0].OperationID != second { t.Fatalf("pending = %+v", pending) } } // Concurrent schedules never exceed the pending bound. func TestScheduleFollowupBoundHoldsUnderConcurrency(t *testing.T) { f, _ := newFollowupFixture(t) token := f.token(t, chatToolSessionScope+"ses_k") var wg sync.WaitGroup var mu sync.Mutex accepted := 0 for i := 0; i < 12; i++ { wg.Add(1) go func() { defer wg.Done() if r := f.call(token, "schedule_followup", `{"message":"m","after_minutes":30}`); !r.IsError { mu.Lock() accepted++ mu.Unlock() } }() } wg.Wait() if pending := len(f.service.pendingFollowups("ses_k")); accepted != chattools.MaxPendingFollowups || pending != chattools.MaxPendingFollowups { t.Fatalf("accepted %d, pending %d", accepted, pending) } } func TestRunFollowupBounds(t *testing.T) { f, runs := newFollowupFixture(t) runs.set(protocol.RunSummary{ID: 5, Status: "succeeded", Outcome: "done"}) runs.set(protocol.RunSummary{ID: 6, Status: protocol.RunStatusWaiting, CurrentStage: "decide"}) token := f.token(t, chatToolSessionScope+"ses_bounds") for _, tc := range []struct{ args, want string }{ {`{"message":"m","run_id":99}`, "there is no run 99"}, {`{"message":"m","run_id":0}`, "positive run number"}, {`{"message":"m","run_id":5}`, "run 5 is already succeeded (done)"}, {`{"message":"m","run_id":6,"on":"attention"}`, "run 6 is already waiting waiting at stage decide"}, {`{"message":"m","run_id":6,"after_minutes":5}`, "not both"}, {`{"message":"m","on":"finished","after_minutes":5}`, "on needs run_id"}, } { if r := f.call(token, "schedule_followup", tc.args); !r.IsError || !strings.Contains(r.Text, tc.want) { t.Errorf("%s: got %v, want %q", tc.args, r, tc.want) } } // A run waiting on a person has not finished: on finished still waits. if r := f.call(token, "schedule_followup", `{"message":"m","run_id":6}`); r.IsError || !strings.Contains(r.Text, "when run 6 finishes") { t.Fatalf("finished follow-up on a waiting run = %v", r) } } // A run-triggered follow-up stays pending while the run works and is // released, with the run's state, once the run needs the operator. func TestRunFollowupIsDeliveredWhenTheRunNeedsAttention(t *testing.T) { previous := shownRunRefreshDelay shownRunRefreshDelay = 10 * time.Millisecond t.Cleanup(func() { shownRunRefreshDelay = previous }) f, runs := newFollowupFixture(t) runs.set(protocol.RunSummary{ID: 7, Status: "running", CurrentStage: "implement"}) token := f.token(t, chatToolSessionScope+"ses_t") r := f.call(token, "schedule_followup", `{"message":"check run 7","run_id":7,"on":"attention"}`) id := followupID(t, r) if !strings.HasPrefix(id, chatRunFollowupPrefix+"7-attention-") || !strings.Contains(r.Text, "when run 7 needs the operator or finishes") { t.Fatalf("schedule = %v", r) } pending := f.service.pendingFollowups("ses_t") if len(pending) != 1 || pending[0].SendAt <= time.Now().Add(6*24*time.Hour).UnixMilli() { t.Fatalf("the follow-up waits with a 7-day deadline: %+v", pending) } f.service.observeRun(protocol.RunEventFrame{RunID: 7}) time.Sleep(50 * time.Millisecond) if p := f.service.pendingFollowups("ses_t"); len(p) != 1 || p[0].SendAt == 0 { t.Fatalf("a still-running run keeps the follow-up waiting: %+v", p) } runs.set(protocol.RunSummary{ID: 7, Status: protocol.RunStatusWaiting, CurrentStage: "decide"}) f.service.observeRun(protocol.RunEventFrame{RunID: 7}) awaitReleased(t, f, "ses_t", "run 7 is now waiting waiting at stage decide") f.service.followups.mu.Lock() watched := len(f.service.followups.items[7]) f.service.followups.mu.Unlock() if watched != 0 { t.Fatal("a released follow-up is no longer watched") } } // After a restart the restored queue re-arms the watch, and a run that // finished meanwhile releases its follow-up at once. func TestRunFollowupsResumeAfterRestart(t *testing.T) { f, runs := newFollowupFixture(t) runs.set(protocol.RunSummary{ID: 8, Status: "running"}) token := f.token(t, chatToolSessionScope+"ses_r") followupID(t, f.call(token, "schedule_followup", `{"message":"after restart","run_id":8}`)) // Forget the in-memory watch, as a restarted server would have. f.service.followups.mu.Lock() f.service.followups.items = nil f.service.followups.mu.Unlock() runs.set(protocol.RunSummary{ID: 8, Status: "failed", Outcome: "error", CurrentStage: "review"}) f.service.resumeRunFollowups(context.Background()) awaitReleased(t, f, "ses_r", "run 8 is now failed (error) at stage review") } func TestShowHTMLWarnsAboutBlockedResourcesAndLightOnlyPages(t *testing.T) { for _, tc := range []struct { html string want []string none bool }{ {html: `

ok link

`, none: true}, {html: ``, want: []string{"JavaScript", "1 remote resource(s) (such as https://cdn.example.com/chart.js)"}}, {html: `
`, want: []string{"2 remote resource(s)", "always shown light"}}, {html: ``, want: []string{"JavaScript"}}, } { warnings := strings.Join(shownHTMLWarnings(tc.html), " ") if tc.none && warnings != "" { t.Errorf("%s: unexpected warnings %q", tc.html, warnings) } for _, want := range tc.want { if !strings.Contains(warnings, want) { t.Errorf("%s: warnings %q lack %q", tc.html, warnings, want) } } } f := newChatToolFixture(t) token := f.token(t, chatToolSessionScope+"ses_h") if r := f.call(token, "show_html", `{"html":"

hi

"}`); r.IsError || !strings.Contains(r.Text, "Warning: it contains JavaScript") || !strings.Contains(r.Text, "always shown light") { t.Fatalf("show_html result = %v", r) } } func TestAmbiguousCallAdviceFitsTheTool(t *testing.T) { for tool, want := range map[string]string{ chattools.ToolShowHTML: "different title", chattools.ToolShowRun: "different title", chattools.ToolNotify: "message wording", chattools.ToolScheduleFollowup: "message wording", chattools.ToolCancelFollowup: "in a moment", } { if got := ambiguousCallAdvice(tool); !strings.Contains(got, want) { t.Errorf("%s: %q lacks %q", tool, got, want) } } }