provider: a model's test can be sent to one chosen account or key (tmr11235 on X)

A provider with two or more accounts or keys that are on now offers
"Test on account..." in a model chip's right-click, an app menu (never a
native select) of those accounts' or keys' names. The pick is posted as
`account` with provider/test and pins the test (provider.TestOn,
accountNamed / keyNamed; an unknown or switched-off one is an error row,
not a silent fallback). Every result now names the account or key it went
to (Result.Account, set in probe), and the status line ends " - <name>"
for such a provider, whether the test was pinned or routing picked.
Test models and the CLI still test with routing's pick.

Core script budget raised 1,263,333 -> 1,263,700 (+367): the model chip
menu is core code and there is no page to move it to; the PLAY icon
literal was folded into one constant and the status call tightened first.

Run: gofmt clean; mote-run go test ./internal/gui ./internal/provider ok
(new TestModelTestPinnedToAKey, TestTestPicksNeedSeveral,
TestModelTestPinnedToAnAccount); model-test-account.test.cjs 10 of 10
(chromium and webkit, en zh zh-TW ja de) on mica. Broken by hand: with
the menu entry disabled the GUI test is 0 of 10. GUI batch model-*,
provider-*, i18n-*, gui-*: reds are the same on origin/main 2e92d71aa
(model-chip-steady, model-copy-id, provider-fetch-again, provider-max-
output, provider-many-keys, provider-mask, provider-typed, gui-de/ja),
all already filed (#4388, #4621, #3292, #6209, #5109, #4673, #5475).

Not tried: a real multi-account provider end to end; the CLI and the bulk
Test models button (unchanged); vet on windows/linux not rerun beyond the
earlier builds.
This commit is contained in:
yetone
2026-11-12 18:09:14 +08:00
parent 2e92d71aab
commit d964031412
8 changed files with 338 additions and 14 deletions
File diff suppressed because one or more lines are too long
+11 -9
View File
@@ -287,6 +287,7 @@ const CHECK = "m3.5 8.5 3 3 6-7";
const CROSS = "M4.5 4.5l7 7M11.5 4.5l-7 7";
const PLUS = "M8 3.5v9M3.5 8h9";
const OUT = "M6.5 3.5h-3v9h9v-3M9 3.5h3.5V7M12.5 3.5 7.5 8.5";
const PLAY_ICON = "M5.5 3.75v8.5L12.25 8z";
const COPY_ICON = "M5.5 5.5V3.5h7v7h-2M3.5 5.5h7v7h-7z";
const PENCIL = "M3.5 12.5l.5-2.5 6.8-6.8a1.2 1.2 0 0 1 1.7 0l.3.3a1.2 1.2 0 0 1 0 1.7L6 12z M9.8 4.2l2 2";
const PUZZLE = "M6.2 2.8h2.3a1.3 1.3 0 1 1 2.5 0h2.2V5a1.3 1.3 0 1 0 0 2.6v5.6H3V7.6a1.3 1.3 0 1 1 0-2.6V2.8z";
@@ -11350,8 +11351,8 @@ function renderModels(p) {
closeAgentMenu();
closeProtoMenu();
if (again) return;
const acts = [noTest ? { name: "Test this model", icon: "M5.5 3.75v8.5L12.25 8z", off: true, why: noTest, run() {} }
: { name: "Test this model", icon: "M5.5 3.75v8.5L12.25 8z", run: () => testOne(id) }];
const acts = [noTest ? { name: "Test this model", icon: PLAY_ICON, off: true, why: noTest, run() {} }
: { name: "Test this model", icon: PLAY_ICON, run: () => testOne(id) }];
// asked as Codex or Claude Code asks, for a relay that serves only
// them (耍赖天都爱 on Discord); Claude Code's once it has come
// through magpie, its headers being the ones it came with
@@ -11359,8 +11360,9 @@ function renderModels(p) {
for (const [as, agent, name] of [["codex", "Codex", "Test as Codex"], ["claude-code", "Claude Code", "Test as Claude Code"]]) {
if (!(as in (p.testsAs || {}))) continue;
const why = p.testsAs[as] ? t(p.testsAs[as]) : "";
acts.push({ name, icon: "M5.5 3.75v8.5L12.25 8z", off: !!why, why, tip: t("Asked as {agent} asks, for a relay that serves only {agent}", { agent }), run: () => testOne(id, as) });
acts.push({ name, icon: PLAY_ICON, off: !!why, why, tip: t("Asked as {agent} asks, for a relay that serves only {agent}", { agent }), run: () => testOne(id, as) });
}
if (p.testPicks) acts.push({ name: "Test on account…", icon: PLAY_ICON, tip: t("Pick the account or key the test is sent to"), run: () => openProtoMenu(c, p.testPicks.map((k) => ({ v: k.id, name: k.name, literalName: true })), null, (v) => testOne(id, "", v), "Account to test", "model-account-menu") });
}
// its id as agents and the gateway name it, to paste where a model is
// typed (ARNO, Discord: 右击菜单除了测试模型外,还能添加拷贝模型id的功能)
@@ -12073,17 +12075,17 @@ function renderModels(p) {
draw();
});
// one model, the others' results kept
const testOne = async (id, as) => {
// on one of its accounts or keys, where it has several: the result says which (tmr11235 on X)
const testOne = async (id, as, account) => {
const got = modelTests[p.id] = modelTests[p.id] || {};
got[id] = null;
draw();
try {
const r = await provTest(p.id, { ...asTyped(), test: [id], ...(as ? { as } : {}) });
const r = await provTest(p.id, { ...asTyped(), test: [id], as, account });
const x = got[id] = r.results[0];
const via = x.protocol ? apiLabel(x.protocol) : "";
const error = (x.status ? x.status + " · " : "") + x.error;
status(x.ok ? (via ? t("{model} answered via {api} in {took}", { model: id, api: via, took: ledTook(x.ms) }) : t("{model} answered in {took}", { model: id, took: ledTook(x.ms) }))
: via ? t("{model} didn't answer via {api}: {error}", { model: id, api: via, error }) : t("{model} didn't answer: {error}", { model: id, error }), x.ok ? "ok" : "err");
const api = x.protocol ? apiLabel(x.protocol) : "", took = ledTook(x.ms), model = id, error = (x.status ? x.status + " · " : "") + x.error;
status((x.ok ? (api ? t("{model} answered via {api} in {took}", { model, api, took }) : t("{model} answered in {took}", { model, took }))
: api ? t("{model} didn't answer via {api}: {error}", { model, api, error }) : t("{model} didn't answer: {error}", { model, error })) + (p.testPicks && x.account ? " · " + x.account : ""), x.ok ? "ok" : "err");
} catch (e) { delete got[id]; testErr(e); }
draw();
};
+12
View File
@@ -2994,6 +2994,9 @@ const I18N = {
"Right-click a model to test just it": "右键点击某个模型可单独测试它",
"Each model is tested with the first ticked key that can serve it": "每个模型用第一个已勾选、能提供它的密钥测试",
"Test this model": "测试此模型",
"Test on account…": "在账号上测试…",
"Pick the account or key the test is sent to": "选择发送测试请求的账号或密钥",
"Account to test": "测试所用账号",
"Test as Codex": "以 Codex 身份测试",
"Test as Claude Code": "以 Claude Code 身份测试",
"Asked as {agent} asks, for a relay that serves only {agent}": "按 {agent} 的请求方式发送,适用于只服务 {agent} 的中转站",
@@ -8086,6 +8089,9 @@ const I18N = {
"Right-click a model to test just it": "右鍵點選某個模型可單獨測試它",
"Each model is tested with the first ticked key that can serve it": "每個模型用第一個已勾選、能提供它的金鑰測試",
"Test this model": "測試此模型",
"Test on account…": "在帳號上測試…",
"Pick the account or key the test is sent to": "選擇傳送測試請求的帳號或金鑰",
"Account to test": "測試所用帳號",
"Test as Codex": "以 Codex 身分測試",
"Test as Claude Code": "以 Claude Code 身分測試",
"Asked as {agent} asks, for a relay that serves only {agent}": "依 {agent} 的請求方式傳送,適用於只服務 {agent} 的中轉站",
@@ -13200,6 +13206,9 @@ const I18N = {
"Right-click a model to test just it": "モデルを右クリックするとそのモデルだけをテストできます",
"Each model is tested with the first ticked key that can serve it": "各モデルは、それを提供できる最初のチェック済みキーでテストされます",
"Test this model": "このモデルをテスト",
"Test on account…": "アカウントを選んでテスト…",
"Pick the account or key the test is sent to": "テストを送るアカウントまたはキーを選びます",
"Account to test": "テストするアカウント",
"Test as Codex": "Codex としてテスト",
"Test as Claude Code": "Claude Code としてテスト",
"Asked as {agent} asks, for a relay that serves only {agent}": "{agent} と同じ形式で送信します({agent} 専用の中継サービス向け)",
@@ -18323,6 +18332,9 @@ const I18N = {
"Right-click a model to test just it": "Rechtsklick auf ein Modell testet nur dieses",
"Each model is tested with the first ticked key that can serve it": "Jedes Modell wird mit dem ersten angehakten Schlüssel getestet, der es bereitstellen kann",
"Test this model": "Dieses Modell testen",
"Test on account…": "Auf Konto testen…",
"Pick the account or key the test is sent to": "Konto oder Schlüssel wählen, an den der Test geht",
"Account to test": "Zu testendes Konto",
"Test as Codex": "Als Codex testen",
"Test as Claude Code": "Als Claude Code testen",
"Asked as {agent} asks, for a relay that serves only {agent}": "So gesendet, wie {agent} fragt – für ein Relay, das nur {agent} bedient",
+1 -1
View File
@@ -18,7 +18,7 @@ import (
// `git log -L` of this file.
const (
appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had
coreScriptBudget = 1_263_333 // every core script at 8016205e3, the old measure 682 over its cap there (#5918)
coreScriptBudget = 1_263_700 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to
)
// codeBytes is how many bytes of b are code: its blank lines, its lines
@@ -0,0 +1,113 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// tmr11235 on X: in a provider with several accounts or keys the model test
// goes to the one routing picks, and says nothing of which. A model chip's
// right-click now offers "Test on account…", the app's own menu (never a
// native select) of the accounts or keys that are on (testPicks): the pick
// is posted as `account` with provider/test, and the status line names the
// one that was asked. A provider with one shows no such entry. Narrow, as
// the panel is, in every language, 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 base = { icon: "generic", responses: "", anthropic: "", catalog: "", agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "" };
const PICKS = [{ id: "k1", name: "Work" }, { id: "k2", name: "Spare" }];
const relay = { ...base, id: "relay", name: "Relay", chat: "https://relay.example.com/v1",
models: [{ id: "gpt-5.5", name: "gpt-5.5", on: true }], testPicks: PICKS };
const plain = { ...base, id: "plain", name: "Plain", chat: "https://plain.example.com/v1",
models: [{ id: "model-p", name: "model-p", on: true }] };
function serve(lang, tests) {
const providers = { providers: [relay, plain], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().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") return json(state);
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/provider/test") {
const body = route.request().postDataJSON();
tests.push(body);
return json({ results: body.test.map((model) => ({ ok: true, ms: 123, model, protocol: "responses", account: (PICKS.find((k) => k.id === body.account) || PICKS[0]).name })) });
}
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 });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: a model is tested on the account picked`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 420, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], tests = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, tests));
await page.goto("http://magpie.test/?view=providers");
const tr = (k, vars = {}) => page.evaluate(([k, vars]) => t(k, vars), [k, vars]);
if (lang !== "en") {
const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang]?.[k]), [lang,
["Test on account…", "Pick the account or key the test is sent to", "Account to test"]]);
assert.deepEqual(missing, [], `every string has its ${lang}`);
}
const menu = page.locator(".pop.row-menu");
const rightClick = async (c) => {
await c.scrollIntoViewIfNeeded();
await page.waitForTimeout(200);
await c.click({ button: "right" });
await menu.waitFor();
};
await page.locator(".row.provider", { hasText: "Relay" }).click();
const chip = page.locator(".editor .mchips .mchip", { hasText: "gpt-5.5" });
await chip.waitFor();
await rightClick(chip);
const entry = menu.getByRole("menuitem", { name: new RegExp("^" + (await tr("Test on account…")).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) });
assert.equal(await entry.getAttribute("title"), await tr("Pick the account or key the test is sent to"));
await entry.click();
// the app's menu, not a native select
const pick = page.locator(".pop.proto-menu");
await pick.waitFor();
assert.equal(await page.locator(".editor select").count(), 0, "no native select");
assert.equal(await pick.locator(".pm-head").textContent(), await tr("Account to test"));
assert.deepEqual(await pick.locator(".pm-name").allTextContents(), ["Work", "Spare"]);
const box = await pick.boundingBox();
assert(box.x >= 0 && box.x + box.width <= 420, `the menu fits: ${JSON.stringify(box)}`);
await pick.locator(".pm-item", { hasText: "Spare" }).click();
for (let i = 0; i < 60 && !tests.length; i++) await page.waitForTimeout(50);
assert.deepEqual(tests.map((b) => ({ id: b.id, test: b.test, account: b.account })), [{ id: "relay", test: ["gpt-5.5"], account: "k2" }]);
await chip.locator(".tdot.ok").waitFor();
// the result says which was asked
const said = await page.locator("#status").textContent();
assert(said.endsWith(" · Spare"), said);
// Test this model names no account: routing's pick, still named
await rightClick(chip);
await menu.getByRole("menuitem", { name: await tr("Test this model") }).click();
for (let i = 0; i < 60 && tests.length < 2; i++) await page.waitForTimeout(50);
assert.equal(tests[1].account, undefined, "a plain test names no account");
await page.waitForFunction(() => document.querySelector("#status")?.textContent.endsWith(" · Work"));
// a provider with one account has no such entry
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "Plain" }).click();
const other = page.locator(".editor .mchips .mchip", { hasText: "model-p" });
await other.waitFor();
await rightClick(other);
assert.equal(await menu.getByRole("menuitem", { name: await tr("Test on account…") }).count(), 0);
assert.deepEqual(errors, []);
});
}
}
+26 -3
View File
@@ -425,9 +425,24 @@ func (p Provider) testOne(ctx context.Context, model string) Result {
// (AccountsFor; #4992, scutken: a newapi pool's grok-4.7, served by
// its third account alone, was asked of the first and failed 503 "no
// available channel" while real requests were answered)
acct, ok := p.accountFor(model)
if !ok {
return Result{Model: model, Error: "every account that's on is set not to serve this model"}
var acct Provider
if ref := testOnRef(ctx); ref != "" && p.Account != nil {
// the account the user picked to test (TestOn)
var found bool
if acct, found = p.accountNamed(ref); !found {
return Result{Model: model, Error: fmt.Sprintf("no account %q that's on", ref)}
}
} else if ref != "" {
var found bool
if p, found = p.keyNamed(ref); !found {
return Result{Model: model, Error: "no such key that's on"}
}
acct = p
} else {
var ok bool
if acct, ok = p.accountFor(model); !ok {
return Result{Model: model, Error: "every account that's on is set not to serve this model"}
}
}
ctx, p = p.loggedAs(ctx, acct), acct
if p.isClaudeAccount() {
@@ -789,6 +804,14 @@ func (p Provider) ownRequests(ctx context.Context, kind string) context.Context
// write the status alone, so a failed test's row said nothing of why
// (ysm119 on Discord: "no answer", and no error to find anywhere).
func probe(ctx context.Context, p Provider, proto Protocol, url string, body []byte, model string, wait time.Duration) Result {
r := probeRetried(ctx, p, proto, url, body, model, wait)
if r.Account == "" {
r.Account = p.testedAccount()
}
return r
}
func probeRetried(ctx context.Context, p Provider, proto Protocol, url string, body []byte, model string, wait time.Duration) Result {
r := probeAt(ctx, p, proto, url, body, model, wait)
if r.Status != http.StatusNotFound {
return r
+96
View File
@@ -0,0 +1,96 @@
package provider
import (
"context"
"strings"
)
// A test can be pinned to one of a provider's accounts or keys (tmr11235
// on X): a provider of several is tested with the one routing would send
// the model to, so a model that failed said nothing of the other accounts.
// TestOn asks the one named: a pool account by its user, a key by its id
// (KeyInfo.ID). The result names the account or key that was asked.
type testOnKey struct{}
// TestOn is ctx with Test and TestModels asking ref's account or key
// ("" as routing picks one).
func TestOn(ctx context.Context, ref string) context.Context {
return context.WithValue(ctx, testOnKey{}, strings.TrimSpace(ref))
}
func testOnRef(ctx context.Context) string {
r, _ := ctx.Value(testOnKey{}).(string)
return r
}
// TestPick is one account or key a test can be pinned to.
type TestPick struct {
ID string `json:"id"`
Name string `json:"name"`
}
// TestPicks are the accounts or keys of p that are on, to pick one from
// for a test; none when p has fewer than two.
func (p Provider) TestPicks() []TestPick {
var out []TestPick
if p.Account != nil {
for _, a := range p.AccountsOn() {
out = append(out, TestPick{ID: a.Account.User, Name: p.AccountShown(a.Account.User)})
}
} else {
for _, k := range p.KeyList() {
if !k.On {
continue
}
name := k.Name
if name == "" {
name = k.Masked
}
out = append(out, TestPick{ID: k.ID, Name: name})
}
}
if len(out) < 2 {
return nil
}
return out
}
// accountNamed is p as its account named ref (a pool's user), on or not
// served by the user's say-so: the user asked for this one.
func (p Provider) accountNamed(ref string) (Provider, bool) {
for _, a := range p.AccountsOn() {
if strings.EqualFold(a.Account.User, ref) {
return a.Provider, true
}
}
return p, false
}
// keyNamed is p using its key on with id ref, whichever models the user
// let it serve: the user asked for this one.
func (p Provider) keyNamed(ref string) (Provider, bool) {
for _, k := range p.KeysOn() {
if keyID(k.Key) == ref {
q := p.WithKey(k)
q.AccountModels = nil
return q, true
}
}
return p, false
}
// testedAccount is who a request sent with p goes as, for a result to
// name: a pool's account, or the key of a provider that has several.
func (p Provider) testedAccount() string {
if p.Account != nil {
return p.Account.User
}
if len(p.Keys) == 0 || p.Key == "" {
return ""
}
if p.KeyName != "" {
return p.KeyName
}
return Mask(p.Key)
}
+78
View File
@@ -0,0 +1,78 @@
package provider
import (
"context"
"testing"
"time"
)
// A model's test can be pinned to one of a provider's keys (tmr11235 on
// X), and its result names the key that was asked: without the pick,
// routing sends m to the first key that serves it and the others are
// never tried.
func TestModelTestPinnedToAKey(t *testing.T) {
probeHome(t)
srv, asked := askingRelay(t, "sk-b", "m")
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1",
Key: "sk-a", KeyName: "first", Keys: []KeyAccount{{Name: "second", Key: "sk-b"}}, Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
p, err := Find("relay")
if err != nil {
t.Fatal(err)
}
picks := p.TestPicks()
if len(picks) != 2 || picks[0].Name != "first" || picks[1].Name != "second" || picks[1].ID != keyID("sk-b") {
t.Fatalf("the picks: %+v", picks)
}
// the key asked: sk-b answers m, sk-a is turned away, and each result says who was asked
rs := p.TestModels(TestOn(context.Background(), keyID("sk-b")), []string{"m"})
if len(rs) != 1 || !rs[0].OK || rs[0].Account != "second" {
t.Fatalf("pinned to the second key: %+v (asked %v)", rs, asked())
}
rs = p.TestModels(TestOn(context.Background(), keyID("sk-a")), []string{"m"})
if len(rs) != 1 || rs[0].OK || rs[0].Account != "first" {
t.Fatalf("pinned to the first key: %+v (asked %v)", rs, asked())
}
// nothing pinned: routing's pick, still named
rs = p.TestModels(context.Background(), []string{"m"})
if len(rs) != 1 || rs[0].Account == "" {
t.Fatalf("unpinned: %+v", rs)
}
// a key that isn't there is said, not swapped for another
rs = p.TestModels(TestOn(context.Background(), "nope"), []string{"m"})
if len(rs) != 1 || rs[0].OK || rs[0].Error == "" {
t.Fatalf("a key that is not there: %+v", rs)
}
}
// One key is nothing to pick from.
func TestTestPicksNeedSeveral(t *testing.T) {
if got := (Provider{ID: "x", Key: "sk-a"}).TestPicks(); got != nil {
t.Fatalf("one key: %+v", got)
}
}
// A pool's test pinned to its second account asks it, though the first
// is the one routing takes, and names it (twoAccountPlugin's fake vendor
// answers b@fake alone).
func TestModelTestPinnedToAnAccount(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
p, wrong := twoAccountPlugin(t, ctx, nil)
if got := p.TestPicks(); len(got) != 2 || got[0].ID != "a@fake" || got[1].ID != "b@fake" {
t.Fatalf("the picks: %+v", got)
}
rs := p.TestModels(TestOn(ctx, "b@fake"), []string{"fake-1"})
if len(rs) != 1 || !rs[0].OK || rs[0].Account != "b@fake" {
t.Fatalf("pinned to b@fake: %+v (others asked %v)", rs, wrong())
}
rs = p.TestModels(TestOn(ctx, "a@fake"), []string{"fake-1"})
if len(rs) != 1 || rs[0].OK || rs[0].Account != "a@fake" {
t.Fatalf("pinned to a@fake, which the vendor turns away: %+v", rs)
}
rs = p.TestModels(TestOn(ctx, "c@fake"), []string{"fake-1"})
if len(rs) != 1 || rs[0].OK || rs[0].Error == "" {
t.Fatalf("an account that isn't there: %+v", rs)
}
}