From d9640314123d0c74a7b9c1e3a3cdaab0997ea3cc Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 12 Nov 2026 18:09:14 +0800 Subject: [PATCH] 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 " - " 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. --- docs/subsystems/providers-accounts.md | 2 +- internal/gui/assets/app.js | 20 ++-- internal/gui/assets/i18n.js | 12 ++ internal/gui/core_budget_test.go | 2 +- .../gui/tests/model-test-account.test.cjs | 113 ++++++++++++++++++ internal/provider/test.go | 29 ++++- internal/provider/test_pick.go | 96 +++++++++++++++ internal/provider/test_pick_test.go | 78 ++++++++++++ 8 files changed, 338 insertions(+), 14 deletions(-) create mode 100644 internal/gui/tests/model-test-account.test.cjs create mode 100644 internal/provider/test_pick.go create mode 100644 internal/provider/test_pick_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index f1924769f..dbcc87f9c 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -86,7 +86,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) | | Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call on a process's first ask, whatever the kept list's age, and hourly after (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. The magpie serving the gateway fetches it when it starts and whenever it is due, asked for or not (`KeepPartnersFresh`), so an app left open on another page still learns of a partner added. The file also says when the last fetch started (`tried`) and, when it failed, why (`error`, logged once until a fetch gets the list again), so a list that stops changing tells a fetch that fails from one that never came back (`tried` after `at`, no error) and from none asked (#3362). Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon, used as it is while its `iconUrl` stays the same; the prune after a save of `providers.json` (`pruneIcons`) leaves the logos of the partners listed now (`keptPartnerIcons`), as it leaves a plugin's. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) | | Local servers | A preset of `KindLocal` (Ollama, LM Studio, oMLX, MLX-Serve) is at its server's default port on this machine. Another address — a port, or another computer — is given in the window's editor, in its Server address field, shown first above the key and never folded (a folded one read as an LM Studio whose base URL can't be changed, mengxiangziyou on X), or in the TUI (asked on adding, `w` after); on the command line with `address=` (`atAddress` in `providers_cli.go`: every URL moves, from the preset's when the provider was saved with none, and `address=` alone puts a local server back at its preset's), or the URLs themselves (`url=`, `anthropic=`, `responses=`). `AtAddress` replaces only each URL's scheme, host and port, each API keeping its path; `AddressOf` is the address an editor starts from. The window sends the URLs moved only when the address was changed, so a Save doesn't move URLs set apart (another app's import). A provider of the user's own (no preset) has `w` in the TUI too: each base URL it has is asked in turn, typed in as it is, Enter alone keeping one (`customURLsAsk`). | [`local_address.go`](../../internal/provider/local_address.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) | -| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Each API is asked with a model that chats, if the list has one; an embedding or rerank model (`catalog.ServesOf`) is asked only on Chat's URL, at its `/embeddings` or `/rerank` with the smallest body and no extra body, as the gateway's `retrieve` asks it, and the other APIs say why they weren't asked (heatonz on Discord: a vendor of only those detected nothing, asked to chat; `TestDetectEmbeddingOnly`). A saved provider whose list has nothing to chat with tests on such a model (`testModel`, `TestTestEmbeddingOnly`), and its editor and the add form's Fetch models say the models need no pick (`retrieval` in the list's answer and the provider's JSON, `provider-retrieval-only.test.cjs`). A model's test (Test models, a model's right-click, `magpie provider test`) asks the account or key a request for it goes to: `provider.AccountsFor` and `provider.KeysFor` ([`route_accounts.go`](../../internal/provider/route_accounts.go)), which the gateway's `perKeyEvery` routes by too, its usage and spend caps aside (one the user lets serve it, `AccountModels`; whose own list or plan has it, `Account.Lists`, `PlanServing`, `Serving`; in the user's order, `AccountsOn`), so a pool whose accounts list different models (a newapi plugin's) asks the one whose list has it, and one every account is barred from isn't asked. The provider's Test picks each endpoint's model from every account's and asks it of the account that serves it (`routedTo`), and with keys the first key with a model of its own to test (`testWith`). The request log's row names the account asked (`loggedAs`; #4992, `TestModelTestAsksTheAccountThatServesIt`). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. A Chat or Responses URL typed without its version (CRS's `…/openai`, Cyrus_4433 on X: CRS serves `/openai/v1/chat/completions` and `/openai/responses`, and answers anything else 404 `Not Found`) that is answered 404 is asked once more under `/v1` (`missingV1`, not for an account, Azure, Bedrock or Vertex); answered there, the saved provider's URL takes the `/v1` (`setV1`), the result carries it (`Result.V1`), Detect hands it on as the base, and the editor's URL field follows (`draft.onV1`), so Save doesn't put it back. A model's own 404 at both stays a 404 and changes nothing. CRS lists at `/api/v1/models`, which `catalog.RelayOpenAIList` adds to an unversioned `…/openai` base's list URLs, and a list answered there adds `/v1` as `fixV1` does (`TestCRSOpenAIBaseTestsUnderV1`, `TestCRSOpenAIBaseListsAtAPI`, `TestCRSOpenAIBaseDetectsV1`, `TestModel404KeepsBase`, `provider-test-v1.test.cjs`). A model's test that the vendor turns away with its word that the model is served on another API (`catalog.WrongEndpoint`, the gateway's words) asks the next API the provider has a URL for, as the gateway's `usable` takes it (the model's picked or listed API, else each API it isn't named-only on), with a key that sees the model there (`keySeeing`); that API's answer is the model's, and with none left, or every one saying it, the first stays. As Codex the next API is asked with Codex's headers, as the gateway sends them on Responses and Chat; as Claude Code it isn't, since the gateway sends Claude Code's on Messages alone (#3766, `TestTestModelsMovesToTheAPIServingIt`, `TestTestModelsKeepsAModelOnItsAPI`, `TestTestModelsAsAClientMovesAsTheGatewayDoes`). User-supplied headers still apply through `Sign`. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (`picked`, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (`copyOf`). The probe writes nothing and adds no provider, and the route stays behind `magpie web`'s key. An endpoint or model test fails fast and can be stopped (RIck on Discord: 测试模型 took long to fail and couldn't be cancelled): a probe on magpie's own client that has no connection in `connectWait` (10s) fails then (`connecting`, an httptrace `GotConn`), and a host that couldn't be reached (no connection, DNS, refused, a bad certificate) fails the run's other models at once (`withUnreached`, `TestTestModelsUnreachedHostFailsOnce`); a stream that breaks off before an answer is a failure. While a test runs its Test models and endpoints' Test read Stop, which aborts the window's request and posts `provider/teststop` with the test's `run`, ending the vendor's request on the server too (`testRuns` in [`providers.go`](../../internal/gui/providers.go), since WebView2 doesn't end the request when a fetch is aborted; `TestProviderTestStops`, `model-test-stop.test.cjs`). | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) | +| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Each API is asked with a model that chats, if the list has one; an embedding or rerank model (`catalog.ServesOf`) is asked only on Chat's URL, at its `/embeddings` or `/rerank` with the smallest body and no extra body, as the gateway's `retrieve` asks it, and the other APIs say why they weren't asked (heatonz on Discord: a vendor of only those detected nothing, asked to chat; `TestDetectEmbeddingOnly`). A saved provider whose list has nothing to chat with tests on such a model (`testModel`, `TestTestEmbeddingOnly`), and its editor and the add form's Fetch models say the models need no pick (`retrieval` in the list's answer and the provider's JSON, `provider-retrieval-only.test.cjs`). A model's test (Test models, a model's right-click, `magpie provider test`) asks the account or key a request for it goes to: `provider.AccountsFor` and `provider.KeysFor` ([`route_accounts.go`](../../internal/provider/route_accounts.go)), which the gateway's `perKeyEvery` routes by too, its usage and spend caps aside (one the user lets serve it, `AccountModels`; whose own list or plan has it, `Account.Lists`, `PlanServing`, `Serving`; in the user's order, `AccountsOn`), so a pool whose accounts list different models (a newapi plugin's) asks the one whose list has it, and one every account is barred from isn't asked. The provider's Test picks each endpoint's model from every account's and asks it of the account that serves it (`routedTo`), and with keys the first key with a model of its own to test (`testWith`). The request log's row names the account asked (`loggedAs`; #4992, `TestModelTestAsksTheAccountThatServesIt`). A model's right-click *Test on account…* (tmr11235 on X; a provider with two or more accounts or keys that are on, `TestPicks`) pins its test to one of them (`TestOn`, `accountNamed`, `keyNamed`, the GUI's `account`; `TestModelTestPinnedToAKey`, `TestModelTestPinnedToAnAccount`, `model-test-account.test.cjs`), and every result names the account or key it went to (`Result.Account`, `testedAccount`), so the status line says which one answered. Test models and `magpie providers` still test with routing's pick. Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. A Chat or Responses URL typed without its version (CRS's `…/openai`, Cyrus_4433 on X: CRS serves `/openai/v1/chat/completions` and `/openai/responses`, and answers anything else 404 `Not Found`) that is answered 404 is asked once more under `/v1` (`missingV1`, not for an account, Azure, Bedrock or Vertex); answered there, the saved provider's URL takes the `/v1` (`setV1`), the result carries it (`Result.V1`), Detect hands it on as the base, and the editor's URL field follows (`draft.onV1`), so Save doesn't put it back. A model's own 404 at both stays a 404 and changes nothing. CRS lists at `/api/v1/models`, which `catalog.RelayOpenAIList` adds to an unversioned `…/openai` base's list URLs, and a list answered there adds `/v1` as `fixV1` does (`TestCRSOpenAIBaseTestsUnderV1`, `TestCRSOpenAIBaseListsAtAPI`, `TestCRSOpenAIBaseDetectsV1`, `TestModel404KeepsBase`, `provider-test-v1.test.cjs`). A model's test that the vendor turns away with its word that the model is served on another API (`catalog.WrongEndpoint`, the gateway's words) asks the next API the provider has a URL for, as the gateway's `usable` takes it (the model's picked or listed API, else each API it isn't named-only on), with a key that sees the model there (`keySeeing`); that API's answer is the model's, and with none left, or every one saying it, the first stays. As Codex the next API is asked with Codex's headers, as the gateway sends them on Responses and Chat; as Claude Code it isn't, since the gateway sends Claude Code's on Messages alone (#3766, `TestTestModelsMovesToTheAPIServingIt`, `TestTestModelsKeepsAModelOnItsAPI`, `TestTestModelsAsAClientMovesAsTheGatewayDoes`). User-supplied headers still apply through `Sign`. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (`picked`, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (`copyOf`). The probe writes nothing and adds no provider, and the route stays behind `magpie web`'s key. An endpoint or model test fails fast and can be stopped (RIck on Discord: 测试模型 took long to fail and couldn't be cancelled): a probe on magpie's own client that has no connection in `connectWait` (10s) fails then (`connecting`, an httptrace `GotConn`), and a host that couldn't be reached (no connection, DNS, refused, a bad certificate) fails the run's other models at once (`withUnreached`, `TestTestModelsUnreachedHostFailsOnce`); a stream that breaks off before an answer is a failure. While a test runs its Test models and endpoints' Test read Stop, which aborts the window's request and posts `provider/teststop` with the test's `run`, ending the vendor's request on the server too (`testRuns` in [`providers.go`](../../internal/gui/providers.go), since WebView2 doesn't end the request when a fetch is aborted; `TestProviderTestStops`, `model-test-stop.test.cjs`). | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) | | A pasted curl command | A curl command from a vendor's docs pasted into a custom provider's Base URL or API key fills the editor in (@mark_li21 on X). `curlOf` reads it as a shell would (lines joined by `\`, cmd's `^` or PowerShell's backtick; `curl.exe`; quotes and escapes), and takes: the API its URL's endpoint names (`…/chat/completions` Chat, `…/messages` Anthropic Messages, `…/responses` Responses) with the base URL before it, spelled as that API wants it (`respellURL`: Anthropic at its root, `/v1` after a bare host); the key from `Authorization: Bearer`, `x-api-key` or `api-key`, unless it only stands for one (`$OPENAI_API_KEY`, `${X}`, `%X%`, ``, `YOUR_API_KEY`), when the key's box is left empty and focused; and the `model` of its JSON body, added to a new provider's models (a saved one's picks are left alone, since adding to none would narrow what it serves). A preset's editor takes only the key. A note (`editorError`, kind `note`) says what was taken, a placeholder like `{WorkspaceId}` left in the URL, and a URL with no known endpoint. Text that isn't a curl command pastes as before, several keys included. Tested on the docs' own examples (`fixtures/curl`). | [`app.js`](../../internal/gui/assets/app.js) (`curlOf`, `fromCurl`), [`provider-curl-paste.test.cjs`](../../internal/gui/tests/provider-curl-paste.test.cjs) | | Saved proxies | `settings.Proxies` holds named proxies (`NamedProxy`: id, name, address, optional login), kept in Settings › Network. Wherever a proxy is chosen (global, plugin downloads, app updates, a provider, a key, a Claude account) the value is "" (inherit), `direct`, an address as typed, or `@` for a saved one (@tsingchao on X). Addresses as typed are untouched. App updates take a proxy of their own, Settings › Network › App updates (`settings.UpdateProxy`, `magpie settings set updateProxy `; moonlityu on X: models direct, updates through a proxy): "" follows the global proxy as before, a proxy given to one `magpie update --proxy` run comes first, and it covers the feed, the notes and the release's file (`updateProxy` in [`update.go`](../../internal/update/update.go); `TestUpdateTakesItsOwnProxy`, `settings-update-proxy.test.cjs`). Per-model proxies within one provider are not offered: a proxy belongs to a provider, an account or a key, and a model that needs the other route is a second provider on the same URL. `netproxy.Parse`, `Resolve`, `Redact`, `EnvWith` and `Dispatch` resolve an `@id` at the lowest layer, so an edit reaches every user at the next request; a Claude Code `settings.json` env is a snapshot and is rewritten after an edit (`provider.ProxyEdited`). An `@id` this computer lacks fails closed (`netproxy.DeadProxy`, the request error and the provider row say "Proxy missing: {name}", `provider.ProxyGone`); it never goes direct. The password is written to settings.json (0600) and never read back by the page, logged or put in `Settings` sync; the list rides with the providers part of a sync (`backup.Bundle.Proxies`, `settings.MergeProxies`, passwords only with keys). A proxy in use cannot be deleted (409). `TestSavedProxyChoice`, `TestDanglingProxyReferenceFailsClosed`, `TestSavedProxiesTravelWithProviders`, `saved-proxies.test.cjs`, `provider-proxy-missing.test.cjs`. | [`proxies.go`](../../internal/settings/proxies.go), [`netproxy.go`](../../internal/netproxy/netproxy.go), [`proxies.go`](../../internal/gui/proxies.go) | diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index c232b0506..6bb4e67c1 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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(); }; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 232c0004c..7ed495679 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 9846a4481..9e9863a5e 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -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 diff --git a/internal/gui/tests/model-test-account.test.cjs b/internal/gui/tests/model-test-account.test.cjs new file mode 100644 index 000000000..35a1b432a --- /dev/null +++ b/internal/gui/tests/model-test-account.test.cjs @@ -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, []); + }); + } +} diff --git a/internal/provider/test.go b/internal/provider/test.go index 19f1efba0..984a6eda3 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -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 diff --git a/internal/provider/test_pick.go b/internal/provider/test_pick.go new file mode 100644 index 000000000..5cf6e88c7 --- /dev/null +++ b/internal/provider/test_pick.go @@ -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) +} diff --git a/internal/provider/test_pick_test.go b/internal/provider/test_pick_test.go new file mode 100644 index 000000000..dad4266ac --- /dev/null +++ b/internal/provider/test_pick_test.go @@ -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) + } +}