gateway: the key page's Claude Code setup keeps each tier on its own family

The /me page's Claude Code tab wrote the picked model into
ANTHROPIC_MODEL and into ANTHROPIC_DEFAULT_OPUS_MODEL, _SONNET_ and
_HAIKU_ alike, so picking Opus sent every Haiku background call to Opus
too (and picking a GPT model made "haiku" a GPT model).

The pick now sets only ANTHROPIC_MODEL. /v1/magpie/me returns `tiers`,
built by keyPageTiers from the models this key may use: for opus,
sonnet and haiku, the newest model of that family (claudeTier and
claudeVersionOf; routing groups and fable are skipped). A tier the key
has no model for is left out of the snippet, so Claude Code keeps its
own default for it.

Siblings: the agent writer (internal/agent/claude.go) has its own tier
design (tiers follow the main model, haiku to the provider's Haiku, the
user's own tiers kept) and writes the user's real config; it is a
different situation and is left as is. OpenMausBot's snippet writes
only ANTHROPIC_MODEL.

Run (mote, via suite.lock):
- go test -count=1 -run KeyPage ./internal/gateway/: ok
- GUI key-page.test.cjs: chromium 13/13, webkit 13/13
- gofmt -l: clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., and go build for darwin, linux (nogui) and
  windows: ok
Broken by hand:
- old keypage.html: the new GUI test is red in both engines
  (ANTHROPIC_DEFAULT_HAIKU_MODEL 'claude/claude-opus-5', want
  'claude/claude-haiku-4-5')
- keyInfo without keyPageTiers: TestKeyPageTiersAreTheirFamilys red
  ("tiers map[]")
Full suite (go test -tags nogui -timeout 45m ./...): queued behind
other sessions on suite.lock at push time; its result goes on the
follow-up, with an issue for any red.
Not tried: a real Claude Code against the page's snippet, and the
gateway binary in a sandbox HOME.

Reported-by: strinah (Discord)
This commit is contained in:
yetone
2026-11-09 14:22:05 +08:00
parent bceeabd93a
commit c630d9a29c
6 changed files with 159 additions and 7 deletions
+8 -2
View File
@@ -775,13 +775,19 @@ only `access.Caller`'s own: no key, a wrong one, one turned off and
magpie's own token are 401 alike, and `?key=` is refused 400, so a key is
never written into an address or a log. It names no account, no other key,
no provider and no secret; its models are `/v1/models`' for that key
(`keyAllowed`), none for a read-only key. The page loads nothing from
(`keyAllowed`), none for a read-only key. Its Claude Code setup writes the
picked model as `ANTHROPIC_MODEL` only; `ANTHROPIC_DEFAULT_OPUS_MODEL`,
`_SONNET_` and `_HAIKU_` are `tiers`, the newest Claude model of each family
among the key's models (`keyPageTiers`, no routing group, a tier with none
left out), so Claude Code's /model tiers and its small asks on haiku keep
their own family (strinah on Discord). The page loads nothing from
elsewhere, posts no form and can't be framed (its CSP), keeps the key in
the tab's `sessionStorage` only, and sends it to its own origin with
`credentials: "omit"`. Gateway → Gateway keys shows the page's address
(`MAGPIE_PUBLIC_URL`, else the LAN address offered) with a Copy, while
shared and with a key (`gatewayKeyPage` in `keys.js`). `key_page.go`, and
`TestKeyPageTellsAKeyItsOwn`, `TestKeyPageRefusesWithoutItsKey` and
`TestKeyPageTellsAKeyItsOwn`, `TestKeyPageRefusesWithoutItsKey`,
`TestKeyPageTiersAreTheirFamilys`, `TestKeyPageTiersPickTheNewest` and
`TestKeyPageOpensWithoutAKey` in
[`key_page_test.go`](../../internal/gateway/key_page_test.go);
`internal/gui/tests/key-page.test.cjs` drives the page itself.
+40
View File
@@ -88,6 +88,7 @@ func (s *Server) keyInfo(w http.ResponseWriter, r *http.Request) {
}
}
models := []map[string]string{}
tiers := map[string]string{}
// a read-only key is refused every model (readOnlyGuard)
if !who.ReadOnly {
// as /v1/models tells this key, for no agent in particular
@@ -97,6 +98,7 @@ func (s *Server) keyInfo(w http.ResponseWriter, r *http.Request) {
for i, e := range shown {
models = append(models, map[string]string{"id": e.ID, "label": labels[i]})
}
tiers = keyPageTiers(shown)
}
writeJSON(w, 200, map[string]any{
"name": who.KeyName,
@@ -105,10 +107,48 @@ func (s *Server) keyInfo(w http.ResponseWriter, r *http.Request) {
"usage": sums,
"topModels": top,
"models": models,
"tiers": tiers,
"version": Version,
})
}
// keyPageTiers are the models the key page's Claude Code setup names for
// Claude Code's opus, sonnet and haiku tiers (ANTHROPIC_DEFAULT_<TIER>_MODEL):
// of the models the key may use, the newest Claude model of each family,
// the first listed of a version served by more than one. A tier with none
// is left out, as is a routing group, which isn't one model of a family.
// The model picked on the page is ANTHROPIC_MODEL alone: written into every
// tier, a pick of Opus ran Claude Code's small asks (a session's title,
// Explore subagents, WebFetch's reading), meant for Haiku, on Opus, and
// /model's sonnet and haiku on it too (strinah on Discord).
func keyPageTiers(shown []provider.Entry) map[string]string {
out := map[string]string{}
best := map[string][2]int{}
for _, e := range shown {
if e.Group != "" {
continue
}
m := e.Model
if m == "" {
m = e.ID
}
t := claudeTier(m)
if t == "" || t == "fable" {
continue
}
major, minor, ok := claudeVersionOf(m)
if !ok {
continue
}
if b, seen := best[t]; seen && (major < b[0] || major == b[0] && minor <= b[1]) {
continue
}
best[t] = [2]int{major, minor}
out[t] = e.ID
}
return out
}
// keyPageTotals are the sums the key page shows of a key's calls.
type keyPageTotals struct {
Calls int `json:"calls"`
+67
View File
@@ -251,3 +251,70 @@ func TestKeyPageReadOnlyKey(t *testing.T) {
t.Fatalf("%+v", got)
}
}
// strinah on Discord: the key page's Claude Code setup wrote the picked
// model into every tier, so a pick of Opus ran haiku's small asks and
// /model's sonnet and haiku on Opus. Each tier is named the newest model
// of its family the key may use, none where it may use none, and a model
// the key is held from is never named.
func TestKeyPageTiersAreTheirFamilys(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
budget.Forget()
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: "http://127.0.0.1:1/v1", Models: []string{
"gpt-6", "claude-opus-4-8", "claude-opus-5", "claude-sonnet-4-6", "claude-sonnet-5", "claude-haiku-4-5-20251001", "claude-fable-5-1",
}}); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Held", "Whole")
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/gpt-6", "plan/claude-opus-4-8", "plan/claude-sonnet-4-6"}}); err != nil {
t.Fatal(err)
}
h := lanGuard(New().Handler())
want := []map[string]string{
{"opus": "plan/claude-opus-4-8", "sonnet": "plan/claude-sonnet-4-6"},
{"opus": "plan/claude-opus-5", "sonnet": "plan/claude-sonnet-5", "haiku": "plan/claude-haiku-4-5-20251001"},
}
for i, secret := range secrets {
w := keyPageReq{method: "GET", path: keyPageData, from: "192.168.1.9:5000", header: map[string]string{"Authorization": "Bearer " + secret}}.do(h)
if w.Code != 200 {
t.Fatal(w.Code, w.Body.String())
}
var got struct {
Tiers map[string]string `json:"tiers"`
}
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if len(got.Tiers) != len(want[i]) {
t.Errorf("%s: tiers %v, want %v", keys[i].Name, got.Tiers, want[i])
}
for tier, id := range want[i] {
if got.Tiers[tier] != id {
t.Errorf("%s: %s tier %q, want %q (all %v)", keys[i].Name, tier, got.Tiers[tier], id, got.Tiers)
}
}
}
}
func TestKeyPageTiersPickTheNewest(t *testing.T) {
got := keyPageTiers([]provider.Entry{
{ID: "a/claude-haiku-4-5", Model: "claude-haiku-4-5"},
{ID: "copilot/claude-opus-5.5", Model: "claude-opus-5.5"},
{ID: "b/claude-opus-5-5", Model: "claude-opus-5-5"},
{ID: "or/anthropic/claude-sonnet-4.6", Model: "anthropic/claude-sonnet-4.6"},
{ID: "a/claude-opus-4-8", Model: "claude-opus-4-8"},
{ID: "group/auto-claude", Model: "claude-haiku-5-5", Group: "auto-claude"},
{ID: "x/old", Model: "claude-3-5-haiku-20241022"},
{ID: "a/claude-fable-5-1", Model: "claude-fable-5-1"},
})
want := map[string]string{"opus": "copilot/claude-opus-5.5", "sonnet": "or/anthropic/claude-sonnet-4.6", "haiku": "a/claude-haiku-4-5"}
if len(got) != len(want) {
t.Errorf("tiers %v, want %v", got, want)
}
for tier, id := range want {
if got[tier] != id {
t.Errorf("%s tier %q, want %q", tier, got[tier], id)
}
}
}
+7 -4
View File
@@ -436,10 +436,13 @@ function drawSetup() {
};
if (tab === "claude") {
$("tabNote").textContent = t("claudeNote") + " " + t("pick");
block("~/.claude/settings.json", JSON.stringify({ env: {
ANTHROPIC_BASE_URL: BASE, ANTHROPIC_AUTH_TOKEN: k, ANTHROPIC_MODEL: m,
ANTHROPIC_DEFAULT_OPUS_MODEL: m, ANTHROPIC_DEFAULT_SONNET_MODEL: m, ANTHROPIC_DEFAULT_HAIKU_MODEL: m,
} }, null, 2));
// the pick is the main model alone; each tier keeps its family's model
// the key may use (keyPageTiers), so /model's tiers and Claude Code's
// small asks on haiku still go to their own
const env = { ANTHROPIC_BASE_URL: BASE, ANTHROPIC_AUTH_TOKEN: k, ANTHROPIC_MODEL: m };
const tiers = data?.tiers || {};
for (const tier of ["opus", "sonnet", "haiku"]) if (tiers[tier]) env["ANTHROPIC_DEFAULT_" + tier.toUpperCase() + "_MODEL"] = tiers[tier];
block("~/.claude/settings.json", JSON.stringify({ env }, null, 2));
} else if (tab === "codex") {
$("tabNote").textContent = t("codexNote") + " " + t("pick");
block("~/.codex/config.toml", [
+3 -1
View File
@@ -68,7 +68,9 @@ Chromium and WebKit and every language: a wrong key is told so in the
page's language and shows nothing; the right one shows its limit, its
usage and most used model, picks that model, and gives Claude Code, Codex,
OpenAI-compatible and curl setup at the address the page was opened at,
with a placeholder until "Put my key in the setup" is ticked. A reload
with a placeholder until "Put my key in the setup" is ticked. Claude
Code's setup names the pick as ANTHROPIC_MODEL alone and each tier's
model as the gateway's `tiers` says, leaving out a tier with none. A reload
keeps the key in the tab, Forget takes it away, and no request carries the
key in its address. A read-only key gets no setup. Gateway → Gateway keys
shows the page's address (the LAN one, or `MAGPIE_PUBLIC_URL`) with a
+34
View File
@@ -124,6 +124,40 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
});
}
// strinah on Discord: picking claude/claude-opus-5 wrote it into every
// tier too, so Claude Code's haiku asks and /model's sonnet ran on Opus.
// The pick is ANTHROPIC_MODEL alone; each tier is the gateway's model of
// its family for the key, and a tier it has none for is left out.
test(`${engine}: the pick is the main model, the tiers keep their families`, async (t) => {
const me = {
...ME, topModels: [],
models: [{ id: "claude/claude-opus-5", label: "Opus 5" }, { id: "claude/claude-sonnet-5", label: "Sonnet 5" }, { id: "claude/claude-haiku-4-5", label: "Haiku 4.5" }, { id: "plan/m1", label: "m1" }],
tiers: { opus: "claude/claude-opus-5", sonnet: "claude/claude-sonnet-5", haiku: "claude/claude-haiku-4-5" },
};
const { browser, page, seen } = await open(engine, "en", me);
t.after(() => browser.close());
await signIn(page, KEY);
await page.locator("#info").waitFor();
const tiers = { ANTHROPIC_DEFAULT_OPUS_MODEL: "claude/claude-opus-5", ANTHROPIC_DEFAULT_SONNET_MODEL: "claude/claude-sonnet-5", ANTHROPIC_DEFAULT_HAIKU_MODEL: "claude/claude-haiku-4-5" };
for (const pick of ["claude/claude-opus-5", "plan/m1", "claude/claude-haiku-4-5"]) {
await page.click(`#models [data-id="${pick}"]`);
const env = JSON.parse(await snippet(page)).env;
assert.deepEqual(env, { ANTHROPIC_BASE_URL: BASE, ANTHROPIC_AUTH_TOKEN: "YOUR_GATEWAY_KEY", ANTHROPIC_MODEL: pick, ...tiers }, pick);
}
// a key with no Claude of a family gets no tier for it
await browser.close();
const two = await open(engine, "en", { ...me, tiers: { opus: "claude/claude-opus-5" } });
t.after(() => two.browser.close());
await signIn(two.page, KEY);
await two.page.locator("#info").waitFor();
await two.page.click('#models [data-id="plan/m1"]');
const env = JSON.parse(await snippet(two.page)).env;
assert.deepEqual(Object.keys(env).filter((k) => k.startsWith("ANTHROPIC_DEFAULT_")), ["ANTHROPIC_DEFAULT_OPUS_MODEL"]);
assert.equal(env.ANTHROPIC_MODEL, "plan/m1");
assert.deepEqual(seen.errors, []);
assert.deepEqual(two.seen.errors, []);
});
test(`${engine}: a read-only key is shown its usage and no setup`, async (t) => {
const { browser, page } = await open(engine, "en", { ...ME, readOnly: true, models: [], limits: [] });
t.after(() => browser.close());