diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index d9298a53c..5cbaa953a 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -406,6 +406,53 @@ recorded as a prediction failure (`noPrediction`). `TestUnroutedMaskingNotCutOff`, `TestUnroutedSlotWaitNotCutOff`, `TestUnroutedMostLeavesOutMasking`, `TestMaskingModelWaitNotCutOffAtMost`. +## A route group held to chosen accounts + +A routing group may be held to some accounts of a provider (`Group.Accounts`, +entries `/` in a gateway key's +form; duanckham on X: a personal and a company GPT account, one tool and one +gateway, and a group's models must not spend the other's). The rule is the +gateway key's (#905, `Identity.AllowsAccount`): a provider the group names is +used only on the accounts it names, one it doesn't name on every account. + +- The asked group narrows the request's identity (`heldByGroup` in + [`key_models.go`](../../internal/gateway/key_models.go), by + `access.Identity.HeldToGroup`): the strict intersection with the key's own + list, `/\x00` (`heldToNone`) when the two share none of a + provider, and `Identity.Group` set to the group's name. Every gate that holds + a request to its key's accounts (`accountAllowed`, `allowedCandidates`, + `onKeys`, `allowedKey`) then holds it to the group's, on every route: chat, + responses and messages (`serve`), streamed or not, `count_tokens` + (`heldByGroupAt`), embeddings, images and video. +- A group reached through another one, as a member or as a fallback, is held + by `planLevel`'s `hold` and `Member.Via` (`groupHeld`): its candidates on an + account it leaves out are Held rows with `Weighed.HeldBy`, which the Routing + page's trace tells ("not an account Work may use"). +- Fallback stays within the group's own entries: an allowed account that is + resting, out or refused falls to the next member, never to an account the + group leaves out. With every allowed account gone the request gets the + group's usual error; when a key and the group share no account it is 403 + naming the group and the Routing page (`keyAccountsError`, + `groupsHeldError`), and nothing upstream is asked. +- `provider.SaveGroup` resolves each entry (`cleanGroupAccounts`, + `provider.ResolveAccount`): an account named by the name it is shown by is + kept as its stable id, duplicates collapse, and a new unknown provider or + account is refused. One the group already held that is gone (signed out, a + key rotated) is kept, matching nothing, so the group stays held rather than + let off to every account. A shared or + imported group carries no accounts (`ShareGroup`, `ImportGroup`): they are + this computer's. +- The group editor's Accounts section (`drawAccounts` in the routing plugin's + `client.js`) has a row for each member's provider with more than one account + (`/api/groups`' `accounts`, `groupAccounts` in + [`groups.go`](../../internal/gui/groups.go)): "Any of its accounts" until + some are ticked in its menu (`openPicker`, `multi`). Every save sends the + group's accounts, since a save replaces the group. + +`TestGroupAccountsHoldEveryRoute`, `TestGroupAccountsFallBackWithinTheGroup`, +`TestGroupAccountsAndAKeysAccounts`, `TestGroupAccountsSaved`, +`TestHeldToGroup`, `group-accounts.test.cjs`. + ## Remote magpie APIs `GET /v1/magpie/trace` answers the routing this gateway has decided, for a diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 94168d6df..34703f8d2 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -315,6 +315,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them. - A preset marked `NoList` uses its preset model list instead of requesting `/models`, and ignores previously fetched lists, including their protocol and key restrictions, unless the user sets `ModelsURL` or chooses a region marked `Lists`. Each region can carry a different list. Volcengine Ark's Coding Plan and Agent Plan use separate preset lists. Both plans include their embedding model separately from agents' chat-model lists; Agent Plan additionally exposes its image- and video-generation models to Settings → Images; Ark itself refuses video generation on Small and Medium Agent Plans, which include it only in the Large and Max tiers. Models magpie does not yet serve (Agent Plan's speech models) are not advertised. Ark's pay-as-you-go region still fetches its own list. Coding's `/api/coding/v3/models` returns a general Ark catalog instead of the plan's model ids, while Agent's `/api/plan/v3/models` returns 404. [`presets.go`](../../internal/provider/presets.go) defines these choices; `List`, `fetch`, `live`, `planModels`, `PlanEmbeddings`, `PlanDrawers` and `PlanVideos` in [`models.go`](../../internal/provider/models.go) apply them when adding, refreshing and reading cached models. `TestVolcengineModelLists` checks that the plans make no list requests, ignore old cached lists and return their own preset models; pay-as-you-go and an explicit list URL still make requests. - A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as its models allow. A key that lists accounts and no model may use only those accounts' providers' models (`access.HeldModels`, applied where `access.Authenticate` makes the request's `Identity`, so every route's model check holds it; Linka on Discord: ticking only an account let the key list and use every other provider's models; `TestGatewayKeyAccountsOnlyHoldTheModels`). The key's menu says so on each account of such a provider ("Used: no … account is picked" when its models reach the provider, "Not used: no … model or account is picked" when they don't), and its badge's tooltip that a key is kept off a provider by its models (#2077: unticking every Codex account left Codex's models served), or, with no model picked, that only the picked accounts' providers' models are the key's. The list keeps an account by its stable id — `logins.json`'s `id`, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's. +- A routing group may be held to some accounts the same way (`Group.Accounts`, duanckham on X): a request through it uses only those of a provider it names, and with a gateway key only those both allow. Entries are resolved and checked when the group is saved (`cleanGroupAccounts`, `ResolveAccount`), and dropped from a shared or imported group. See [gateway-routing](gateway-routing.md#a-route-group-held-to-chosen-accounts). - A sub2api key's windows are fixed: each starts at the key's first request after it was empty, aligned to the relay's day, and a window not started yet says `used 0` with no `reset_at`, so it is taken to renew a span from now. They count this key's spend only, not the relay's accounts behind it. `ForgetBalances` (a key or Balance URL changed) has every key's windows read again at its next ask, a read begun before dropped; until then the last reading stands, fresher than the card's, which routing's reads never write. A key changed is another key (`keyID`), with windows of its own. - A Volcengine Ark provider's access key (`TakesVolcAccessKey`: any of its bases on `ark..volces.com`) is kept with its keys and never sent to the GUI: `/api/providers` tells the editor its ID and whether a Secret is saved (`accessKey`). A save that leaves the Secret blank keeps it, one that leaves the ID out or sends it blank keeps both (an editor opened before the key was given sends `""`, #1821), and `clearAccessKey` drops both. The ID and Secret go together everywhere the keys go: a copy takes them, also when its form sends the source's ID without the Secret (`AddCopy`), a backup or sync without keys has neither (`withoutKeys`), and a restore, mirror or sync keeps this machine's (`KeepSecrets` in `Restore`, `Mirror`, davsync's `take`) when it came without keys, or with the same key and no access key at all, as a magpie before v0.1.1142 or one the access key was never given on sends it (#1821); another key is another account and brings its own. A copy without keys keeps this machine's secret headers (`SecretHeader`) the same way. A plan endpoint with no provider on it holding the access key is a card that says which to give (`accessKeyCard`, `needsAccessKey`), with a button to the provider's settings, not a card left out. A `providers.json` saved with a UTF-8 BOM is read through it, not taken for a broken file whose `.bak` stands in. The plan read is the endpoint's: `/api/coding` asks `GetCodingPlanUsage`, `/api/plan` asks `GetAFPUsage`, pay-as-you-go (`/api/v3`) has no card; the region is the host's. One card is read for each access key and plan. `GetCodingPlanUsage`'s reply (`QuotaUsage[]` with `Level`, `Percent`, `ResetTimestamp` in seconds) is the one three tools built on it read; `GetAFPUsage`'s buckets are read in each form those tools read (`Used` of `Quota` or `Total`, or `Percent`; `ResetTime` or `ResetTimestamp`), none of them seen from a real account here. A reply none of that reads says so on the card with the reply's head. Changing the access key drops the cached cards (`ForgetPlanQuotas`). - A Tencent Cloud provider's SecretId and SecretKey are kept, listed and saved the same way, in the same fields (`AccessKeyVendor` tells the editor whose: `accessKey.vendor`, the preset's `accessKeyVendor`). Only the Token Plan 企业版's endpoints are read with them (`TakesTencentAccessKey`: `/plan` on `tokenhub.tencentmaas.com`, region `ap-guangzhou`, or `tokenhub-intl.tencentmaas.com`, `ap-singapore`); the personal plan (`api.lkeap.cloud.tencent.com`) has no usage API and TokenHub's pay as you go no plan, so neither has a card. The preset lists its regions that take one (`accessKeyRegions`, `presetAccessKey`), and the editor shows SecretId and SecretKey at those alone. `DescribeTokenPlanList` gives the account's team plans (a sub-user sees the ones it made); each is asked `DescribeTokenPlan` for its `PackageInfo` and `TokenSummary`, the list's kept for what the reply leaves out. The card's one window is `TotalUsed` of `CycleQuota` (else `TotalQuota`), resetting at `TokenSummary.CycleEndTime`, else counted in months from `StartTime` and never past `ExpireTime`. A plan not `enable` says its status beside the plan's name. Errors come back as 200 with `Response.Error`; an `AuthFailure…` or `UnauthorizedOperation` one says to check the key. Built from the API docs (api/1823/132270 and siblings) and the signing doc's worked example; never seen from a real account here. diff --git a/internal/access/access.go b/internal/access/access.go index 7b7570c89..21c356650 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -174,6 +174,9 @@ type Identity struct { // gateway from beyond loopback, never one the user made for someone // else. Default bool + // Group is the routing group, by name, whose own accounts hold the + // request as well (HeldToGroup); "" when none does. + Group string } type contextKey struct{} diff --git a/internal/access/accounts.go b/internal/access/accounts.go index 6d03df823..36d9fe4bb 100644 --- a/internal/access/accounts.go +++ b/internal/access/accounts.go @@ -2,7 +2,6 @@ package access import ( "errors" - "fmt" "slices" "strings" @@ -32,24 +31,10 @@ func CleanAccounts(in []string) ([]string, error) { if len(a) > 300 { return nil, errors.New("A key's account is at most 300 characters") } - p, err := provider.Find(pid) + kept, err := provider.ResolveAccount(pid, ref) if err != nil { return nil, err } - id := "" - for _, r := range p.AccountIDs() { - if strings.EqualFold(r.ID, ref) || strings.EqualFold(r.User, ref) { - id = r.ID - break - } - } - if id == "" { - if p.Account == nil { - return nil, fmt.Errorf("%s has no key %q", p.Name, ref) - } - return nil, fmt.Errorf("%s has no account %q", p.Name, ref) - } - kept := p.ID + "/" + id if !slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, kept) }) { out = append(out, kept) } @@ -82,6 +67,64 @@ func (who Identity) AllowsAccount(pid, ref string) bool { return !named } +// heldToNone is the account an entry "/" names: none +// a provider has, so the list names the provider and allows none of it. +const heldToNone = "\x00" + +// HeldToGroup is who held to a routing group's accounts too (accounts, +// a Group's Accounts, in the key's form): a provider the group names is +// used only on the accounts the group names that the key may use as well, +// none when the two share none, never one either leaves out; a provider +// only the key names, on the key's; one neither names, on every account +// it has. Group is set to the group's name, for the error to say whose +// accounts held the request. A group naming no account is who as it is. +// Everything that holds a request to its key's accounts +// (AllowsAccount) holds it to the group's then, by the one rule. +func (who Identity) HeldToGroup(group string, accounts []string) Identity { + named := map[string][]string{} // a provider the group names, in lower case: its entries as written + var order []string + for _, a := range accounts { + a = strings.TrimSpace(a) + pid, ref, ok := strings.Cut(a, "/") + if pid = strings.ToLower(pid); !ok || pid == "" || ref == "" { + continue + } + if _, seen := named[pid]; !seen { + order = append(order, pid) + } + named[pid] = append(named[pid], a) + } + if len(order) == 0 { + return who + } + var out []string + for _, a := range who.Accounts { + if pid, _, _ := strings.Cut(strings.TrimSpace(a), "/"); named[strings.ToLower(pid)] == nil { + out = append(out, a) + } + } + for _, pid := range order { + some := false + for _, a := range named[pid] { + _, ref, _ := strings.Cut(a, "/") + if who.AllowsAccount(pid, ref) && !slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, a) }) { + out, some = append(out, a), true + } + } + if !some { + out = append(out, pid+"/"+heldToNone) + } + } + who.Accounts, who.Group = out, group + return who +} + +// ShownAccounts is who's accounts as a message lists them: the entries +// HeldToGroup adds to name a provider with none of its accounts left out. +func (who Identity) ShownAccounts() []string { + return slices.DeleteFunc(slices.Clone(who.Accounts), func(a string) bool { return strings.HasSuffix(a, "/"+heldToNone) }) +} + // ReplaceAccount moves every key's account list from one of provider // pid's keys to the fingerprint it has now (#1869: the key's value // replaced in place), so a key held to it is held to it still. It diff --git a/internal/access/group_accounts_test.go b/internal/access/group_accounts_test.go new file mode 100644 index 000000000..484aab565 --- /dev/null +++ b/internal/access/group_accounts_test.go @@ -0,0 +1,41 @@ +package access + +import ( + "slices" + "testing" +) + +// A routing group's accounts narrow whoever asks through it: a request +// with no key is held to the group's, a key's own list meets the group's +// (a provider both name keeps only the accounts both allow, and none +// when they share none), and a provider the group doesn't name is the +// key's as before. A group naming nothing changes nothing. +func TestHeldToGroup(t *testing.T) { + anyone := Identity{} + if got := anyone.HeldToGroup("Work", nil); got.Group != "" || len(got.Accounts) != 0 { + t.Fatalf("a group with no accounts: %+v", got) + } + got := anyone.HeldToGroup("Work", []string{"codex/work@x.com"}) + if got.Group != "Work" || !got.AllowsAccount("codex", "work@x.com") || got.AllowsAccount("codex", "me@x.com") || !got.AllowsAccount("relay", "k") { + t.Fatalf("no key: %+v", got) + } + key := Identity{Accounts: []string{"codex/me@x.com", "codex/work@x.com", "relay/k1"}} + got = key.HeldToGroup("Work", []string{"codex/work@x.com", "codex/other@x.com"}) + if !slices.Equal(got.Accounts, []string{"relay/k1", "codex/work@x.com"}) { + t.Fatalf("a key and a group: %v", got.Accounts) + } + if got.AllowsAccount("codex", "other@x.com") || got.AllowsAccount("relay", "k2") { + t.Fatalf("a key and a group allow too much: %v", got.Accounts) + } + apart := Identity{Accounts: []string{"codex/me@x.com"}}.HeldToGroup("Work", []string{"codex/work@x.com"}) + if apart.AllowsAccount("codex", "me@x.com") || apart.AllowsAccount("codex", "work@x.com") || !apart.AllowsAccount("relay", "k") { + t.Fatalf("apart: %v", apart.Accounts) + } + if shown := apart.ShownAccounts(); len(shown) != 0 { + t.Fatalf("apart shows %v", shown) + } + // the key it was given is not changed + if len(key.Accounts) != 3 || key.Group != "" { + t.Fatalf("the key's identity changed: %+v", key) + } +} diff --git a/internal/gateway/decide_group.go b/internal/gateway/decide_group.go index c017c98d4..0b1d28543 100644 --- a/internal/gateway/decide_group.go +++ b/internal/gateway/decide_group.go @@ -90,6 +90,7 @@ func (s *Server) serveDecisionGroup(w http.ResponseWriter, r *http.Request, body return } g = g.Live() + r = heldByGroup(r, g) // held to the group's accounts, if it is keyWho, keyHeld := keyHolds(r) accWho, accHeld := accountHolds(r) // a gateway key held to some models (#882) names the group, or the @@ -272,6 +273,9 @@ func (s *Server) askDecisionGroup(wait time.Duration, model string, intents []st g = g.Live() ms, _ = provider.PausedOut(g, ms, RouterAgent, "", ruleClock()) cs, _, _ := s.decideTries(g, ms) + // held to the group's own accounts, if it is: no request carries a + // caller here to hold (heldByGroup) + cs = slices.DeleteFunc(cs, func(c candidate) bool { return groupHeld(c, []provider.Group{g}) != "" }) cs = probeOne(cs) // of those resting, only the one back soonest (#1799) if len(cs) == 0 { return verdict{}, true, fmt.Errorf("no decision model of the group %s can be asked now", g.Name) diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 2508f675b..3b26bee4c 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -528,6 +528,9 @@ func (s *Server) images(edit bool) http.HandlerFunc { return } g, ms, isGroup := drawingGroup(d.Model, p, model) + if isGroup { + r = heldByGroup(r, g) // held to the group's accounts, if it is + } keyWho, keyHeld := keyHolds(r) if keyHeld && named && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { fail(403, keyModelError(keyWho, d.Model)) diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go index ddf552063..46249c36f 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -117,6 +117,9 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op return } g, ms, isGroup := provider.FindGroup(asked) + if isGroup { + r = heldByGroup(r, g) // held to the group's accounts, if it is + } if keyWho, held := keyHolds(r); held && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { msg := keyModelError(keyWho, asked) call.Status, call.Error = 403, msg @@ -144,8 +147,16 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op // (429) or one whose vendor fails; a model is asked on its own tries := []candidate{{p: p, model: model}} if isGroup { - if cs, _ := s.planGroup(g.Live(), ms, provider.Chat); len(cs) > 0 { + cs, pl := s.planGroup(g.Live(), ms, provider.Chat) + if len(cs) > 0 { tries = cs + } else if slices.ContainsFunc(pl.left, func(w Weighed) bool { return w.HeldBy != "" }) { + // every account a group in it may use is none it has + msg := groupsHeldError(asked, pl.left) + call.Status, call.Error = 403, msg + writeError(w, provider.Chat, 403, msg) + s.record(call) + return } } else { // a model of one provider goes over its keys or accounts as a diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 9c6583ab2..c4fac206a 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -564,7 +564,7 @@ func planFallbackGroup(g provider.Group, ms []provider.Member, from provider.Pro at, leftAt, unlistedAt := len(pl.order), len(pl.left), len(pl.unlistedW) var asides []candidate var wAsides []Weighed - out := planLevel(g, ms, 0, from, pl, &asides, &wAsides) + out := planLevel(g, ms, 0, from, pl, &asides, &wAsides, []provider.Group{g}) if sinks(g.Sink, g.Routing) { var order []Weighed out, order = sinkPlanned(out, pl.order[at:]) @@ -599,7 +599,7 @@ func (s *Server) planGroup(g provider.Group, ms []provider.Member, from provider var pl planned var asides []candidate var wAsides []Weighed - out := planLevel(g, ms, 0, from, &pl, &asides, &wAsides) + out := planLevel(g, ms, 0, from, &pl, &asides, &wAsides, nil) if sinks(g.Sink, g.Routing) { out, pl.order = sinkPlanned(out, pl.order) } @@ -652,9 +652,27 @@ func innerPatience(m provider.Member) int { // planLevel orders the models ms of g, a group depth groups down from the // one asked for, adding to pl's order as it goes: those set aside and // those unlisted it gathers for planGroup to put last. -func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.Protocol, pl *planned, asides *[]candidate, wAsides *[]Weighed) []candidate { +func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.Protocol, pl *planned, asides *[]candidate, wAsides *[]Weighed, hold []provider.Group) []candidate { keys := func(m provider.Member) []candidate { cs, aside, left, barred := perKeyBarred(m.Provider, m.Model, from) + // a group the member is reached through that is held to some + // accounts (Group.Accounts) holds it to them: one it leaves out + // is said on the plan's left, held, as a gateway key's are + if by := append(slices.Clip(hold), m.Via...); slices.ContainsFunc(by, func(h provider.Group) bool { return len(h.Accounts) > 0 }) { + out := func(l []candidate) []candidate { + return slices.DeleteFunc(l, func(c candidate) bool { + name := groupHeld(c, by) + if name == "" { + return false + } + w := weighed(c, m.Provider, weighing{}, false, from) + w.Held, w.HeldBy, w.Via = true, name, m.Groups() + pl.left = append(pl.left, w) + return true + }) + } + cs, aside, left, barred = out(cs), out(aside), out(left), out(barred) + } // the effort the member is fixed at goes with each of its keys: // the same model at another effort is another member's for _, l := range [][]candidate{cs, aside, left, barred} { @@ -712,7 +730,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. j++ } var sub planned - cs := planLevel(m.Via[depth], ms[i:j], depth+1, from, &sub, asides, wAsides) + cs := planLevel(m.Via[depth], ms[i:j], depth+1, from, &sub, asides, wAsides, hold) cs, sub.order = sinkOwn(m.Via[depth], cs, sub.order) pl.left = append(pl.left, sub.left...) pl.capped = append(pl.capped, sub.capped...) @@ -804,7 +822,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. j++ } at := len(pl.order) - cs := planLevel(m.Via[depth], ms[i:j], depth+1, from, pl, asides, wAsides) + cs := planLevel(m.Via[depth], ms[i:j], depth+1, from, pl, asides, wAsides, hold) var order []Weighed cs, order = sinkOwn(m.Via[depth], cs, pl.order[at:]) pl.order = append(pl.order[:at], order...) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b19da3873..2350c8de5 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1545,6 +1545,9 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) { if countHeld(w, r, provider.Anthropic, id) { return } + // a routing group held to some accounts counts on one of them, or + // the local estimate says the count, as for a key's (countOn) + r = heldByGroupAt(r, id) // nor on one the user disabled (#1867) if countOff(w, provider.Anthropic, id) { return @@ -2204,6 +2207,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } maskDone = true logBody(body) + // a routing group held to some accounts holds the request to them + // from here on, as a gateway key's accounts do + if isGroup { + r = heldByGroup(r, g) + } // a gateway key held to some models (#882) is refused another, or a // group it doesn't name with one it may not use in it keyWho, keyHeld := keyHolds(r) @@ -2561,10 +2569,22 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // not use (#905), the plan's left saying so: told before the barred // and ready ones it may also have call.Status, call.Error = 403, "every account outside the key's accounts" + if keyWho.Group != "" { + call.Error = "every account outside the group's accounts" + } writeError(w, from, 403, keyAccountsError(keyWho, call.Model)) turnedAway() return } + if len(cands) == 0 && slices.ContainsFunc(pl.left, func(w Weighed) bool { return w.HeldBy != "" }) && + !slices.ContainsFunc(pl.left, func(w Weighed) bool { return !w.Barred && !w.Held && w.Capped == 0 }) { + // every one left was held by a group in the group, or a group a + // fallback reached, held to other accounts + call.Status, call.Error = 403, "every account outside the group's accounts" + writeError(w, from, 403, groupsHeldError(call.Model, pl.left)) + turnedAway() + return + } if len(cands) == 0 && len(pl.left) > 0 && !slices.ContainsFunc(pl.left, func(w Weighed) bool { return !w.Barred }) { // every account or key there is was set not to serve the model call.Status, call.Error = 403, "every account barred" diff --git a/internal/gateway/group_accounts_test.go b/internal/gateway/group_accounts_test.go new file mode 100644 index 000000000..002d9e4be --- /dev/null +++ b/internal/gateway/group_accounts_test.go @@ -0,0 +1,338 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// keyedUpstream answers chat, messages and count_tokens, each reply +// naming the key it came in on, and records the keys it was asked on. +// refuse, when set, answers that key with a 429. +type keyedUpstream struct { + mu sync.Mutex + keys []string + refuse map[string]bool +} + +func (u *keyedUpstream) asked() []string { + u.mu.Lock() + defer u.mu.Unlock() + return append([]string(nil), u.keys...) +} + +func (u *keyedUpstream) reset() { + u.mu.Lock() + u.keys = nil + u.mu.Unlock() +} + +func (u *keyedUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + key := r.Header.Get("x-api-key") + if key == "" { + key = strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + } + u.mu.Lock() + u.keys = append(u.keys, key) + refused := u.refuse[key] + u.mu.Unlock() + if refused { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(429) + io.WriteString(w, `{"error":{"message":"rate limited","type":"rate_limit_error"}}`) + return + } + stream := strings.Contains(string(body), `"stream":true`) + text := "from " + key + switch { + case strings.HasSuffix(r.URL.Path, "/count_tokens"): + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"input_tokens":5}`) + case strings.HasSuffix(r.URL.Path, "/messages") && stream: + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"m","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"`+text+`"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`)) + case strings.HasSuffix(r.URL.Path, "/messages"): + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"`+text+`"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`) + case stream: + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"id":"c1","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"`+text+`"}}]}`, + `data: {"id":"c1","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`, + `data: [DONE]`)) + default: + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"`+text+`"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`) + } +} + +// groupAccountsSetup: a relay "relay" with a personal key and a company +// key, speaking chat and messages, and a second provider "other" with +// one key, both serving m. +func groupAccountsSetup(t *testing.T) (relay, other *keyedUpstream) { + t.Helper() + fresh(t) + t.Cleanup(noRests) + relay, other = &keyedUpstream{}, &keyedUpstream{} + ru, ou := httptest.NewServer(relay), httptest.NewServer(other) + t.Cleanup(ru.Close) + t.Cleanup(ou.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: ru.URL + "/v1", Anthropic: ru.URL, Key: "sk-mine", + Keys: []provider.KeyAccount{{Key: "sk-work"}}, Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Chat: ou.URL + "/v1", Anthropic: ou.URL, Key: "sk-other", Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + return relay, other +} + +func askGroup(h http.Handler, secret, path, body string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", path, strings.NewReader(body)) + if secret != "" { + req.Header.Set("Authorization", "Bearer "+secret) + } + h.ServeHTTP(rec, req) + return rec +} + +// every route a request through a group can take, each one asked for +// the model given +func groupRoutes(model string) [][2]string { + return [][2]string{ + {"/v1/chat/completions", `{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]}`}, + {"/v1/chat/completions", `{"model":"` + model + `","stream":true,"messages":[{"role":"user","content":"hi"}]}`}, + {"/v1/responses", `{"model":"` + model + `","input":"hi"}`}, + {"/v1/responses", `{"model":"` + model + `","stream":true,"input":"hi"}`}, + {"/v1/messages", `{"model":"` + model + `","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`}, + {"/v1/messages", `{"model":"` + model + `","max_tokens":10,"stream":true,"messages":[{"role":"user","content":"hi"}]}`}, + {"/v1/messages/count_tokens", `{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]}`}, + } +} + +// A routing group held to some accounts of a provider (duanckham on X: a +// personal GPT account and a company one, a group for each) is served by +// those alone, on every route: chat, responses and messages, streamed or +// not, and count_tokens. The same model through a group without the +// setting is served as before, by the provider's first key. +func TestGroupAccountsHoldEveryRoute(t *testing.T) { + relay, _ := groupAccountsSetup(t) + work := "relay/" + provider.KeyID("sk-work") + if err := provider.SaveGroup(provider.Group{Name: "Work", Members: []string{"relay/m"}, Routing: provider.Ordered, Accounts: []string{work}}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{Name: "Mine", Members: []string{"relay/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + if g, _, _ := provider.FindGroup("group/work"); len(g.Accounts) != 1 || g.Accounts[0] != work { + t.Fatalf("saved accounts %v", g.Accounts) + } + h := New().Handler() + for _, rt := range groupRoutes("group/work") { + for range 2 { + relay.reset() + w := askGroup(h, "", rt[0], rt[1]) + if w.Code != 200 { + t.Fatalf("%s %s: %d %s", rt[0], rt[1], w.Code, w.Body.String()) + } + asked := relay.asked() + if len(asked) == 0 && !strings.HasSuffix(rt[0], "/count_tokens") { + t.Fatalf("%s %s: no upstream asked", rt[0], rt[1]) + } + for _, k := range asked { + if k != "sk-work" { + t.Fatalf("%s %s: the group spent %s, asked %v", rt[0], rt[1], k, asked) + } + } + if len(asked) > 0 && !strings.HasSuffix(rt[0], "/count_tokens") && !strings.Contains(w.Body.String(), "from sk-work") { + t.Fatalf("%s %s: answered %s", rt[0], rt[1], w.Body.String()) + } + } + } + // a group without the setting: as before, the provider's first key + relay.reset() + if w := askGroup(h, "", "/v1/chat/completions", `{"model":"group/mine","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 || !strings.Contains(w.Body.String(), "from sk-mine") { + t.Fatalf("an unheld group: %d %s", w.Code, w.Body.String()) + } + // and the model asked by itself is not held by any group + relay.reset() + if w := askGroup(h, "", "/v1/chat/completions", `{"model":"relay/m","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 || !strings.Contains(w.Body.String(), "from sk-mine") { + t.Fatalf("the bare model: %d %s", w.Code, w.Body.String()) + } + // the route's left says why the other key was held out, and by whom + var held *Weighed + h2 := New() + relay.reset() + if w := askGroup(h2.Handler(), "", "/v1/chat/completions", `{"model":"group/work","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 { + t.Fatalf("work: %d %s", w.Code, w.Body.String()) + } + r := h2.trace.routes[len(h2.trace.routes)-1] + for i := range r.Left { + if r.Left[i].Held { + held = &r.Left[i] + } + } + if held == nil || held.HeldBy != "Work" { + t.Fatalf("route left %+v", r.Left) + } +} + +// A group's allowed account resting or refusing never sends the request +// to an account it excluded: with another member it falls back to that +// member, alone it answers the error a group returns today. A group in +// it holds its own members the same way. +func TestGroupAccountsFallBackWithinTheGroup(t *testing.T) { + relay, other := groupAccountsSetup(t) + work := "relay/" + provider.KeyID("sk-work") + relay.refuse = map[string]bool{"sk-work": true} + if err := provider.SaveGroup(provider.Group{Name: "Alone", Members: []string{"relay/m"}, Routing: provider.Ordered, Accounts: []string{work}}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{Name: "Pair", Members: []string{"relay/m", "other/m"}, Routing: provider.Ordered, Accounts: []string{work}}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{Name: "Outer", Members: []string{"group/alone"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + h := New().Handler() + chat := func(model string) *httptest.ResponseRecorder { + return askGroup(h, "", "/v1/chat/completions", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`) + } + spent := func(where string) { + t.Helper() + for _, k := range relay.asked() { + if k != "sk-work" { + t.Fatalf("%s: an excluded account was spent: %v", where, relay.asked()) + } + } + } + // alone: the refusal, twice (the second time the key rests), never + // the personal key + for i := range 2 { + relay.reset() + w := chat("group/alone") + if w.Code < 400 { + t.Fatalf("alone %d: %d %s", i, w.Code, w.Body.String()) + } + spent("alone") + } + // through a group in a group: held the same + relay.reset() + if w := chat("group/outer"); w.Code < 400 { + t.Fatalf("outer: %d %s", w.Code, w.Body.String()) + } + spent("outer") + // with another member: that member answers + noRests() + relay.reset() + other.reset() + if w := chat("group/pair"); w.Code != 200 || !strings.Contains(w.Body.String(), "from sk-other") { + t.Fatalf("pair: %d %s", w.Code, w.Body.String()) + } + spent("pair") + if len(other.asked()) != 1 { + t.Fatalf("other asked %v", other.asked()) + } + // the work key back: the pair is served by it, not by other + relay.refuse = nil + noRests() + sticks.Lock() + sticks.m = map[string]stick{} + sticks.Unlock() + relay.reset() + if w := chat("group/pair"); w.Code != 200 || !strings.Contains(w.Body.String(), "from sk-work") { + t.Fatalf("pair, work back: %d %s", w.Code, w.Body.String()) + } +} + +// A group held to accounts a gateway key may not use is a 403 that names +// the group and its accounts, and reaches no provider; a key and a group +// that share an account are served by it. +func TestGroupAccountsAndAKeysAccounts(t *testing.T) { + relay, _ := groupAccountsSetup(t) + work, mine := "relay/"+provider.KeyID("sk-work"), "relay/"+provider.KeyID("sk-mine") + if err := provider.SaveGroup(provider.Group{Name: "Work", Members: []string{"relay/m"}, Routing: provider.Ordered, Accounts: []string{work}}); err != nil { + t.Fatal(err) + } + keys, secrets := newCaller(t, "Personal") + if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{mine}}); err != nil { + t.Fatal(err) + } + h := New().Handler() + relay.reset() + w := askGroup(h, secrets[0], "/v1/chat/completions", `{"model":"group/work","messages":[{"role":"user","content":"hi"}]}`) + var e struct { + Error struct{ Message, Type string } + } + json.Unmarshal(w.Body.Bytes(), &e) + if w.Code != 403 || !strings.Contains(e.Error.Message, "Work") || !strings.Contains(e.Error.Message, "Routing") { + t.Fatalf("a key and a group apart: %d %s", w.Code, w.Body.String()) + } + if len(relay.asked()) != 0 { + t.Fatalf("held apart, asked %v", relay.asked()) + } + // both may use the work key + if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{mine, work}}); err != nil { + t.Fatal(err) + } + relay.reset() + if w := askGroup(h, secrets[0], "/v1/chat/completions", `{"model":"group/work","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 || !strings.Contains(w.Body.String(), "from sk-work") { + t.Fatalf("a key and a group together: %d %s", w.Code, w.Body.String()) + } +} + +// SaveGroup takes an account by its name or id, refuses one the provider +// doesn't have, and a shared group carries no accounts: they are this +// magpie's. +func TestGroupAccountsSaved(t *testing.T) { + groupAccountsSetup(t) + if err := provider.SaveGroup(provider.Group{Name: "Bad", Members: []string{"relay/m"}, Accounts: []string{"relay/nobody"}}); err == nil { + t.Fatal("an account the provider lacks was saved") + } + if err := provider.SaveGroup(provider.Group{Name: "Bad", Members: []string{"relay/m"}, Accounts: []string{"nothing"}}); err == nil { + t.Fatal("an entry with no provider was saved") + } + work := "relay/" + provider.KeyID("sk-work") + if err := provider.SaveGroup(provider.Group{Name: "Work", Members: []string{"relay/m"}, Accounts: []string{work, work}}); err != nil { + t.Fatal(err) + } + if g, _, _ := provider.FindGroup("group/work"); len(g.Accounts) != 1 { + t.Fatalf("twice saved as %v", g.Accounts) + } + text, err := provider.ShareGroup("work") + if err != nil { + t.Fatal(err) + } + if strings.Contains(text, provider.KeyID("sk-work")) { + t.Fatalf("shared with its accounts: %s", text) + } + // one shared with accounts in it (by hand, or an older magpie's) + // is imported without them + text = strings.Replace(text, `"name":"Work"`, `"name":"Imported","accounts":["`+work+`"]`, 1) + if !strings.Contains(text, `"accounts"`) { + t.Fatalf("no accounts put in %s", text) + } + if _, err := provider.ImportGroup(text); err != nil { + t.Fatal(err) + } + for _, g := range provider.Groups() { + if g.Name == "Imported" && len(g.Accounts) != 0 { + t.Fatalf("imported with accounts %v", g.Accounts) + } + } +} diff --git a/internal/gateway/key_models.go b/internal/gateway/key_models.go index 68897ae0d..cc3be4f1d 100644 --- a/internal/gateway/key_models.go +++ b/internal/gateway/key_models.go @@ -1,6 +1,7 @@ package gateway import ( + "cmp" "context" "fmt" "net/http" @@ -268,7 +269,7 @@ func allowedCandidates(who access.Identity, cs []candidate, pl planned, members held = true if i < len(pl.order) { w := pl.order[i] - w.Held = true + w.Held, w.HeldBy = true, who.Group pl.left = append(pl.left, w) } continue @@ -311,6 +312,47 @@ func accountAllowed(who access.Identity, c candidate) bool { return who.AllowsAccount(c.p.ID, c.p.AccountID()) } +// heldByGroup is r with its caller held to the routing group g's own +// accounts too (Group.Accounts, duanckham on X): a request through the +// group is held to them by everything that holds one to its gateway key's +// accounts (accountHolds, accountAllowed, onKeys, allowedKey), on every +// route, as one rule (access.HeldToGroup). A group with none is r. +func heldByGroup(r *http.Request, g provider.Group) *http.Request { + if len(g.Accounts) == 0 { + return r + } + who := access.Caller(r.Context()).HeldToGroup(cmp.Or(g.Name, g.ID), g.Accounts) + return r.WithContext(access.WithIdentity(r.Context(), who)) +} + +// heldByGroupAt is heldByGroup for the routing group id names, as a +// request may name one (a bare group's name, auto/); r when it +// names none. +func heldByGroupAt(r *http.Request, id string) *http.Request { + if gid, ok := provider.GroupFor(id); ok { + id = gid + } + if sid, ok := provider.AutoStandIn(id); ok { + id = sid + } + if g, _, ok := provider.FindGroup(id); ok { + return heldByGroup(r, g) + } + return r +} + +// groupHeld is the name of the first of gs, routing groups a candidate is +// reached through, held to accounts (Group.Accounts) that leave its account +// or key out — by AllowsAccount, a gateway key's rule; "" for none. +func groupHeld(c candidate, gs []provider.Group) string { + for _, g := range gs { + if len(g.Accounts) > 0 && !(access.Identity{Accounts: g.Accounts}).AllowsAccount(c.p.ID, c.p.AccountID()) { + return cmp.Or(g.Name, g.ID) + } + } + return "" +} + // allowedKey is p sent on the first of its keys in use the calling key // may use (#905), for the paths that send on one key of the provider // rather than over its candidates — a Grok or Volcengine video, which is @@ -372,19 +414,46 @@ func keyModelError(who access.Identity, model string) string { } // keyAccountsError is what a request every candidate of which was an -// account or key its key may not use is told. +// account or key its key may not use is told — or its routing group, +// held to some accounts (who.Group). func keyAccountsError(who access.Identity, model string) string { + if who.Group != "" { + msg := fmt.Sprintf("The routing group %q is held to some accounts, and none of the accounts or keys behind %s is one of them; it may use %s. Change the group's accounts in magpie's Routing page", + who.Group, model, keyAccountNames(who)) + if who.KeyName != "" { + msg += fmt.Sprintf(" (and the gateway key %q's in its Gateway page)", who.KeyName) + } + return msg + ", or use an account it has." + } return fmt.Sprintf("The gateway key %q is not allowed to use the accounts behind %s: no account or key behind it is one the key may use; it may use %s. Change the key's accounts in magpie's Gateway page, or use an account it has.", who.KeyName, model, keyAccountNames(who)) } +// groupsHeldError is what a request is told when every account or key +// left was one a routing group it went through — a group in the group, a +// group a fallback reached — is held away from (Weighed.HeldBy). +func groupsHeldError(model string, left []Weighed) string { + var by []string + for _, w := range left { + if w.HeldBy != "" && !slices.Contains(by, w.HeldBy) { + by = append(by, w.HeldBy) + } + } + return fmt.Sprintf("Every account or key behind %s is one the routing group %s is held away from: it is held to other accounts. Change the group's accounts in magpie's Routing page, or use an account it has.", + model, strings.Join(by, ", ")) +} + // keyAccountNames is the key's accounts as an error message shows them: // named as the accounts list names them, "/" where a // provider has the account now, the id alone otherwise. func keyAccountNames(who access.Identity) string { names := provider.AccountNames() - shown := make([]string, len(who.Accounts)) - for i, a := range who.Accounts { + accounts := who.ShownAccounts() + if len(accounts) == 0 { + return "none" + } + shown := make([]string, len(accounts)) + for i, a := range accounts { if n, ok := names[a]; ok { shown[i] = n } else { diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 2bc4390f2..cdd045150 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -323,8 +323,10 @@ type Weighed struct { // own list of models leaving it out (#474) Barred bool `json:"barred,omitempty"` // Held: left out as the gateway key asking may not use its account or - // key (#905) - Held bool `json:"held,omitempty"` + // key (#905), or a routing group it was reached through is held to + // other accounts (Group.Accounts): HeldBy names that group + Held bool `json:"held,omitempty"` + HeldBy string `json:"heldBy,omitempty"` // Capped: left out as held at the usage cap the user set on the // account, this cap in percent; Used is then its fullest window's // share, CapBack when the last window at or past it renews diff --git a/internal/gateway/video.go b/internal/gateway/video.go index 0cd0cb23c..112c56f29 100644 --- a/internal/gateway/video.go +++ b/internal/gateway/video.go @@ -773,6 +773,9 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) { return } g, ms, isGroup := drawingGroup(f.Model, p, model) + if isGroup { + r = heldByGroup(r, g) // held to the group's accounts, if it is + } keyWho, keyHeld := keyHolds(r) if keyHeld && named && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { fail(403, keyModelError(keyWho, f.Model)) diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 406242be3..8df59da69 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -584,7 +584,7 @@ function routingPage(part) { // from its vendor does — relays list each key its own group's models // or the user set the account or key to serve other models only (#474) // or it is held at the usage cap the user set on the account - const unlistedWord = (w) => w.held ? t("not an account the gateway key may use") : w.noCredits ? t("held: its allowance used up, set not to spend credits") : w.capped ? t("held at its {cap}% usage cap", { cap: w.capped }) : w.barred ? t("set to serve other models, not {model}", { model: w.model }) : w.kind === "key" ? t("{name}'s list for this key has no {model}", { name: w.name, model: w.model }) : t("its plan doesn't list {model}", { model: w.model }); + const unlistedWord = (w) => w.heldBy ? t("not an account {group} may use", { group: w.heldBy }) : w.held ? t("not an account the gateway key may use") : w.noCredits ? t("held: its allowance used up, set not to spend credits") : w.capped ? t("held at its {cap}% usage cap", { cap: w.capped }) : w.barred ? t("set to serve other models, not {model}", { model: w.model }) : w.kind === "key" ? t("{name}'s list for this key has no {model}", { name: w.name, model: w.model }) : t("its plan doesn't list {model}", { model: w.model }); // noURLWord: its keys are all set to a protocol its provider has no URL // for, so it went out on the URLs it has (#1702) const noURLWord = (w) => t("key set to {api} only, no {api} URL · sent on the others", { api: API[w.noURL] || w.noURL }); @@ -869,7 +869,9 @@ function routingPage(part) { } // leftWhy is why a member was skipped before it was tried (r.left) - const leftWhy = (x) => x.held + const leftWhy = (x) => x.heldBy + ? t("{who} is left out: the routing group {group} is held to other accounts of its provider.", { who: who(x), group: x.heldBy }) + : x.held ? t("{who} is left out: the gateway key asking may not use its account.", { who: who(x) }) : x.window ? t("{who} is left out: this request is longer than its {n} context window, so it would only refuse it. It's asked only once every one with room is out of its allowance.", { who: who(x), n: ctxShort(x.window) }) @@ -5325,7 +5327,7 @@ function routingPage(part) { // there, rather than leaving the slot empty. const openGroupEditor = async (g) => { if (groupDirty() && !(await confirmDiscard())) return false; - gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; + gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, accounts: [...(g.accounts || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; renderGroups(); return true; }; @@ -6037,7 +6039,7 @@ function routingPage(part) { closeProtoMenu(); if (v === cur || (groupDirty() && !(await confirmDiscard()))) return b.focus({ preventScroll: true }); const n = opts.find(([id]) => id === v)?.[1] || v; - await groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, unlists: !!g.unlists }, + await groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, accounts: g.accounts || [], unlists: !!g.unlists }, t("{name}: {routing}", { name: g.name, routing: t(n) })); // the rows were drawn anew: the keyboard stays on this one's routing gList.querySelector(`.rt-group[data-id="${CSS.escape(g.id)}"] .rt-groute`)?.focus({ preventScroll: true }); @@ -6166,7 +6168,7 @@ function routingPage(part) { b.onclick = (e) => { e.stopPropagation(); // the card opens the editor; this picks if (on) return; - groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, unlists: !!g.unlists }, + groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, accounts: g.accounts || [], unlists: !!g.unlists }, t("{name}: every request to {model}", { name: g.name, model: memberName(id) })); }; box.append(b); @@ -6178,7 +6180,7 @@ function routingPage(part) { // whoever opened it, a draft has what the editor and Add read: a group // made from a model (newGroupWith) had no fast, and Add threw on it // and did nothing (悠悠哥 on Discord) - for (const k of ["members", "match", "matched", "fast", "off", "rules"]) if (!Array.isArray(d[k])) d[k] = []; + for (const k of ["members", "match", "matched", "fast", "off", "rules", "accounts"]) if (!Array.isArray(d[k])) d[k] = []; if (!d.weights || typeof d.weights !== "object") d.weights = {}; const ed = el("div", "editor rt-gedit"); ed.dataset.gslot = g ? g.id : ""; @@ -6342,7 +6344,10 @@ function routingPage(part) { }; return b; }; + // the Accounts section below, drawn again as members come and go + let drawAccounts = () => {}; const draw = () => { + drawAccounts(); list.replaceChildren(); d.members.forEach((id, i) => { const m = modelOf(id), s = subOf(id); @@ -6530,6 +6535,48 @@ function routingPage(part) { mw.append(box, el("div", "hint", t("The first answers for what the model can do. In order, they are tried top first."))); ed.append(el("label", "", t("Models")), mw); + // accounts (duanckham on X): a provider with several accounts, a + // personal one and a company one, can be held to some of them in this + // group, so a task on it never spends the others (Group.Accounts, the + // same rule as a gateway key's accounts). A provider left on all of + // them uses each, as before; the section shows only for a member's + // provider with more than one account + const accLabel = el("label", "rt-gacc", t("Accounts")), accBox = el("div", "rt-gacc"), accList = el("div", "rt-gaccts"); + accBox.append(accList, el("div", "hint", t("Requests to this group's models spend only the accounts picked here. A provider left on any of its accounts uses them all."))); + ed.append(accLabel, accBox); + const accountsOf = (pid) => groups.accounts?.[pid] || []; + const accountPids = () => [...new Set(d.members.map((id) => modelOf(id)?.provider).filter((pid) => pid && accountsOf(pid).length))]; + drawAccounts = () => { + const pids = accountPids(); + accLabel.hidden = accBox.hidden = !pids.length; + accList.replaceChildren(); + for (const pid of pids) { + const all = accountsOf(pid), on = d.accounts.filter((a) => a.startsWith(pid + "/")); + const nameOf = (a) => all.find((x) => x.id === a)?.name || a.slice(pid.length + 1); + const pname = all[0]?.providerName || pid; + const row = el("div", "fbrow"); + const icon = d.members.find((id) => modelOf(id)?.provider === pid); + const n = el("span", "n"); + n.append(el("span", "", pname)); + row.append(memberIcon(icon), n, el("span", "grow")); + const b = el("button", "rt-cond rt-fixed rt-gacct" + (on.length ? " on" : "")); + b.type = "button"; + // in a span, so a long account name ellipsizes in the row + b.append(el("span", "", on.length === 1 ? nameOf(on[0]) : on.length ? t("{n} of its accounts", { n: on.length }) : t("Any of its accounts"))); + b.title = on.length ? t("This group spends only {accounts} of {provider}", { accounts: on.map(nameOf).join(", "), provider: pname }) : t("This group may spend every account of {provider}", { provider: pname }); + b.setAttribute("aria-label", `${pname}: ${b.textContent}`); + b.onclick = (ev) => openPicker({ id: "", name: "", fields: [] }, { key: "account", label: "account", value: "", menu: true, multi: true, + options: all.map((a) => ({ value: a.id, label: a.name, note: a.plan || "" })), picked: (v) => d.accounts.includes(v), onPick: (v) => { + if (!v) return; + d.accounts = d.accounts.includes(v) ? d.accounts.filter((x) => x !== v) : [...d.accounts, v]; + drawAccounts(); + } }, b, ev); + row.append(b); + accList.append(row); + } + }; + drawAccounts(); + // patterns: models found by their ids, now and as providers list new // ones (#766): after the models named, in the catalog's order, until // the user puts them in another; then each keeps its place, one gone @@ -7400,7 +7447,7 @@ function routingPage(part) { if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn"); saveBtn.classList.add("busy"); // refused, Add can be pressed again (busy, it takes no clicks) - groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) + groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) .then(() => saveBtn.classList.remove("busy")); }; // what goes wrong is said where it is seen, never a click that does nothing diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 0828a0895..248cb683a 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -642,6 +642,13 @@ magpie.strings({ "Report copied": "报告已复制", "Couldn't read the report: {error}": "读不到这份报告:{error}", "Open Folder": "打开文件夹", + "not an account {group} may use": "不是 {group} 可用的账号", + "{who} is left out: the routing group {group} is held to other accounts of its provider.": "{who} 被跳过:路由组 {group} 只用该服务商的其他账号。", + "Requests to this group's models spend only the accounts picked here. A provider left on any of its accounts uses them all.": "发到这个组里模型的请求只消耗这里选中的账号。保持“任一账号”的服务商会用它的所有账号。", + "{n} of its accounts": "{n} 个账号", + "Any of its accounts": "任一账号", + "This group spends only {accounts} of {provider}": "这个组只消耗 {provider} 的 {accounts}", + "This group may spend every account of {provider}": "这个组可以消耗 {provider} 的每个账号", }, "zh-TW": { "{name}, {n} accounts: {windows}": "{name}({n} 個帳號):{windows}", @@ -1284,6 +1291,13 @@ magpie.strings({ "Report copied": "報告已複製", "Couldn't read the report: {error}": "讀不到這份報告:{error}", "Open Folder": "打開資料夾", + "not an account {group} may use": "不是 {group} 可用的帳號", + "{who} is left out: the routing group {group} is held to other accounts of its provider.": "{who} 被略過:路由組 {group} 只用該服務商的其他帳號。", + "Requests to this group's models spend only the accounts picked here. A provider left on any of its accounts uses them all.": "發到這個組裡模型的請求只消耗這裡選中的帳號。保持「任一帳號」的服務商會用它的所有帳號。", + "{n} of its accounts": "{n} 個帳號", + "Any of its accounts": "任一帳號", + "This group spends only {accounts} of {provider}": "這個組只消耗 {provider} 的 {accounts}", + "This group may spend every account of {provider}": "這個組可以消耗 {provider} 的每個帳號", }, ja: { "{name}, {n} accounts: {windows}": "{name}({n} アカウント):{windows}", @@ -1926,6 +1940,13 @@ magpie.strings({ "Report copied": "レポートをコピーしました", "Couldn't read the report: {error}": "レポートを読み込めませんでした:{error}", "Open Folder": "フォルダを開く", + "not an account {group} may use": "{group} が使えるアカウントではありません", + "{who} is left out: the routing group {group} is held to other accounts of its provider.": "{who} は外されました:ルーティンググループ {group} はこのプロバイダーの別のアカウントだけを使います。", + "Requests to this group's models spend only the accounts picked here. A provider left on any of its accounts uses them all.": "このグループのモデルへのリクエストは、ここで選んだアカウントだけを使います。「どのアカウントでも」のままのプロバイダーは、すべてのアカウントを使います。", + "{n} of its accounts": "{n} 個のアカウント", + "Any of its accounts": "どのアカウントでも", + "This group spends only {accounts} of {provider}": "このグループは {provider} の {accounts} だけを使います", + "This group may spend every account of {provider}": "このグループは {provider} のすべてのアカウントを使えます", }, de: { "{name}, {n} accounts: {windows}": "{name}, {n} Konten: {windows}", @@ -2568,5 +2589,12 @@ magpie.strings({ "Report copied": "Bericht kopiert", "Couldn't read the report: {error}": "Der Bericht konnte nicht gelesen werden: {error}", "Open Folder": "Ordner öffnen", + "not an account {group} may use": "kein Konto, das {group} nutzen darf", + "{who} is left out: the routing group {group} is held to other accounts of its provider.": "{who} wird ausgelassen: Die Routing-Gruppe {group} nutzt nur andere Konten dieses Anbieters.", + "Requests to this group's models spend only the accounts picked here. A provider left on any of its accounts uses them all.": "Anfragen an die Modelle dieser Gruppe verbrauchen nur die hier gewählten Konten. Ein Anbieter auf „Jedes seiner Konten“ nutzt alle.", + "{n} of its accounts": "{n} seiner Konten", + "Any of its accounts": "Jedes seiner Konten", + "This group spends only {accounts} of {provider}": "Diese Gruppe verbraucht nur {accounts} von {provider}", + "This group may spend every account of {provider}": "Diese Gruppe darf jedes Konto von {provider} verbrauchen", }, }); diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index 412bea667..ed40acb44 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -665,6 +665,10 @@ button.rt-session { cursor: pointer; } desktop app's member row doesn't wrap (only body.web's does) */ .rt-gedit .fbrow .rt-inner { flex: 0 1 auto; min-width: 0; } .rt-gedit .fbrow .rt-inner > span { overflow: hidden; text-overflow: ellipsis; } +/* a group's account choice (Group.Accounts): a long account name ellipsizes */ +.rt-gedit .fbrow .rt-gacct { flex: 0 1 auto; min-width: 0; } +.rt-gedit .fbrow .rt-gacct > span { overflow: hidden; text-overflow: ellipsis; } +.rt-gedit > .rt-gacc[hidden] { display: none; } .rt-gadd { justify-self: start; display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 11px 0 9px; border-radius: 8px; diff --git a/internal/gui/groups.go b/internal/gui/groups.go index 12678e216..f159c1e58 100644 --- a/internal/gui/groups.go +++ b/internal/gui/groups.go @@ -1,6 +1,7 @@ package gui import ( + "cmp" "encoding/json" "fmt" "net/http" @@ -48,6 +49,10 @@ type groupsJSON struct { // Imported: import's answer, the group added and what of the text // this magpie has none of (provider.ImportGroup) Imported *provider.Imported `json:"imported,omitempty"` + // Accounts: by provider id, the accounts and keys a group may be held + // to (Group.Accounts), as a gateway key's list has them (#905): each + // provider with more than one, or one a group names already + Accounts map[string][]keyModelJSON `json:"accounts"` } type skippableJSON struct { @@ -245,6 +250,32 @@ type clockJSON struct { Offset int `json:"offset"` } +// groupAccounts is groupsJSON's Accounts: the accounts and keys of each +// provider with more than one, which a group may be held to some of, and +// of each one a group in gs names already, so its choice can be undone. +func groupAccounts(gs []provider.Group) map[string][]keyModelJSON { + named := map[string]bool{} + for _, g := range gs { + for _, a := range g.Accounts { + if pid, _, ok := strings.Cut(a, "/"); ok { + named[strings.ToLower(pid)] = true + } + } + } + out := map[string][]keyModelJSON{} + for _, p := range provider.All() { + refs := p.AccountIDs() + if len(refs) < 2 && !named[strings.ToLower(p.ID)] { + continue + } + name := cmp.Or(p.Name, p.ID) + for _, a := range refs { + out[p.ID] = append(out[p.ID], keyModelJSON{ID: p.ID + "/" + a.ID, Name: a.Shown(p), Provider: p.ID, ProviderName: name, Account: !a.Key, Key: a.Key, Plan: a.Plan}) + } + } + return out +} + func groupsState() groupsJSON { _, offset := time.Now().Zone() out := groupsJSON{Groups: []groupJSON{}, Models: []modelRef{}, Pools: []poolJSON{}, Deciders: []modelRef{}, Found: provider.AutoGroupsOn(), Templates: provider.Templates(), @@ -267,6 +298,7 @@ func groupsState() groupsJSON { for _, e := range provider.OfferedDeciders(func(id string) bool { return named[id] }) { out.Deciders = append(out.Deciders, modelRef{ID: e.ID, Name: e.Name, Provider: e.Provider.ID, PName: e.Provider.Name, Icon: e.Provider.Icon, Sub: e.Provider.Account != nil}) } + out.Accounts = groupAccounts(all) served := provider.Served() for _, e := range served { if e.Group == "" { diff --git a/internal/gui/tests/group-accounts.test.cjs b/internal/gui/tests/group-accounts.test.cjs new file mode 100644 index 000000000..baafadc02 --- /dev/null +++ b/internal/gui/tests/group-accounts.test.cjs @@ -0,0 +1,176 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A routing group can be held to chosen accounts of a provider (duanckham on +// X: personal and company GPT accounts, one tool, one gateway). The group +// editor shows an Accounts section for each member's provider with more than +// one account. Its button says "Any of its accounts" until accounts are +// ticked in a menu that stays open; one ticked account shows its name, two +// show how many. Save sends the picks as Group.Accounts. A group whose +// providers have one account each shows no section. Nothing on the page +// moves. In every language, Chromium and WebKit, at a wide and a narrow +// window. +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: "codex/gpt-6.1-sol", name: "gpt-6.1-sol", provider: "codex", providerName: "Codex", icon: "generic" }, + { id: "rl/glm-5", name: "glm-5", provider: "rl", providerName: "Relay", icon: "generic" }, +]; +const accounts = { + codex: [ + { id: "codex/me@x.com", name: "me@x.com", provider: "codex", providerName: "Codex", account: true, plan: "Plus" }, + { id: "codex/work@corp.example", name: "work@corp.example", provider: "codex", providerName: "Codex", account: true, plan: "Team" }, + ], +}; +const groups = (members, held) => ({ + models, pools: [], accounts: held === false ? {} : accounts, + groups: [{ id: "work", name: "Work", members, routing: "order", ready: true, accounts: [], + memberInfo: members.map((id) => ({ id, ready: true })) }], +}); + +const words = { + en: { edit: "Edit", save: "Save", accounts: "Accounts", any: "Any of its accounts", two: "2 of its accounts" }, + zh: { edit: "编辑", save: "保存", accounts: "账号", any: "任一账号", two: "2 个账号" }, + "zh-TW": { edit: "編輯", save: "儲存", accounts: "帳號", any: "任一帳號", two: "2 個帳號" }, + ja: { edit: "編集", save: "保存", accounts: "アカウント", any: "どのアカウントでも", two: "2 個のアカウント" }, + de: { edit: "Bearbeiten", save: "Speichern", accounts: "Konten", any: "Jedes seiner Konten", two: "2 seiner Konten" }, +}; + +function serve(lang, posts, members, held) { + 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(members, held)); + if (url.pathname.startsWith("/api/groups/")) { + posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") }); + return json(groups(members, held)); + } + 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 }); + }; +} + +async function open(engine, lang, width, members, held, t) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 1600 }, reducedMotion: "reduce" })).newPage(); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-group-accounts.png`) }); + } + await 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, members, held)); + await page.goto("http://magpie.test/?view=routing"); + const card = page.locator(".rt-group", { hasText: "Work" }); + await card.waitFor(); + return { page, card, errors, posts }; +} + +const option = (page, text) => page.locator("#pop:not([hidden]) #list li:not(.group)", { has: page.locator(".v", { hasText: new RegExp("^" + text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "$") }) }); + +async function save(page, w) { + const b = page.locator(".rt-gedit button.primary", { hasText: w.save }); + await b.scrollIntoViewIfNeeded(); + await b.click(); + await page.waitForFunction(() => !document.querySelector(".rt-gedit")); +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [1100, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: a group is held to chosen accounts`, async (t) => { + const { page, card, errors, posts } = await open(engine, lang, width, ["codex/gpt-6.1-sol", "rl/glm-5"], true, t); + await card.locator("button", { hasText: w.edit }).click(); + const ed = page.locator(".rt-gedit"); + const label = ed.locator("> label.rt-gacc"); + await label.waitFor(); + assert.equal((await label.textContent()).trim(), w.accounts); + // one row, for Codex only: Relay has no accounts listed + const rows = ed.locator(".rt-gaccts .fbrow"); + assert.equal(await rows.count(), 1); + assert((await rows.first().textContent()).includes("Codex")); + const chip = rows.first().locator("button.rt-gacct"); + const said = async () => (await chip.textContent()).trim(); + assert.equal(await said(), w.any); + assert.doesNotMatch((await chip.getAttribute("class")) || "", /\bon\b/); + + // the reader scrolls the button into view with the wheel + await page.mouse.move(width / 2, 800); + for (let i = 0; i < 20 && (await chip.boundingBox()).y > 1200; i++) await page.mouse.wheel(0, 200), await page.waitForTimeout(100); + await page.waitForTimeout(200); + const box = await chip.boundingBox(); + assert(box.y >= 0 && box.y + box.height <= 1600, `the button is in view before the click: ${box.y}`); + const at = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop && !e.closest("#pop")).map((e) => [e.id || e.className, e.scrollTop]).join(";") + "|" + Math.round(document.querySelector(".rt-gedit").getBoundingClientRect().top)); + const before = await at(); + + // the menu lists each account, none ticked, and stays open as one is + await chip.click(); + await option(page, "work@corp.example").waitFor(); + assert.deepEqual(await page.locator("#pop #list li:not(.group) .v").allTextContents(), ["me@x.com", "work@corp.example"]); + assert.doesNotMatch((await option(page, "work@corp.example").getAttribute("class")) || "", /\bcur\b/); + await option(page, "work@corp.example").click(); + await page.waitForFunction(() => !document.querySelector("#pop").hidden); + assert.match((await option(page, "work@corp.example").getAttribute("class")) || "", /\bcur\b/); + assert.equal(await said(), "work@corp.example"); + assert.match((await chip.getAttribute("class")) || "", /\bon\b/); + // two ticked say how many; unticking one says its name again + await option(page, "me@x.com").click(); + assert.equal(await said(), w.two); + await option(page, "me@x.com").click(); + assert.equal(await said(), "work@corp.example"); + await page.keyboard.press("Escape"); + await page.waitForFunction(() => document.querySelector("#pop").hidden); + assert.equal(await at(), before, "the picks moved nothing"); + + // the row fits a narrow window, the page doesn't scroll sideways + const over = await page.evaluate(() => { + const row = document.querySelector(".rt-gaccts .fbrow"), b = row.querySelector(".rt-gacct"); + return { page: document.documentElement.scrollWidth - document.documentElement.clientWidth, row: b.getBoundingClientRect().right - row.getBoundingClientRect().right }; + }); + assert(over.page <= 0, `the page scrolls sideways by ${over.page}px`); + assert(over.row <= 1, `the account button sticks out of its row by ${over.row}px`); + + await save(page, w); + const sent = posts.filter((p) => p.path === "/api/groups/save").at(-1).body; + assert.deepEqual(sent.accounts, ["codex/work@corp.example"]); + assert.deepEqual(errors, []); + }); + + if (width === 1100) { + test(`${engine} ${lang}: a group whose providers have one account shows no Accounts`, async (t) => { + const { page, card, errors, posts } = await open(engine, lang, width, ["rl/glm-5"], false, t); + await card.locator("button", { hasText: w.edit }).click(); + const ed = page.locator(".rt-gedit"); + await ed.locator("button.primary", { hasText: w.save }).waitFor(); + assert.equal(await ed.locator("> .rt-gacc:visible").count(), 0); + await save(page, w); + const sent = posts.filter((p) => p.path === "/api/groups/save").at(-1).body; + assert.deepEqual(sent.accounts, []); + assert.deepEqual(errors, []); + }); + } + } + } +} diff --git a/internal/provider/account_models.go b/internal/provider/account_models.go index 5d15006dd..1bd75ac17 100644 --- a/internal/provider/account_models.go +++ b/internal/provider/account_models.go @@ -105,6 +105,27 @@ func (p Provider) AccountIDs() []AccountRef { return out } +// ResolveAccount is the entry "/" an account list — a +// gateway key's (#905), a routing group's — keeps for provider pid's +// account or key ref: an account named by its stable id or the name it +// is shown by, resolved to that id, a key by its fingerprint. It fails +// for a provider magpie doesn't have, or one with no such account or key. +func ResolveAccount(pid, ref string) (string, error) { + p, err := Find(pid) + if err != nil { + return "", err + } + for _, r := range p.AccountIDs() { + if strings.EqualFold(r.ID, ref) || strings.EqualFold(r.User, ref) { + return p.ID + "/" + r.ID, nil + } + } + if p.Account == nil { + return "", fmt.Errorf("%s has no key %q", p.Name, ref) + } + return "", fmt.Errorf("%s has no account %q", p.Name, ref) +} + // AccountID is the stable id of p's account or key as a gateway key's // account list knows it (#905): the account's, kept through renames, or // a key's fingerprint. diff --git a/internal/provider/group.go b/internal/provider/group.go index bc532f1eb..ba2843109 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -262,6 +262,14 @@ type Group struct { // naming one is still served. A group in it keeps its own, as it // says. Not while the group is switched off. Unlists bool `json:"unlists,omitempty"` + // Accounts hold the group to some accounts or keys of the providers + // they name (duanckham on X: a personal and a company GPT account, + // each group's tasks on its own), as a gateway key's account list + // does (#905) and in its form, "/": a request through the group is sent only on those + // of a provider it names, a provider it names none of on every + // account it has. Empty, every account of every member serves. + Accounts []string `json:"accounts,omitempty"` // Auto is set on a group magpie found: one model served by several // providers. It is derived, never stored. Auto bool `json:"auto,omitempty"` @@ -417,6 +425,7 @@ func cloneGroups(gs []Group) []Group { for i, g := range gs { g.Members, g.Match, g.Matched, g.Placed = slices.Clone(g.Members), slices.Clone(g.Match), slices.Clone(g.Matched), slices.Clone(g.Placed) g.Off, g.Levels, g.Fast = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast) + g.Accounts = slices.Clone(g.Accounts) g.Weights = maps.Clone(g.Weights) if g.Rules != nil { rs := make([]Rule, len(g.Rules)) @@ -534,6 +543,7 @@ func (g Group) own() Group { g.Off = slices.Clone(g.Off) g.Levels = slices.Clone(g.Levels) g.Fast = slices.Clone(g.Fast) + g.Accounts = slices.Clone(g.Accounts) g.Weights = maps.Clone(g.Weights) g.Rules = slices.Clone(g.Rules) for i, r := range g.Rules { @@ -1445,6 +1455,13 @@ func SaveGroup(g Group) error { if err := cleanWeights(entries, &g); err != nil { return err } + var was []string + if i := slices.IndexFunc(f.Groups, func(x Group) bool { return x.ID == g.ID }); i >= 0 { + was = f.Groups[i].Accounts + } + if g.Accounts, err = cleanGroupAccounts(g.Accounts, was); err != nil { + return err + } if g.Routing != Manual && len(g.Members) > 0 && len(g.Off) == len(g.Members) { return fmt.Errorf("every model in %s is switched off: switch one on, or it has nothing to send to", g.Name) } @@ -1522,6 +1539,44 @@ func SaveGroup(g Group) error { return store(f) } +// cleanGroupAccounts is a group's account list as kept: each entry +// "/", resolved as a gateway key's are (ResolveAccount) +// — an account by its stable id or the name it is shown by, a key by its +// fingerprint — trimmed, each once, in the order given. One the group +// held already and its provider has no more (an account signed out, a key +// rotated) is kept as it was, matching nothing, so the group stays held +// rather than let off to every account; a new one must be one magpie has. +func cleanGroupAccounts(in, was []string) ([]string, error) { + var out []string + for _, a := range in { + a = strings.TrimSpace(a) + if a == "" { + continue + } + pid, ref, ok := strings.Cut(a, "/") + if !ok || pid == "" || ref == "" { + return nil, errors.New("a group's account is / or /, like codex/me@example.com: " + a) + } + if len(a) > 300 { + return nil, errors.New("a group's account is at most 300 characters") + } + kept, err := ResolveAccount(pid, ref) + if err != nil { + if !slices.ContainsFunc(was, func(w string) bool { return strings.EqualFold(strings.TrimSpace(w), a) }) { + return nil, err + } + kept = a + } + if !slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, kept) }) { + out = append(out, kept) + } + } + if len(out) > 500 { + return nil, errors.New("a group can list at most 500 accounts") + } + return out, nil +} + // groupsInGroup checks the groups a group has in it: each one magpie has, // and none that has the group in it, however deep — the group would be // in itself, and a request to it would go round for ever. diff --git a/internal/provider/group_share.go b/internal/provider/group_share.go index ece9ac951..ce910f078 100644 --- a/internal/provider/group_share.go +++ b/internal/provider/group_share.go @@ -52,6 +52,7 @@ func ShareGroup(id string) (string, error) { g.Members, g.Match = ownMembers(g) g.Matched = nil g.Auto, g.Hidden, g.Disabled = false, false, false + g.Accounts = nil // this magpie's accounts: another has its own g.Rules = slices.DeleteFunc(g.Rules, Rule.ByFolder) out, err := json.Marshal(SharedGroup{Magpie: ShareMark, Version: ShareVersion, Group: g}) return string(out), err @@ -143,6 +144,7 @@ func ImportGroup(text string) (Imported, error) { return Imported{}, err } g := s.Group + g.Accounts = nil // another magpie's accounts, never this one's entries := providerEntries() all := Groups() var res Imported