Files
pipelines/internal/server/chat_tools_items_test.go
T

225 lines
9.2 KiB
Go

package server
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/chattools"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func shownID(t *testing.T, r chattools.Result) string {
t.Helper()
_, rest, ok := strings.Cut(r.Text, "Item id: ")
if r.IsError || !ok {
t.Fatalf("the result names the item id: %v", r)
}
return strings.Fields(rest)[0]
}
func TestUnknownOrMisnamedArgumentsAreRefused(t *testing.T) {
f := newChatToolFixture(t)
token := f.token(t, chatToolSessionScope+"ses_v")
for _, tc := range []struct{ tool, args, want string }{
{"show_file", `{"file":"a.txt"}`, `unknown argument "file"; show_file takes path (required), replace, title`},
{"show_html", `{"html":"<p>","heigth_hint":200}`, `unknown argument "heigth_hint"`},
{"show_image", `{"path":"a.png"}`, "show_image takes url_or_path (required)"},
{"show_run", `{"run_id":"7"}`, "run_id must be an integer"},
{"notify", `{"title":"t","body":"m"}`, `unknown argument "body"`},
} {
r := f.call(token, tc.tool, tc.args)
if !r.IsError || !strings.Contains(r.Text, tc.want) {
t.Errorf("%s %s: got %v, want %q", tc.tool, tc.args, r, tc.want)
}
}
if len(f.items(t, "ses_v")) != 0 || len(f.notified) != 0 {
t.Fatal("a refused call does nothing")
}
}
func TestReplaceUpdatesAnItemInPlace(t *testing.T) {
f := newChatToolFixture(t)
token := f.token(t, chatToolSessionScope+"ses_p")
other := f.token(t, chatToolSessionScope+"ses_q")
first := shownID(t, f.call(token, "show_html", `{"html":"<p>v1</p>","title":"Chart"}`))
shownID(t, f.call(token, "show_html", `{"html":"<p>later</p>"}`))
created := f.items(t, "ses_p")[0].CreatedAt
f.service.now = func() time.Time { return time.UnixMilli(created + 5000) }
r := f.call(token, "show_html", `{"html":"<p>v2</p>","title":"Chart","replace":"`+first+`"}`)
if r.IsError || !strings.Contains(r.Text, "Updated item "+first+" in place") {
t.Fatalf("replace: %v", r)
}
items := f.items(t, "ses_p")
if len(items) != 2 || items[0].ID != first || items[0].HTML != "<p>v2</p>" || items[0].CreatedAt != created || items[0].UpdatedAt != created+5000 {
t.Fatalf("the replaced item keeps its id and place: %+v", items)
}
for _, tc := range []struct{ token, tool, args, want string }{
{token, "show_diff", `{"replace":"` + first + `"}`, "is a html item; show_diff can only replace diff"},
{token, "show_html", `{"html":"x","replace":"shown_nope"}`, "is not an item shown in this chat"},
{other, "show_html", `{"html":"x","replace":"` + first + `"}`, "is not an item shown in this chat"},
} {
if r := f.call(tc.token, tc.tool, tc.args); !r.IsError || !strings.Contains(r.Text, tc.want) {
t.Errorf("%s: got %v, want %q", tc.args, r, tc.want)
}
}
if len(f.items(t, "ses_q")) != 0 {
t.Fatal("another chat's item cannot be replaced")
}
}
func TestShownFilesAreSnapshotsOrTrackedForChanges(t *testing.T) {
f := newChatToolFixture(t)
token := f.token(t, chatToolSessionScope+"ses_n")
small := filepath.Join(f.home, "small.txt")
large := filepath.Join(f.home, "large.log")
gone := filepath.Join(f.home, "gone.log")
write := func(path string, size int, fill byte) {
t.Helper()
if err := os.WriteFile(path, []byte(strings.Repeat(string(fill), size)), 0o600); err != nil {
t.Fatal(err)
}
}
write(small, 10, 'a')
write(large, chattools.MaxSnapshotBytes+1, 'b')
write(gone, chattools.MaxSnapshotBytes+1, 'c')
smallID := shownID(t, f.call(token, "show_file", `{"path":"`+small+`"}`))
shownID(t, f.call(token, "show_file", `{"path":"`+large+`"}`))
shownID(t, f.call(token, "show_file", `{"path":"`+gone+`"}`))
items := f.items(t, "ses_n")
if !items[0].Snapshot || items[1].Snapshot || items[1].SHA256 == "" || items[1].ModTime == 0 {
t.Fatalf("small files are copied, large ones tracked: %+v", items)
}
write(small, 12, 'z')
later := time.Now().Add(time.Minute)
write(large, chattools.MaxSnapshotBytes+1, 'B')
if err := os.Chtimes(large, later, later); err != nil {
t.Fatal(err)
}
if err := os.Remove(gone); err != nil {
t.Fatal(err)
}
frame := f.hub.shownFrame("ses_n")
if frame == nil || len(frame.Items) != 3 {
t.Fatalf("frame = %+v", frame)
}
if got := []string{frame.Items[0].State, frame.Items[1].State, frame.Items[2].State}; got[0] != "" || got[1] != protocol.ChatShownFileChanged || got[2] != protocol.ChatShownFileMissing {
t.Fatalf("states = %q (the snapshot still shows what was shown)", got)
}
if data, _ := os.ReadFile(frame.Items[0].Path); string(data) != strings.Repeat("a", 10) {
t.Fatalf("the snapshot keeps the shown version: %q", data)
}
// Replacing a snapshot item copies the new version; the old copy is swept
// once it is past the grace period.
oldDir := filepath.Dir(items[0].Path)
f.service.now = func() time.Time { return time.Now().Add(2 * shownSnapshotGrace) }
if r := f.call(token, "show_file", `{"path":"`+small+`","replace":"`+smallID+`"}`); r.IsError {
t.Fatal(r.Text)
}
replaced := f.items(t, "ses_n")[0]
if data, _ := os.ReadFile(replaced.Path); replaced.ID != smallID || string(data) != strings.Repeat("z", 12) {
t.Fatalf("replaced snapshot = %+v %q", replaced, data)
}
if _, err := os.Stat(oldDir); !os.IsNotExist(err) {
t.Fatalf("the replaced snapshot is swept: %v", err)
}
}
type fakeShownRuns map[int64]protocol.RunSummary
func (f fakeShownRuns) RunSummaryByID(_ context.Context, id int64) (protocol.RunSummary, bool, error) {
run, ok := f[id]
return run, ok, nil
}
func TestShowRunFollowsTheRun(t *testing.T) {
previous := shownRunRefreshDelay
shownRunRefreshDelay = 10 * time.Millisecond
t.Cleanup(func() { shownRunRefreshDelay = previous })
f := newChatToolFixture(t)
runs := fakeShownRuns{7: {ID: 7, Name: "feature", Title: "Add the run card", Status: "running", CurrentStage: "implement", CreatedAt: "2026-12-01T10:00:00Z"}}
f.service.runs = runs
token := f.token(t, chatToolSessionScope+"ses_r")
if r := f.call(token, "show_run", `{"run_id":99}`); !r.IsError || !strings.Contains(r.Text, "there is no run 99") {
t.Fatalf("an unknown run is refused: %v", r)
}
r := f.call(token, "show_run", `{"run_id":7}`)
if r.IsError || !strings.Contains(r.Text, "run 7 of feature, running at stage implement") {
t.Fatalf("show_run: %v", r)
}
item := f.items(t, "ses_r")[0]
if item.Kind != protocol.ChatShownRun || item.Run == nil || item.Run.Title != "Add the run card" || item.Run.StartedAt != time.Date(2026, 12, 1, 10, 0, 0, 0, time.UTC).UnixMilli() {
t.Fatalf("run item = %+v", item)
}
runs[7] = protocol.RunSummary{ID: 7, Name: "feature", Title: "Add the run card", Status: "succeeded", Outcome: "done", CreatedAt: "2026-12-01T10:00:00Z", FinishedAt: "2026-12-01T10:30:00Z"}
f.service.observeRun(protocol.RunEventFrame{RunID: 7, Status: "succeeded"})
deadline := time.Now().Add(5 * time.Second)
for {
item = f.items(t, "ses_r")[0]
if item.Run.Status == "succeeded" {
break
}
if time.Now().After(deadline) {
t.Fatalf("the run item was not updated: %+v", item.Run)
}
time.Sleep(10 * time.Millisecond)
}
if item.Run.FinishedAt == 0 || item.Run.Outcome != "done" {
t.Fatalf("finished run = %+v", item.Run)
}
f.service.watch.mu.Lock()
followed := len(f.service.watch.items[7])
f.service.watch.mu.Unlock()
if followed != 0 {
t.Fatal("a finished run is no longer followed")
}
}
func TestScheduleFollowupBounds(t *testing.T) {
f := newChatToolFixture(t)
now := time.Date(2026, 12, 2, 12, 0, 0, 0, time.UTC)
f.service.now = func() time.Time { return now }
token := f.token(t, chatToolSessionScope+"ses_b")
for _, tc := range []struct{ args, want string }{
{`{"message":"check","after_minutes":0}`, "after_minutes must be between 1 and 10080"},
{`{"message":"check","after_minutes":10081}`, "after_minutes must be between 1 and 10080"},
{`{"message":"check","at":"2026-12-02T12:00:30Z"}`, "at least 1 minute from now"},
{`{"message":"check","at":"2026-12-09T12:01:00Z"}`, "at most 7 days"},
{`{"message":"check","at":"tomorrow"}`, "RFC 3339"},
{`{"message":"check","at":"2026-12-02T13:00:00Z","after_minutes":5}`, "not both"},
{`{"message":"check"}`, "give at"},
{`{"message":" ","after_minutes":5}`, "message is empty"},
{`{"message":"check","after_minutes":5}`, "not available on this server"},
} {
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)
}
}
}
func TestFollowupsStepAsideUntilDue(t *testing.T) {
now := time.Now()
followup := &chatQueuedPrompt{operationID: chatFollowupPrefix + "a", sendAt: now.Add(time.Hour)}
operator := &chatQueuedPrompt{operationID: "op-1"}
scheduled := &chatQueuedPrompt{operationID: "op-2", sendAt: now.Add(time.Minute)}
if head, wait := chatQueueHead([]*chatQueuedPrompt{followup, operator}, now); head != 1 || wait != time.Hour {
t.Fatalf("a pending follow-up lets the operator's prompt through: %d %v", head, wait)
}
if head, _ := chatQueueHead([]*chatQueuedPrompt{followup}, now); head != -1 {
t.Fatal("a queue of pending follow-ups has nothing to deliver")
}
if head, _ := chatQueueHead([]*chatQueuedPrompt{followup}, now.Add(2*time.Hour)); head != 0 {
t.Fatal("a due follow-up is delivered")
}
if head, _ := chatQueueHead([]*chatQueuedPrompt{scheduled, operator}, now); head != 0 {
t.Fatal("an operator's scheduled prompt still holds the queue (FIFO)")
}
}