models: a model of a key's provider can be asked on System One

axelburks on Discord: a relay serves its decision model under a name of
its own (an Ark endpoint id). A key's provider with a System One URL
beside a conversation URL can set a model's API to decide (System One
in Model settings' API row, its chip's right-click, or `magpie model
api <pid/model> decide`). The model is then a decision model there:
asked on System One by its own name, offered to routing groups, kept
out of the conversation models, and a turn for it is refused with 400
before the vendor is asked. Auto gives it back. A provider with no
System One URL, with that URL alone, an account, a remote magpie and
Vertex refuse it, saying why. Chat routing (apisAmong) ignores decide.

Broken by hand: removing the decideSet check in DecidesModel turns
TestModelSetToSystemOneIsADecisionModel and
TestModelSetToSystemOneAskedThere red.

Run, on this stack over origin/main 0fc3455e2 (mote's suite lock had
hours of queue, so the suites ran on WSL magpie-desktop under flock):
- go test -timeout 45m ./internal/{provider,gateway,gui,cli,settings,fx}
  on WSL, ok; ./internal/codexcat on mote, ok; gofmt -l clean;
  go vet on mac, GOOS=linux -tags nogui and GOOS=windows on mote, ok;
  TestCoreScriptBudget ok (paid by cutting comments, no raise).
- GUI, both engines, every language, on WSL at the pushed head and at
  0fc3455e2: every touched test file plus the provider-editor files a
  first run found red. No red at head that isn't red at 0fc3455e2. The
  shared reds have issues: i18n-keys #5332, model-chip-steady #4388,
  model-copy-id #4621, models-works-only #4391, plugin-move-unserved
  #4392, provider-fetch-again #5232, provider-levels-save #4394,
  provider-levels-scroll #4395, provider-models-rest #4396,
  provider-picks-stay #4397, provider-typed #4673, remote-magpie #4398,
  zero-priced-free #5262, model-reasonless (webkit de) #4100,
  name-suffix-no-names #1937.
- Rebased on origin/main 4ab1191bc (gateway.go moved under it) and run
  again at the pushed head: gateway and provider ok on WSL, gofmt,
  vet (mac, linux nogui, windows) and the budget ok, i18n-keys,
  model-headers and routing-groups-back with only #5332's red.
Not run at push: the whole GUI suite (1277 files).

Not tried: a real relay's System One endpoint; fake vendors only.

Reported-by: axelburks (Discord)
This commit is contained in:
yetone
2026-11-08 11:28:54 +08:00
parent 7a6211d047
commit 7880a00ac6
12 changed files with 401 additions and 30 deletions
+14
View File
@@ -1816,6 +1816,20 @@ is refused, and when several models are named all are checked first, so a
refused command writes nothing. A setting kept for a model the vendor no
longer lists can still be taken off with `--reset`.
A key's provider with a System One URL beside a conversation URL can set a
model to `decide` (System One in the editor): the model becomes one of its
decision models. It is asked on the System One URL by its own name, offered
to routing groups as a decision model, and kept out of the conversation
models, and a conversation turn for it is refused. This is how a relay that
serves its decision model under a name of its own, such as an Ark endpoint
id, is used for System One. Auto gives it back to the conversation models. A
provider with no System One URL, one with only that URL, and a signed-in
account refuse it.
```sh
magpie model api ark/ep-decide decide # asked on System One
```
### Routing groups
A routing group is several models, from one provider or many, that an agent
+12
View File
@@ -122,6 +122,18 @@ the remote has none, suppressing the UI's legacy name-based guessing.
The editor offers one remote address; its System One endpoint is derived
from that address and has no separate input. Unnamed decisions use their
model ids for display names and provider labels.
A key's provider with a System One URL beside a conversation URL
(`TakesDecideAPI` in
[`modelprefs.go`](../../internal/provider/modelprefs.go): no account, no
remote magpie, no Vertex) takes `decide` as a model's API (`DecideAPI`,
saved in `modelAPIs`). `DecidesModel` is then true for that model alone, so
it leaves `buildEntries`, joins `Deciders`, and the gateway refuses a turn
for it; `decideModels` lists it first, and `resolveDecideModel` asks
System One by its own name (axelburks on Discord: an Ark endpoint id).
`apisAmong` ignores `decide`, so it never picks a conversation URL. The GUI
offers it when `providerInfo`'s `decideAPIKind` is set and a System One URL
is saved.
Refresh replaces the list: removed decisions stop routing, and an empty
remote list never gains a fabricated Jev alias.
An older peer without the decision-list extension continues serving its
+17 -9
View File
@@ -19,9 +19,10 @@ import (
const apiUsage = `usage:
magpie model api <provider/model> the API the model is asked on, and the ones its provider has
magpie model api <provider/model>... <api> ask the model(s) on this API: chat, responses, anthropic or
gemini; auto leaves it to the vendor's list and every URL the
provider has, as by default
magpie model api <provider/model>... <api> ask the model(s) on this API: chat, responses, anthropic,
gemini, or decide (System One: a decision model a routing
group asks as a turn begins); auto leaves it to the vendor's
list and every URL the provider has, as by default
magpie model api <provider/model>... --reset the same as auto
magpie model apis [<provider>] the models you set an API for; with a provider, each of its
models and the API it is asked on
@@ -29,7 +30,8 @@ const apiUsage = `usage:
It is the provider editor's "API this model is asked on", under Model settings, and is
saved the same way: the app, a running gateway and the agents' model lists go by it at once.
The provider needs a URL for the API (More endpoints in its editor), and at least two of
chat, responses, anthropic and gemini, for there to be a choice. Several models in one command
chat, responses, anthropic and gemini, or a System One URL beside one of them, for there
to be a choice. Several models in one command
are all checked first: a model the provider doesn't list, or an API it has no URL for, refuses
the whole command, and nothing is written.
@@ -40,28 +42,34 @@ const apiUsage = `usage:
// apiNames are the APIs a model can be set to be asked on, in the
// editor's order.
var apiNames = []provider.Protocol{provider.Chat, provider.Responses, provider.Anthropic, provider.Gemini}
var apiNames = []provider.Protocol{provider.Chat, provider.Responses, provider.Anthropic, provider.Gemini, provider.DecideAPI}
// apiLabels are the editor's names of them.
var apiLabels = map[provider.Protocol]string{
provider.Chat: "Chat", provider.Responses: "Responses", provider.Anthropic: "Anthropic", provider.Gemini: "Gemini",
provider.DecideAPI: "System One",
}
// apiChoices are the APIs one of p's models can be asked on alone, as the
// editor offers them (modelAPIs in app.js): those p has a URL for, when it
// has more than one. Vertex AI's model id says its one API.
// has more than one, and System One when it has a URL there beside a
// conversation one. Vertex AI's model id says its one API.
func apiChoices(p *provider.Provider) []provider.Protocol {
if p.IsVertex() {
return nil
}
var out []provider.Protocol
for _, a := range apiNames {
if strings.TrimSpace(p.Base(a)) != "" {
if a != provider.DecideAPI && strings.TrimSpace(p.Base(a)) != "" {
out = append(out, a)
}
}
if len(out) < 2 {
return nil
out = nil
}
// a System One URL beside a conversation one (provider.TakesDecideAPI)
if p.TakesDecideAPI() {
out = append(out, provider.DecideAPI)
}
return out
}
@@ -89,7 +97,7 @@ func modelAPICmd(args []string) error {
if isReset([]string{val}) || val == provider.Auto {
val = ""
} else if !slices.Contains(apiNames, provider.Protocol(val)) {
return fmt.Errorf("a model's API is chat, responses, anthropic, gemini or auto, not %q\n\n%s", args[len(args)-1], apiUsage)
return fmt.Errorf("a model's API is chat, responses, anthropic, gemini, decide or auto, not %q\n\n%s", args[len(args)-1], apiUsage)
}
// every model is checked before any is written
type one struct {
+43
View File
@@ -130,3 +130,46 @@ func TestModelHeadersReachSystemOne(t *testing.T) {
t.Errorf("System One: X-Route = %q, want the model's", v)
}
}
// axelburks on Discord: a model of a relay with a System One URL beside
// its chat URL, set to be asked on System One, is asked there by its own
// name, and a conversation turn for it is refused as Jev's is.
func TestModelSetToSystemOneAskedThere(t *testing.T) {
fresh(t)
var mu sync.Mutex
var paths, bodies []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
paths, bodies = append(paths, r.URL.Path), append(bodies, string(b))
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"model":"ep-decide","usage":{"input_tokens":1,"output_tokens":1}}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "ark", Name: "Ark", Key: "upstream", Chat: up.URL + "/api/v3",
Decide: up.URL + "/api/v3", Models: []string{"ep-chat", "ep-decide"}}); err != nil {
t.Fatal(err)
}
if err := provider.SetModelAPI("ark/ep-decide", "decide"); err != nil {
t.Fatal(err)
}
code, out := sendTo(New(), "/v1/systemone", `{"model":"ark/ep-decide","state":{"message":"hi"},"questions":{}}`)
if code != 200 {
t.Fatalf("System One: %d %s", code, out)
}
mu.Lock()
if len(paths) != 1 || !strings.HasSuffix(paths[0], "/systemone") || !strings.Contains(bodies[0], `"ep-decide"`) {
t.Fatalf("asked %v %v", paths, bodies)
}
mu.Unlock()
code, out = sendTo(New(), "/v1/chat/completions", `{"model":"ark/ep-decide","messages":[{"role":"user","content":"hi"}]}`)
if code != 400 {
t.Fatalf("a turn for it: %d %s", code, out)
}
mu.Lock()
defer mu.Unlock()
if len(paths) != 1 {
t.Fatalf("the turn reached the vendor: %v", paths)
}
}
+14 -15
View File
@@ -9138,9 +9138,7 @@ const PROTOS = [["chat", "OpenAI", "Chat Completions — most agents"], ["respon
const VERTEX_EP_HINT = "Gemini generateContent — what Vertex AI serves at your Google Cloud project";
// apiLabel: the name an API (a protocol) goes by in the editor
const apiLabel = (proto) => (PROTOS.find(([k]) => k === proto) || [])[1] || proto;
// vertexBase is where a Vertex AI provider's requests go, the address its
// project and location make (provider.vertexBase): "" until the project
// typed is one an address can be made of
// vertexBase: a Vertex AI provider's address (provider.vertexBase), "" till its project is one
function vertexBase(v) {
const project = (v?.project || "").trim().toLowerCase(), loc = (v?.location || "").trim().toLowerCase() || "global";
if (!/^[a-z0-9][a-z0-9.:-]*[a-z0-9]$/.test(project) || !/^[a-z]+(-[a-z0-9]+)*$/.test(loc)) return "";
@@ -9154,11 +9152,15 @@ function vertexOfDraft() {
}
const decideOnly = (p) => !!p?.decide && !(p.chat || p.responses || p.anthropic || p.gemini);
// OpenRouter lists its decision models apart
const decidesModel = (p, id) => !!p.decide && (decideOnly(p) || (p.deciders ? p.deciders.includes(id) : id.split("/").some((s) => /^jev(?:-|$)/i.test(s))));
// modelAPIs: those p has a URL for, if 2+ (01huadalang, Kayphoon)
// or one set to be asked on System One (axelburks)
const decidesModel = (p, id) => !!p.decide && (decideOnly(p) || p.models?.find((m) => m.id === id)?.api === "decide" || (p.deciders ? p.deciders.includes(id) : id.split("/").some((s) => /^jev(?:-|$)/i.test(s))));
// modelAPIs: those p has a URL for, if 2+ (01huadalang, Kayphoon), and
// System One beside a conversation URL (axelburks)
const modelAPIs = (p) => {
const urls = ["chat", "responses", "anthropic", "gemini"].filter((k) => ((draft?.id === p.id ? draft[k] : undefined) ?? p[k] ?? "").trim());
return urls.length < 2 ? [] : PROTOS.filter(([k]) => urls.includes(k));
const of = (k) => ((draft?.id === p.id ? draft[k] : undefined) ?? p[k] ?? "").trim();
const urls = ["chat", "responses", "anthropic", "gemini"].filter(of);
const decide = p.decideAPIKind && urls.length > 0 && of("decide");
return PROTOS.filter(([k]) => urls.length > 1 && urls.includes(k) || decide && k === "decide");
};
// pickedOf: the models the user picked for p, only the picks (#614).
@@ -11175,6 +11177,7 @@ function renderModels(p) {
const dashed = () => p.models.filter((m) => !noAPI(m) && (!draft.best || m.best)).slice(0, 24).map((m) => m.id);
const noAPI = (m) => {
const set = draft.modelPrefs?.[m.id]?.api;
if (set === "decide") return false;
if (set === undefined || !p.speaks?.length) return !!m.noAPI;
const on = set ? [set] : (m.auto || []);
return on.length > 0 && !on.some((a) => p.speaks.includes(a));
@@ -11248,7 +11251,7 @@ function renderModels(p) {
// its id as agents and the gateway name it, to paste where a model is
// typed (ARNO, Discord: 右击菜单除了测试模型外,还能添加拷贝模型id的功能)
acts.push({ name: "Copy model ID", icon: COPY_ICON, tip: id, run: () => copy(id, id, null, t("Model ID {model} copied", { model: id })) });
if (apis.length && !decidesModel(p, id)) {
if (apis.length && (!decidesModel(p, id) || apiNow(id) === "decide")) {
const now = apiNow(id);
acts.push({ name: now ? t("Asked on {api}…", { api: apiLabel(now) }) : t("Asked on: Auto…"), icon: "M2.5 5h11M2.5 11h11M10.5 2.5 13.5 5l-3 2.5M5.5 8.5 2.5 11l3 2.5", tip: t("Pick the API this model is asked on"), run: () => pickAPI(c, id) });
}
@@ -11264,7 +11267,7 @@ function renderModels(p) {
openRowMenu(c, acts);
};
// the API it is asked on, when one is picked (or staged)
const now = apis.length && !decidesModel(p, id) ? apiNow(id) : "";
const now = apis.length && (!decidesModel(p, id) || apiNow(id) === "decide") ? apiNow(id) : "";
if (now) {
const tag = el("span", "badge mapi-tag", apiLabel(now));
tag.title = t("Asked on {api} alone; right-click to change", { api: apiLabel(now) });
@@ -11478,9 +11481,7 @@ function renderModels(p) {
sfx.append(sfxSaid, el("span", "where", t("“Provider in model names” is one setting for every provider")), where);
sfx.append(noNamesLine("span", "said"));
names.append(sfx);
// the APIs a model can be asked on alone: those of a key's provider
// it has a URL for, when it has more than one (01huadalang on Discord:
// 一个 api 里有很多模型但是不同协议)
// the APIs a model can be asked on (modelAPIs)
const apis = modelAPIs(p);
for (const id of ids) {
const m = p.models.find((x) => x.id === id) || { id, name: id };
@@ -11491,9 +11492,7 @@ function renderModels(p) {
const levels = m.efforts || [];
const savedKept = m.kept?.length || m.given ? m.kept || [] : levels;
const nameNow = () => prefs[id]?.name ?? savedName;
// none of its levels kept: it is sent no reasoning field at all
// (yuexian7 on Discord: a model models.dev says reasons answered
// reasoning_effort with 422, and worked without it)
// none of its levels kept: no reasoning field (yuexian7)
const noneNow = () => prefs[id]?.reasonless ?? !!m.reasonless;
const keptNow = () => noneNow() ? [] : prefs[id]?.efforts ? (prefs[id].efforts.length || m.given ? prefs[id].efforts : levels) : savedKept;
const imagesNow = () => prefs[id]?.ownImages ? !!m.ownImages : prefs[id]?.images ?? !!m.images;
File diff suppressed because one or more lines are too long
+5 -1
View File
@@ -209,6 +209,10 @@ type providerJSON struct {
// headers of their own (provider.SetModelHeaders); a signed-in
// account's and a plugin's carry their sign-in's
TakesModelHeaders bool `json:"takesModelHeaders,omitempty"`
// DecideAPIKind: a provider whose models can each be asked on its
// System One URL once it has one beside a conversation URL
// (provider.DecideAPI); the editor offers System One then
DecideAPIKind bool `json:"decideAPIKind,omitempty"`
// an account-wide balance token (provider.BalanceToken): whether the
// vendor takes one, and whether one is saved; never the token itself
BalanceToken struct {
@@ -760,7 +764,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(),
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(),
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(),
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate,
@@ -0,0 +1,132 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A key's provider with a System One URL beside its chat URL (axelburks on
// Discord: a relay's own decision model, named as the relay names it): a
// model can be set to be asked on System One from Model settings' API row,
// and the Save sends it as modelPrefs. With one conversation URL the row
// offers Auto and System One alone. One saved so is tagged System One on
// its chip, and its chip's right-click can set it back. A provider with no
// System One URL, and a signed-in account, offer none. Every language,
// Chromium and WebKit, wide and at a phone's width.
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(process.env.MAGPIE_ASSETS || path.resolve(__dirname, "../assets"));
const base = { icon: "generic", catalog: "", agents: [], fallback: [], headers: {}, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ready: true, key: { set: true, masked: "sk-…one" } };
const relay = (saved) => ({
...base, id: "ark", name: "Ark", chat: "https://ark.example.com/api/v3", responses: "", anthropic: "", gemini: "", decide: "https://ark.example.com/api/v3", decideAPIKind: true, takesModelHeaders: true,
models: [{ id: "ep-chat", name: "ep-chat", on: true }, { id: "ep-decide", name: "ep-decide", on: true, ...(saved ? { api: "decide" } : {}) }],
chosen: ["ep-chat", "ep-decide"],
});
const plain = { ...base, id: "plain", name: "Plain", chat: "https://plain.example.com/v1", responses: "", anthropic: "", gemini: "", decideAPIKind: true, models: [{ id: "m1", name: "m1", on: true }], chosen: ["m1"] };
const account = { ...base, id: "codex", name: "Codex", icon: "openai", account: { kind: "codex" }, decide: "https://x.example.com/v1", models: [{ id: "gpt-5.5", name: "GPT-5.5", on: true }], chosen: ["gpt-5.5"] };
function serve(lang, posts, saved) {
const providers = { providers: [relay(saved), plain, account], 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/plugins") return json({ plugins: [] });
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/provider/save") { posts.push(route.request().postDataJSON()); return json(providers); }
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const say = (page, lang, s, vars) => page.evaluate(([l, s, v]) => {
let out = l === "en" ? s : I18N[l][s];
for (const [k, x] of Object.entries(v || {})) out = out?.replace(`{${k}}`, x);
return out;
}, [lang, s, vars]);
async function rclick(loc) {
await loc.click({ button: "right", trial: true });
await loc.page().evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
await loc.click({ button: "right" });
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1200, 420]) {
test(`${engine} ${lang} ${width}px: a model set to be asked on System One`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const open = async (saved) => {
const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts, saved));
await page.goto("http://magpie.test/?view=providers");
return { page, errors, posts };
};
const settingsOf = async (page, name) => {
await page.locator(".row.provider", { hasText: name }).first().click();
const editor = page.locator("#modal:not([hidden]) .editor");
if (!(await editor.locator(".mnames:not([hidden])").count())) await editor.getByRole("button", { name: await say(page, lang, "Model settings"), exact: true }).click();
await editor.locator(".mnames:not([hidden]) .mname").first().waitFor();
return editor;
};
// staged in Model settings, made with the Save
let { page, errors, posts } = await open(false);
let editor = await settingsOf(page, "Ark");
const row = (id) => editor.locator(".mnames:not([hidden]) .mname", { has: page.locator("code", { hasText: new RegExp(`^${id}$`) }) });
assert.deepEqual(await row("ep-decide").locator(".mapi .opt").evaluateAll((os) => os.map((o) => o.dataset.api)), ["", "decide"], "Auto and System One: one conversation URL is no choice");
await row("ep-decide").locator('.mapi .opt[data-api="decide"]').click();
assert.equal(await row("ep-decide").locator(".mapi .opt.on").getAttribute("data-api"), "decide");
const over = await page.evaluate(() => {
const ed = document.querySelector("#modal:not([hidden]) .editor").getBoundingClientRect();
return [...document.querySelectorAll(".editor .mnames .mapi")].map((m) => m.getBoundingClientRect()).filter((r) => r.width && (r.right > ed.right + 1 || r.left < ed.left - 1)).length
+ (document.documentElement.scrollWidth > innerWidth + 1 ? 100 : 0);
});
assert.equal(over, 0, "the API choice stays inside the editor");
assert.equal(posts.length, 0, "staged, not saved");
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}-model-api-decide.png`) });
}
await editor.locator(".bar button.primary").click();
for (let i = 0; i < 100 && !posts.length; i++) await page.waitForTimeout(20);
assert.deepEqual(posts[0]?.modelPrefs, { "ep-decide": { api: "decide" } });
// no System One URL, or an account: nothing to set
editor = await settingsOf(page, "Plain");
assert.equal(await editor.locator(".mnames:not([hidden]) .mapi").count(), 0, "no System One URL: no API row");
assert.deepEqual(errors, []);
({ page, errors } = await open(false));
editor = await settingsOf(page, "Codex");
assert.equal(await editor.locator(".mnames:not([hidden]) .mapi").count(), 0, "an account: no API row");
assert.deepEqual(errors, []);
// saved: tagged on its chip, and set back to Auto from its right-click
({ page, errors, posts } = await open(true));
await page.locator(".row.provider", { hasText: "Ark" }).first().click();
const chip = page.locator(".editor .mchips .mchip", { hasText: "ep-decide" });
await chip.waitFor();
assert.equal(await chip.locator(".mapi-tag").textContent(), "System One");
await rclick(chip);
await page.locator(".pop.row-menu").getByRole("menuitem", { name: await say(page, lang, "Asked on {api}…", { api: "System One" }) }).click();
const apiMenu = page.locator(".pop.proto-menu.model-api-menu");
await apiMenu.waitFor();
assert.deepEqual((await apiMenu.locator(".pm-name").allTextContents()).slice(1), ["System One"]);
await apiMenu.locator(".pm-item").first().click();
await apiMenu.waitFor({ state: "detached" });
await page.locator("#modal:not([hidden]) .editor .bar button.primary").click();
for (let i = 0; i < 100 && !posts.length; i++) await page.waitForTimeout(20);
assert.deepEqual(posts[0]?.modelPrefs, { "ep-decide": { api: "" } });
assert.deepEqual(errors, []);
});
}
}
}
+13 -1
View File
@@ -137,6 +137,10 @@ func (p Provider) DecidesModel(model string) bool {
if p.DecideOnly() {
return true
}
// one the user set to be asked on System One (DecideAPI)
if p.decideSet(model) {
return true
}
if p.bailianApart() {
m, _ := vendorDecision(p.Decide)
return model == m.ID
@@ -406,7 +410,15 @@ func (p Provider) Jev() string {
// list when fetched, else Jev's aliases (a gateway's one Jev), each with
// its window and whether it takes images where its vendor's docs say.
func (p Provider) decideModels() []catalog.Model {
return withDecideFacts(p.decideListed())
ms := p.decideListed()
// and the ones the user set to be asked on System One, first
if set := p.decideSetModels(); len(set) > 0 {
set = slices.DeleteFunc(set, func(m catalog.Model) bool {
return slices.ContainsFunc(ms, func(l catalog.Model) bool { return l.ID == m.ID })
})
ms = append(set, ms...)
}
return withDecideFacts(ms)
}
// A decision model's window and whether it reads images, as its vendor's
+5 -1
View File
@@ -269,7 +269,11 @@ func TestModelAPI(t *testing.T) {
if err := SetModelAPI("relay/mixed", "gemini"); err == nil || !strings.Contains(err.Error(), "no gemini URL") {
t.Fatalf("gemini with no Gemini URL: %v", err)
}
if err := SetModelAPI("relay/mixed", "decide"); err == nil || !strings.Contains(err.Error(), "not \"decide\"") {
// System One, with no URL there (TestModelSystemOneNeedsItsURL)
if err := SetModelAPI("relay/mixed", "decide"); err == nil || !strings.Contains(err.Error(), "no System One URL") {
t.Fatalf("System One with no URL there: %v", err)
}
if err := SetModelAPI("relay/mixed", "jev"); err == nil || !strings.Contains(err.Error(), "not \"jev\"") {
t.Fatalf("an API a model isn't asked on: %v", err)
}
if err := SetModelAPI("relay/nope", "anthropic"); err == nil {
@@ -0,0 +1,87 @@
package provider
import (
"slices"
"strings"
"testing"
)
// axelburks on Discord: a key's provider with a System One URL beside its
// chat URL serves a decision model under a name of its own (an Ark
// endpoint id); the model's API can be set to System One, which makes it a
// decision model there: offered to routing groups, asked on System One by
// its own name, and kept out of the conversation models. Auto again gives
// it back to them.
func TestModelSetToSystemOneIsADecisionModel(t *testing.T) {
prefillHome(t)
if err := Save(Provider{ID: "ark", Name: "Ark", Key: "ark-k", Chat: "https://ark.example/api/v3",
Decide: "https://ark.example/api/v3/systemone", Models: []string{"ep-chat", "ep-decide"}}); err != nil {
t.Fatal(err)
}
if err := SetModelAPI("ark/ep-decide", "decide"); err != nil {
t.Fatal(err)
}
p, err := Find("ark")
if err != nil {
t.Fatal(err)
}
if !p.DecidesModel("ep-decide") || p.DecidesModel("ep-chat") {
t.Fatalf("decides: ep-decide %v, ep-chat %v", p.DecidesModel("ep-decide"), p.DecidesModel("ep-chat"))
}
if api, ok := p.ModelAPI("ep-decide"); !ok || api != DecideAPI {
t.Fatalf("ModelAPI = %q %v", api, ok)
}
if m, ok := resolveDecideModel(*p, "ep-decide"); !ok || m != "ep-decide" {
t.Fatalf("asked on System One as %q %v, want its own name", m, ok)
}
ids := func(es []Entry) []string {
var out []string
for _, e := range es {
if strings.HasPrefix(e.ID, "ark/") {
out = append(out, e.ID)
}
}
return out
}
if got := ids(Deciders()); !slices.Contains(got, "ark/ep-decide") || slices.Contains(got, "ark/ep-chat") {
t.Fatalf("Deciders = %v", got)
}
if got := ids(buildEntries()); !slices.Contains(got, "ark/ep-chat") || slices.Contains(got, "ark/ep-decide") {
t.Fatalf("conversation models = %v", got)
}
// Auto: a conversation model again
if err := SetModelAPI("ark/ep-decide", ""); err != nil {
t.Fatal(err)
}
if p, _ = Find("ark"); p.DecidesModel("ep-decide") {
t.Fatal("still a decision model after Auto")
}
if got := ids(buildEntries()); !slices.Contains(got, "ark/ep-decide") {
t.Fatalf("conversation models after Auto = %v", got)
}
}
// Only a key's provider with a System One URL beside a conversation URL
// takes it: one with no System One URL, or with that alone (every model a
// decision model already), refuses it, saying why.
func TestModelSystemOneNeedsItsURL(t *testing.T) {
prefillHome(t)
for _, p := range []Provider{
{ID: "relay", Name: "Relay", Key: "k", Chat: "https://relay.example/v1", Models: []string{"m"}},
{ID: "jev", Name: "Jev", Key: "k", Decide: "https://jev.example/v1", Models: []string{"m"}},
} {
if err := Save(p); err != nil {
t.Fatal(err)
}
if err := SetModelAPI(p.ID+"/m", "decide"); err == nil || !strings.Contains(err.Error(), "System One") {
t.Fatalf("%s: %v", p.ID, err)
}
}
if (Provider{Decide: "https://x/v1", Chat: "https://x/v1", Account: &Account{}}).TakesDecideAPI() {
t.Fatal("an account takes it")
}
if (Provider{Decide: "https://x/v1", Chat: "https://x/v1", Preset: RemoteMagpiePreset}).TakesDecideAPI() {
t.Fatal("a remote magpie takes it")
}
}
+58 -2
View File
@@ -437,9 +437,16 @@ func setModelAPI(ref, api string) (bool, error) {
return false, err
}
proto := Protocol(strings.TrimSpace(api))
if proto != "" {
if proto == DecideAPI {
if !p.TakesDecideAPI() {
return false, fmt.Errorf("%s has no System One URL beside a conversation one to ask %s on: add it under More endpoints first", p.ID, model)
}
if !p.serves(model) {
return false, fmt.Errorf("%s has no model %s (magpie provider %s lists them)", p.ID, model, p.ID)
}
} else if proto != "" {
if !modelAPI(proto) {
return false, fmt.Errorf("a model's API is chat, responses, anthropic or gemini, not %q", api)
return false, fmt.Errorf("a model's API is chat, responses, anthropic, gemini or decide (System One), not %q", api)
}
if p.Base(proto) == "" {
return false, fmt.Errorf("%s has no %s URL to ask %s on: add it under More endpoints first", p.ID, proto, model)
@@ -479,6 +486,9 @@ func (p Provider) ModelAPI(model string) (Protocol, bool) {
if !ok {
return "", false
}
if proto == DecideAPI {
return proto, p.TakesDecideAPI()
}
n := 0
for range p.speaking {
if n++; n == 2 {
@@ -488,6 +498,52 @@ func (p Provider) ModelAPI(model string) (Protocol, bool) {
return p.modelAPIAmong(n, proto)
}
// DecideAPI is the API a model is set to be asked on (SetModelAPI) when it
// is a decision model at its provider's System One URL (axelburks on
// Discord: a relay that serves its chat models and its own decision model
// under one key, the decision model named as the relay names it). Such a
// model is a decision model (DecidesModel): a routing group can ask it as
// a turn begins, and it is refused for a conversation, as Jev is.
const DecideAPI Protocol = "decide"
// TakesDecideAPI reports whether p's models can be set to be asked on its
// System One URL: a key's provider with one beside a conversation URL. A
// provider with a System One URL alone asks every model there already; a
// signed-in account, a plugin and a remote magpie say which of theirs
// decide themselves.
func (p Provider) TakesDecideAPI() bool {
return p.Decides() && !p.DecideOnly() && p.DecideAPIKind()
}
// DecideAPIKind reports whether p is a provider whose models could be set
// to be asked on System One once it has a URL for it there.
func (p Provider) DecideAPIKind() bool {
return p.Account == nil && !p.IsRemoteMagpie() && !p.IsVertex()
}
// decideSet reports whether the user set p's model to be asked on System
// One, and p takes it.
func (p Provider) decideSet(model string) bool {
proto, ok := p.apiSet(model)
return ok && proto == DecideAPI && p.TakesDecideAPI()
}
// decideSetModels are p's models the user set to be asked on System One,
// in id order.
func (p Provider) decideSetModels() []catalog.Model {
if !p.TakesDecideAPI() {
return nil
}
var out []catalog.Model
for k, v := range heldSettings().ModelAPIs {
if m, ok := strings.CutPrefix(k, p.ID+"/"); ok && Protocol(v) == DecideAPI {
out = append(out, catalog.Model{ID: m})
}
}
slices.SortFunc(out, func(a, b catalog.Model) int { return strings.Compare(a.ID, b.ID) })
return out
}
// apiSet is the API the user set model to be asked on, false with
// none.
func (p Provider) apiSet(model string) (Protocol, bool) {