diff --git a/internal/gui/api.go b/internal/gui/api.go index d2c7be369..8caabbef0 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -186,6 +186,9 @@ type fieldJSON struct { Label string `json:"label"` Value string `json:"value"` Options []agent.Option `json:"options"` + // List is, in place of Options, which of the state's OptionLists the + // field offers, from 1 (shareOptions); 0 when Options is its own + List int `json:"list,omitempty"` } type agentJSON struct { @@ -336,6 +339,11 @@ type stateJSON struct { // GatewayHeld: the program that has the gateway's port when this magpie // couldn't listen on it, as far as it could be read (gateway.PortHeld) GatewayHeld *gateway.PortHeld `json:"gatewayHeld,omitempty"` + // OptionLists are the fields' option lists, each once, that a field's + // List names (shareOptions). With real accounts 13 agents' model + // pickers offered the same 51KB catalog, 650KB of a 690KB state. + // Last of the fields: writeStateJSON writes them after the rest. + OptionLists [][]agent.Option `json:"optionLists,omitempty"` } // unlistedJSON is a model of a provider kept for routing groups, and the diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 2ef41934c..dd38eb3eb 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -150,6 +150,8 @@ async function api(path, body, heads, signal) { try { data = text ? JSON.parse(text) : null; } catch { throw new Error(notJSON(res, text)); } + // a state sends each fields' option list once (shareOptions, statewrite.go) + if (data?.optionLists) for (const a of data.agents) for (const f of a.fields) if (f.list) f.options = data.optionLists[f.list - 1]; if (!res.ok) { const err = new Error(data?.error || `${res.status} ${res.statusText}`); if (data?.code === "runtime_unavailable") { diff --git a/internal/gui/laststate.go b/internal/gui/laststate.go index cca6376a2..d377a56c4 100644 --- a/internal/gui/laststate.go +++ b/internal/gui/laststate.go @@ -80,6 +80,8 @@ func keepState(s stateJSON) { // keptFile is what keepState keeps of s. func keptFile(s stateJSON) stateFile { + // kept as it is sent, each option list once + s = shareOptions(s) s.Settings = settings.Settings{} // and what is told once: a notice, a file recovered after a crash s.Notice, s.Connected, s.Recovered = "", nil, nil diff --git a/internal/gui/statewrite.go b/internal/gui/statewrite.go index 865a3306f..81ee430f9 100644 --- a/internal/gui/statewrite.go +++ b/internal/gui/statewrite.go @@ -7,7 +7,11 @@ import ( "encoding/json" "io" "net/http" + "reflect" + "slices" "sync/atomic" + + "github.com/yetone/magpie/internal/agent" ) // stateHeld is what writeStateJSON writes through, used again from poll @@ -48,10 +52,13 @@ const agentsNull = `{"agents":null` // now, straight to both, and only the rest of the state, without its // agents, is encoded twice (with the settings and without). false when // the sum wasn't found; s was written all the same, when it could be. +// s goes as shareOptions has it, each option list once. func writeStateJSON(rw http.ResponseWriter, s stateJSON) ([32]byte, bool) { - agents := s.Agents + s = shareOptions(s) + agents, lists := s.Agents, s.OptionLists f := keptFile(s) s.Agents, f.State.Agents = nil, nil + s.OptionLists, f.State.OptionLists = nil, nil bufs := stateHeld.Swap(nil) if bufs == nil { bufs = new(stateBufs) @@ -69,8 +76,9 @@ func writeStateJSON(rw http.ResponseWriter, s stateJSON) ([32]byte, bool) { v, _ := json.Marshal(Version) keptHead := `{"version":` + string(v) + `,"state":` + agentsNull if agents == nil || err != nil || kerr != nil || - !bytes.HasPrefix(tail, []byte(agentsNull)) || !bytes.HasPrefix(keptTail, []byte(keptHead)) { - s.Agents = agents + !bytes.HasPrefix(tail, []byte(agentsNull)) || !bytes.HasPrefix(keptTail, []byte(keptHead)) || + !bytes.HasSuffix(tail, []byte("}")) || !bytes.HasSuffix(keptTail, []byte("}}")) { + s.Agents, s.OptionLists = agents, lists writeJSON(rw, s) sum, err := encodedSum(keptFile(s)) return sum, err == nil @@ -84,26 +92,39 @@ func writeStateJSON(rw http.ResponseWriter, s stateJSON) ([32]byte, bool) { out := bufs.out defer out.Flush() h := sha256.New() + both := io.MultiWriter(out, h) _, _ = out.WriteString(`{"agents":[`) h.Write([]byte(keptHead[:len(keptHead)-len("null")] + "[")) // each agent goes straight to rw and the sum, as Encode writes it - enc := json.NewEncoder(lineless{io.MultiWriter(out, h)}) + enc := json.NewEncoder(lineless{both}) for i := range agents { if i > 0 { - _ = out.WriteByte(',') - h.Write([]byte{','}) + _, _ = both.Write([]byte{','}) } // a pointer, so a method on *T is used as it is in the slice if enc.Encode(&agents[i]) != nil { return [32]byte{}, false } } - _ = out.WriteByte(']') - _, _ = out.Write(tail[len(agentsNull):]) - _ = out.WriteByte('\n') - h.Write([]byte{']'}) - h.Write(keptTail[len(keptHead):]) - h.Write([]byte{'\n'}) + _, _ = both.Write([]byte{']'}) + // the rest, up to the state's closing brace: the option lists, the + // state's last field, go after it one by one, as the agents do + _, _ = out.Write(tail[len(agentsNull) : len(tail)-1]) + h.Write(keptTail[len(keptHead) : len(keptTail)-2]) + if len(lists) > 0 { + _, _ = both.Write([]byte(`,"optionLists":[`)) + for i := range lists { + if i > 0 { + _, _ = both.Write([]byte{','}) + } + if enc.Encode(lists[i]) != nil { + return [32]byte{}, false + } + } + _, _ = both.Write([]byte{']'}) + } + _, _ = out.WriteString("}\n") + h.Write([]byte("}}\n")) return [32]byte(h.Sum(nil)), true } @@ -118,3 +139,55 @@ func (l lineless) Write(b []byte) (int, error) { } return l.w.Write(b) } + +// shareOptions is s with each fields' option list sent once, in +// OptionLists, and named by the field's List: a list two fields offer +// alike is one entry. s's own agents are left as they were. The page +// puts each field's list back as it reads the state (api in app.js). +func shareOptions(s stateJSON) stateJSON { + if s.OptionLists != nil { + return s + } + agents := slices.Clone(s.Agents) + var lists [][]agent.Option + for i := range agents { + fields := agents[i].Fields + cloned := false + for j := range fields { + opts := fields[j].Options + if len(opts) < 2 { + continue + } + k := slices.IndexFunc(lists, func(l []agent.Option) bool { return sameOptions(l, opts) }) + if k < 0 { + lists = append(lists, opts) + k = len(lists) - 1 + } + if !cloned { + fields, cloned = slices.Clone(fields), true + } + fields[j].Options, fields[j].List = nil, k+1 + } + agents[i].Fields = fields + } + if lists == nil { + return s + } + s.Agents, s.OptionLists = agents, lists + return s +} + +// sameOptions reports whether a and b are the same options, in the same +// order. +func sameOptions(a, b []agent.Option) bool { + if len(a) != len(b) { + return false + } + if &a[0] == &b[0] { + return true + } + if a[0].Value != b[0].Value || a[len(a)-1].Value != b[len(b)-1].Value { + return false + } + return reflect.DeepEqual(a, b) +} diff --git a/internal/gui/statewrite_test.go b/internal/gui/statewrite_test.go index 525deecde..7a329304c 100644 --- a/internal/gui/statewrite_test.go +++ b/internal/gui/statewrite_test.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "runtime" + "slices" "testing" "github.com/yetone/magpie/internal/agent" @@ -69,7 +70,7 @@ func TestStateWrittenAsEncoded(t *testing.T) { w := &sinkWriter{keep: true} sum, ok := writeStateJSON(w, s) var want bytes.Buffer - if err := json.NewEncoder(&want).Encode(s); err != nil { + if err := json.NewEncoder(&want).Encode(shareOptions(s)); err != nil { t.Fatal(err) } if !bytes.Equal(w.body.Bytes(), want.Bytes()) { @@ -114,3 +115,97 @@ func TestStateWriteGrowsNoBufferItsSize(t *testing.T) { t.Fatalf("writing a %d-byte state allocated %d bytes, want under half its size", size, per) } } + +// Each field's option list goes once: the fields offering one list alike +// name it, and what the page puts back (api in app.js) is the state as +// it was. With real accounts 13 agents' model pickers offered the same +// 51KB catalog, 650KB of a 690KB state read. +func TestStateSendsEachOptionListOnce(t *testing.T) { + catalog := []agent.Option{{Value: "a/1", Label: "One", Icons: []string{"x"}}, {Value: "a/2", Note: "fast"}} + same := slices.Clone(catalog) // equal, not the same backing array + other := slices.Clone(catalog) + other[1].FastFor = "codex" + icons := slices.Clone(catalog) + icons[0].Icons = []string{"y"} + s := stateJSON{Agents: []agentJSON{ + {ID: "a", Fields: []fieldJSON{{Key: "model", Options: catalog}, {Key: "effort", Options: []agent.Option{{Value: "low"}}}}}, + {ID: "b", Fields: []fieldJSON{{Key: "model", Options: same}, {Key: "small", Options: catalog}}}, + {ID: "c", Fields: []fieldJSON{{Key: "model", Options: other}}}, + {ID: "d", Fields: []fieldJSON{{Key: "model", Options: icons}}}, + {ID: "e", Fields: []fieldJSON{{Key: "model", Options: []agent.Option{}}}}, + }} + var before bytes.Buffer + if err := json.NewEncoder(&before).Encode(s); err != nil { + t.Fatal(err) + } + w := &sinkWriter{keep: true} + writeStateJSON(w, s) + var sent struct { + Agents []struct { + ID string `json:"id"` + Fields []struct { + Key string `json:"key"` + Options []agent.Option `json:"options"` + List int `json:"list"` + } `json:"fields"` + } `json:"agents"` + OptionLists [][]agent.Option `json:"optionLists"` + } + if err := json.Unmarshal(w.body.Bytes(), &sent); err != nil { + t.Fatal(err) + } + if len(sent.OptionLists) != 3 { + t.Fatalf("%d option lists sent, want 3 (the catalog, the fast one's, the other icons'): %s", len(sent.OptionLists), w.body.Bytes()) + } + lists := map[string]int{} + for _, a := range sent.Agents { + for _, f := range a.Fields { + if f.List != 0 { + if f.Options != nil { + t.Fatalf("%s's %s sent its options and a list", a.ID, f.Key) + } + lists[a.ID+"/"+f.Key] = f.List + } + } + } + if lists["a/model"] == 0 || lists["a/model"] != lists["b/model"] || lists["a/model"] != lists["b/small"] { + t.Fatalf("the fields offering one list name %v", lists) + } + if lists["c/model"] == lists["a/model"] || lists["d/model"] == lists["a/model"] { + t.Fatalf("a list unlike the catalog was sent as it: %v", lists) + } + if lists["a/effort"] != 0 || lists["e/model"] != 0 { + t.Fatalf("a list of one or none was moved: %v", lists) + } + // put back as the page does, it is the state as it was + var back map[string]any + if err := json.Unmarshal(w.body.Bytes(), &back); err != nil { + t.Fatal(err) + } + ol := back["optionLists"].([]any) + for _, a := range back["agents"].([]any) { + for _, f := range a.(map[string]any)["fields"].([]any) { + f := f.(map[string]any) + if l, ok := f["list"].(float64); ok { + f["options"] = ol[int(l)-1] + delete(f, "list") + } + } + } + delete(back, "optionLists") + var want map[string]any + if err := json.Unmarshal(before.Bytes(), &want); err != nil { + t.Fatal(err) + } + b1, _ := json.Marshal(back) + b2, _ := json.Marshal(want) + if !bytes.Equal(b1, b2) { + t.Fatalf("put back, the state is\n%s\nwant\n%s", b1, b2) + } + // and the state given is as it was + var after bytes.Buffer + _ = json.NewEncoder(&after).Encode(s) + if !bytes.Equal(before.Bytes(), after.Bytes()) { + t.Fatal("writing the state changed the caller's agents") + } +} diff --git a/internal/gui/tests/state-option-lists.test.cjs b/internal/gui/tests/state-option-lists.test.cjs new file mode 100644 index 000000000..ec3a8d809 --- /dev/null +++ b/internal/gui/tests/state-option-lists.test.cjs @@ -0,0 +1,107 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A state sends each fields' option list once (shareOptions, statewrite.go): +// with real accounts 13 agents' model pickers offered the same 51KB +// catalog, 650KB of a 690KB /api/state. A field names its list by List, +// from 1, and api() puts the list back before anything reads the state. +// Two agents' model pickers sharing one list each show it whole, a field +// with its own options keeps them, and the state kept from the last read +// (?last=1), shared the same way, draws too. Chromium and WebKit, wide +// and narrow, in every language. +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 catalog = [ + { value: "magpie/codex/gpt-5.5", ref: "codex/gpt-5.5", label: "GPT-5.5", note: "", group: "ChatGPT" }, + { value: "magpie/zai/glm-5", ref: "zai/glm-5", label: "GLM-5", note: "", group: "Z.ai" }, + { value: "magpie/kimi/k2", ref: "kimi/k2", label: "Kimi K2", note: "", group: "Kimi" }, +]; +const effort = [{ value: "low", note: "" }, { value: "high", note: "" }]; + +function sharedState(lang, last) { + return { + agents: [ + { id: "codex", name: "Codex", path: "/test/codex", wired: true, fields: [ + { key: "model", label: "model", value: "magpie/zai/glm-5", options: null, list: 1 }, + { key: "effort", label: "effort", value: "high", options: effort }, + ] }, + { id: "crush", name: "Crush", path: "/test/crush", wired: true, fields: [ + { key: "model", label: "model", value: "magpie/kimi/k2", options: null, list: 1 }, + ] }, + ], + profiles: [], settings: { lang, theme: "light" }, served: 3, + optionLists: [catalog], + ...(last ? { last: true } : {}), + }; +} + +function serve(lang, fresh) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + 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") { + if (url.searchParams.get("last") === "1") return json(sharedState(lang, true)); + await fresh; // the kept state draws first + return json(sharedState(lang, false)); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname.startsWith("/api/")) return 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 pop = "#pop:not([hidden]) #list li"; +const LANGS = ["en", "zh", "zh-TW", "ja", "de"]; +const cases = [...LANGS.map((lang) => [lang, 1000]), ["en", 420], ["zh", 420]]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": fields sharing one option list each show it whole", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const [lang, width] of cases) { + await t.test(`${lang} ${width}px`, async () => { + const errors = []; + let release; + const fresh = new Promise((r) => { release = r; }); + const page = await (await browser.newContext({ viewport: { width, height: 640 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, fresh)); + await page.goto("http://magpie.test/?view=agents"); + // drawn from the kept state, before the fresh one comes + await page.locator('.row.agent[data-id="crush"]').waitFor(); + const read = () => page.evaluate(() => state.agents.map((a) => [a.id, a.fields.map((f) => [f.key, (f.options || []).map((o) => o.value)])])); + const want = [ + ["codex", [["model", catalog.map((o) => o.value)], ["effort", ["low", "high"]]]], + ["crush", [["model", catalog.map((o) => o.value)]]], + ]; + assert.deepEqual(await read(), want, "the kept state's lists put back"); + release(); + await page.waitForFunction(() => !state.last); + assert.deepEqual(await read(), want, "the fresh state's lists put back"); + for (const id of ["codex", "crush"]) { + const field = page.locator(`.row.agent[data-id="${id}"] .field[data-key="model"]`).first(); + if (!(await field.isVisible())) await page.locator(`.row.agent[data-id="${id}"] .ag-sum`).click(); + await field.click(); + await page.locator(pop).first().waitFor(); + for (const o of catalog) assert.equal(await page.locator(pop).filter({ hasText: o.label }).count() > 0, true, `${id}'s picker lists ${o.label}`); + await page.keyboard.press("Escape"); + await page.locator("#pop").waitFor({ state: "hidden" }); + } + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + }); +}