Files
magpie/internal/gui/api_settings_test.go
T
yetone 197849ad4d gateway: image generation's timeout is a setting, 1 to 60 minutes
neighbads on X: a slow image endpoint needed more than the fixed 5
minutes. Settings > Images > Image generation timeout (imageTimeout in
settings.json, 5 when unset, 1 to 60 accepted, anything else a 400) now
gives every drawing that long, on each route it takes:

- drawTimeout() reads the setting; drawWithin marks the context as a
  drawing and sets its deadline. Error texts say the time it was given
  (givenTo), ModelScope's task polling too.
- A marked drawing goes through a vendor transport with no
  ResponseHeaderTimeout (drawsApart), since an images API sends its
  headers only once it has drawn; everything else keeps the 10-minute
  upstreamHeaderWait, so a 30-minute setting isn't cut at 10.
- An image answered as a link is downloaded within the same time
  (imageLongest, never under ImageLongest).
- Videos keep 5 minutes per call (videoTimeout): a video is made between
  its calls, so the setting isn't theirs.
- magpie mcp image waits on a call up to callLongest (2h1m, past the
  60-minute bound twice over), since it may not read the settings (WSL);
  ToolTimeout, which agent configs carry, is unchanged.
- The plugin path: Bun 1.4.2's fetch has no 5-minute cap (tried against
  a server answering after 330s), so nothing changes there.
- api.go keeps the saved value when a page doesn't send imageTimeout;
  prefsKeep carries it on every other Settings save.

GUI: a segmented row under Image generation (5, 10, 15, 30, 60 min; a
value set by hand gets its own segment), in en, zh, zh-TW, ja and de.

Three GUI tests clicked controls the new row pushed under the window's
foot or past the viewport; they now wheel to them with reader.cjs's
reach (disabled-models, search-api, refusal-retries-setting).
searcher-pick checks the help has no title before reach's pointer
passes over it (the app's mouseover sets one on cut-short text).

Run, at 224ea7d5b plus this change (origin/main 9fd80b212 fetched):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. GOOS=linux go build -tags nogui and
  GOOS=windows go build: ok.
- go test -p 4 -timeout 45m ./...: 64 packages ok, exit 0.
- New tests: TestLongImageTimeoutLetsASlowVendorFinish (drawUnit and
  upstreamHeaderWait shrunk, no sleeps: a vendor slower than the header
  wait succeeds when given 30, is a 504 at the default),
  TestImageTimeoutSettingReachesTheVendor, TestImageDownloadGetsTheSetMinutes,
  TestOnlyDrawingsWaitPastTheHeaderWait, TestImageTimeoutKeptAndBounded,
  TestCallOutwaitsTheLongestDrawing, TestSettingsImageTimeout,
  image-timeout-setting.test.cjs (5 languages x 1100/420 x chromium and
  webkit, plus a hand-set 45 min kept across another save).
- Broken by hand, each red, then restored: drawsApart sending everything
  through the header-timeout transport (2 red); drawTimeout fixed at 5
  minutes (2 red); callLongest back to ToolTimeout (red at 11m); the
  settings bound at 600 ("61 minutes accepted"); imageTimeout left out of
  prefsKeep (hand-set test red, wanted 45); api.go's keep removed
  ("imageTimeout 0").
- GUI, NODE_PATH at playwright 1.62.0, chromium and webkit: the 115 files
  that reach Settings or the changed assets, 1646 tests, 1627 pass. Of
  the 18 reds: codex-predictions (420, every language) and s3-sync are
  red on 224ea7d5b's own copy too, untouched here; refusal-retries,
  disabled-models, search-api and searcher-pick were the clicks fixed
  above; sidebar's "the list opens and folds as it plays" (chromium)
  samples getAnimations() once and missed the unroll under a load of
  ~175. Rerun of those five files plus image-timeout-setting: 104 of
  104 pass.

Not tried: a real slow image vendor; WSL; the Windows box; Bun other
than 1.4.2; the GUI files that can't reach Settings.
2026-10-19 21:47:35 +08:00

274 lines
10 KiB
Go

package gui
import (
"net/http"
"net/http/httptest"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/yetone/magpie/internal/settings"
)
func TestSettingsSearchProviderOff(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
h := Handler(nil, nil)
for _, body := range []string{`{"searcher":"off"}`, `{"theme":"dark","searcher":"off"}`} {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(body)))
if rec.Code != http.StatusOK {
t.Fatalf("saving %s: %d %s", body, rec.Code, rec.Body)
}
if got := settings.Load().Searcher; got != "off" {
t.Fatalf("searcher = %q, want off", got)
}
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(`{"searcher":"missing-provider"}`)))
if rec.Code != http.StatusBadRequest || settings.Load().Searcher != "off" {
t.Fatalf("invalid provider changed the choice: %d %s", rec.Code, rec.Body)
}
}
// The Settings page sends only its own choices. What the settings keep per
// model — every name, level, price and image answer the user gave of a model
// on a page of its own — is set elsewhere, so a save from this page has to
// carry it over. This drives the real handler: POST /api/settings with a body
// naming nothing but the theme.
//
// The tables are the settings' own — settings.PerModelKeys, the walk the
// save itself goes by — each seeded with an entry saying which table it was
// written for, so a table added to the settings later is carried and checked
// here without this test being changed.
func TestSettingsPageSaveCarriesEveryPerModelTable(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
seed := settings.Load()
if seedPerModelTables(t, &seed) == 0 {
t.Fatal("the settings hold no per-model map: there is nothing here for a save to carry over")
}
if err := settings.Save(seed); err != nil {
t.Fatal(err)
}
// what the settings say once written and read back, so what is compared
// after the request is what really reached the disk, not what was set
before := perModelTables(t)
rec := httptest.NewRecorder()
Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(`{"theme":"dark"}`)))
if rec.Code != http.StatusOK {
t.Fatalf("saving the theme: %d %s", rec.Code, rec.Body)
}
if s := settings.Load(); s.Theme != "dark" {
t.Fatalf("the theme was saved as %q, not dark", s.Theme)
}
now := perModelTables(t)
for name, was := range before {
got, ok := now[name]
if !ok {
t.Fatalf("%s is not one of the settings' per-model maps any more", name)
}
if !reflect.DeepEqual(was.Interface(), got.Interface()) {
t.Errorf("%s did not survive the Settings page's save:\n\tsaved %v\n\tnow %v", name, was.Interface(), got.Interface())
}
}
}
// CarryPerModel walks the Model* tables only. Which models an agent is shown
// is keyed by the agent, not by "<provider>/<model>", so Visible and
// HiddenModels are not among them and the save has to name them itself — the
// one place this page still lists what it keeps. A table added to that list
// later without a line here is dropped by a save; this says so rather than
// leaving it to be found.
func TestSettingsPageSaveKeepsWhichModelsAnAgentIsShown(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
seed := settings.Load()
seed.Visible = map[string][]string{"claude": {"p/m"}}
seed.HiddenModels = map[string][]string{"codex": {"p/n", "group/g"}}
if err := settings.Save(seed); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(`{"theme":"dark"}`)))
if rec.Code != http.StatusOK {
t.Fatalf("saving the theme: %d %s", rec.Code, rec.Body)
}
got := settings.Load()
if !reflect.DeepEqual(got.Visible, map[string][]string{"claude": {"p/m"}}) {
t.Errorf("Visible after a save of the Settings page: %v; want map[claude:[p/m]]", got.Visible)
}
if !reflect.DeepEqual(got.HiddenModels, map[string][]string{"codex": {"p/n", "group/g"}}) {
t.Errorf("HiddenModels after a save of the Settings page: %v; want map[codex:[p/n group/g]]", got.HiddenModels)
}
}
// perModelTables are the settings' per-model maps as they stand now, by
// name: the settings' own walk of them (settings.PerModelKeys, which is the
// walk the save goes by too) rather than a list written out here, which a
// table added to the settings later would not be in.
func perModelTables(t *testing.T) map[string]reflect.Value {
t.Helper()
s := settings.Load()
out := map[string]reflect.Value{}
settings.PerModelKeys(&s, func(name string, m reflect.Value) { out[name] = m })
return out
}
// seedPerModelTables puts an entry into every per-model map of s, saying
// which table it was written for, so a table that came back empty, or with
// another's entry in it, is told apart. It counts the tables it seeded.
func seedPerModelTables(t *testing.T, s *settings.Settings) int {
t.Helper()
var n int
settings.PerModelKeys(s, func(name string, m reflect.Value) {
m.Set(reflect.MakeMap(m.Type()))
m.SetMapIndex(reflect.ValueOf("p/"+name).Convert(m.Type().Key()), perModelValue(m.Type().Elem(), name))
n++
})
return n
}
// perModelValue is a value of a per-model table's own type, saying which
// table it was written for, so a table that came back empty, or with another's
// entry in it, is told apart. A type with nothing said of it is left zero:
// the key alone gives the table away.
func perModelValue(typ reflect.Type, table string) reflect.Value {
switch typ.Kind() {
case reflect.String:
return reflect.ValueOf("said of " + table).Convert(typ)
case reflect.Bool:
return reflect.ValueOf(true).Convert(typ)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return reflect.ValueOf(int64(len(table))).Convert(typ)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return reflect.ValueOf(uint64(len(table))).Convert(typ)
case reflect.Float32, reflect.Float64:
return reflect.ValueOf(float64(len(table))).Convert(typ)
case reflect.Slice:
out := reflect.MakeSlice(typ, 1, 1)
out.Index(0).Set(perModelValue(typ.Elem(), table))
return out
case reflect.Array:
out := reflect.New(typ).Elem()
out.Index(0).Set(perModelValue(typ.Elem(), table))
return out
case reflect.Map:
out := reflect.MakeMap(typ)
out.SetMapIndex(reflect.ValueOf(table).Convert(typ.Key()), perModelValue(typ.Elem(), table))
return out
}
return reflect.Zero(typ)
}
// How often a refused request is asked again (DD on Discord) is set by the
// Settings page, null for every one left, and kept by a save from a page
// that doesn't send it.
func TestSettingsRefusalRetries(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
handler := Handler(nil, nil)
for _, x := range []struct {
body string
want int // -1 for unset
}{
{`{"theme":"dark","refusalRetries":0}`, 0},
{`{"theme":"light"}`, 0},
{`{"theme":"light","refusalRetries":2}`, 2},
{`{"theme":"light","refusalRetries":null}`, -1},
} {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(x.body)))
if rec.Code != http.StatusOK {
t.Fatalf("%s: %d %s", x.body, rec.Code, rec.Body)
}
got := settings.Load().RefusalRetries
if x.want < 0 && got != nil || x.want >= 0 && (got == nil || *got != x.want) {
t.Fatalf("%s: refusalRetries %v", x.body, got)
}
}
}
// How long an image is given to be drawn (neighbads on X) is set by the
// Settings page, 0 for the default 5 minutes, kept by a save from a page
// that doesn't send it, and refused past 60 with the saved value kept.
func TestSettingsImageTimeout(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
handler := Handler(nil, nil)
for _, x := range []struct {
body string
code int
want int
}{
{`{"theme":"dark","imageTimeout":30}`, http.StatusOK, 30},
{`{"theme":"light"}`, http.StatusOK, 30},
{`{"theme":"light","imageTimeout":61}`, http.StatusBadRequest, 30},
{`{"theme":"light","imageTimeout":0}`, http.StatusOK, 0},
} {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(x.body)))
if rec.Code != x.code {
t.Fatalf("%s: %d %s", x.body, rec.Code, rec.Body)
}
if got := settings.Load().ImageTimeout; got != x.want {
t.Fatalf("%s: imageTimeout %d", x.body, got)
}
}
}
func TestSettingsColorblindMode(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
handler := Handler(nil, nil)
getBoot := func() string {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest("GET", "/boot.js", nil))
if rec.Code != http.StatusOK {
t.Fatalf("GET /boot.js: %d %s", rec.Code, rec.Body)
}
return rec.Body.String()
}
if boot := getBoot(); strings.Contains(boot, `"colorblind":true`) {
t.Fatalf("colorblind off by default, got boot.js: %s", boot)
}
for _, tc := range []struct {
body string
want bool
}{
{`{"theme":"dark","colorblind":true}`, true},
{`{"theme":"dark","colorblind":false}`, false},
} {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(tc.body)))
if rec.Code != http.StatusOK {
t.Fatalf("%s: %d %s", tc.body, rec.Code, rec.Body)
}
if got := settings.Load().Colorblind; got != tc.want {
t.Fatalf("%s: Colorblind = %v, want %v", tc.body, got, tc.want)
}
if boot := getBoot(); strings.Contains(boot, `"colorblind":true`) != tc.want {
t.Fatalf("%s: boot.js = %s, want colorblind=%v", tc.body, boot, tc.want)
}
}
}