diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ea69742d7..908830f31 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -873,6 +873,21 @@ and `TestKeySlotEveryRoute` in `key_slots_test.go`, `TestKeyConcurrency` in `internal/access`, `TestGatewayKeyConcurrencyCLI`, `gateway-key-concurrency.test.cjs`. +A key's `ServiceTier` (JackyFill on X; `access.Key`, set by the `tier-key` +action, the key row's service-tier badge or `magpie gateway-key tier +follow|standard|fast|ultrafast`; stored as "", "default", "priority" or +"ultrafast") sends its Responses and Chat requests at that tier whatever the +client asked, and over Codex's own setting (`keyTiered` in `codex_tier.go`, +after `codexTiered` in `handle` and in `codexBackend`): standard takes the +tier off, and Ultrafast on a bare model no account lists it on goes as +priority, as `codexTiered` does. Unset follows the request. It only sets the +request's `service_tier`: what is then sent upstream is the providers' own +rule (`fits`, `takesTier`, the ultrafast to priority fallback), so a vendor +that honours no service tier is sent none, and Anthropic-protocol requests +(Claude's `speed`) are left alone. Tests: `TestGatewayKeyServiceTier`, +`TestKeyTieredChat`, `TestKeyServiceTier` in `internal/access`, +`TestGatewayKeyTierCLI`, `gateway-key-tier.test.cjs`. + `GET /me` is the key page: a gateway key's holder opens it in a browser at the address they reach the gateway at, types their key, and sees that key's own name, limits, usage (today, 7 and 30 days, its most used models) and diff --git a/internal/access/access.go b/internal/access/access.go index 4b717ca26..70fb2343d 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -192,6 +192,28 @@ type Key struct { // queue and go out in order, as over a provider's MaxConcurrency. // 0 for no limit. MaxConcurrency int `json:"maxConcurrency,omitempty"` + // ServiceTier is the service tier the key's OpenAI-API requests (Chat + // and Responses) are sent at whatever the client asked (JackyFill on + // X): settings.CodexTierStandard for none, "priority" (Codex's Fast) + // or "ultrafast"; "" follows the request. + ServiceTier string `json:"serviceTier,omitempty"` +} + +// CleanTier is a key's service tier as it is kept: "" to follow the +// request, settings.CodexTierStandard, "priority" or "ultrafast", read from +// the words people use for them too (normal, fast, ultra_fast). +func CleanTier(v string) (string, error) { + switch strings.ToLower(strings.NewReplacer("-", "", "_", "", " ", "").Replace(strings.TrimSpace(v))) { + case "", "follow", "asked", "off": + return "", nil + case "default", "standard", "normal", "none": + return settings.CodexTierStandard, nil + case "priority", "fast": + return "priority", nil + case "ultrafast": + return "ultrafast", nil + } + return "", fmt.Errorf("Service tier: one of follow, standard, fast or ultrafast, not %q", v) } // MaxKeyConcurrency is the most MaxConcurrency a key may have, as a @@ -238,6 +260,8 @@ type Identity struct { // (Key.MaxConcurrency), 0 for none; an issued key is held to its // issuer's too (Issuer.MaxConcurrency). MaxConcurrency int + // ServiceTier is Key.ServiceTier. + ServiceTier string // Default: the key is the sharing key magpie made itself (Default), // the one it writes into this computer's own agents that reach the // gateway from beyond loopback, never one the user made for someone @@ -447,6 +471,9 @@ type Change struct { // MaxConcurrency is what "concurrency-key" sets: how many requests // the key may have in flight at once, 0 for no limit. MaxConcurrency int `json:"maxConcurrency,omitempty"` + // ServiceTier is what "tier-key" sets (Key.ServiceTier), "" to follow + // the request. + ServiceTier string `json:"serviceTier,omitempty"` // Secret is the value "add-key" gives the new key, one its clients // already send (love1sbug on X: keys handed out from another gateway), // or "rotate-key" gives the key; "" for one magpie makes. @@ -623,6 +650,12 @@ func Update(action string, in Change) (string, error) { return "", fmt.Errorf("Concurrency: a whole number from 0 to %d", MaxKeyConcurrency) } keys[i].MaxConcurrency = in.MaxConcurrency + case "tier-key": + tier, err := CleanTier(in.ServiceTier) + if err != nil { + return "", err + } + keys[i].ServiceTier = tier case "issuer-key": // may issue short-lived keys under itself (POST /v1/magpie/keys) if in.Issues && keys[i].Browser { @@ -668,7 +701,7 @@ func Update(action string, in Change) (string, error) { default: return "", fmt.Errorf("unknown key action %q", action) } - if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "access-key" && action != "issuer-key" && action != "move-key" { + if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "tier-key" && action != "access-key" && action != "issuer-key" && action != "move-key" { mirror = &keys[i] } } diff --git a/internal/access/issue.go b/internal/access/issue.go index 1032404d5..e802a43de 100644 --- a/internal/access/issue.go +++ b/internal/access/issue.go @@ -353,7 +353,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) { return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q names an account group, and magpie can't read its account groups now: %v", k.Name, err)} } k.Accounts = accounts - who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency} + who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier} // the default key as Default tells it: marked LAN, or the id the // settings name (settings read only for an unmarked key) who.Default = k.LAN || (k.ID != "" && settings.Load().LANKeyID == k.ID) diff --git a/internal/access/tier_test.go b/internal/access/tier_test.go new file mode 100644 index 000000000..9973c1c52 --- /dev/null +++ b/internal/access/tier_test.go @@ -0,0 +1,33 @@ +package access + +import ( + "testing" + "time" +) + +// JackyFill on X: a gateway key can be set to a service tier. tier-key sets +// it (from the words people use too), Authenticate tells it, "follow" takes +// it off, and a word it doesn't know is refused with the key left as it was. +func TestKeyServiceTier(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + clockAt(t, time.Date(2026, 11, 11, 9, 0, 0, 0, time.UTC)) + id, secret := addKey(t, "Team") + if who, _ := Authenticate(secret); who.ServiceTier != "" { + t.Fatal("a new key has a tier:", who.ServiceTier) + } + for in, want := range map[string]string{"fast": "priority", "Ultra_Fast": "ultrafast", "normal": "default", "priority": "priority", "follow": "", "": ""} { + if _, err := Update("tier-key", Change{Key: id, ServiceTier: in}); err != nil { + t.Fatal(in, err) + } + if who, ok := Authenticate(secret); !ok || who.ServiceTier != want { + t.Fatalf("%q: tier %q, want %q", in, who.ServiceTier, want) + } + } + Update("tier-key", Change{Key: id, ServiceTier: "fast"}) + if _, err := Update("tier-key", Change{Key: id, ServiceTier: "turbo"}); err == nil { + t.Fatal("turbo was taken") + } + if who, _ := Authenticate(secret); who.ServiceTier != "priority" { + t.Fatal("a refused word changed the key:", who.ServiceTier) + } +} diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index b52913f9b..abf528b65 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -16,6 +16,7 @@ import ( "github.com/yetone/magpie/internal/budget" "github.com/yetone/magpie/internal/oidc" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" ) func gatewayKeys(args []string) error { return gatewayKeysTo(os.Stdout, args) } @@ -53,6 +54,10 @@ func gatewayKeysTo(out io.Writer, args []string) error { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyConcurrency(out, args[1:]) } + if action == "tier" { + access.MigrateLegacyLANKeyBestEffort() + return gatewayKeyTier(out, args[1:]) + } if action == "mcp" { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyMCP(out, args[1:]) @@ -106,7 +111,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { args = args[:2] } if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) { - return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/*|re: ...] | aliases [none | =/ ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/*|re: ...] | aliases [none | =/ ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | tier [follow | standard | fast | ultrafast] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") } switch action { case "list", "add", "rotate", "remove": @@ -817,6 +822,35 @@ func gatewayKeyConcurrency(out io.Writer, args []string) error { return err } +// gatewayKeyTier shows or sets the service tier a key's OpenAI-API requests +// are sent at whatever the client asked (JackyFill on X): +// +// magpie gateway-key tier its tier +// magpie gateway-key tier follow|standard|fast|ultrafast set it +func gatewayKeyTier(out io.Writer, args []string) error { + if len(args) == 0 || len(args) > 2 { + return fmt.Errorf("usage: magpie gateway-key tier [follow | standard | fast | ultrafast]") + } + id := args[0] + if len(args) == 2 { + if _, err := access.Update("tier-key", access.Change{Key: id, ServiceTier: args[1]}); err != nil { + return err + } + } + keys, err := access.List() + if err != nil { + return err + } + i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == id }) + if i < 0 { + return fmt.Errorf("Key not found") + } + k := keys[i] + word := map[string]string{"": "follows the request", settings.CodexTierStandard: "standard", "priority": "fast", "ultrafast": "ultrafast"}[k.ServiceTier] + _, err = fmt.Fprintf(out, "%s: service tier %s\n", k.Name, word) + return err +} + // accessWord is a key's access as the list says it: "browser" (Magpie // Browser's, access.Key.Browser), "read-only" or "full". func accessWord(k access.Key) string { diff --git a/internal/cli/gateway_keys_cli_test.go b/internal/cli/gateway_keys_cli_test.go index 535490dc6..aac683170 100644 --- a/internal/cli/gateway_keys_cli_test.go +++ b/internal/cli/gateway_keys_cli_test.go @@ -739,3 +739,42 @@ func TestGatewayKeyAccountGroupsCLI(t *testing.T) { t.Fatal(got, err) } } + +// JackyFill on X: `gateway-key tier [follow|standard|fast|ultrafast]` +// shows or sets a key's service tier; a word it doesn't know is refused. +func TestGatewayKeyTierCLI(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if err := settings.Save(settings.Settings{LAN: true}); err != nil { + t.Fatal(err) + } + call := func(args ...string) (string, error) { + var out bytes.Buffer + err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...)) + return out.String(), err + } + if _, err := call("add", "Team"); err != nil { + t.Fatal(err) + } + keys, _ := access.List() + id := keys[0].ID + for _, c := range [][3]string{{"", "", "follows the request"}, {"fast", "", "fast"}, {"ultrafast", "", "ultrafast"}, {"standard", "", "standard"}, {"follow", "", "follows the request"}} { + args := []string{"tier", id} + if c[0] != "" { + args = append(args, c[0]) + } + if got, err := call(args...); err != nil || got != "Team: service tier "+c[2]+"\n" { + t.Fatalf("%v: %q %v", args, got, err) + } + } + call("tier", id, "fast") + for _, args := range [][]string{{"tier"}, {"tier", id, "turbo"}, {"tier", id, "--help"}, {"tier", id, "fast", "x"}, {"tier", "missing", "fast"}, {"tier", "missing"}} { + if _, err := call(args...); err == nil { + t.Error("accepted", args) + } + } + if keys, _ = access.List(); keys[0].ServiceTier != "priority" { + t.Fatalf("a refused call changed it: %q", keys[0].ServiceTier) + } +} diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index cda5d63c6..0c5d15ac3 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -120,6 +120,7 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) { noteAsked(r.Context(), model) // the service tier set for Codex, in place of the one it asked body = codexTiered(r, body, model) + body = keyTiered(r, body, model) // a turn of the conversation's own: the model its side calls may // follow (codexFollowTo) meta := requestSessionMetadata(r.Header, body) diff --git a/internal/gateway/codex_tier.go b/internal/gateway/codex_tier.go index 0f14bbcce..e9a0593b7 100644 --- a/internal/gateway/codex_tier.go +++ b/internal/gateway/codex_tier.go @@ -5,6 +5,7 @@ import ( "net/http" "strings" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" ) @@ -34,6 +35,26 @@ func codexTiered(r *http.Request, body []byte, model string) []byte { return withServiceTier(body, set) } +// keyTiered is body with the service tier the gateway key behind r is set +// to (access.Key.ServiceTier, JackyFill on X) in place of the one the client +// asked, for any OpenAI-API request. "" follows the request. A bare model +// that no account lists Ultrafast on is asked for priority instead, as +// codexTiered does. Whether the tier is then sent is the providers' own +// say (serve, fits), so a vendor without service tiers never sees it. +func keyTiered(r *http.Request, body []byte, model string) []byte { + set := access.Caller(r.Context()).ServiceTier + if set == "" { + return body + } + if set == "ultrafast" && !strings.Contains(model, "/") && !provider.UltraModels()[model] { + set = "priority" + } + if set == settings.CodexTierStandard { + set = "" + } + return withServiceTier(body, set) +} + // withServiceTier is body with its top-level service_tier set to tier, or // without one for "", every other byte as it came. A body that isn't a // JSON object goes as it came. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 589a99f3d..fd01b831f 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2182,6 +2182,11 @@ func (s *Server) handle(from provider.Protocol) http.HandlerFunc { // asked (codexTiered) body = codexTiered(r, body, model) } + // the service tier the gateway key is set to, over the client's + // ask and the Codex setting (keyTiered) + if from == provider.Responses || from == provider.Chat { + body = keyTiered(r, body, model) + } if from == provider.Chat { body = thinkingEffort(body) // OpenCode 1's promptCacheKey (#5468) diff --git a/internal/gateway/key_tier_test.go b/internal/gateway/key_tier_test.go new file mode 100644 index 000000000..5d3e38d2a --- /dev/null +++ b/internal/gateway/key_tier_test.go @@ -0,0 +1,99 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/settings" +) + +// JackyFill on X: a gateway key carries a service tier. Its requests go at +// that tier whatever the client asked (and over Codex's own setting), a key +// set to "follow" or another key goes as asked, standard drops the tier, +// and Ultrafast on a model no account lists it on goes as priority. +func TestGatewayKeyServiceTier(t *testing.T) { + tried := tierAccounts(t, nil, nil) + s := New() + cfg := settings.Load() + cfg.LAN = true + if err := settings.Save(cfg); err != nil { + t.Fatal(err) + } + secret, err := access.Update("add-key", access.Change{Name: "Tiered"}) + if err != nil { + t.Fatal(err) + } + other, err := access.Update("add-key", access.Change{Name: "Plain"}) + if err != nil { + t.Fatal(err) + } + keys, _ := access.List() + var id string + for _, k := range keys { + if k.Name == "Tiered" { + id = k.ID + } + } + send := func(key, path, model, asked string) string { + t.Helper() + b := `{"model":"` + model + `","stream":true,"input":"ping","messages":[{"role":"user","content":"ping"}]` + if asked != "" { + b += `,"service_tier":"` + asked + `"` + } + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", path, strings.NewReader(b+"}")) + req.Header.Set("Authorization", "Bearer "+key) + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", path, rec.Code, rec.Body) + } + got := tried() + if len(got) == 0 { + t.Fatal("nothing was asked of the backend") + } + return got[len(got)-1] + } + // (a Chat request to a Codex model reaches the fake backend on a host that + // is not chatgpt.com, which the translation sends no tier to: TestKeyTieredChat) + for _, path := range []string{"/v1/responses"} { + for _, c := range []struct{ set, asked, want string }{ + {"", "priority", "acct-plus:priority"}, + {"", "", "acct-plus:"}, + {"fast", "", "acct-plus:priority"}, + {"fast", "ultrafast", "acct-plus:priority"}, + {"standard", "priority", "acct-plus:"}, + {"ultrafast", "", "acct-pro:ultrafast"}, + } { + if _, err := access.Update("tier-key", access.Change{Key: id, ServiceTier: c.set}); err != nil { + t.Fatal(err) + } + if got := send(secret, path, "codex/gpt-6-luna", c.asked); got != c.want { + t.Errorf("%s, key %q, asked %q: tried %s, want %s", path, c.set, c.asked, got, c.want) + } + // another key is never touched by it + if got := send(other, path, "codex/gpt-6-luna", c.asked); got != map[string]string{"": "acct-plus:", "priority": "acct-plus:priority", "ultrafast": "acct-pro:ultrafast"}[c.asked] { + t.Errorf("%s, other key, asked %q: tried %s", path, c.asked, got) + } + } + } +} + +// A Chat request carries the key's tier the same way: the body the route +// goes on with has it, replaced, added or taken away. +func TestKeyTieredChat(t *testing.T) { + for _, c := range []struct{ set, body, want string }{ + {"", `{"model":"gpt-5","service_tier":"priority"}`, `{"model":"gpt-5","service_tier":"priority"}`}, + {"priority", `{"model":"gpt-5"}`, `{"service_tier":"priority","model":"gpt-5"}`}, + {"priority", `{"model":"gpt-5","service_tier":"flex"}`, `{"service_tier":"priority","model":"gpt-5"}`}, + {"default", `{"model":"gpt-5","service_tier":"priority"}`, `{"model":"gpt-5"}`}, + {"ultrafast", `{"model":"gpt-5"}`, `{"service_tier":"priority","model":"gpt-5"}`}, + } { + r := httptest.NewRequest("POST", "/v1/chat/completions", nil) + r = r.WithContext(access.WithIdentity(r.Context(), access.Identity{KeyID: "k", ServiceTier: c.set})) + if got := string(keyTiered(r, []byte(c.body), "gpt-5")); got != c.want { + t.Errorf("key %q on %s: %s, want %s", c.set, c.body, got, c.want) + } + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index f75dfde8c..6c77ccbc2 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3151,12 +3151,12 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } #gatewayKeys .amodels.key-models { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } /* a key's quotas and concurrency badges (#2216) take no room until the row is hovered, and give way before the row runs past a narrow window */ -#gatewayKeys .amodels:is(.key-quotas, .key-conc) { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } +#gatewayKeys .amodels:is(.key-quotas, .key-conc, .key-tier) { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } /* unset, shown by a hover, they give way before the masked key does: the key squeezed by them on a narrow window slid its copy button under the pointer that came to drag the row */ -#gatewayKeys .acc > :is(.key-quotas, .key-conc):not(.set) { flex-shrink: 8; } -#gatewayKeys .acc:not(:hover) > :is(.key-quotas, .key-conc):not(.set, .open, :focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; } +#gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier):not(.set) { flex-shrink: 8; } +#gatewayKeys .acc:not(:hover) > :is(.key-quotas, .key-conc, .key-tier):not(.set, .open, :focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; } /* the MCP servers a key held to some may use: cut, and gives way first */ #gatewayKeys .amodels.key-mcp { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* a read-only key's tag, always shown, never a button */ @@ -4564,8 +4564,8 @@ body.panel .modal { padding: 16px 12px; } body.web .accts.keys .acc > :is(.amodels, .proto, .alane, .aspend, .abal):not(.set) { margin-left: 0 !important; } body.web .accts.keys .acc > .abal.abal-many { flex-shrink: 1 !important; padding-block: 2px !important; } body.web .accts.keys .key-acts > .text.quiet { margin-right: 0 !important; } - body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc) { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } - body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc):not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } + body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier) { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } + body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier):not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } } /* Import from other apps: a checklist per app */ diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index d94745a7c..ed1332a6b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2774,6 +2774,11 @@ const I18N = { "{who}: at most {n} requests at once": "{who}:最多同时 {n} 个请求", "{who}: no limit on requests at once": "{who}:同时请求数不限", "Requests at once": "同时请求数", + "Service tier": "服务层级", + "As the request asks": "按请求的指定", + "This key's requests go at this service tier, whatever they ask": "这个密钥的请求按此服务层级发出,无论请求指定什么", + "This key's requests keep the service tier they ask for": "这个密钥的请求保持各自指定的服务层级", + "{who}: service tier {tier}": "{who}:服务层级 {tier}", "Provider's": "沿用提供商", "Any number at once": "同时任意多个", "A number of your own, up to 1000": "自定义数字,最大 1000", @@ -7830,6 +7835,11 @@ const I18N = { "{who}: at most {n} requests at once": "{who}:最多同時 {n} 個請求", "{who}: no limit on requests at once": "{who}:同時請求數不限", "Requests at once": "同時請求數", + "Service tier": "服務層級", + "As the request asks": "依請求的指定", + "This key's requests go at this service tier, whatever they ask": "這個金鑰的請求依此服務層級送出,無論請求指定什麼", + "This key's requests keep the service tier they ask for": "這個金鑰的請求保持各自指定的服務層級", + "{who}: service tier {tier}": "{who}:服務層級 {tier}", "Provider's": "沿用提供商", "Any number at once": "同時任意多個", "A number of your own, up to 1000": "自定義數字,最大 1000", @@ -12864,6 +12874,11 @@ const I18N = { "{who}: at most {n} requests at once": "{who}:同時に最大 {n} 件", "{who}: no limit on requests at once": "{who}:同時リクエスト数は無制限", "Requests at once": "同時リクエスト数", + "Service tier": "サービス階層", + "As the request asks": "リクエストの指定どおり", + "This key's requests go at this service tier, whatever they ask": "このキーのリクエストは、指定にかかわらずこのサービス階層で送られます", + "This key's requests keep the service tier they ask for": "このキーのリクエストは、指定されたサービス階層のまま送られます", + "{who}: service tier {tier}": "{who}:サービス階層 {tier}", "Provider's": "プロバイダーに従う", "Any number at once": "同時数の制限なし", "A number of your own, up to 1000": "任意の数(最大 1000)", @@ -17929,6 +17944,11 @@ const I18N = { "{who}: at most {n} requests at once": "{who}: höchstens {n} Anfragen gleichzeitig", "{who}: no limit on requests at once": "{who}: keine Grenze für gleichzeitige Anfragen", "Requests at once": "Gleichzeitige Anfragen", + "Service tier": "Service-Stufe", + "As the request asks": "Wie die Anfrage es verlangt", + "This key's requests go at this service tier, whatever they ask": "Anfragen dieses Schlüssels laufen in dieser Service-Stufe, egal was sie anfordern", + "This key's requests keep the service tier they ask for": "Anfragen dieses Schlüssels behalten die Service-Stufe, die sie anfordern", + "{who}: service tier {tier}": "{who}: Service-Stufe {tier}", "Provider's": "Wie der Anbieter", "Any number at once": "Beliebig viele gleichzeitig", "A number of your own, up to 1000": "Eine eigene Zahl, bis 1000", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index 32b2910a1..5911ca19d 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -234,7 +234,7 @@ function renderGatewayKeys() { tick.onclick = () => gatewayKeyAction(k.off ? "on-key" : "off-key", { key: k.id }); // the copy sits by the key it copies (the owner: stranded among the // badges it read as nobody's); Rotate and Remove wait in the row's menu - row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), ...gatewayKeptOutBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k)); + row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), ...gatewayKeptOutBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k), gatewayTierBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k)); const under = gatewayLimit?.id === k.id ? [gatewayLimitEditor(k)] : keyUsed(k).map((u) => gatewayLimitLine(k, u)); if (under.length) row.classList.add("with-limit"), row.append(...under); list.append(row); @@ -968,6 +968,37 @@ function gatewayConcurrencyBadge(k) { return b; } +// the service tier a key's requests go at (JackyFill on X): as they ask, or +// standard, Fast or Ultrafast whatever they ask; a provider with no service +// tiers is sent none +const KEY_TIERS = [ + { v: "", name: "As the request asks", note: "" }, + { v: "default", name: "Standard", note: "" }, + { v: "priority", name: "Fast", note: "priority" }, + { v: "ultrafast", name: "Ultrafast", note: "ultrafast" }, +]; +function gatewayTierBadge(k) { + const own = k.serviceTier || ""; + const cur = KEY_TIERS.find((o) => o.v === own) || KEY_TIERS[0]; + const b = el("button", "amodels key-tier" + (own ? " set" : "")); + b.type = "button"; + b.textContent = t(own ? cur.name : "Service tier"); + b.title = t(own ? "This key's requests go at this service tier, whatever they ask" : "This key's requests keep the service tier they ask for"); + b.setAttribute("aria-label", t("Service tier")); + b.setAttribute("aria-haspopup", "menu"); + b.setAttribute("aria-expanded", "false"); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, KEY_TIERS, cur.v, async (v) => { + if (v === cur.v) return; + const out = await gatewayKeyAction("tier-key", { key: k.id, serviceTier: v }); + if (out) status(t("{who}: service tier {tier}", { who: k.name, tier: t(KEY_TIERS.find((o) => o.v === v).name) }), "ok"); + }, "Service tier", "sess-menu"); + }; + return b; +} + // ---- a gateway key's own limit (#585) ---- // "days" is every N days from when the limit is set or reset (#1509), diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index 3c0e53324..ff67245ad 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -228,6 +228,7 @@ function fixture(lang, theme, events, options = {}) { if (!Number.isInteger(body.maxConcurrency) || body.maxConcurrency < 0 || body.maxConcurrency > 1000) return route.fulfill({ status: 400, json: { error: "Concurrency: a whole number from 0 to 1000" } }); k.maxConcurrency = body.maxConcurrency || undefined; } + if (action === "tier-key") k.serviceTier = body.serviceTier || undefined; if (action === "access-key") k.readOnly = body.readOnly || undefined; // a key put at a place in the list, as access.Update keeps it; // options.refuseMove: the store can't be written diff --git a/internal/gui/tests/gateway-key-tier.test.cjs b/internal/gui/tests/gateway-key-tier.test.cjs new file mode 100644 index 000000000..1b29448ea --- /dev/null +++ b/internal/gui/tests/gateway-key-tier.test.cjs @@ -0,0 +1,69 @@ +// A gateway key's service tier (JackyFill on X): a badge on the key's row, +// shown always while set and on hover while not, opens the app's menu (no +// native select): as the request asks, Standard, Fast or Ultrafast. It +// sends "tier-key"; a read-only key has none. +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +const words = { + en: { label: "Service tier", asks: "As the request asks", fast: "Fast", ultra: "Ultrafast", standard: "Standard" }, + zh: { label: "服务层级", asks: "按请求的指定", fast: "快速", ultra: "极速", standard: "标准" }, + "zh-TW": { label: "服務層級", asks: "依請求的指定", fast: "快速", ultra: "極速", standard: "標準" }, + ja: { label: "サービス階層", asks: "リクエストの指定どおり", fast: "高速", ultra: "超高速", standard: "標準" }, + de: { label: "Service-Stufe", asks: "Wie die Anfrage es verlangt", fast: "Schnell", ultra: "Ultrafast", standard: "Standard" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const [lang, w] of Object.entries(words)) { + test(`${engine} ${width} ${lang}: a key's service tier is set from the app's menu`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const events = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { serviceTier: "priority" }, laptop: { readOnly: true } } })); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#gatewayKeys .acc[data-key]").last().waitFor(); + const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`); + const badge = (id) => row(id).locator(".key-tier"); + const item = (name) => page.locator(".proto-menu .pm-item", { has: page.locator(".pm-name", { hasText: new RegExp(`^${name}$`) }) }); + const sent = () => events.filter((e) => e.action === "tier-key").map((e) => e.body); + const reads = (id, text) => page.waitForFunction(([id, text]) => document.querySelector(`#gatewayKeys .acc[data-key="${id}"] .key-tier`)?.textContent === text, [id, text]); + + // set: said always, not only on hover; a read-only key has none + await page.mouse.move(0, 0); + assert.equal(await badge("server").textContent(), w.fast); + assert.equal(await badge("server").evaluate((b) => getComputedStyle(b).opacity), "1"); + assert.equal(await badge("server").getAttribute("aria-label"), w.label); + assert.equal(await badge("laptop").count(), 0); + // unset: on hover only + assert.equal(await badge("work").evaluate((b) => getComputedStyle(b).opacity), "0"); + await row("work").hover(); + assert.equal(await badge("work").textContent(), w.label); + + await badge("work").click(); + await page.locator(".proto-menu").waitFor(); + assert.equal(await page.locator(".proto-menu .pm-head").textContent(), w.label); + await item(w.ultra).click(); + await reads("work", w.ultra); + assert.deepEqual(sent(), [{ key: "work", serviceTier: "ultrafast" }]); + + await row("server").hover(); + await badge("server").click(); + await item(w.asks).click(); + await reads("server", w.label); + assert.deepEqual(sent().at(-1), { key: "server", serviceTier: "" }); + + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(over <= 0, `the page scrolls sideways by ${over}px`); + assert.equal(await page.locator("select").count(), 0, "no native select"); + assert.deepEqual(errors, []); + }); + } + } +}