diff --git a/internal/agent/agent.go b/internal/agent/agent.go index fc3178149..44fdf21c7 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -58,6 +58,12 @@ type Option struct { // signed in to itself, so the agent reaches it on its own too: the // picker folds these into one row a click opens (Claude Code, #496) Same bool `json:"same,omitempty"` + // Served is a model of the agent's own that magpie's list shows it + // too, on the very account it is signed in to (Codex's ChatGPT + // models, its list's Codex section): not left out with the agent's + // own models (Picks), as the list's tick decides it (shiqi_40904: a + // routing group switched on took every one out of Codex's picker) + Served bool `json:"served,omitempty"` // Alias is the value of the option a dated id is another name of // (claude-opus-4-5-20251101 → claude-opus-4-5): the picker shows one // row for the two, the alias, unless the dated one is the value set @@ -559,8 +565,9 @@ func (a *Agent) Picks(f Field, cur map[string]string) []Option { } // Own reports whether o is a model the agent reaches on its own, not one of -// magpie's catalog: what Picks leaves out on the user's word. -func Own(o Option) bool { return o.Ref == "" && o.Value != "" } +// magpie's catalog: what Picks leaves out on the user's word. One magpie's +// list shows the agent too (Served) is the list's to show or not. +func Own(o Option) bool { return o.Ref == "" && o.Value != "" && !o.Served } // OwnModels reports whether one of a's pickers that picks among magpie's // catalog offers models of the agent's own too, which Picks can leave out. diff --git a/internal/agent/codex.go b/internal/agent/codex.go index bcdcc660d..7dc88bd25 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -1023,7 +1023,7 @@ func codexIn(at place) *Agent { if p != "" && p != magpieID && !isCCSwitchMirror(p) { own = say(group(p, options(catalog.Codex(), ""))) } else { - own = say(group("OpenAI", options(ownCodex(), ""))) + own = codexInMagpie(say(group("OpenAI", options(ownCodex(), "")))) // with magpie Codex's provider (magpie API, or a magpie model // picked with no ChatGPT sign-in beside it), Codex's own models // are reached through magpie on a ChatGPT account there: picked @@ -1876,6 +1876,27 @@ func ownCodex() []catalog.Model { return out } +// codexInMagpie marks Served those of Codex's own models that magpie's list +// shows Codex on a ChatGPT account of the user's (codex/gpt-5.5): its +// pickers leave out magpie's codex/… as only a hop (viaMagpieFor), so these +// are how they are offered, and the agent's own models switched off +// (provider.OwnModelsHidden) never takes them out. It did once a routing +// group gave the picker a catalog entry, and Codex's picker was the group +// alone (shiqi_40904 on Discord). +func codexInMagpie(own []Option) []Option { + shown, _ := provider.CatalogFor("codex") + on := map[string]bool{} + for _, e := range shown { + if provider.CodexOwn(e) { + on[e.Model] = true + } + } + for i := range own { + own[i].Served = on[own[i].Value] + } + return own +} + // codexOwnViaMagpie is the catalog id magpie serves one of Codex's own // models by on a ChatGPT account of the user's ("codex/gpt-5.5"), those // shown to Codex first; "" when none serves it. diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index 874bcad50..529fc101d 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -298,7 +298,7 @@ var wslKinds = []wslKind{ if codexFailover() { return append(group("OpenAI", options(ownCodex(), "")), viaMagpie("codex", "")...) } - return append(group("OpenAI", options(ownCodex(), "")), viaMagpieFor("codex", "")...) + return append(codexInMagpie(group("OpenAI", options(ownCodex(), ""))), viaMagpieFor("codex", "")...) } case "effort": return func(cur map[string]string) []Option { diff --git a/internal/gui/agent_models_codex_group_test.go b/internal/gui/agent_models_codex_group_test.go new file mode 100644 index 000000000..32af3addb --- /dev/null +++ b/internal/gui/agent_models_codex_group_test.go @@ -0,0 +1,100 @@ +package gui + +import ( + "encoding/base64" + "encoding/json" + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// Codex's own models, a ChatGPT account's, stay in its model picker with a +// routing group switched on and its own models switched off (shiqi_40904 on +// Discord: "开启路由组后 … 模型列表里不会显示 codex 模型"). magpie's list shows +// them Codex as its Codex section, and its pickers offer them as Codex's own +// (codex/… would only add a hop), so the switch for the agent's own models +// never takes them out. It did once the group gave the picker one of +// magpie's models, which is what the switch waits for: the picker was the +// group alone, and with the group off every model was back. +func TestCodexOwnModelsStayWithGroupOn(t *testing.T) { + home := sandboxHome(t) + codexHome := filepath.Join(home, ".codex") + t.Setenv("CODEX_HOME", codexHome) + os.MkdirAll(codexHome, 0o700) + jwt := func(c any) string { + b, _ := json.Marshal(c) + return "e30." + base64.RawURLEncoding.EncodeToString(b) + ".sig" + } + auth, _ := json.Marshal(map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{ + "id_token": jwt(map[string]any{"email": "a@x.y", "https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "plus", "chatgpt_account_id": "acc"}}), + "access_token": jwt(map[string]any{"exp": time.Now().Add(24 * time.Hour).Unix()}), "refresh_token": "r", "account_id": "acc"}}) + os.WriteFile(filepath.Join(codexHome, "auth.json"), auth, 0o600) + os.WriteFile(filepath.Join(codexHome, "config.toml"), []byte("model = \"gpt-5.5\"\n"), 0o600) + ids := []string{"gpt-5.5", "gpt-5.4", "gpt-5.4-mini", "gpt-5.3-codex", "gpt-5.2"} + var cache []map[string]any + var live []catalog.Model + for i, id := range ids { + cache = append(cache, map[string]any{"slug": id, "display_name": id, "visibility": "list", "priority": i, "context_window": 400000}) + live = append(live, catalog.Model{ID: id, Context: 400000}) + } + b, _ := json.Marshal(map[string]any{"etag": "x", "models": cache}) + os.WriteFile(filepath.Join(codexHome, "models_cache.json"), b, 0o600) + provider.ForgetAccounts() + t.Cleanup(provider.ForgetAccounts) + catalog.Reset() + t.Cleanup(catalog.Reset) + if err := catalog.SaveLive("codex", provider.CodexBase, live); err != nil { + t.Fatal(err) + } + if err := provider.SetOwnModelsHidden("codex", true); err != nil { + t.Fatal(err) + } + codex, err := agent.Find("codex") + if err != nil { + t.Fatal(err) + } + picks := func() (out []string) { + t.Helper() + for _, f := range agentFields(codex, codex.Values()) { + if f.Key == "model" { + for _, o := range f.Options { + out = append(out, o.Value) + } + } + } + return out + } + for _, id := range ids { + if got := picks(); !slices.Contains(got, id) { + t.Fatalf("group off: %s not in Codex's picker %v", id, got) + } + } + if err := provider.SaveGroup(provider.Group{ID: "mygpt", Name: "MyGPT", Members: []string{"codex/gpt-5.5", "codex/gpt-5.4"}}); err != nil { + t.Fatal(err) + } + got := picks() + for _, id := range append(slices.Clone(ids), "group/mygpt") { + if !slices.Contains(got, id) { + t.Fatalf("group on: %s not in Codex's picker %v", id, got) + } + } + // nothing of Codex's own is left for the switch to take out, so the + // list has none to show + if codex.OwnModels(codex.Values()) { + t.Fatal("Codex's list offers a switch for its own models, every one of them magpie's too") + } + // one the list takes out is the switch's again: magpie no longer shows + // it Codex + if err := provider.SetHiddenModels("codex", []string{"codex/gpt-5.4"}); err != nil { + t.Fatal(err) + } + if got := picks(); slices.Contains(got, "gpt-5.4") || !slices.Contains(got, "gpt-5.4-mini") { + t.Fatalf("gpt-5.4 taken out of the list, own models off: picker %v", got) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 4c051e7f3..715abc876 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -3155,11 +3155,12 @@ function closeAgentModels() { // was put back comes with the state if (m.hidden) for (const f of m.a.fields || []) f.options = f.options.filter((o) => !o.ref || !m.hidden.has(o.ref) || o.value === f.value); // the agent's own, left out, go as the server leaves them out - // (agent.Picks): from a picker of magpie's models, but its default and - // the one it is set to + // (agent.Picks): from a picker of magpie's models, but its default, the + // one it is set to and those magpie's list shows it too (served: Codex's + // ChatGPT models) if (m.ownHidden) { for (const f of m.a.fields || []) { - if (f.options.some((o) => o.ref)) f.options = f.options.filter((o) => o.ref || !o.value || o.value === f.value); + if (f.options.some((o) => o.ref)) f.options = f.options.filter((o) => o.ref || o.served || !o.value || o.value === f.value); } } // the agents' pickers list what's left once the writes are in diff --git a/internal/gui/tests/agent-models-own-served.test.cjs b/internal/gui/tests/agent-models-own-served.test.cjs new file mode 100644 index 000000000..1f189cfe4 --- /dev/null +++ b/internal/gui/tests/agent-models-own-served.test.cjs @@ -0,0 +1,151 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Codex's own models that magpie's list shows it too, a ChatGPT account's +// (served), stay in its model picker when its own models are switched off +// in its list (shiqi_40904 on Discord: with a routing group on, Codex's +// picker was the group alone). The picker drops the others at once on +// closing the list, as the server does (agent.Picks); the served ones, the +// group and the one it is set to stay, before the state is read again and +// after. In English and Chinese, at a narrow and a wide window; no backend, +// the API is faked here. +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 served = ["gpt-5.5", "gpt-5.4", "gpt-5.4-mini"].map((v) => ({ value: v, note: "", group: "OpenAI", icon: "openai", via: true, served: true })); +// one Codex lists that magpie doesn't serve: the switch's to take out +const lone = { value: "gpt-oss-lone", note: "", group: "OpenAI", icon: "openai", via: true }; +const grp = { value: "group/mygpt", label: "MyGPT", ref: "group/mygpt", note: "routing group", group: "Routing groups", icons: ["codex-color"] }; +const list = [ + { id: "group/mygpt", name: "MyGPT", group: "Routing groups", icons: ["codex-color"] }, + ...served.map((o, i) => ({ id: "codex/" + o.value, name: o.value, group: "Codex", icon: "codex-color", own: true, inUse: i === 0 })), +]; + +function fixture(lang) { + let ownHidden = false, late = 0; + const posts = []; + const count = { shown: list.length, listed: list.length, by: [{ name: "Routing groups", icons: ["codex-color"], n: 1 }, { name: "Codex", icon: "codex-color", n: 3 }] }; + // the server's agent.Picks: the agent's own left out, but served ones + const options = () => [...served, ...(ownHidden ? [] : [lone]), grp]; + const state = () => ({ + agents: [ + { id: "codex", name: "Codex", icon: "codex-color", path: "/fixture/codex", wired: true, models: count, + fields: [{ key: "model", label: "model", value: "gpt-5.5", options: options() }] }, + ], + profiles: [], settings: { lang, theme: "light" }, + }); + async function serve(route) { + const req = route.request(); + const 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") { + // the state read after a switch comes late, so what the picker + // offers before it is the page's own doing + if (Date.now() < late) await new Promise((r) => setTimeout(r, late - Date.now())); + return json(state()); + } + const m = url.pathname.match(/^\/api\/agent-models\/(\w+)$/); + if (m) { + if (req.method() === "POST") { + const body = req.postDataJSON(); + posts.push({ id: m[1], ...body }); + if (body.ownHidden !== undefined) { + ownHidden = body.ownHidden; + late = Date.now() + 1500; + return json({ ownHidden }); + } + return json({ models: list, count }); + } + return json({ models: list, ordered: false, only: false, own: true, ownHidden }); + } + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + 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 }); + } + return { serve, posts }; +} + +const W = { + en: { show: "Show Codex's own models" }, + zh: { show: "显示 Codex 自带的模型" }, +}; +const row = '.row.agent[data-id="codex"]'; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(W)) { + for (const width of [420, 1100]) { + test(`${engine} ${lang} ${width}: Codex's served models stay with its own switched off`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await browser.newPage({ viewport: { width, height: 760 } }); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const fx = fixture(lang); + await page.route("**/*", fx.serve); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-own-served.png`) }); + } + await browser.close(); + }); + await page.goto("http://magpie.test/?view=agents"); + await page.locator(row).waitFor(); + const pop = page.locator(".am-pop:not(.leaving)"); + const picked = async () => { + await page.locator(`${row} .field[data-key="model"]`).click(); + await page.locator("#pop:not([hidden]) #list li").first().waitFor(); + const texts = await page.locator("#pop:not([hidden]) #list li").allTextContents(); + await page.keyboard.press("Escape"); + await page.locator("#pop").waitFor({ state: "hidden" }); + return texts.map((s) => s.trim()); + }; + // a row by its model: gpt-5.4, not gpt-5.4-mini + const at = (rows, v) => rows.some((s) => s.startsWith(v) && !s.startsWith(v + "-")); + const has = (rows) => { + for (const v of ["gpt-5.4", "gpt-5.4-mini", "MyGPT"]) assert(at(rows, v), `${v} gone from Codex's picker: ${JSON.stringify(rows)}`); + }; + + let rows = await picked(); + has(rows); + assert(at(rows, "gpt-oss-lone")); + + const r = page.locator(row); + const entry = r.locator(".ag-exp .ag-chips .ag-quiet"); + if (!(await entry.isVisible())) await r.locator(".ag-link").click(); + await entry.waitFor(); + await page.waitForFunction(() => document.getAnimations().length === 0); + await entry.click(); + await pop.waitFor(); + const box = pop.locator(".am-own"); + assert.equal(await box.innerText(), W[lang].show); + await box.locator(".lib-switch").click(); + await page.waitForTimeout(250); + assert.deepEqual(fx.posts.at(-1), { id: "codex", ownHidden: true }); + await page.keyboard.press("Escape"); + await pop.waitFor({ state: "detached" }); + + // at once, before the state comes: the lone one gone, served stay + rows = await picked(); + assert(!at(rows, "gpt-oss-lone"), "Codex's own not served still offered"); + has(rows); + // and in the state read again + await page.waitForTimeout(1800); + rows = await picked(); + assert(!at(rows, "gpt-oss-lone")); + has(rows); + + assert.equal(await page.locator(".status.err, #status.err").count(), 0); + assert.deepEqual(errors, []); + }); + } + } +}