gateway: with model ids without the provider on, a routing group the user made is listed by its own id too (小八 on Discord)

"路由组的外显模型名可以选择去掉 group/ 这个前缀吗": with Settings ›
Network and sharing › Model ids without the provider on, /v1/models
listed a user's routing group only as group/<id>, though the gateway
already takes a request for its bare id (GroupFor). BareEntries skipped
every group row. Now a group the user made adds a row by its own id
(fast beside group/fast; under Only in group/fast's place, through
OnlyBare as before), and GET /v1/models/fast and Ollama's lookup answer
it (BareEntry). Only where the id is the group's alone: not when a
provider serves a model by it (the model's bare id is listed, reaching
the group as the gateway routes it), when it is listed already, when
GroupFor of it reaches another group, for a group magpie found (its
auto/<model> row is already listed under the model's bare id), or for a
group a gateway key can't use.

Agents: unchanged. magpie still writes group/<id> into an agent's
config, as it writes provider/model under Only; the gateway takes either
id, so turning the setting on or off rewrites nothing. The Settings help
text says nothing that is now false, so i18n is unchanged.

Run (mica, mica-run, mote over 18 cores):
- go test -timeout 45m -count=1 ./internal/provider ./internal/gateway:
  ok (152s, 1059s)
- GOOS=linux go vet -tags nogui ./...: ok; GOOS=windows go vet ./...: ok
- gofmt -l on the changed Go files: nothing
- After the rebase onto origin/main: TestBare in internal/gateway again.

Broken by hand: with bare.go at its old version, TestBareIDsListUserGroups
fails "on: [... glm-5.3 only-a only-b], want [...] and then fast once".
With the found-group and already-reached checks taken out of groupBare /
BareEntries, it fails listing "auto-glm-5-3".

Not tried: a real client against a running magpie; the full ./... suite
and the GUI suite (no GUI file changed); Windows and Linux runs beyond vet.
This commit is contained in:
yetone
2026-11-17 21:10:26 +08:00
parent 8e1534f5f9
commit 3126b0bacd
3 changed files with 181 additions and 5 deletions
+15 -3
View File
@@ -2998,7 +2998,15 @@ the row of the entry that id reaches, with its label, under the bare id.
agent with a subscription of its own is refused an id several other
providers serve (`provider.OffSpread`).
- An id already in the catalog as is (a group's or a provider's own id) is
not listed twice. Group rows themselves add nothing.
not listed twice.
- A routing group the user made is listed by its own id too, `fast` beside
`group/fast` (`groupBare`; 小八 on Discord), after the models' bare ids,
and under Only in `group/fast`'s place. Only where that id is the
group's alone: not when a provider serves a model by it (that model's
bare id is listed, reaching the group as `GroupFor` routes it), when it
is listed already, when `GroupFor` of it reaches another group, or for a
group magpie found (its `auto/<model>` row is listed under the model's
bare id already). A group a model's bare id already reaches adds nothing.
- The target must be in the list shown: a gateway key held to some models
sees only the bare ids that reach one of its models, so a key held to
`b/*` doesn't see `glm-5.3` that would go to `a`.
@@ -3006,7 +3014,8 @@ the row of the entry that id reaches, with its label, under the bare id.
list each model twice, nor for Claude Desktop's list, which has its own
shape.
- No agent file changes: magpie still writes `provider/model` ids
(`magpieModels`), so turning it on or off rewrites nothing.
(`magpieModels`), and `group/<id>` for a group, so turning it on or off
rewrites nothing; the gateway takes either id.
- Only (`{"on":true,"only":true}`, `settings.BareModelIDsOnly`,
`provider.SetBareIDs`, `provider.BareOnly`): the bare ids in place of the
rows they stand for, not beside them (qQianye on X: a Docker magpie's
@@ -3029,6 +3038,9 @@ the row of the entry that id reaches, with its label, under the bare id.
place, found groups on and off, `provider/model` still served, Claude
Code's discovery, a held key, another magpie) in
[`bare_ids_test.go`](../../internal/gateway/bare_ids_test.go),
`TestBareIDsListUserGroups` (a user's group by its own id, on and Only,
a group named like a model, a found group, a held key) in
[`bare_group_ids_test.go`](../../internal/gateway/bare_group_ids_test.go),
`TestBareModelIDsSetting` and `TestBareModelIDsOnlySetting` in
`internal/gui`, and `internal/gui/tests/bare-ids.test.cjs`.
- A URL magpie downloads but didn't choose itself is downloaded from public addresses only, wherever the request came from ([`image_fetch_guard.go`](../../internal/gateway/image_fetch_guard.go)). That is an image a caller names (an `/v1/images/edits` or `/v1/images/generations` reference image, for an images API that takes files, Gemini's own API or Code Assist: `fetchPicture` in [`draw.go`](../../internal/gateway/draw.go), `publicClient`), a page `web_fetch` reads (`webFetchClient`), and an image or video a vendor answers by URL, which what the model was asked to draw or do can steer (the inline download for a `b64_json` caller in `draw.go` and `/v1/videos/{id}/content` in [`video.go`](../../internal/gateway/video.go), `vendorClient`; generate_image's own download in [`internal/imagemcp`](../../internal/imagemcp/imagemcp.go), `PublicClient`). Every address the host resolves to must be public (`publicAddr`, which is [`internal/netguard`](../../internal/netguard/netguard.go)'s `Public`, the rule a provider's icon uses too: not loopback, RFC 1918, fc00::/7, link-local with 169.254.169.254, CGNAT 100.64/10, unspecified, multicast, documentation, reserved, benchmarking, Teredo, nor an IPv4-mapped, NAT64 or 6to4 form of one; an AAAA record Loon synthesizes for an A answer in the same reply, `fd27:712::/96` with that IPv4 address inside, is left out and the A answer judged in its place, `dropLoon`), and the request goes to the address checked, so a name that resolves elsewhere the second time changes nothing; a direct connection is checked again on the address dialled (`guardDialer`). Through a proxy the proxy is sent that address, never the name (an `https://` CONNECT or SOCKS keeps the name for TLS and Host; a plain `http://` URL through an HTTP proxy is asked for by the address in Host too). A fake-IP resolver's answer is the one shape let past that (#2593; ggbdpq, with h4rk8s's and TomXPRIME's reports): Clash's TUN with fake-ip, Clash Verge, Surge's enhanced mode and Loon answer every name in 198.18.0.0/15 (`netguard.FakeIP`), so with one on every download was refused as a private address. A name (never an address literal) whose every answer is in that range is fetched: with no proxy (pure TUN) its fake address is pinned and dialled, the dial guard letting that one address in, and the TUN carries it; through a proxy on this computer (a loopback address or `localhost`, `onThisComputer`) the proxy is given the name, never the fake address, which a real proxy can't route (h4rk8s: a CONNECT by the name went through where one by its 198.18 address failed), and a plain `http://` request's Host is the checked name, never the caller's own; through a proxy elsewhere it is refused. The fake-IP resolver's own AAAA beside its fake A answer (an IPv6 address in fc00::/7 or 2001:2::/48 while an A answer is in 198.18.0.0/15, `netguard.FakePaired`: mihomo's `fake-ip-range6`, which Clash Verge Rev turns on by default as `fdfe:dcba:9876::1/64` or fills in as `2001:2::/64`; jiezhengj, whose every `web_fetch` was refused) is left out by `dropLoon` and never dialled, the fake A answer judged and pinned in its place. An answer with any other address beside the fake ones (private or public) is judged as any, so a fake one beside 192.168.x is refused. The trust this asks for is the fake-IP resolver's: which host the name stands for, and so where the TUN or the proxy connects, is decided where magpie can't see, and a name that really points at the user's network is reached if that resolver's rules send it there. A provider's icon was already fetched this way (`publicIP` in [`internal/provider/icon.go`](../../internal/provider/icon.go), #252), and shares the rule. `TestFakeIPNameGoesToALocalProxyByName`, `TestFakeIPNameDialledThroughTheTUN`, `TestFakeIPWithItsIPv6Answer`, `TestFakeIPRefusesTheRest` in [`fakeip_test.go`](../../internal/gateway/fakeip_test.go). Each redirect, up to 5, is checked the same, and a caller's image must sniff as an image. A request from this computer gets nothing more: a reverse proxy or relay in front of magpie on the same host makes every request it carries arrive from loopback, so where a request came from is never a reason to reach a private address. Two things are: settings.json's `fetchPrivate` (`settings.FetchPrivate`, none by default, no Settings page, this computer's own and never brought by a sync or restore), a list of names, `name:port`s, IPs and CIDR ranges the user lets magpie download from (`allowFor`; a settings.json that can't be read lets nothing extra in), and for a vendor's URL the `host:port` of that provider's own endpoints, which the user named themselves (a provider on the LAN that serves its images from itself). A vendor's image that can't be downloaded is answered by its URL, never dropped; its video is a 502 naming why. A URL left for the vendor to fetch (a chat model's message) is the vendor's to fetch.
@@ -3424,7 +3436,7 @@ go test -tags nogui ./internal/gateway -run 'TestBedrock'
go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer|TestFetchPrivateEntries|TestVendorImageURLAtPrivateAddress|TestVideoContentAtPrivateAddress'
go test -tags nogui ./internal/gateway ./internal/provider ./internal/cli ./internal/gui -run 'TestDisabled|TestModelDisableCmd'
node --test internal/gui/tests/disabled-models.test.cjs
go test -tags nogui ./internal/gateway ./internal/gui -run 'TestBareModelIDs'
go test -tags nogui ./internal/gateway ./internal/gui -run 'TestBare(ModelIDs|IDsList)'
node --test internal/gui/tests/bare-ids.test.cjs
go test -tags nogui ./internal/gateway -run 'TestTextWritten|TestGLMTextCall|TestPluginTextWrittenCall|TestQuietWholeReplyStreamed|TestDSMLAlma'
go test -tags nogui ./internal/gateway -run 'TestAutoMode|TestClaudeBridgeSafeguard|TestSafeguardsRefused'
+125
View File
@@ -0,0 +1,125 @@
package gateway
import (
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
// 小八 on Discord: "路由组的外显模型名可以选择去掉 group/ 这个前缀吗". With
// Model ids without the provider on, a routing group the user made is
// listed by its own id too (fast beside group/fast), and with Only in
// place of group/fast; GET /v1/models/fast answers for it, and a request
// for fast reaches the group. Not listed so: a group whose id a provider
// serves a model by (that bare id is the model row's, which reaches the
// group as the gateway routes it, listed once), a group magpie found
// (auto/glm-5.3, listed as glm-5.3 already), and a group a key may not
// use. Off, the list is as it was.
func TestBareIDsListUserGroups(t *testing.T) {
fresh(t)
for _, p := range []provider.Provider{
{ID: "a", Name: "A", Key: "k", Models: []string{"glm-5.3", "only-a"}},
{ID: "b", Name: "B", Key: "k", Models: []string{"glm-5.3", "only-b"}},
} {
f := &fake{t: t, ctype: "application/json", reply: `{"id":"from-` + p.ID + `","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`}
up := httptest.NewServer(f)
t.Cleanup(up.Close)
p.Chat = up.URL + "/v1"
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
for _, g := range []provider.Group{
{ID: "fast", Name: "Fast", Members: []string{"b/only-b", "a/only-a"}, Routing: provider.Ordered},
{ID: "only-a", Name: "Only A", Members: []string{"a/only-a"}, Routing: provider.Ordered},
} {
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
}
if err := provider.SetAutoGroups(true); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Held")
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"a/*"}}); err != nil {
t.Fatal(err)
}
get := func(secret string) []string {
r := httptest.NewRequest("GET", "/v1/models", nil)
if secret != "" {
r.Header.Set("Authorization", "Bearer "+secret)
}
return listedIDs(t, r)
}
count := func(ids []string, id string) int {
n := 0
for _, x := range ids {
if x == id {
n++
}
}
return n
}
chat := func(path, body string) (int, string) {
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
return rec.Code, rec.Header().Get("X-Magpie-Provider")
}
off := get("")
if !slices.Contains(off, "group/fast") || slices.Contains(off, "fast") {
t.Fatalf("off: %v", off)
}
if err := provider.SetBareIDs(true, false); err != nil {
t.Fatal(err)
}
on := get("")
if !slices.Equal(on[:len(off)], off) || count(on, "fast") != 1 || count(on, "group/fast") != 1 {
t.Fatalf("on: %v, want %v and then fast once", on, off)
}
if count(on, "only-a") != 1 || slices.Contains(on, "auto-glm-5-3") || count(on, "glm-5.3") != 1 {
t.Fatalf("on: only-a and glm-5.3 once each, no auto-glm-5-3: %v", on)
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models/fast", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"id":"fast"`) {
t.Fatalf("GET /v1/models/fast: %d %s", rec.Code, rec.Body.String())
}
for _, c := range []struct{ path, body string }{
{"/v1/chat/completions", `{"model":"fast","messages":[{"role":"user","content":"hi"}]}`},
} {
if code, by := chat(c.path, c.body); code != 200 || by != "b" {
t.Fatalf("%s fast: %d by %q, want the group's first member, b", c.path, code, by)
}
}
// a key held to a/* isn't shown the group, by either id
if held := get(secrets[0]); slices.Contains(held, "fast") || slices.Contains(held, "group/fast") {
t.Fatalf("held key: %v", held)
}
if err := provider.SetBareIDs(true, true); err != nil {
t.Fatal(err)
}
only := get("")
if slices.Contains(only, "group/fast") || count(only, "fast") != 1 {
t.Fatalf("Only: %v", only)
}
// in group/fast's place
if i, j := slices.Index(off, "group/fast"), slices.Index(only, "fast"); i != j {
t.Fatalf("Only put fast at %d of %v, group/fast was at %d of %v", j, only, i, off)
}
rec = httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models/fast", nil))
if rec.Code != 200 {
t.Fatalf("Only, GET /v1/models/fast: %d %s", rec.Code, rec.Body.String())
}
// an agent configured with group/fast is still served
if code, by := chat("/v1/chat/completions", `{"model":"group/fast","messages":[{"role":"user","content":"hi"}]}`); code != 200 || by != "b" {
t.Fatalf("group/fast under Only: %d by %q", code, by)
}
}
+41 -2
View File
@@ -21,7 +21,8 @@ import (
// bare id that is a catalog id already, or that the gateway would take to
// a model the list doesn't show (a gateway key held to other models, an
// id like anthropic/claude-x that names a provider of the user's), isn't
// listed by it.
// listed by it. A routing group the user made is listed by its own id as
// well (fast for group/fast), where nothing else goes by that id.
// BareModelIDs says whether /v1/models lists models by their bare ids too.
func BareModelIDs() bool { return settings.Shared().BareModelIDs }
@@ -60,7 +61,8 @@ type Bare struct {
}
// BareEntries are the rows a list of shown adds for the bare ids, in the
// order the models first appear in shown, each once.
// order the models first appear in shown, each once, then the routing
// groups the user made, by their own ids (groupBare).
func BareEntries(shown []Entry) []Bare {
defer Hold()()
ids := make(map[string]bool, len(shown))
@@ -71,6 +73,7 @@ func BareEntries(shown []Entry) []Bare {
all := groupsIn(entries)
var out []Bare
seen := map[string]bool{}
reached := map[int]bool{}
for _, e := range shown {
m := e.Model
if e.Group != "" || m == "" || seen[m] || ids[m] {
@@ -79,11 +82,47 @@ func BareEntries(shown []Entry) []Bare {
seen[m] = true
if i := bareTarget(shown, all, entries, m); i >= 0 {
out = append(out, Bare{ID: m, Of: i})
reached[i] = true
}
}
// then each routing group the user made that no model's bare id
// reaches, by its own id
for j, e := range shown {
if e.Group == "" || reached[j] {
continue
}
if b, ok := groupBare(shown, all, entries, ids, seen, j); ok {
seen[b.ID] = true
out = append(out, b)
}
}
return out
}
// groupBare is the Bare for the routing group the user made at shown[j]
// (小八 on Discord: group/fast is long to type into a client), by the id
// a request for it reaches it by: its own id, fast. Only where that is
// unambiguous: not for a group magpie found (listed under its model's
// bare id already, or by its auto/<model>), nor by an id listed already
// or given to another row, one a provider serves a model by, or one
// GroupFor takes elsewhere.
func groupBare(shown []Entry, all []Group, entries []Entry, ids, seen map[string]bool, j int) (Bare, bool) {
e := shown[j]
id := e.Group
if !e.Named || id == "" || e.ID != GroupPrefix+id || strings.Contains(id, "/") || ids[id] || seen[id] {
return Bare{}, false
}
for _, x := range entries {
if x.Model == id || x.ID == id {
return Bare{}, false
}
}
if i := bareTarget(shown, all, entries, id); i < 0 || shown[i].Group != id {
return Bare{}, false
}
return Bare{ID: id, Of: j}, true
}
// bareTarget is the index in shown of the entry a request for the bare id
// reaches: the routing group GroupFor gives it, else the provider's model
// Resolve does; -1 when shown has neither.