diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 2626a9375..a66dc30d2 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -358,6 +358,7 @@ var notYet = map[string]string{ "POST /api/sessions/carry": U, // sessions.go "POST /api/sessions/export": U, // sessions.go "POST /api/sessions/terminal": W, // sessions.go + "GET /api/model-loads": U, // speeds.go "GET /api/model-speeds": U, // speeds.go "GET /api/gateway/held/{name}": U, // trace.go "GET /api/gateway/history": U, // trace.go diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 5877eb833..205aacb42 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2313,6 +2313,9 @@ body .foot .status.lift { white-space: normal; overflow-wrap: anywhere; text-ove .field .fast-tag { display: inline-flex; flex: none; color: var(--accent); } .field .fast-tag path { fill: currentColor; } .ag-open .field .fast-tag { order: 1; } +/* a model's load by it, as its picker row says it (axelburks on Discord) */ +.field .badge.load { flex: none; padding: 0 4px; font-size: 9px; line-height: 14px; } +.ag-open .field .badge.load { order: 1; } /* Ultrafast (#1954): two bolts, overlapped to fit the bolt's place */ .bolts { display: inline-flex; align-items: center; } .bolts svg + svg { margin-left: -8px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index ab5f5f643..6aada34fc 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -496,8 +496,7 @@ function renderAgents() { if (tiers) shownFields.push(tiers); const sorted = shownFields.sort((x, y) => wide(y) - wide(x) || extra(x) - extra(y)); const plain = sorted.filter((f) => !extra(f)).length; - // the squares share one cell, side by side: two (Codex's subagents and - // sign-in) wrapped the second under the first + // the squares share one cell, side by side const extras = el("span", "extras-cell"); const fieldBtn = (f, cls) => { const b = el("button", "field " + cls); @@ -507,8 +506,7 @@ function renderAgents() { if (f.value && opt?.direct) b.title += "\n" + directSaid(a, opt); const effort = f.key === "effort" || f.label === "effort" || f.label === "thinking" || TIER_EFFORTS.includes(f.label) || f.label === SUB_EFFORT; if (opt?.icon || opt?.icons?.length) b.append(optionIcon(opt)); - // a field with no logo of its own still leads with an icon: how much - // effort, or the agent's own for its default, as the picker shows it + // no logo of its own: effort's icon, or the agent's for its default else if (effort) b.append(effortIcon(f)); else if (!f.value && !f.menu && a.icon) b.append(icon(a.icon)); else if (!wide(f) || !f.value) b.append(el("span", "k", t(f.label))); @@ -517,6 +515,7 @@ function renderAgents() { if (f.menu) b.title = f.options.map((o) => `${o.label}: ${o.note}`).join("\n"); b.append(el("span", "v" + (f.value || f.custom ? "" : " empty"), shown)); if (f.value && opt?.fast) b.append(fastTag(opt.ultra)); + if (f.value && opt?.ref) { b.dataset.ref = opt.ref; const g = loadTag(loadOf(opt.ref)); if (g) b.append(g); } const c = el("span", "chev"); c.append(svg(CHEV, 11, 1.7)); b.append(c); @@ -4338,6 +4337,7 @@ async function load(again) { tintPanel(); tintTitleBar(); renderAgents(); + readLoads(true); redrawSuffix(); redrawNoNames(); // Update all's outcome stays until the agents are read again @@ -4833,7 +4833,7 @@ function openPicker(agent, field, anchor, ev, only) { } const modelPicker = (["model", "small", "large", MEMORIES, SUB_MODEL, AUTO_MODE, "executor", "planner", ...ROLE_MODELS].includes(field.label) || hermesBot(field)) && !only; pick = { agent, field, options, groups, anchor, cursor: 0, free: !only && !field.menu, modelPicker, effortPicker, groupFilter: "all" }; - if (modelPicker) readSpeeds(); + if (modelPicker) { readSpeeds(); readLoads(); } anchor.classList.add("open"); const pop = $("#pop"); pop.classList.toggle("model-picker", modelPicker); @@ -5263,7 +5263,7 @@ function rateTag(rate = 0, was = 0) { // loadTag: how busy its plugin says the model is now (magpie.load) function loadTag(n) { if (n == null) return null; - const g = el("span", "badge ctx", Math.round(n) + "%"); + const g = el("span", "badge ctx load", Math.round(n) + "%"); g.title = t("{n}% busy now, as its plugin says", { n: Math.round(n) }); return g; } @@ -5324,14 +5324,7 @@ function contextTag(n, name) { return tag; } -// pathTag: an agent's model picker says by each model whether the agent -// asks it through magpie or of its own vendor directly (Claude Code on its -// own sign-in), and its Default, while it is connected, that it takes the -// agent off magpie. Every agent's picker says it so, in one tag the note's -// ellipsis can't cut off: the others' "· via magpie" ended their notes, -// where Claude Code's was a tag (EZN7L2C3, #834). Codex's own models, -// through magpie while it is routed, say so too (via); Codex's, Grok -// Build's and Antigravity CLI's own said nothing at all +// pathTag: magpie or the vendor direct, by a picker's model (#834) function pathTag(o) { if (!pick?.agent || o.custom || o.run) return null; let tag = null; @@ -5348,10 +5341,7 @@ function pathTag(o) { return tag; } -// modelSpeeds: each catalog ref's speed this week from the usage ledger -// ({ttft ms, tps, n}, /api/model-speeds), read when a model picker opens, -// at most once a minute; a model several providers serve shows which of -// them answers it fastest (axuhere on X) +// modelSpeeds: each ref's speed this week, read once a minute at most let modelSpeeds = {}, speedsRead = 0; function readSpeeds() { if (Date.now() - speedsRead < 60000) return; @@ -5362,16 +5352,14 @@ function readSpeeds() { }).catch(() => { speedsRead = 0; }); } -// speedRank: about how long a 200-token reply takes on o's provider, in -// seconds; Infinity when no reply was timed +// speedRank: a 200-token reply's seconds function speedRank(o) { const s = o.ref && modelSpeeds[o.ref]; if (!s || !(s.ttft || s.tps)) return Infinity; return (s.ttft || 0) / 1000 + (s.tps ? 200 / s.tps : 0); } -// speedTag: the quiet speed by a picker's model, tokens a second, or the -// first token's wait when only that was timed +// speedTag: tok/s, else the first token's wait function speedTag(o) { const s = o.ref && modelSpeeds[o.ref]; if (!s || !(s.ttft || s.tps)) return null; @@ -5381,6 +5369,29 @@ function speedTag(o) { return tag; } +// modelLoads: by ref lowercased, read every 30s at most (axelburks) +let modelLoads = {}, loadsRead = 0; +function readLoads(rows) { + if (Date.now() - loadsRead < 3e4 || (rows && !$(".field[data-ref]"))) return; + loadsRead = Date.now(); + api("model-loads").then((l) => { + l ||= {}; + if (JSON.stringify(l) === JSON.stringify(modelLoads)) return; + modelLoads = l; + for (const b of $$(".field[data-ref]")) { + b.querySelector(".load")?.remove(); + const g = loadTag(loadOf(b.dataset.ref)); + if (g) b.insertBefore(g, b.querySelector(".chev")); + } + if (pick?.modelPicker) { const o = pick.items?.[pick.cursor]; filter(o && ((x) => x === o)); } + }).catch(() => { loadsRead = 0; }); +} +// loadOf: ref's load, a model@size's its model's +function loadOf(ref) { + const k = (ref || "").toLowerCase(), at = k.lastIndexOf("@"); + return modelLoads[k] ?? (at > k.indexOf("/") + 1 ? modelLoads[k.slice(0, at)] : null); +} + function renderList() { const list = $("#list"); list.replaceChildren(); @@ -5408,18 +5419,15 @@ function renderList() { if (ctx) words.append(ctx); const speed = pick.modelPicker && speedTag(o); if (speed) words.append(speed); - // an Aside account's note is its e-mail, or Aside's "Local Account", - // then whether Aside has it active: the words are magpie's, the e-mail not + const busy = pick.modelPicker && loadTag(loadOf(o.ref)); + if (busy) words.append(busy); + // an Aside account's note: its e-mail (as is), then magpie's words let note = o.note && o.note !== (o.label || o.value) ? (own ? t(o.note) : asideAccount(pick.agent, pick.field) ? o.note.split(" · ").map((w) => t(w)).join(" · ") : o.note) : ""; - // which way the model goes, as a tag the note's ellipsis can't cut - // off: "· via magpie" ended a long note (an account's e-mail), and - // Claude Code's own models said nothing, so an Opus asked of Anthropic - // directly and a Sonnet through magpie looked alike (#726) + // which way the model goes, a tag the note's ellipsis can't cut (#726) const path = pathTag(o); if (path) { words.append(path); note = note.replace(/(^| · )via magpie$/, ""); } if (q && o.group && !note) note = o.group; - // a note cut off by its ellipsis (the other groups a model is in, - // #907) reads whole on hover + // a note cut off by its ellipsis reads whole on hover (#907) if (note) { const n = el("span", "n", note); n.title = note; words.append(n); } li.append(words); if (o.run) li.title = t(DISCONNECT_TIP, { agent: pick.agent.name }); @@ -24100,6 +24108,7 @@ document.addEventListener("visibilitychange", () => { if (!document.hidden) { lo // never under an open menu setInterval(async () => { if (document.hidden || !state?.agents || document.querySelector(".pop:not([hidden])")) return; + readLoads(true); let drift; try { drift = await api("drift"); } catch { return; } let changed = false; diff --git a/internal/gui/model_loads_test.go b/internal/gui/model_loads_test.go new file mode 100644 index 000000000..88adfe9e4 --- /dev/null +++ b/internal/gui/model_loads_test.go @@ -0,0 +1,66 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/settings" +) + +// /api/model-loads says how busy each plugin model is, keyed by the ref +// an agent's model picker gives the row, lowercased, so the Agents page +// shows the provider editor's figure by the model (axelburks on Discord). +// A model the user lists by another id is under that id; a stale load, +// and a model never reported, say nothing. +func TestModelLoadsByRef(t *testing.T) { + sandboxHome(t) + plugin.ForgetLoads() + t.Cleanup(plugin.ForgetLoads) + s := settings.Load() + s.ModelIDs = map[string]string{"acme/Fast": "big", "acme/grok": "grok-4.7@256k"} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + now := time.Now() + plugin.NoteLoadsForTest("acme", map[string]float64{"big": 87.4, "grok-4.7": 60, "GLM-5": 130}, now) + plugin.NoteLoadsForTest("acme", map[string]float64{"old": 40}, now.Add(-plugin.LoadFresh-time.Minute)) + mux := http.NewServeMux() + speedsAPI(mux) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/model-loads", nil)) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + var got map[string]float64 + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + for ref, want := range map[string]float64{"acme/fast": 87.4, "acme/grok": 60, "acme/glm-5": 130} { + if v, ok := got[ref]; !ok || v != want { + t.Errorf("%s = %v (%v); want %v", ref, v, ok, want) + } + } + for _, ref := range []string{"acme/old", "acme/quiet"} { + if v, ok := got[ref]; ok { + t.Errorf("%s says %v; want nothing", ref, v) + } + } +} + +// With no plugin reporting, the answer is an empty object, not null: the +// page reads it as a map. +func TestModelLoadsNoneReported(t *testing.T) { + sandboxHome(t) + plugin.ForgetLoads() + mux := http.NewServeMux() + speedsAPI(mux) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/model-loads", nil)) + if b := w.Body.String(); w.Code != 200 || (b != "{}" && b != "{}\n") { + t.Fatalf("%d %q; want {}", w.Code, b) + } +} diff --git a/internal/gui/speeds.go b/internal/gui/speeds.go index e3e4cbb3f..93e285357 100644 --- a/internal/gui/speeds.go +++ b/internal/gui/speeds.go @@ -2,7 +2,9 @@ package gui import ( "net/http" + "time" + "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/usage" ) @@ -41,4 +43,12 @@ func speedsAPI(mux *http.ServeMux) { mux.HandleFunc("GET /api/model-speeds", func(rw http.ResponseWriter, r *http.Request) { writeJSON(rw, modelSpeeds()) }) + // how busy each model's plugin says it is now, by the same ref + // lowercased, for the Agents page's model and its picker (axelburks + // on Discord: only the provider editor showed it). Read when a picker + // opens and with the Agents page's drift check, each at most every + // 30s; with no plugin reporting it is an empty map at once. + mux.HandleFunc("GET /api/model-loads", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, provider.ModelLoads(time.Now())) + }) } diff --git a/internal/gui/tests/agent-model-load.test.cjs b/internal/gui/tests/agent-model-load.test.cjs new file mode 100644 index 000000000..108d36837 --- /dev/null +++ b/internal/gui/tests/agent-model-load.test.cjs @@ -0,0 +1,107 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Agents page says how busy a model's plugin says it is now, by the +// model picked on the row and by each model in its picker, the figure the +// provider editor shows (/api/model-loads, by the picker's ref lowercased): +// axelburks on Discord found it only in the provider's editor, too deep to +// pick a model by. A model with no load reported says nothing; a model@size +// has its model's. In Chromium and WebKit, at a wide and a narrow window, +// in every language. ARTIFACT_DIR keeps screenshots. +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 row = (group, icon, id, label) => ({ value: id, ref: id, label, group, icon }); +const options = [ + row("Inhouse", "generic", "Inhouse/GLM-5", "GLM-5"), + row("Inhouse", "generic", "inhouse/grok-4.7@256k", "Grok 4.7 (256K)"), + row("Inhouse", "generic", "inhouse/quiet", "Quiet"), + row("Kimi", "kimi", "kimi/k3", "Kimi K3"), +]; +const loads = { "inhouse/glm-5": 87.4, "inhouse/grok-4.7": 130 }; +const said = { + en: "87% busy now, as its plugin says", + zh: "插件报告当前负载 87%", + "zh-TW": "外掛回報目前負載 87%", + ja: "プラグインの報告では現在 87% の負荷", + de: "laut seinem Plugin gerade zu 87 % ausgelastet", +}; + +function serve(lang, asked) { + return async (route) => { + const url = new URL(route.request().url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(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: { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", icon: "codex-color", wired: true, fields: [{ key: "model", label: "model", value: "Inhouse/GLM-5", options }] }], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/model-loads") { asked.n++; return route.fulfill({ json: loads }); } + if (url.pathname === "/api/agents/cli") return route.fulfill({ json: { agents: {}, pending: false } }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + 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 inside = (tag, box) => { + const b = tag.getBoundingClientRect(), r = box.getBoundingClientRect(); + return b.width > 0 && b.left >= r.left - 0.5 && b.right <= r.right + 0.5 && b.top >= r.top - 0.5 && b.bottom <= r.bottom + 0.5; +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1000, 440]) { + for (const lang of Object.keys(said)) { + test(`${engine} ${width}px ${lang}: the picked model and each picker row say its load`, async () => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + try { + const page = await browser.newPage({ viewport: { width, height: 760 } }); + const errors = [], asked = { n: 0 }; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("http://magpie.test/**", serve(lang, asked)); + await page.goto("http://magpie.test/"); + await page.locator('#nav [data-view="agents"]').click(); + const field = page.locator('#agents [data-key="model"]').first(); + await field.locator(".badge.load").waitFor(); + const f = await field.evaluate((b, inside) => { + const tag = b.querySelector(".badge.load"); + return { text: tag.textContent, title: tag.title, inside: new Function("return " + inside)()(tag, b), shown: b.querySelector(".v").getBoundingClientRect().width > 0 }; + }, inside.toString()); + assert.equal(f.text, "87%"); + assert.equal(f.title, said[lang]); + assert(f.inside, "the load sits inside the model's button"); + assert(f.shown, "the model's name still shows beside it"); + if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `agent-load-row-${engine}-${width}-${lang}.png`) }); + // the rows drawn again (a drift, a change) keep it, with no read between + await page.evaluate(() => renderAgents()); + assert.equal(await field.locator(".badge.load").textContent({ timeout: 1000 }), "87%", "drawn again, the row keeps its load"); + + await field.click(); + await page.locator("#list .badge.load").first().waitFor(); + const rows = await page.evaluate((inside) => { + const within = new Function("return " + inside)(); + return [...document.querySelectorAll("#list li:not(.group):not(.custom)")].map((li) => { + const tag = li.querySelector(".badge.load"); + return { name: li.querySelector(".v")?.textContent, tag: tag?.textContent || "", title: tag?.title || "", inside: !tag || within(tag, li) }; + }); + }, inside.toString()); + const by = Object.fromEntries(rows.map((r) => [r.name, r])); + assert.equal(by["GLM-5"].tag, "87%"); + assert.equal(by["GLM-5"].title, said[lang]); + assert.equal(by["Grok 4.7 (256K)"].tag, "130%", "a model@size has its model's load"); + assert.equal(by.Quiet.tag, "", "no load reported, nothing said"); + assert.equal(by["Kimi K3"].tag, "", "no load reported, nothing said"); + assert(rows.every((r) => r.inside), `each load inside its row: ${JSON.stringify(rows)}`); + if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `agent-load-menu-${engine}-${width}-${lang}.png`) }); + // read once for the row and the picker both, not again at the open + assert.equal(asked.n, 1, "model-loads read once within 30s"); + assert.deepEqual(errors, [], "page runtime errors"); + } finally { + await browser.close(); + } + }); + } + } +} diff --git a/internal/gui/tests/menu-scroll.test.cjs b/internal/gui/tests/menu-scroll.test.cjs index 66b83d241..01b544395 100644 --- a/internal/gui/tests/menu-scroll.test.cjs +++ b/internal/gui/tests/menu-scroll.test.cjs @@ -40,7 +40,7 @@ async function serve(route) { if (url.pathname === "/api/gateway/trace") return json({ mine: false, now: date, totals: { requests: 0, rerouted: 0, errors: 0 } }); if (url.pathname === "/api/plugins/updates") return json({ waiting: [] }); if (url.pathname === "/api/usage/quotas" || url.pathname === "/api/usage/quotas/history" || url.pathname === "/api/agents/install" || url.pathname === "/api/plugins/agents") return json([]); - if (url.pathname === "/api/whatsnew" || url.pathname === "/api/model-speeds") return json({}); + if (url.pathname === "/api/whatsnew" || url.pathname === "/api/model-speeds" || url.pathname === "/api/model-loads") return json({}); if (url.pathname === "/api/upstream") return json({ vendors: [], providers: {} }); // the sidebar's plugin pages, and plugin panels in magpie's pages: none if (url.pathname === "/api/plugin-pages" || url.pathname === "/api/plugin-panels") return json([]); diff --git a/internal/plugin/load.go b/internal/plugin/load.go index 108c6c2cc..55dddf9d7 100644 --- a/internal/plugin/load.go +++ b/internal/plugin/load.go @@ -90,6 +90,30 @@ func ModelLoad(provider, model string, now time.Time) (pct float64, at time.Time return l.pct, l.at, true } +// FreshLoads is every load reported less than LoadFresh before now, by +// plugin provider id and then the model id lowercased, as ModelLoad +// answers each: nil when none is (a magpie with no plugin reporting). +func FreshLoads(now time.Time) map[string]map[string]float64 { + loads.Lock() + defer loads.Unlock() + var out map[string]map[string]float64 + for provider, m := range loads.m { + for k, l := range m { + if now.Sub(l.at) > LoadFresh { + continue + } + if out == nil { + out = map[string]map[string]float64{} + } + if out[provider] == nil { + out[provider] = map[string]float64{} + } + out[provider][k] = l.pct + } + } + return out +} + // NoteLoadsForTest is a "load" event's loads reported at at, for a test. func NoteLoadsForTest(provider string, got map[string]float64, at time.Time) { noteLoads(provider, got, at) diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index 044cda147..45511e21f 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -147,6 +147,30 @@ func (p Provider) PluginProvider() string { return p.Account.plugin.ID } +// ModelLoads is how busy each model is that a plugin reported a load for +// in the last plugin.LoadFresh, by the ref an agent's model picker gives +// it ("provider/model", lowercased), the figure the provider editor shows +// by the model (plugin.ModelLoad): a model the user lists by another id +// (SetModelID) under that id, one listed as its own under its own. A +// model@size the plugin reported only by its model is left for the +// reader to look up by the model (axelburks on Discord: the Agents page +// shows it too). Nothing reported, nothing more is read. +func ModelLoads(now time.Time) map[string]float64 { + out := map[string]float64{} + for pp, ms := range plugin.FreshLoads(now) { + id := PluginID(pp) + for own, pct := range ms { + out[strings.ToLower(id+"/"+own)] = pct + } + for own, listed := range modelIDsOf(id).local { + if pct, _, ok := plugin.ModelLoad(pp, own, now); ok { + out[strings.ToLower(id+"/"+listed)] = pct + } + } + } + return out +} + // OpenAIBase is where p takes the OpenAI-shaped requests that are no chat // (embeddings, rerank, speech, transcriptions): its Chat base, and a // plugin's fetch under plugin:///v1 whatever API its chat models are