From 1a37cc851692df2a82ff792859603819cf9ca8cd Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 9 Nov 2026 03:22:14 +0800 Subject: [PATCH] agent: Antigravity CLI's thinking effort is picked in its row, and the gateway asks it of Gemini xyenon on Discord: agy's effort can't be set for magpie's models. agy 1.5.3 has --effort for one session only, and turns it away for a custom model (/effort says "not adjustable"); settings.json has no key for it (--settings rejects every name tried as an unknown setting). Its requests ask thinkingConfig {"includeThoughts":true,"thinkingBudget":-1}, the model's own choice. So the pick lives in magpie, as the Antigravity app's and Cursor Private Inference's do: agy's row gets an effort field (provider.AgentEffort("agy")), shown while agy is on magpie's models, with the levels the model lists. Nothing picked leaves agy's requests as today. The gateway had no Gemini case in withFixedEffort, so a pick, a fixed member, a rule's effort or a mapped level did nothing on a Gemini-wire request. withGeminiEffort writes the thinkingConfig as the model takes it, from vertexBudgets: a Gemini 2.5 gets a budget in its range (it refuses a level; none is its least, or 0 for flash), a Gemini 3 a level from low to high (minimal kept), a Gemini before 2.5 is left alone. includeThoughts is kept as asked. The effort block and the needs-reasoning retry call it with the upstream model (withModelEffort). At a stopped WSL distro the field reads nothing (#3896), as TestWSLColdPlaceOpensNothing asks. Run on mote (mote-run), at the pushed head (rebased on 192d2eda8): - gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean. - go test ./internal/agent ./internal/gateway, whole packages: ok (gateway 943s) before the rebase; internal/agent again whole after the cold fix: ok. At the head: -run "Agy|WSLCold|AntigravityEffort" and -run "Agy|Effort": ok. - GUI: agy-effort.test.cjs (new; window and panel, chromium and webkit, en zh zh-TW ja de) and cursor-local-effort: 54 pass, 0 fail. agent-field-names, agent-layout pass; i18n-keys' "a plugin's words are its own" is red as on main (#5332). Broken by hand, each red then restored: - withModelEffort returning the body as sent: TestAgyAgentEffort red (thinkingBudget -1 sent at high). - agy's effort field taken out: TestAgyEffort red ("no effort field"). - 2.5's budgets taken from vertexBudgets: TestAgyAgentEffort and TestWithGeminiEffort red (thinkingLevel sent to gemini-2.5-flash). - the field's cold check taken out (its first version): TestWSLColdPlaceOpensNothing red, stat of agy's settings.json. Not tried: the full ./... suite (the suite lock on mote had ~10 runs queued, some for 9h; agent and gateway were run whole instead); the real agy binary against a sandbox gateway (TestAgyAgentEffort sends agy 1.5.3's captured request body); a real Gemini API with a pick; a real stopped distro. Reported-by: xyenon --- internal/agent/agy.go | 27 +++- internal/agent/agy_effort_test.go | 76 +++++++++++ internal/agent/cursorlocal.go | 2 +- internal/gateway/agy_agent_effort_test.go | 147 ++++++++++++++++++++++ internal/gateway/decide.go | 101 +++++++++++++++ internal/gateway/gateway.go | 8 +- internal/gui/tests/agy-effort.test.cjs | 134 ++++++++++++++++++++ 7 files changed, 489 insertions(+), 6 deletions(-) create mode 100644 internal/agent/agy_effort_test.go create mode 100644 internal/gateway/agy_agent_effort_test.go create mode 100644 internal/gui/tests/agy-effort.test.cjs diff --git a/internal/agent/agy.go b/internal/agent/agy.go index 2af5d07cd..a1d2f5bdf 100644 --- a/internal/agent/agy.go +++ b/internal/agent/agy.go @@ -40,6 +40,7 @@ import ( "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/update" ) @@ -400,7 +401,31 @@ func agyIn(at place) *Agent { } return withVia(group("Antigravity CLI", own), "agy", magpieID+"/") }, - }}, + }, agyEffortField(func() bool { return !at.cold && usesMagpie(get()) })}, + } +} + +// agyEffortField is how hard agy's models reason, picked in its row. agy +// 1.5 has --effort for one session only, which it allows for a model +// whose name it knows and turns away for magpie's ("not adjustable" in +// /effort, xyenon on Discord), and settings.json has no key for it +// (--settings: unknown setting "effort"). Its request asks +// thinkingBudget -1, the model's own choice. The gateway asks its +// requests for the level picked here (provider.AgentEffort), as the +// model takes it (withGeminiEffort); with none they go as agy asks. +// Shown only while agy is on magpie's models, and never read at a +// stopped distro (#3896). +func agyEffortField(on func() bool) Field { + return Field{ + Key: "effort", Label: "effort", + Get: func() string { return provider.AgentEffort("agy") }, + Set: func(v string) error { return provider.SetAgentEffort("agy", v) }, + Options: func(map[string]string) []Option { + if !on() { + return nil + } + return pickedEfforts("agy") + }, } } diff --git a/internal/agent/agy_effort_test.go b/internal/agent/agy_effort_test.go new file mode 100644 index 000000000..d52d315d3 --- /dev/null +++ b/internal/agent/agy_effort_test.go @@ -0,0 +1,76 @@ +package agent + +import ( + "os" + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// agy has no effort magpie can write (xyenon on Discord): settings.json has +// no key for it and --effort, for one session, is turned away for magpie's +// models. Its row picks one, kept in magpie (provider.AgentEffort "agy"), +// among the levels its models have, offered only while agy is on magpie's; +// settings.json is never touched for it. +func TestAgyEffort(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + if err := provider.Save(provider.Provider{ID: "think", Name: "Think", Chat: "https://think.test/v1", Key: "key", Models: []string{"gemini-3.8-flash"}}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("think", "https://think.test/v1", []catalog.Model{{ID: "gemini-3.8-flash", Efforts: []string{"low", "high"}}}); err != nil { + t.Fatal(err) + } + path := filepath.Join(home, ".gemini", "antigravity-cli", "settings.json") + os.MkdirAll(filepath.Dir(path), 0o755) + os.WriteFile(path, []byte(`{"model":"mine","modelProvider":"vertex"}`), 0o644) + a, err := Find("agy") + if err != nil { + t.Fatal(err) + } + f := a.Field("effort") + if f == nil { + t.Fatal("no effort field") + } + values := func() []string { + var out []string + for _, o := range f.Options(map[string]string{}) { + out = append(out, o.Value) + } + return out + } + if got := values(); got != nil { + t.Fatalf("offered %q while on the user's own model", got) + } + if err := a.Apply("model", "magpie/think/gemini-3.8-flash"); err != nil { + t.Fatal(err) + } + if got := values(); !slices.Equal(got, []string{"", "low", "high"}) { + t.Fatalf("offered %q", got) + } + before, _ := os.ReadFile(path) + if err := f.Set("high"); err != nil { + t.Fatal(err) + } + if got, kept := f.Get(), provider.AgentEffort("agy"); got != "high" || kept != "high" { + t.Fatalf("picked high: shown %q, kept %q", got, kept) + } + if provider.AgentEffort("antigravity") != "" { + t.Fatal("agy's pick went to Antigravity's app") + } + if after, _ := os.ReadFile(path); string(after) != string(before) { + t.Errorf("the pick touched settings.json:\n%s\nwas\n%s", after, before) + } + if err := f.Set("hard"); err == nil { + t.Fatal("a word that isn't a level was kept") + } + if err := f.Set(""); err != nil || provider.AgentEffort("agy") != "" { + t.Fatalf("back to the default: %v, kept %q", err, provider.AgentEffort("agy")) + } +} diff --git a/internal/agent/cursorlocal.go b/internal/agent/cursorlocal.go index 152e48484..a5cc7452d 100644 --- a/internal/agent/cursorlocal.go +++ b/internal/agent/cursorlocal.go @@ -326,7 +326,7 @@ func cursorLocal() *Agent { } // pickedEfforts are the levels an agent's effort picked in magpie -// (provider.AgentEffort: Cursor Private Inference, Antigravity) is picked +// (provider.AgentEffort: Cursor Private Inference, Antigravity, agy) is picked // among: the default, its requests going as it asks, then every level a // model its list shows has (low, medium and high for models that reason // with levels unknown). None when no model it lists reasons. diff --git a/internal/gateway/agy_agent_effort_test.go b/internal/gateway/agy_agent_effort_test.go new file mode 100644 index 000000000..7087fb1a8 --- /dev/null +++ b/internal/gateway/agy_agent_effort_test.go @@ -0,0 +1,147 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// Antigravity CLI (agy) has no effort magpie can set: its --effort is for +// one session, turned away for magpie's models, and settings.json has no +// key for it (xyenon on Discord). Its requests ask thinkingBudget -1, the +// model's own choice. With an effort picked for it in magpie, its requests +// to a Gemini API go out at that effort in the words the model takes: a +// Gemini 2.5 a budget in its range (it turns a level away), a Gemini 3 a +// level of its own. With none picked they go as agy sent them, and another +// agent's never take its pick. +func TestAgyAgentEffort(t *testing.T) { + fresh(t) + var mu sync.Mutex + var sent []byte + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + sent = b + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":1}}`)) + })) + t.Cleanup(up.Close) + const flash, pro = "gemini-2.5-flash", "gemini-3.1-pro-preview" + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{flash, pro}, Gemini: up.URL + "/v1beta"}); err != nil { + t.Fatal(err) + } + // their levels, as the Gemini API lists them for a Google key + if err := catalog.SaveLive("relay", up.URL+"/v1beta", []catalog.Model{{ID: flash, Efforts: []string{"low", "medium", "high"}}, {ID: pro, Efforts: []string{"low", "medium", "high"}}}); err != nil { + t.Fatal(err) + } + if p, _ := provider.Find("relay"); !p.Thinks(flash) || !p.Thinks(pro) { + t.Fatal("the relay's models don't reason") + } + s := New() + // agy's own request, as captured from agy 1.5.3 against a stub + const body = `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"thinkingConfig":{"includeThoughts":true,"thinkingBudget":-1}}}` + // the thinkingConfig the relay was sent + asked := func(agent, model string) gjson.Result { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1beta/models/relay/"+model+":streamGenerateContent?alt=sse", strings.NewReader(body)) + req.Header.Set("x-goog-api-key", TokenFor(agent)) + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "ok") { + t.Fatalf("%s asking %s: %d %s", agent, model, rec.Code, rec.Body) + } + mu.Lock() + defer mu.Unlock() + return gjson.GetBytes(sent, "generationConfig.thinkingConfig") + } + const asSent = `{"includeThoughts":true,"thinkingBudget":-1}` + same := func(got gjson.Result, _ string) bool { + return got.Get("includeThoughts").Raw == "true" && got.Get("thinkingBudget").Raw == "-1" && !got.Get("thinkingLevel").Exists() + } + for _, m := range []string{flash, pro} { + if got := asked("agy", m); !same(got, asSent) { + t.Fatalf("none picked, %s: sent %s, want %s as agy sent it", m, got.Raw, asSent) + } + } + for _, c := range []struct { + pick, model string + budget int64 // a Gemini 2.5's + level string // a Gemini 3's + }{ + {"high", flash, 24000, ""}, + {"low", flash, 4096, ""}, + {"high", pro, 0, "high"}, + {"low", pro, 0, "low"}, + {"max", pro, 0, "high"}, // no Gemini takes max + } { + if err := provider.SetAgentEffort("agy", c.pick); err != nil { + t.Fatal(err) + } + got := asked("agy", c.model) + if got.Get("includeThoughts").Raw != "true" { + t.Errorf("picked %s, %s: thoughts no longer asked for: %s", c.pick, c.model, got.Raw) + } + if c.level == "" { + if got.Get("thinkingLevel").Exists() || got.Get("thinkingBudget").Int() != c.budget { + t.Errorf("picked %s, %s: sent %s, want thinkingBudget %d and no level", c.pick, c.model, got.Raw, c.budget) + } + } else if got.Get("thinkingBudget").Exists() || got.Get("thinkingLevel").String() != c.level { + t.Errorf("picked %s, %s: sent %s, want thinkingLevel %q and no budget", c.pick, c.model, got.Raw, c.level) + } + // another agent's request goes as it asks + if got := asked("opencode", c.model); !same(got, asSent) { + t.Errorf("picked %s for agy, opencode's to %s went %s, want %s", c.pick, c.model, got.Raw, asSent) + } + } + if err := provider.SetAgentEffort("agy", ""); err != nil { + t.Fatal(err) + } + if got := asked("agy", pro); !same(got, asSent) { + t.Errorf("taken off: sent %s, want %s", got.Raw, asSent) + } +} + +// withGeminiEffort writes a Gemini request's thinkingConfig as the model +// takes it, and a Gemini before 2.5, which doesn't think, is left alone. +func TestWithGeminiEffort(t *testing.T) { + const in = `{"contents":[],"generationConfig":{"temperature":1,"thinkingConfig":{"includeThoughts":true,"thinkingLevel":"HIGH"}}}` + for _, c := range []struct{ model, effort, want string }{ + {"gemini-2.5-pro", "none", `{"thinkingBudget":128}`}, + {"gemini-2.5-flash", "none", `{"thinkingBudget":0}`}, + {"gemini-2.5-flash-lite", "minimal", `{"includeThoughts":true,"thinkingBudget":4096}`}, + {"models/gemini-2.5-pro", "xhigh", `{"includeThoughts":true,"thinkingBudget":32000}`}, + {"gemini-3-flash-preview", "minimal", `{"includeThoughts":true,"thinkingLevel":"minimal"}`}, + {"gemini-3.1-pro-preview", "none", `{"includeThoughts":true,"thinkingLevel":"low"}`}, + {"gemini-3.1-pro-preview", "medium", `{"includeThoughts":true,"thinkingLevel":"medium"}`}, + {"openai/gpt-5.5", "xhigh", `{"includeThoughts":true,"thinkingLevel":"xhigh"}`}, + {"openai/gpt-5.5", "none", `{"thinkingBudget":0}`}, + } { + out := withGeminiEffort([]byte(in), c.model, c.effort) + if got := gjson.GetBytes(out, "generationConfig.thinkingConfig").Raw; got != c.want { + t.Errorf("%s at %s: %s, want %s", c.model, c.effort, got, c.want) + } + if gjson.GetBytes(out, "generationConfig.temperature").Raw != "1" { + t.Errorf("%s at %s: the rest of generationConfig lost: %s", c.model, c.effort, out) + } + } + if out := withGeminiEffort([]byte(in), "gemini-2.0-flash", "high"); string(out) != in { + t.Errorf("gemini-2.0: %s", out) + } + // a request with no generationConfig is given one + if got := gjson.GetBytes(withGeminiEffort([]byte(`{"contents":[]}`), "gemini-3-flash", "high"), "generationConfig.thinkingConfig").Raw; got != `{"thinkingLevel":"high"}` { + t.Errorf("no generationConfig: %s", got) + } + // withFixedEffort, which has no model but the one the body names + if got := gjson.GetBytes(withFixedEffort(provider.Gemini, []byte(`{"model":"gemini-2.5-flash","contents":[]}`), "high"), "generationConfig.thinkingConfig").Raw; got != `{"thinkingBudget":24000}` { + t.Errorf("withFixedEffort: %s", got) + } +} diff --git a/internal/gateway/decide.go b/internal/gateway/decide.go index 189ada619..96819beb7 100644 --- a/internal/gateway/decide.go +++ b/internal/gateway/decide.go @@ -854,10 +854,111 @@ func withFixedEffort(proto provider.Protocol, body []byte, effort string) []byte return body } return withFields(body, map[string]any{"thinking": map[string]any{"type": "enabled", "budget_tokens": budget}}) + case provider.Gemini: + var v struct { + Model string `json:"model"` + } + if decodeJSON(body, &v) != nil { + return body + } + return withGeminiEffort(body, v.Model, effort) } return body } +// withModelEffort is withFixedEffort for a request going to model: a +// Gemini request's thinkingConfig is the one model takes (withGeminiEffort), +// which the model the client named needn't tell. +func withModelEffort(proto provider.Protocol, body []byte, model, effort string) []byte { + if proto == provider.Gemini && effort != "" { + return withGeminiEffort(body, model, effort) + } + return withFixedEffort(proto, body, effort) +} + +// withGeminiEffort asks a Gemini request's generationConfig.thinkingConfig +// for effort, as model takes it, keeping includeThoughts as asked: a +// Gemini 2.5 a budget in its range (vertexBudgets; it turns a level away), +// a Gemini 3 a level of low..high (none takes xhigh or max, and it can't +// stop thinking, so none is low), a Gemini before 2.5 nothing, as it +// doesn't think. Another model (agy asking an OpenAI one on Gemini's API) +// is asked the level itself, which the translation reads, and none as a +// budget of 0. Antigravity CLI's own request sends thinkingBudget -1, or +// an upper-case level with --effort, which agy allows only per session. +func withGeminiEffort(body []byte, model, effort string) []byte { + if effort == "" { + return body + } + m := strings.ToLower(strings.TrimPrefix(model, "models/")) + if i := strings.LastIndex(m, "/"); i >= 0 { + m = m[i+1:] + } + if strings.HasPrefix(m, "gemini-1") || strings.HasPrefix(m, "gemini-2.0") { + return body + } + dec := json.NewDecoder(bytes.NewReader(body)) + dec.UseNumber() + var top map[string]any + if dec.Decode(&top) != nil { + return body + } + gcKey, tcKey := "generationConfig", "thinkingConfig" + if _, ok := top[gcKey]; !ok { + if _, ok := top["generation_config"]; ok { + gcKey = "generation_config" + } + } + gc, _ := top[gcKey].(map[string]any) + if gc == nil { + gc = map[string]any{} + } + if _, ok := gc[tcKey]; !ok { + if _, ok := gc["thinking_config"]; ok { + tcKey = "thinking_config" + } + } + old, _ := gc[tcKey].(map[string]any) + include := old["includeThoughts"] + if include == nil { + include = old["include_thoughts"] + } + tc := map[string]any{} + if include != nil { + tc["includeThoughts"] = include + } + // the level as fitted to the model's own (a Gemini 3 Flash takes + // minimal), in effortRank's words + level := strings.ToLower(strings.TrimSpace(effort)) + if l := effortOf(level); l != "" && level != "none" && level != "minimal" { + level = l + } + switch off, least, most, ok := vertexBudgets(m); { + case ok && level == "none": + // asked to think no more than it can help: thoughts aren't asked + // for where thinking is off ("include_thoughts is only enabled + // when thinking is enabled") + tc = map[string]any{"thinkingBudget": off} + case ok: + tc["thinkingBudget"] = min(max(budgetOf(effortOf(level)), least), most) + case strings.HasPrefix(m, "gemini-"): + switch at := slices.Index(effortRank, level); { + case level == "none" || at >= 0 && at < slices.Index(effortRank, "low"): + if level != "minimal" { + level = "low" + } + case at > slices.Index(effortRank, "high"): + level = "high" + } + tc["thinkingLevel"] = level + case level == "none": + tc = map[string]any{"thinkingBudget": 0} + default: + tc["thinkingLevel"] = level + } + gc[tcKey] = tc + return withFields(body, map[string]any{gcKey: gc}) +} + // groupLevels are the reasoning levels the group offers for the member a // candidate is of, where the user named them (Group.Levels, #295): the // group's own, else those of the outermost group in it that names some. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 3a4f23105..38356cd48 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3637,16 +3637,16 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if mapped != "none" { mapped = fitLevel(mapped, c.p.Efforts(c.model)) } - attemptBody = withFixedEffort(from, attemptBody, mapped) + attemptBody = withModelEffort(from, attemptBody, c.model, mapped) } else if ruled != "" { // asked even of a request that asked for no reasoning, as a // member fixed at an effort is; already fitted to its levels - attemptBody = withFixedEffort(from, attemptBody, ruled) + attemptBody = withModelEffort(from, attemptBody, c.model, ruled) } else if fixed != "" { // a member fixed at an effort is asked for it, at the level its // model has nearest, whatever the agent asked or the turn's // pick: even a request that asked for no reasoning - attemptBody = withFixedEffort(from, attemptBody, fitLevel(fixed, c.p.Efforts(c.model))) + attemptBody = withModelEffort(from, attemptBody, c.model, fitLevel(fixed, c.p.Efforts(c.model))) } else if effort != "" { // the level this model has nearest to the one picked; one whose // levels aren't known isn't asked for more than high, which @@ -6736,7 +6736,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if offEffort(e) { s.markUnfit(p.ID, offRefused(model), proto) } - if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(withFixedEffort(proto, body, onEffort(p, model))), r.Header); err != nil { + if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(withModelEffort(proto, body, model, onEffort(p, model))), r.Header); err != nil { return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true } } diff --git a/internal/gui/tests/agy-effort.test.cjs b/internal/gui/tests/agy-effort.test.cjs new file mode 100644 index 000000000..d4503e067 --- /dev/null +++ b/internal/gui/tests/agy-effort.test.cjs @@ -0,0 +1,134 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Antigravity CLI's effort (xyenon on Discord): agy's --effort is for one +// session and turned away for magpie's models, and its settings.json has +// no key for one, so its row has an effort, which magpie's gateway asks +// its requests for. The default (as agy asks) is the first stop, then the +// levels its models have. In the window it is in the row opened from its +// link; in the tray panel the row opens to its slider. A pick posts the +// field; nothing runs off the side of a narrow window. +// English, Simplified and Traditional Chinese, Japanese and German, +// Chromium and WebKit. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const levels = ["low", "high"]; +const model = "magpie/think/gemini-3.8-flash"; +const agy = (effort) => ({ + id: "agy", name: "Antigravity CLI", icon: "antigravity-color", path: "/home/u/.gemini/antigravity-cli/settings.json", wired: true, + fields: [ + { key: "model", label: "model", value: model, options: [{ value: model, icon: "gemini-color", ref: "think/gemini-3.8-flash" }] }, + { key: "effort", label: "effort", value: effort, options: [{ value: "" }, ...levels.map((value) => ({ value }))] }, + ], +}); +const filler = Array.from({ length: 6 }, (_, i) => ({ id: "pi" + i, name: "Pi " + i, path: "/p", fields: [{ key: "model", label: "model", value: "", options: [] }] })); + +function serve(lang, sets) { + let effort = ""; + const st = () => ({ agents: [agy(effort), ...filler], profiles: [], settings: { lang, theme: "light", guideHidden: true } }); + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: st() }); + if (url.pathname === "/api/set") { + const b = req.postDataJSON(); + sets.push(b); + if (b.field === "effort") effort = b.value; + return route.fulfill({ json: st() }); + } + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { effort: "effort", def: "default", high: "high" }, + zh: { effort: "推理强度", def: "默认", high: "高" }, + "zh-TW": { effort: "推理強度", def: "預設", high: "高" }, + ja: { effort: "推論レベル", def: "デフォルト", high: "高" }, + de: { effort: "Reasoning-Effort", def: "Standard", high: "hoch" }, +}; +const row = `.row.agent[data-id="agy"]`; +const noSideScroll = (page) => page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: Antigravity CLI has an effort`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + const open = async (mode, sets) => { + const page = await (await browser.newContext({ viewport: { width: mode ? 440 : 560, height: 640 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, sets)); + await page.goto("http://magpie.test/" + (mode ? "?mode=" + mode : "")); + await page.locator(row).waitFor(); + return page; + }; + + await t.test("the window", async () => { + const sets = []; + const page = await open("", sets); + await page.locator(`${row} .ag-link`).click(); + await page.locator(`${row} .ag-exp`).waitFor(); + const field = page.locator(`${row} .field[data-key="effort"]`); + assert.equal(await field.count(), 1); + assert.equal(await field.locator(".v").textContent(), w.def); + const box = await field.boundingBox(); + assert(box.x >= 0 && box.x + box.width <= 560, `the effort runs off the window: ${JSON.stringify(box)}`); + assert(await noSideScroll(page), "the window scrolls sideways"); + + const y = await page.evaluate(() => scrollY); + await field.click(); + await page.locator("#effortControl:not([hidden])").waitFor(); + assert.equal(await page.evaluate(() => scrollY), y, "the click scrolled the page"); + assert.equal(await page.locator("#effortTitle").textContent(), w.effort); + assert.equal(await page.locator("#effortValue").textContent(), w.def); + // the default, then its models' two levels + assert.equal(await page.locator("#effortTicks i").count(), 3); + await page.locator("#effortRange").evaluate((r) => { + r.value = "2"; + r.dispatchEvent(new Event("input", { bubbles: true })); + r.dispatchEvent(new Event("change", { bubbles: true })); + }); + assert.equal(await page.locator("#effortValue").textContent(), w.high); + await page.waitForFunction(() => document.querySelector('.row.agent[data-id="agy"] .field[data-key="effort"] .v')?.textContent !== document.querySelector("#effortMin")?.textContent); + assert.deepEqual(sets, [{ agent: "agy", field: "effort", value: "high" }]); + assert.equal(await page.locator(`${row} .field[data-key="effort"] .v`).textContent(), w.high); + assert(await noSideScroll(page), "the window scrolls sideways"); + }); + + await t.test("the panel", async () => { + const sets = []; + const page = await open("panel", sets); + await page.locator(`${row} .ag-sum`).click(); + await page.waitForTimeout(700); + const box = page.locator(`${row} .ag-open .effort-control`); + assert.equal(await box.locator(".effort-ticks i").count(), 3); + assert.equal(await box.locator(".effort-ends span").first().textContent(), w.def); + await box.locator(".eslide").press("ArrowRight"); + await page.waitForTimeout(300); + assert.deepEqual(sets, [{ agent: "agy", field: "effort", value: "low" }]); + assert(await noSideScroll(page), "the panel scrolls sideways"); + }); + + assert.deepEqual(errors, []); + }); + } +}