routing: a group's model picker offers the providers' image models, and a group of them draws (jzw690 on X)

jzw690 on X: the Routing page's group editor ("Add a model") listed no
image models, so a group of image models, to draw at
/v1/images/generations and to pick in Settings > Images, couldn't be
made.

What changed:
- /api/groups gains `drawers`: each provider's image models
  (gateway.Drawers, less ones unticked in its editor unless a group
  names them), apart from the chat `models`. The picker offers them
  after the chat models, noted "<provider> · Image model" (an existing,
  translated key); a member row says so and offers no reasoning level.
  Decision-model groups don't offer them. Image models stay out of the
  chat catalog, so agents are not offered them.
- An image member drew only when its provider had no picks: picks are
  of chat models, so membersFound dropped it as unpicked, and GroupDraws,
  resolveDrawing, the group's turns and DrawerMissing all failed.
  provider.FindDrawingGroup keeps such a member when drawsModel holds;
  the image path uses it (drawingMembers), video keeps FindGroup.
  DrawerMissing for a group ref asks GroupDraws.
- Routing card: such a member reads ready (groupsState), and Settings >
  Images lists every group that draws, not only those reached through
  Served.
- docs/subsystems/gateway-routing.md says so.

Tests:
- TestImageGroupOfUnpickedImageModelsDraws (gateway), from the
  reporter's case: two key providers whose live lists hold gpt-5.5 and
  gpt-image-2, one with gpt-5.5 picked. group/<id> draws at
  /v1/images/generations (the first member's 502 moves on to the next),
  as the Settings pick a request naming no model draws, and the model
  gone from the list makes it missing.
- TestGroupEditorOffersImageModels (gui): drawers listed, an unticked
  one not offered unless a group names it, none among chat models, the
  group's members ready, Settings offers the group.
- group-pick-drawers.test.cjs: the picker offers it with its note, adds
  it, no reasoning button, Save posts it; en and zh, Chromium and
  WebKit.

Broken by hand: drawingMembers passing nil instead of drawsModel made
the gateway test red ("group/pix-images doesn't draw"); turning off the
groups.go drawer branch made the gui test red ("group not ready").

Run at b295d1196 plus this change (mote unless said):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -count=1 -timeout 45m ./internal/provider ./internal/gateway
  ./internal/gui: provider ok. Two reds, neither on this path:
  TestCodexPoolSaysTheClientsVersion (full run only, passes alone 3/3;
  #4807) and TestMainWindowCorners (red on origin/main f49f6ba68 too,
  macOS 27; #3949). Both commented.
- GUI on the Linux VM (Playwright 1.62.0, both engines), 62 files:
  group-*, routing-group*, settings-groups, fallback-group,
  agent-model-groups, image*/images*, panel-routing*, routing-manual,
  routing-levels, i18n-keys. 698/710. i18n-keys was red on a comment of
  this change saying ", with an image" (reworded; 4/4 after). The
  WebKit reds under concurrency 4 passed on a serial run except
  group-member-info webkit zh, red 2/2 on origin/main f49f6ba68 too
  (#1745, commented).

Rebased on origin/main 809801f1f (its 8 commits change client.js and
gateway-routing.md), then again on mote: gofmt clean, go test -run
of the budgets, TestImageGroup*, TestDrawing*, TestGroupMember* and
TestGroupEditorOffersImageModels in gateway, gui and provider: ok; on
the Linux VM, both engines, group-pick-drawers, group-pick-filter,
group-decide-members, group-editor-fits, group-member-off,
routing-levels, settings-groups, image-models-hide, i18n-keys: 96/96.
Rebased last onto 03d7927a8 (search strings, i18n.js values only;
none of this change's files), not run again.

Not tried: a real provider's image model drawn through a group in the
running app; Windows and the real Linux app (WebKitGTK).
This commit is contained in:
yetone
2026-11-03 11:57:11 +08:00
parent 03d7927a8f
commit 1d8658abca
10 changed files with 399 additions and 19 deletions
File diff suppressed because one or more lines are too long
+33 -4
View File
@@ -115,9 +115,11 @@ func DrawerMissing() string { return drawerMissing(settings.Load().ImageGen) }
// with it: pickedMissing's, and a routing group ("group/<id>", 7up6666 on
// X) none of whose members draws any more.
func drawerMissing(v string) string {
if m := pickedMissing(v); m != "" || !provider.IsGroupRef(v) {
return m
if !provider.IsGroupRef(v) {
return pickedMissing(v)
}
// a group of image models only is no model agents are offered, so
// Resolve doesn't take it: it is missing when none of it draws
if !GroupDraws(v) {
return v
}
@@ -129,7 +131,7 @@ func drawerMissing(v string) string {
// picked in Settings › Images, and draws on those members in its routing's
// order, moving on while one fails (drawingGroup, #2005).
func GroupDraws(ref string) bool {
_, ms, ok := provider.FindGroup(ref)
_, ms, ok := drawingMembers(ref)
if !ok {
return false
}
@@ -141,6 +143,14 @@ func GroupDraws(ref string) bool {
return false
}
// drawingMembers is the routing group ref with its members ready now to
// draw on: FindGroup's, and also an image model of a provider whose picks
// leave it out among them, as the group's editor offers one beside the
// chat models (jzw690 on X).
func drawingMembers(ref string) (provider.Group, []provider.Member, bool) {
return provider.FindDrawingGroup(ref, drawsModel)
}
// drawsModel is whether model is one of p's Drawers, a ChatGPT account's
// other GPT Image names as its one (ListedDrawer).
func drawsModel(p provider.Provider, model string) bool {
@@ -149,6 +159,18 @@ func drawsModel(p provider.Provider, model string) bool {
}
func resolveDrawing(id string) (provider.Provider, string, bool) {
if provider.IsGroupRef(id) {
// its first member that draws: a group of image models only
// isn't among the models agents are offered, which Resolve reads
if _, ms, ok := drawingMembers(id); ok {
for _, m := range ms {
if drawsModel(m.Provider, m.Model) {
return m.Provider, m.Model, true
}
}
}
return provider.Resolve(id)
}
if strings.Contains(id, "/") {
return provider.Resolve(id)
}
@@ -693,6 +715,13 @@ func (s *Server) images(edit bool) http.HandlerFunc {
// goes by (provider.GroupFor) that resolved to one of its members. Any
// other names a model on its own.
func drawingGroup(asked string, p provider.Provider, model string) (provider.Group, []provider.Member, bool) {
return groupToMake(asked, p, model, drawingMembers)
}
// groupToMake is drawingGroup with the group's members found by find:
// a drawing's take its image models in (drawingMembers), a video's are
// FindGroup's.
func groupToMake(asked string, p provider.Provider, model string, find func(ref string) (provider.Group, []provider.Member, bool)) (provider.Group, []provider.Member, bool) {
ref := asked
if !provider.IsGroupRef(ref) {
gid, ok := provider.GroupFor(ref)
@@ -701,7 +730,7 @@ func drawingGroup(asked string, p provider.Provider, model string) (provider.Gro
}
ref = gid
}
g, ms, ok := provider.FindGroup(ref)
g, ms, ok := find(ref)
if !ok || len(ms) == 0 {
return provider.Group{}, nil, false
}
+104
View File
@@ -0,0 +1,104 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// jzw690 on X: a key provider's live list has a chat model and
// gpt-image-2, and the user put gpt-image-2 in a routing group from the
// group editor, which offers each provider's image models beside the chat
// models. Picks are of chat models, so a provider with picks leaves the
// image model out of them; the group still draws on it, at
// /v1/images/generations with model group/<id> and as the Settings ›
// Images pick, the next member asked when one answers 5xx. Such a group
// is no model agents are offered for a conversation.
func TestImageGroupOfUnpickedImageModelsDraws(t *testing.T) {
s, e := easeled(t)
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Cleanup(s.imageStore.running.Wait)
var brokeAsked atomic.Int32
broke := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
brokeAsked.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(502)
io.WriteString(w, `{"error":{"message":"upstream error: bad gateway","type":"upstream_error"}}`)
}))
t.Cleanup(broke.Close)
up := httptest.NewServer(e)
t.Cleanup(up.Close)
live := []catalog.Model{{ID: "gpt-5.5"}, {ID: "gpt-image-2", Draws: true}}
// relay: no picks; pix: its chat model picked, as most users have it
for _, p := range []provider.Provider{
{ID: "relay", Name: "Relay", Chat: broke.URL + "/v1", Key: "key"},
{ID: "pix", Name: "Pix", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-5.5"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive(p.ID, p.Chat, live); err != nil {
t.Fatal(err)
}
}
for _, g := range []provider.Group{
{ID: "images", Name: "Images", Members: []string{"relay/gpt-image-2", "pix/gpt-image-2"}, Routing: "order"},
{ID: "pix-images", Name: "Pix images", Members: []string{"pix/gpt-image-2"}},
} {
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
}
for _, ref := range []string{"group/images", "group/pix-images"} {
if !GroupDraws(ref) {
t.Fatalf("%s doesn't draw", ref)
}
}
for _, en := range provider.Catalog() {
if en.ID == "group/pix-images" || strings.Contains(en.Model, "gpt-image") && en.Provider.ID == "pix" {
t.Fatalf("an image model is offered to agents: %s (%s)", en.ID, en.Model)
}
}
// named at the images API: the first member's 502, then pix draws
code, a, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"group/images","prompt":"a magpie"}`)
if code != 200 || a.Model != "pix/gpt-image-2" || brokeAsked.Load() == 0 {
t.Fatalf("group/images: %d %s (first member asked %d)", code, raw, brokeAsked.Load())
}
if got := e.got("/v1/images/generations"); len(got) != 1 || !strings.Contains(got[0], `"model":"gpt-image-2"`) {
t.Fatalf("pix asked %v", got)
}
code, a, raw = postImages(t, s, "/v1/images/generations", "application/json", `{"model":"group/pix-images","prompt":"a magpie"}`)
if code != 200 || a.Model != "pix/gpt-image-2" {
t.Fatalf("group/pix-images: %d %s", code, raw)
}
// picked in Settings › Images, it draws a request naming no model
st := settings.Load()
st.ImageGen = "group/pix-images"
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
if Drawer() != "group/pix-images" || DrawerMissing() != "" {
t.Fatalf("the group pick isn't what draws: %q missing %q", Drawer(), DrawerMissing())
}
code, a, raw = postImages(t, s, "/v1/images/generations", "application/json", `{"prompt":"a magpie"}`)
if code != 200 || a.Model != "pix/gpt-image-2" {
t.Fatalf("Settings pick: %d %s", code, raw)
}
// gone from pix's list, it draws no more, and the pick is missing
if err := catalog.SaveLive("pix", up.URL+"/v1", []catalog.Model{{ID: "gpt-5.5"}}); err != nil {
t.Fatal(err)
}
if GroupDraws("group/pix-images") || DrawerMissing() != "group/pix-images" {
t.Fatalf("a group whose image model is gone still draws: missing %q", DrawerMissing())
}
}
+1 -1
View File
@@ -842,7 +842,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
fail(404, fmt.Sprintf("magpie knows no model %q to make videos with", f.Model))
return
}
g, ms, isGroup := drawingGroup(f.Model, p, model)
g, ms, isGroup := groupToMake(f.Model, p, model, provider.FindGroup)
if isGroup {
r = heldByGroup(r, g) // held to the group's accounts, if it is
}
+10 -1
View File
@@ -838,12 +838,21 @@ func settingsState() settingsJSON {
}
}
// the routing groups with a member that draws (7up6666 on X): a
// group picked here draws on its members in its routing's order
// group picked here draws on its members in its routing's order. One
// of image models only isn't served to agents (jzw690 on X), so it is
// listed from the groups themselves
listed := map[string]bool{}
for _, e := range provider.Served() {
if e.Group != "" && gateway.GroupDraws(e.ID) {
listed[e.ID] = true
s.ImageGenModels = append(s.ImageGenModels, modelRef{ID: e.ID, Name: e.Name, PName: e.Group})
}
}
for _, g := range provider.Groups() {
if ref := g.Ref(); !g.Hidden && !g.Disabled && !listed[ref] && gateway.GroupDraws(ref) {
s.ImageGenModels = append(s.ImageGenModels, modelRef{ID: ref, Name: cmp.Or(g.Name, g.ID), PName: g.ID})
}
}
if v := gateway.ListedDrawer(s.ImageGen); v != s.ImageGen {
s.ImageGenShown = v
}
+12 -6
View File
@@ -5316,7 +5316,7 @@ function routingPage(part) {
const LEVELS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]; // provider.MemberEfforts
function splitMember(id) {
id = id || "";
if (id.startsWith("group/") || groups?.models.some((m) => m.id === id)) return [id, ""];
if (id.startsWith("group/") || groups?.models.some((m) => m.id === id) || groups?.drawers?.some((m) => m.id === id)) return [id, ""];
const m = /^(.+):((?:none|minimal|low|medium|high|xhigh|max)(?:\+(?:none|minimal|low|medium|high|xhigh|max))*)$/i.exec(id);
if (!m) return [id, ""];
const parts = m[2].toLowerCase().split("+");
@@ -5326,7 +5326,10 @@ function routingPage(part) {
// asked at /v1/systemone (provider/decide_group.go): it is in
// groups.deciders, not groups.models
const deciderOf = (id) => groups?.deciders?.find((m) => m.id === splitMember(id)[0]);
const modelOf = (id) => groups?.models.find((m) => m.id === id) || groups?.models.find((m) => m.id === splitMember(id)[0]) || deciderOf(id);
// an image model (jzw690 on X) is in groups.drawers: a group holding it
// draws on it at the images API, and it takes no reasoning
const drawerOf = (id) => groups?.drawers?.find((m) => m.id === id);
const modelOf = (id) => groups?.models.find((m) => m.id === id) || groups?.models.find((m) => m.id === splitMember(id)[0]) || deciderOf(id) || drawerOf(id);
// a group's patterns (#766, provider.IsPattern): a glob, * any run of
// characters over the provider/model id, or re:<regexp> over the whole
// id, both in any case (provider.compilePattern). The group keeps them,
@@ -5408,7 +5411,7 @@ function routingPage(part) {
};
const modelName = (m) => { const tell = tellOf(m); return (m.name || m.id) + (tell ? " · " + tell : ""); };
const memberName = (id) => { const s = subOf(id), m = modelOf(id), o = !m && offOf(id); return s ? s.name : m ? modelName(m) : o ? o.model : id; };
const memberNote = (id) => { const o = !subOf(id) && !modelOf(id) && offOf(id); return subOf(id) ? t("routing group") : [modelOf(id)?.providerName || o && `${o.name} · ${t("switched off")}`, fixedOf(id) && fixedWords(fixedOf(id))].filter(Boolean).join(" · "); };
const memberNote = (id) => { const o = !subOf(id) && !modelOf(id) && offOf(id); return subOf(id) ? t("routing group") : [modelOf(id)?.providerName || o && `${o.name} · ${t("switched off")}`, drawerOf(id) && t("Image model"), fixedOf(id) && fixedWords(fixedOf(id))].filter(Boolean).join(" · "); };
// a member the group sends in its vendor's fast mode (Group.Fast)
const fastIn = (g, id) => !!g?.fast?.includes(id) && !subOf(id);
// a member Free first and Cheapest first count as costing nothing: its
@@ -6419,7 +6422,7 @@ function routingPage(part) {
const nm = el("span", "", memberName(id));
nm.title = memberName(id);
n.append(nm);
if (m || s) n.append(el("small", "", subOf(id) ? memberNote(id) : m.providerName));
if (m || s) n.append(el("small", "", subOf(id) || drawerOf(id) ? memberNote(id) : m.providerName));
else if (info?.providerOff) n.append(el("small", "", `${info.name} · ${t("switched off")}`));
if (info?.free && !s) {
const fr = el("small", "rt-free", t("free"));
@@ -6455,7 +6458,7 @@ function routingPage(part) {
// (blank), or one of its own whatever the agent asks. A group in
// it reasons as it says.
// a decision model reasons at no level of the group's or its own
if (!s && !deciderOf(id)) {
if (!s && !deciderOf(id) && !drawerOf(id)) {
const [base, fixed] = splitMember(id);
const several = fixed.includes("+");
const fx = el("button", "rt-cond rt-fixed" + (fixed ? " on" : ""), fixed ? fixedWords(fixed) : t("Group's reasoning"));
@@ -6574,7 +6577,10 @@ function routingPage(part) {
const subs = decides ? [] : groups.groups.filter((x) => !x.hidden && !x.decides && x.id !== g?.id && !(g && x.holds?.includes(g.id)))
.map((x) => ({ value: "group/" + x.id, label: x.name, note: noted("group/" + x.id, "group/" + x.id), icons: groupIcons(x), group: ROUTING_GROUPS, ref: "group/" + x.id }));
const ref = (x) => ({ value: x.id, label: x.name || x.id, note: noted(x.providerName, x.id), icon: x.icon, group: x.providerName, ref: x.id, context: x.context });
const options = [...subs, ...(decides ? [] : groups.models.map(ref)), ...(chats ? [] : (groups.deciders || []).map(ref))];
// the image models after them, said as such (jzw690 on X): a group
// of them is picked in Settings › Images, or named at the images API
const drawRef = (x) => ({ ...ref(x), note: noted(`${x.providerName} · ${t("Image model")}`, x.id) });
const options = [...subs, ...(decides ? [] : groups.models.map(ref)), ...(decides ? [] : (groups.drawers || []).map(drawRef)), ...(chats ? [] : (groups.deciders || []).map(ref))];
// the member a model is in the group as: itself, or with its
// reasoning fixed (deepseek/x:max), which is ticked as it and taken
// out by it rather than added twice (#907)
+76
View File
@@ -0,0 +1,76 @@
package gui
import (
"os"
"slices"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// jzw690 on X: the group editor's "Add a model" offers a provider's
// image models (its live list's gpt-image-2) beside its chat models, as
// drawers apart from them; a group holding one, from a provider whose
// picks leave it out, shows it ready, and Settings › Images offers that
// group. One unticked in its provider's editor isn't offered, unless a
// group names it already.
func TestGroupEditorOffersImageModels(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", os.Getenv("HOME"))
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
live := []catalog.Model{{ID: "gpt-5.5"}, {ID: "gpt-image-2", Draws: true}, {ID: "gpt-image-1", Draws: true}}
for _, p := range []provider.Provider{
{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1"},
{ID: "pix", Name: "Pix", Key: "k", Chat: "http://127.0.0.1:2/v1", Models: []string{"gpt-5.5"}, HiddenDrawers: []string{"gpt-image-1"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive(p.ID, p.Chat, live); err != nil {
t.Fatal(err)
}
}
ids := func(ms []modelRef) []string {
var out []string
for _, m := range ms {
out = append(out, m.ID)
}
return out
}
st := groupsState()
for _, want := range []string{"relay/gpt-image-2", "relay/gpt-image-1", "pix/gpt-image-2"} {
if !slices.Contains(ids(st.Drawers), want) {
t.Fatalf("%s not offered: drawers %v", want, ids(st.Drawers))
}
}
if slices.Contains(ids(st.Drawers), "pix/gpt-image-1") {
t.Fatalf("an unticked image model is offered: %v", ids(st.Drawers))
}
for _, m := range st.Models {
if slices.Contains(ids(st.Drawers), m.ID) || m.ID == "pix/gpt-image-2" {
t.Fatalf("an image model among the chat models: %s", m.ID)
}
}
if err := provider.SaveGroup(provider.Group{ID: "pix-images", Name: "Pix images", Members: []string{"pix/gpt-image-2", "pix/gpt-image-1"}}); err != nil {
t.Fatal(err)
}
st = groupsState()
if !slices.Contains(ids(st.Drawers), "pix/gpt-image-1") {
t.Fatalf("an unticked image model a group names isn't listed for its card: %v", ids(st.Drawers))
}
i := slices.IndexFunc(st.Groups, func(g groupJSON) bool { return g.ID == "pix-images" })
if i < 0 || !st.Groups[i].Ready {
t.Fatalf("group not ready: %+v", st.Groups)
}
for _, m := range st.Groups[i].Info {
if !m.Ready || m.Provider != "pix" || m.Model == "" {
t.Fatalf("member shown as missing: %+v", m)
}
}
if !slices.ContainsFunc(settingsState().ImageGenModels, func(m modelRef) bool { return m.ID == "group/pix-images" }) {
t.Fatal("Settings › Images doesn't offer the group")
}
}
+32 -1
View File
@@ -24,6 +24,10 @@ type groupsJSON struct {
// Deciders: the decision providers' models (Jev), which may only be a
// group's classifier
Deciders []modelRef `json:"deciders"`
// Drawers: the providers' image models (gateway.OfferedDrawers) not
// among Models, which a group may hold to draw with at the images API
// (jzw690 on X); agents are never offered them for a conversation
Drawers []modelRef `json:"drawers"`
// Found: magpie finds groups on its own (provider.AutoGroupsOn)
Found bool `json:"found"`
// Skip: the providers kept out of found groups, by id
@@ -282,7 +286,7 @@ func groupAccounts(gs []provider.Group) map[string][]keyModelJSON {
func groupsState() groupsJSON {
_, offset := time.Now().Zone()
out := groupsJSON{Groups: []groupJSON{}, Models: []modelRef{}, Pools: []poolJSON{}, Deciders: []modelRef{}, Found: provider.AutoGroupsOn(), Templates: provider.Templates(),
out := groupsJSON{Groups: []groupJSON{}, Models: []modelRef{}, Pools: []poolJSON{}, Deciders: []modelRef{}, Drawers: []modelRef{}, Found: provider.AutoGroupsOn(), Templates: provider.Templates(),
Clock: clockJSON{Zone: provider.LocalZone(), Offset: offset}}
for i := range out.Templates {
if out.Templates[i].Group.Members == nil {
@@ -304,11 +308,31 @@ func groupsState() groupsJSON {
}
out.Accounts = groupAccounts(all)
served := provider.Served()
chat := map[string]bool{}
for _, e := range served {
if e.Group == "" {
chat[e.ID] = true
out.Models = append(out.Models, servedRef(e))
}
}
// the image models, as Settings › Images lists them: each provider's
// Drawers less those unticked in its editor, but one a group names
// already, so its card still reads it. draws: every one, an unticked
// one included, which draws all the same
draws := map[string]provider.Provider{}
for _, p := range provider.All() {
if !p.On() || p.DecideOnly() {
continue
}
for _, m := range gateway.Drawers(p) {
ref := p.ID + "/" + m.ID
draws[ref] = p
if chat[ref] || p.DrawerHidden(m.ID) && !named[ref] {
continue
}
out.Drawers = append(out.Drawers, modelRef{ID: ref, Name: cmp.Or(m.Name, m.ID), Provider: p.ID, PName: p.Name, Icon: p.Icon, VendorPicks: gateway.VendorPicksDrawer(p)})
}
}
// every provider's models read once for the groups, not once a group
// (#1762)
find := provider.GroupFinder()
@@ -383,6 +407,13 @@ func groupsState() groupsJSON {
}
}
gj.Ready = true
} else if p, ok := draws[of]; ok && effort == "" {
// an image model its provider's picks leave out: the group
// draws on it (gateway.drawingMembers)
_, who := onOf(p)
_, model, _ := strings.Cut(of, "/")
m.Ready, m.Provider, m.Name, m.Icon, m.Model, m.On = true, p.ID, p.Name, p.Icon, model, max(len(who), 1)
gj.Ready = true
} else if pid, model, ok := strings.Cut(of, "/"); ok {
if p, err := provider.Find(pid); err == nil && !p.On() {
m.ProviderOff, m.Provider, m.Name, m.Icon, m.Model = true, p.ID, p.Name, p.Icon, model
@@ -0,0 +1,105 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// jzw690 on X: a group's Add a model picker didn't list the providers'
// image models, so a group of them, to pick in Settings › Images, couldn't
// be made.
// - The picker offers each image model in /api/groups' drawers, its note
// saying it is one; a click adds it, and its row says so and offers no
// reasoning, as an image model takes none.
// - Saved, the group holds it as written.
// In English and Chinese, Chromium and WebKit. Not one <select>.
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 models = [{ id: "a/one", name: "one", providerName: "A", icon: "generic" }];
const drawers = [{ id: "a/gpt-image-2", name: "gpt-image-2", providerName: "A", icon: "generic" }];
const words = {
en: { edit: "Edit", save: "Save", add: "Add another model", image: "Image model" },
zh: { edit: "编辑", save: "保存", add: "再添加一个模型", image: "生图模型" },
};
function serve(lang, posts) {
const groups = () => ({
models, drawers, pools: [],
groups: [{ id: "g", name: "G", members: ["a/one"], off: [], routing: "order", ready: true, memberInfo: [{ id: "a/one", ready: true }] }],
});
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
return async (r) => {
const url = new URL(r.request().url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.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/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json(groups());
if (url.pathname.startsWith("/api/groups/")) {
posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") });
return json(groups());
}
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
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 r.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"]) {
const w = words[lang];
test(`${engine} ${lang}: a group's picker offers the image models`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 }, reducedMotion: "reduce" })).newPage();
t.after(() => browser.close());
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=routing");
const card = page.locator('.rt-group[data-id="g"]');
await card.waitFor();
await card.locator("button", { hasText: w.edit }).click();
const ed = page.locator(".rt-gedit");
await ed.locator("button.rt-gadd", { hasText: w.add }).click();
const pop = page.locator("#pop");
const opt = (name) => pop.locator("li", { has: page.locator(".v", { hasText: new RegExp(`^${name}$`) }) }).first();
await opt("gpt-image-2").waitFor();
assert((await opt("gpt-image-2").locator(".n").textContent()).includes(`A · ${w.image}`), "the picker doesn't say it is an image model");
assert(!(await opt("one").locator(".n").textContent()).includes(w.image), "a chat model said to be an image model");
const rows = ed.locator(".fbl").first().locator(".fbrow");
assert.equal(await rows.count(), 1);
await opt("gpt-image-2").click();
assert.equal(await rows.count(), 2, "clicked, the image model was not added");
await page.keyboard.press("Escape");
await pop.waitFor({ state: "hidden" });
const row = rows.nth(1);
assert((await row.locator("small").first().textContent()).includes(w.image), "its row doesn't say it is an image model");
assert.equal(await row.locator(".rt-fixed").count(), 0, "an image model offered a reasoning level");
assert.equal(await rows.nth(0).locator(".rt-fixed").count(), 1, "the chat model lost its reasoning button");
const b = ed.locator("button.primary", { hasText: w.save });
await page.mouse.move(550, 600);
for (let i = 0; i < 10 && (await b.boundingBox()).y > 1400 - 160; i++) {
await page.mouse.wheel(0, 300);
await page.waitForTimeout(150);
}
const bb = await b.boundingBox();
await page.mouse.click(bb.x + bb.width / 2, bb.y + bb.height / 2);
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
const sent = posts.find((p) => p.path === "/api/groups/save");
assert.deepEqual(sent.body.members, ["a/one", "a/gpt-image-2"]);
assert.equal(await page.locator("select").count(), 0, "a native select");
assert.deepEqual(errors, []);
});
}
}
+25 -5
View File
@@ -948,12 +948,31 @@ func GroupFinder() func(id string) (Group, []Member, bool) {
all, find = groupsIn(entries), entriesBy(entries)
}
if g, ok := groupOf(all, gid); ok && !g.Disabled {
return g, membersFound(entries, find, all, g, disabledNow()), true
return g, membersFound(entries, find, all, g, disabledNow(), nil), true
}
return Group{}, nil, false
}
}
// FindDrawingGroup is FindGroup for a drawing (the gateway's images API):
// a member that is one of its provider's image models, as draws says, is
// the group's even where the provider's picks leave it out (unpicked).
// Picks are of chat models, and an image model is offered to a group
// beside them (jzw690 on X), so a group of image models draws on its
// members without any of them being a model agents are offered.
func FindDrawingGroup(id string, draws func(p Provider, model string) bool) (Group, []Member, bool) {
gid, ok := GroupIDOf(id)
if !ok {
return Group{}, nil, false
}
entries := providerEntries()
all := groupsIn(entries)
if g, ok := groupOf(all, gid); ok && !g.Disabled {
return g, membersFound(entries, entriesBy(entries), all, g, disabledNow(), draws), true
}
return Group{}, nil, false
}
// groupOf is the group of an id among all, unless it was removed.
func groupOf(all []Group, id string) (Group, bool) {
for _, g := range all {
@@ -975,13 +994,14 @@ func membersIn(entries []Entry, all []Group, g Group) []Member {
// membersOff is membersIn less the models off reports.
func membersOff(entries []Entry, all []Group, g Group, off func(pid, model string) bool) []Member {
return membersFound(entries, entriesBy(entries), all, g, off)
return membersFound(entries, entriesBy(entries), all, g, off, nil)
}
// membersFound is membersOff with entries' index made already: GroupFinder
// looks up every group in one list, and indexing it again for each was
// most of what the Providers page spent on groups.
func membersFound(entries []Entry, find entryOf, all []Group, g Group, off func(pid, model string) bool) []Member {
// most of what the Providers page spent on groups. A model also says is
// the group's whatever p's picks are (FindDrawingGroup); nil for none.
func membersFound(entries []Entry, find entryOf, all []Group, g Group, off func(pid, model string) bool, also func(p Provider, model string) bool) []Member {
var out []Member
seen := map[string]int{} // where in out
at := 0
@@ -1001,7 +1021,7 @@ func membersFound(entries []Entry, find entryOf, all []Group, g Group, off func(
model, effort := memberEffortIn(entries, id)
p, m, ok := resolveIn(entries, model)
key := WithMemberEffort(p.ID+"/"+m, effort)
if !ok || unpicked(find, p, m) {
if !ok || unpicked(find, p, m) && (also == nil || !also(p, m)) {
continue // none serves it, or the user unchecked it (#3911)
}
fixed, levels := MemberLevels(effort)