diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index a8e320e33..afbaeb3f9 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -60,7 +60,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | -| Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go) | +| Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go) | | A relay's Codex entries | A provider the user added by its address with a Responses URL may list its models in Codex's own shape (`slug`, `supported_reasoning_levels`, `shell_type`, `base_instructions`: `catalog.CodexEntry`), plainly or when asked with Codex's `client_version`, as sub2api does (ctopsc on Discord: GPT-6.1 Terra was handed models.dev's 922000 window where the relay said 272000). `fetchOne` keeps such a row whole (`catalog.Model.Codex`, with its window, max window and inputs read off it), and when the plain list has none it asks the same URL once more with `client_version` (`codexEntries`): only where the list is fetched (add, key change, Refresh), never per Codex poll. The answer only adds entries to models the plain list has; one that fails or can't be read keeps the last list's entries (failed read = unknown), one that answers plainly says there are none. `codexcat.listedEntry` hands Codex the relay's entry as given, `base_instructions` included, with magpie's slug, name, priority and " via magpie" description; the user's window, compaction, levels and image setting still win (levels keep the relay's descriptions). A saved list from before is enriched at its next Refresh. `TestCodexListedEntry`, `TestCodexListedEntryInPlainList`. | [`codex_entries.go`](../../internal/provider/codex_entries.go), [`live.go`](../../internal/catalog/live.go), [`codexcat.go`](../../internal/codexcat/codexcat.go) | | An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | | The maker's own price | A model priced at its maker (`MakerPrice`, a provider's `ListPrice` after its own catalog, `PricedName`; through `makerListPrice`) is priced at a models.dev provider that lists it as its own (`catalog.MakerPriced`): one whose entry's `canonical_model_id` names it as the maker, or whose id is the maker's with a region (`alibaba-cn`), never a plan's (`-plan`) and never at $0. A maker preset that is such an API is asked first, in preset order, then the other owners by id; only then the maker presets as before (`PricedBy`). A maker preset that resells another lab's model no longer prices it: Mistral's `deepseek-v4-1-flash-1017` at $0.30/$1.20 gave way to DeepSeek's $0.15/$0.60, and a lab that isn't a preset (Meta's `muse-spark`) is priced at all. So a subscription's model (Command Code's, bestony on Discord) is estimated at what its maker charges (`TestMakerPriceIsTheMakersOwn`). A model no maker lists (Kimi K2.5, GLM-5.2 Fast) stays unpriced; the user gives it a price or a same-as model. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index 8f59c136b..069f74e2b 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -61,6 +61,16 @@ this computer's values for a provider it has, and brings a new one without `KeepLoginAs`, an account signed in on the other computer; `hashes` blanks all three (`TestMirrorKeepsKeepLogin`, `TestKeepLoginIsNoChange`). +A Remote magpie's **Use it anyway** (`KeepSelf`) is kept the same way. Sync +carries a Remote magpie provider to the computer it names (hanslin1666 on +Discord: B uses A through one, and on A it points at A), and there it is +found to be this magpie and left out unless kept (see +[providers and accounts](providers-accounts.md)). Whether it is this magpie +is about one computer only, so it is kept in `remote-self.json`, which no +backup or sync carries, and `KeepSelf` is kept by `Mirror` and `Restore` +(false for a provider new here) and blanked by `hashes` +(`TestMirrorKeepsKeepSelf`, `TestKeepSelfIsNoChange`). + The agents part keeps a computer's own pick the same way, field by field (hayden4608 on Discord: two computers on one GitHub sync, each wanting its own Codex model, set each other's on every sync). Each field a sync changes here diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 202ead57d..de6d74219 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -846,6 +846,7 @@ func hashes(b backup.Bundle) map[string]string { ps := slices.Clone(b.Providers) for i := range ps { // this computer's own: kept by Mirror, never synced ps[i].KeepLogin, ps[i].KeepLoginAs, ps[i].SwitchOnly, ps[i].RestartApp = false, "", false, false + ps[i].KeepSelf = false } providers := []any{ps, b.Icons, b.Groups} if b.Searches != nil && len(*b.Searches) > 0 { // as before them, without one diff --git a/internal/davsync/keep_self_test.go b/internal/davsync/keep_self_test.go new file mode 100644 index 000000000..1da8968d0 --- /dev/null +++ b/internal/davsync/keep_self_test.go @@ -0,0 +1,25 @@ +package davsync + +import ( + "testing" + + "github.com/yetone/magpie/internal/backup" + "github.com/yetone/magpie/internal/provider" +) + +// Whether a Remote magpie that is this magpie is used anyway is this +// computer's own (provider.Mirror keeps it): on the other computer the +// same provider points at a magpie that is not that one (hanslin1666 on +// Discord). Changing it uploads nothing. +func TestKeepSelfIsNoChange(t *testing.T) { + p := provider.Provider{ID: "rem", Name: "Rem", Preset: provider.RemoteMagpiePreset} + b := backup.Bundle{Providers: []provider.Provider{p}} + p.KeepSelf = true + kept := backup.Bundle{Providers: []provider.Provider{p}} + if hashes(b)["providers"] != hashes(kept)["providers"] { + t.Fatal("Use it anyway changed the providers hash") + } + if !kept.Providers[0].KeepSelf { + t.Fatal("hashing changed the bundle") + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 9aa1ddd47..74350e3e4 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -266,8 +266,12 @@ func namesInCatalog() map[string]bool { // switchedOff says a request for model went nowhere because p, which // serves it, is switched off in magpie (provider.Provider.Off), or kept to -// Claude Code's own sign-in (provider.Provider.KeptToAgent). +// Claude Code's own sign-in (provider.Provider.KeptToAgent), or a Remote +// magpie that is this one (provider.Provider.SelfLeftOut). func switchedOff(p provider.Provider, model string) string { + if p.SelfLeftOut() && !p.Off { + return fmt.Sprintf("%s is a Remote magpie that is this magpie itself, so %q is not served through it; ask for the model without %q in front, or tick \"Use it anyway\" on it in Magpie's Providers", p.Name, model, p.ID+"/") + } if p.KeptToAgent() { return fmt.Sprintf("%s's accounts are kept to Claude Code's own sign-in in Magpie, so %q is not served; untick \"Only switch Claude Code's sign-in\" under its accounts in Magpie's Providers to use it", p.Name, model) } diff --git a/internal/gateway/main_test.go b/internal/gateway/main_test.go index 8feade50b..543622e0d 100644 --- a/internal/gateway/main_test.go +++ b/internal/gateway/main_test.go @@ -31,6 +31,9 @@ func TestMain(m *testing.M) { limitsOn = gwbudget.Limit(budget.Limiter{}) // the test binary is no magpie: it runs no claude-tui-helper claudeTUIRuns = false + // the tests serve their Remote magpie from this process, which is + // then this magpie itself (remote_self_test.go turns it on again) + provider.LeaveOutSelf = false code, err := isolatedTests(m) if err != nil { fmt.Fprintln(os.Stderr, err) diff --git a/internal/gateway/remote_self_test.go b/internal/gateway/remote_self_test.go new file mode 100644 index 000000000..ec9089490 --- /dev/null +++ b/internal/gateway/remote_self_test.go @@ -0,0 +1,133 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// A Remote magpie that is this magpie (hanslin1666 on Discord: B uses A +// through one, and sync carried it to A, where it points at A) is left +// out: its models are not listed beside this magpie's own, a found group +// doesn't take them, and a request naming one (an agent's pick synced +// from B) is served here at once, not passed through the gateway again. +// "Use it anyway" (KeepSelf) has it back. +func TestRemoteMagpieThatIsThisOneIsLeftOut(t *testing.T) { + provider.LeaveOutSelf = true + t.Cleanup(func() { provider.LeaveOutSelf = false }) + var vendor atomic.Int32 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + io.WriteString(w, `{"object":"list","data":[]}`) + return + } + vendor.Add(1) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"}}]}`) + })) + t.Cleanup(up.Close) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if err := provider.Save(provider.Provider{ID: "own", Name: "Own", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("own", up.URL+"/v1", []catalog.Model{{ID: "m1"}}); err != nil { + t.Fatal(err) + } + var passes atomic.Int32 // chat requests this gateway was asked + h := New().Handler() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + passes.Add(1) + } + h.ServeHTTP(w, r) + })) + t.Cleanup(srv.Close) + id, err := provider.Add(provider.Provider{ID: "rem", Name: "Rem", Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(srv.URL, "http://")}) + if err != nil { + t.Fatal(err) + } + rem, _ := provider.Find(id) + if _, err := rem.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + rem, _ = provider.Find(id) + if !rem.SelfAnswered() || !rem.SelfLeftOut() || rem.On() { + t.Fatalf("a Remote magpie at this magpie's own address: answered as self %v, left out %v, on %v; want true, true, false", rem.SelfAnswered(), rem.SelfLeftOut(), rem.On()) + } + + listed := func() map[string]bool { + t.Helper() + req, _ := http.NewRequest(http.MethodGet, srv.URL+"/v1/models", nil) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var l struct { + Data []struct { + ID string `json:"id"` + } `json:"data"` + } + if err := json.NewDecoder(resp.Body).Decode(&l); err != nil { + t.Fatal(err) + } + out := map[string]bool{} + for _, m := range l.Data { + out[m.ID] = true + } + return out + } + if l := listed(); l["rem/own/m1"] || !l["own/m1"] { + t.Errorf("listed %v; want own/m1 and not rem/own/m1", l) + } + for _, e := range provider.Catalog() { + if e.Provider.ID == "rem" { + t.Errorf("the catalog has %s through this magpie's own Remote magpie", e.ID) + } + } + + ask := func(model string) int { + t.Helper() + req, _ := http.NewRequest(http.MethodPost, srv.URL+"/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "curl/8") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + return resp.StatusCode + } + if code := ask("rem/own/m1"); code != http.StatusOK { + t.Fatalf("a request for rem/own/m1: %d, want 200", code) + } + if p, v := passes.Load(), vendor.Load(); p != 1 || v != 1 { + t.Errorf("rem/own/m1 took %d passes through the gateway and %d vendor requests; want 1 and 1", p, v) + } + + // kept by the user: through the remote as before + if err := provider.SetKeepSelf(id, true); err != nil { + t.Fatal(err) + } + rem, _ = provider.Find(id) + if !rem.SelfAnswered() || rem.SelfLeftOut() || !rem.On() { + t.Fatalf("kept: answered as self %v, left out %v, on %v; want true, false, true", rem.SelfAnswered(), rem.SelfLeftOut(), rem.On()) + } + if l := listed(); !l["rem/own/m1"] { + t.Errorf("kept, listed %v; want rem/own/m1 again", l) + } + passes.Store(0) + if code := ask("rem/own/m1"); code != http.StatusOK || passes.Load() != 2 { + t.Errorf("kept, rem/own/m1: %d in %d passes; want 200 in 2", code, passes.Load()) + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index d4928ab35..2fba68aba 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2702,6 +2702,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .row.model .minfo .mi-img svg, .rt-gedit .fbrow .minfo .mi-img svg { display: block; } .provider .pswitch { margin-left: 8px; } .editor .off-note { grid-column: 1 / -1; } +.editor .self-note label.tick { margin-top: 6px; } .uses { display: flex; align-items: center; gap: 4px; margin-left: auto; flex: none; } .use { width: 26px; height: 26px; border-radius: 8px; diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 7180b06b2..a2d551a38 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -6224,6 +6224,7 @@ function renderProviders(quiet) { const name = el("div", "name", p.name); if (p.sponsored) name.append(el("span", "badge", t("sponsored"))); if (p.off) name.append(el("span", "badge off", t("Switched off"))); + if (p.self) name.append(Object.assign(el("span", "badge" + (p.keepSelf ? "" : " off"), t("This magpie")), { title: selfNote(p) })); if (p.move && p.move.state !== "plugin") name.append(deprecatedBadge()); const n = p.models.filter((m) => m.on).length; // rate windows: what it bills at now (#2463) @@ -9230,6 +9231,14 @@ function drawEditor(p, presetID) { if (p) h.append(providerSwitch(p)); ed.append(h); if (p?.off) ed.append(el("div", "hint off-note", t("Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again."))); + // a Remote magpie that is this magpie, which sync brought here (hanslin1666) + if (p?.self) { + const [keep, cb] = tick(t("Use it anyway"), !!p.keepSelf); + cb.onchange = () => accountAction("provider/keepself", { id: p.id, keepSelf: cb.checked }, t(cb.checked ? "{name} is used anyway" : "{name} is left out: it is this magpie", { name: p.name })); + const note = el("div", "hint off-note self-note", selfNote(p)); + note.append(keep); + ed.append(note); + } } // a vendor's global and China endpoints are presets of their own, one row @@ -20414,6 +20423,11 @@ function askLANNames(urls, then) { }, 300); } +function selfNote(p) { + return t(p.keepSelf ? "This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice." + : "This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once."); +} + function tick(label, on) { const l = el("label", "tick"); const c = el("input"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index b0c73d318..0edc59b19 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1668,6 +1668,12 @@ const I18N = { "{agent} is back on its default": "{agent} 已恢复为默认模型", "{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} 仍在用 magpie 已不再提供的 {model}:{error}", "Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "已关闭:不向 Agent 提供其模型,也不向它发请求。密钥和设置保留,开启即可恢复使用。", + "This magpie": "本机 magpie", + "This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.": "这个远程 magpie 就是本机的 magpie。仍在使用:它的模型与本机自己的模型并列,经它的请求会两次经过本机 magpie。", + "This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.": "这个远程 magpie 就是本机的 magpie:是同步从使用本机的另一台电脑带过来的。它已被排除,模型不会重复列出;请求它的模型时直接由本机提供。", + "Use it anyway": "仍然使用", + "{name} is used anyway": "仍在使用 {name}", + "{name} is left out: it is this magpie": "已排除 {name}:它就是本机 magpie", "API key {masked}": "API 密钥 {masked}", "Local servers need no key": "本地服务无需密钥", "Open the row and paste an API key": "展开这一行并粘贴 API 密钥", @@ -6275,6 +6281,12 @@ const I18N = { "{agent} is back on its default": "{agent} 已恢復為預設模型", "{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} 仍在用 magpie 已不再提供的 {model}:{error}", "Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "已關閉:不向 Agent 提供其模型,也不向它發請求。金鑰和設定保留,開啟即可恢復使用。", + "This magpie": "本機 magpie", + "This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.": "這個遠端 magpie 就是本機的 magpie。仍在使用:它的模型與本機自己的模型並列,經它的請求會兩次經過本機 magpie。", + "This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.": "這個遠端 magpie 就是本機的 magpie:是同步從使用本機的另一台電腦帶過來的。它已被排除,模型不會重複列出;請求它的模型時直接由本機提供。", + "Use it anyway": "仍然使用", + "{name} is used anyway": "仍在使用 {name}", + "{name} is left out: it is this magpie": "已排除 {name}:它就是本機 magpie", "API key {masked}": "API 金鑰 {masked}", "Local servers need no key": "本地服務無需金鑰", "Open the row and paste an API key": "展開這一行並貼上 API 金鑰", @@ -10856,6 +10868,12 @@ const I18N = { "{agent} is back on its default": "{agent} をデフォルトに戻しました", "{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} はまだ {model} を使っていますが、magpie はもう提供していません:{error}", "Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "オフ:エージェントにそのモデルは渡されず、リクエストも送られません。キーと設定は保持されます。オンにすると再び使えます。", + "This magpie": "この magpie", + "This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.": "このリモート magpie はこの magpie 自身です。それでも使用中:モデルがこの magpie 自身のモデルと並んで表示され、これを通るリクエストはこの magpie を 2 回通ります。", + "This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.": "このリモート magpie はこの magpie 自身です:この magpie を使う別のコンピューターから同期で届きました。除外されているため、モデルは二重に表示されず、そのモデルへのリクエストはここで直接処理されます。", + "Use it anyway": "それでも使う", + "{name} is used anyway": "{name} をそれでも使います", + "{name} is left out: it is this magpie": "{name} を除外しました:この magpie 自身です", "API key {masked}": "APIキー {masked}", "Local servers need no key": "ローカルサーバーにキーは不要です", "Open the row and paste an API key": "行を開いて APIキーを貼り付けてください", @@ -15468,6 +15486,12 @@ const I18N = { "{agent} is back on its default": "{agent} nutzt wieder sein Standardmodell", "{agent} is still on {model}, which magpie no longer serves: {error}": "{agent} nutzt noch {model}, das magpie nicht mehr bereitstellt: {error}", "Switched off: agents aren't given its models and no request goes to it. Its keys and settings are kept; switch it on to use it again.": "Ausgeschaltet: Agenten erhalten seine Modelle nicht, und keine Anfrage geht an ihn. Schlüssel und Einstellungen bleiben erhalten; zum erneuten Verwenden einschalten.", + "This magpie": "Dieses magpie", + "This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.": "Dieses Remote-magpie ist dieses magpie selbst. Es wird trotzdem genutzt: Seine Modelle stehen neben den eigenen dieses magpie, und eine Anfrage darüber läuft zweimal durch dieses magpie.", + "This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.": "Dieses Remote-magpie ist dieses magpie selbst: Die Synchronisierung hat es von einem Computer gebracht, der dieses nutzt. Es bleibt außen vor, damit seine Modelle nicht doppelt erscheinen; eine Anfrage nach einem davon wird gleich hier bedient.", + "Use it anyway": "Trotzdem nutzen", + "{name} is used anyway": "{name} wird trotzdem genutzt", + "{name} is left out: it is this magpie": "{name} bleibt außen vor: Es ist dieses magpie", "API key {masked}": "API-Schlüssel {masked}", "Local servers need no key": "Lokale Server brauchen keinen Schlüssel", "Open the row and paste an API key": "Zeile aufklappen und API-Schlüssel einfügen", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 50a1f8e12..2b606e7ba 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -251,6 +251,11 @@ type providerJSON struct { // RestartApp: magpie restarts the Codex app's app-server for an // account change it makes by itself (provider.Provider.RestartApp) RestartApp bool `json:"restartApp,omitempty"` + // Self: a Remote magpie that turned out to be this magpie (sync + // brought it from the computer that uses this one), left out of + // routing unless KeepSelf (provider.Provider.SelfAnswered) + Self bool `json:"self,omitempty"` + KeepSelf bool `json:"keepSelf,omitempty"` // CapStop and CapCareful: how its accounts end at their caps // (plugins#349), set on their own with capstop and capcareful CapStop bool `json:"capStop,omitempty"` @@ -702,7 +707,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)), - Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, + Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()), AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, @@ -2001,6 +2006,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { in.KeepLogin = old.KeepLogin // set on its own, with keeplogin in.KeepLoginAs = old.KeepLoginAs in.SwitchOnly, in.RestartApp = old.SwitchOnly, old.RestartApp // switchonly, restartapp + in.KeepSelf = old.KeepSelf // keepself in.CapStop, in.CapCareful = old.CapStop, old.CapCareful // capstop, capcareful in.Off = old.Off // and this with off and on if in.Contexts == nil { @@ -2246,6 +2252,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } + case "keepself": + // a Remote magpie that is this magpie, used anyway or left out + // (hanslin1666 on Discord) + if err := provider.SetKeepSelf(in.ID, in.KeepSelf); err != nil { + fail(rw, err) + return + } case "capstop": // a request ends at the accounts' caps, 429, or goes on to the // fallbacks (plugins#349) diff --git a/internal/gui/tests/remote-self.test.cjs b/internal/gui/tests/remote-self.test.cjs new file mode 100644 index 000000000..04ea1319e --- /dev/null +++ b/internal/gui/tests/remote-self.test.cjs @@ -0,0 +1,123 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// hanslin1666 on Discord: B uses A through a Remote magpie, and sync +// carried that provider to A, where it points at A itself. magpie now +// finds it (the list it fetches was listed by this magpie) and leaves it +// out. Its row says "This magpie", its editor says why, and "Use it +// anyway" keeps it in: ticking posts provider/keepself, the redraw keeps +// it ticked, unticking posts it off. Another Remote magpie says nothing. +// The page doesn't move. In English, Chinese, Japanese and German, +// Chromium and WebKit, at 1100 and 420 wide. +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 remote = (id, name, more = {}) => ({ + id, name, preset: "remote-magpie", icon: "magpie", host: "192.168.1.20:3425", chat: "http://192.168.1.20:3425/v1", responses: "", anthropic: "", catalog: "", routing: "", + models: [{ id: "own/m1", name: "m1", on: true }], agents: [], fallback: [], headers: {}, keyList: [], key: { set: true, masked: "mg-…a1b2" }, ready: true, ...more, +}); + +function serve(lang, first, posts) { + let list = first; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } }); + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers()); + if (url.pathname === "/api/provider/keepself") { + const body = route.request().postDataJSON(); + posts.push(body); + list = list.map((p) => p.id === body.id ? { ...p, keepSelf: body.keepSelf } : p); + return json(providers()); + } + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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 route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const said = { + en: ["This magpie", "Use it anyway"], + zh: ["本机 magpie", "仍然使用"], + ja: ["この magpie", "それでも使う"], + de: ["Dieses magpie", "Trotzdem nutzen"], +}; +const strings = [ + "This magpie", + "This Remote magpie is this magpie itself. It is used anyway: its models are listed beside this magpie's own, and a request through it passes through this magpie twice.", + "This Remote magpie is this magpie itself: sync brought it from a computer that uses this one. It is left out, so its models aren't listed twice; a request for one of them is served here at once.", + "Use it anyway", + "{name} is used anyway", + "{name} is left out: it is this magpie", +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const lang of Object.keys(said)) { + const open = async (t, list) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, list, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider").first().waitFor(); + return { page, errors, posts }; + }; + + test(`${engine} ${width} ${lang}: a Remote magpie that is this magpie says so, and Use it anyway keeps it`, async (t) => { + const { page, errors, posts } = await open(t, [remote("home", "Home", { self: true }), remote("office", "Office")]); + const row = page.locator(".row.provider", { hasText: "Home" }).first(); + const badge = row.locator(".name .badge", { hasText: said[lang][0] }); + assert.equal(await badge.count(), 1, "the row says it is this magpie"); + assert.ok((await badge.getAttribute("title")).length > 20, "the badge says why"); + assert.match(await badge.getAttribute("class"), /\boff\b/, "left out, it reads as off"); + assert.equal(await page.locator(".row.provider", { hasText: "Office" }).locator(".name .badge").count(), 0, "another Remote magpie says nothing"); + if (lang === "en") { + const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings); + assert.deepEqual(missing, [], "every string has its translations"); + } + await row.click(); + const note = page.locator(".editor .self-note"); + await note.waitFor(); + const keep = note.locator("label.tick"); + assert.equal((await keep.textContent()).trim(), said[lang][1]); + assert.equal(await keep.locator("input").isChecked(), false); + assert.ok((await note.textContent()).length > said[lang][1].length + 20, "the note says why"); + await keep.scrollIntoViewIfNeeded(); + const box = await note.boundingBox(); + assert.ok(box.x >= 0 && box.x + box.width <= width, `the note fits across ${width}`); + const scrollers = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop).concat(document.scrollingElement.scrollTop)); + const before = await scrollers(); + await keep.locator("input").click(); + await page.waitForFunction(() => document.querySelector(".editor .self-note input")?.checked === true); + assert.deepEqual(posts, [{ id: "home", keepSelf: true }]); + await page.waitForFunction(() => [...document.querySelectorAll(".row.provider[data-id=home] .name .badge")].some((b) => b.title && !b.classList.contains("off"))); + assert.deepEqual(await scrollers(), before, "the page doesn't move"); + assert.doesNotMatch(await badge.getAttribute("class"), /\boff\b/, "kept, it no longer reads as off"); + await page.locator(".editor .self-note input").click(); + await page.waitForFunction(() => document.querySelector(".editor .self-note input")?.checked === false); + await page.waitForFunction(() => document.querySelector(".row.provider[data-id=home] .name .badge[title].off")); + assert.deepEqual(posts, [{ id: "home", keepSelf: true }, { id: "home", keepSelf: false }]); + await page.keyboard.press("Escape"); + await page.locator(".editor").waitFor({ state: "detached" }); + await page.locator(".row.provider", { hasText: "Office" }).first().click(); + await page.locator(".editor .ehead", { hasText: "Office" }).waitFor(); + assert.equal(await page.locator(".editor .self-note").count(), 0, "another Remote magpie's editor has no note"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/backup.go b/internal/provider/backup.go index 5c02f9281..9ed64aef4 100644 --- a/internal/provider/backup.go +++ b/internal/provider/backup.go @@ -44,11 +44,14 @@ func Restore(ps []Provider) (added, replaced int, err error) { } } if i < 0 { + p.KeepSelf = false f.Providers = append(f.Providers, p) added++ continue } + keepSelf := f.Providers[i].KeepSelf // this computer's own (Mirror) f.Providers[i] = KeepSecrets(p, f.Providers[i], p.Key == "" && len(p.Keys) == 0) + f.Providers[i].KeepSelf = keepSelf replaced++ } if added+replaced == 0 { @@ -92,8 +95,9 @@ func RestoreGroups(gs []Group) error { // from another computer: one not among them goes, one that came without // keys keeps the keys it has here, and an access key or balance token it // came without is kept too (KeepSecrets). Which account an agent is kept -// signed in to (KeepLogin, KeepLoginAs, SwitchOnly), and whether its app is -// restarted to follow (RestartApp), is this computer's own: +// signed in to (KeepLogin, KeepLoginAs, SwitchOnly), whether its app is +// restarted to follow (RestartApp), and whether a Remote magpie that is +// this magpie is used anyway (KeepSelf), is this computer's own: // one person signs in to a personal account at home and a work account at // the office, and sync set each computer to the other's every day. func Mirror(ps []Provider, gs []Group) error { @@ -114,8 +118,10 @@ func Mirror(ps []Provider, gs []Group) error { if h, ok := here[p.ID]; ok { p = KeepSecrets(p, h, p.Key == "" && len(p.Keys) == 0) p.KeepLogin, p.KeepLoginAs, p.SwitchOnly, p.RestartApp = h.KeepLogin, h.KeepLoginAs, h.SwitchOnly, h.RestartApp + p.KeepSelf = h.KeepSelf } else { p.KeepLoginAs = "" // an account signed in on the other computer + p.KeepSelf = false // kept on the other computer, of a magpie that isn't this one } out = append(out, p) } diff --git a/internal/provider/group.go b/internal/provider/group.go index adcb33bf6..e236ae873 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -1136,7 +1136,7 @@ func unpicked(find entryOf, p Provider, m string) bool { // Resolve, which still takes it. func ResolveRoute(id string) (Provider, string, bool) { entries := providerEntries() - p, m, ok := resolveIn(entries, strings.TrimSuffix(strings.TrimSpace(id), "[1m]")) + p, m, ok := resolveIn(entries, ThroughSelf(strings.TrimSuffix(strings.TrimSpace(id), "[1m]"))) // one pass for the one model, not a map of every entry (entriesBy): // a request asks it for each fallback it may go to find := func(pid, model string) int { diff --git a/internal/provider/models.go b/internal/provider/models.go index 05e689b03..86f391f7c 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -423,8 +423,17 @@ func relistPicks(q *Provider, now map[string]bool) bool { return true } -// fetch is Fetch without the picks looked after. +// fetch is Fetch without the picks looked after. A Remote magpie's list +// also tells whether it is this magpie (noteSelf). func (p Provider) fetch(ctx context.Context) ([]catalog.Model, error) { + ms, err := p.fetchList(ctx) + if err == nil { + noteSelf(p, ms) + } + return ms, err +} + +func (p Provider) fetchList(ctx context.Context) ([]catalog.Model, error) { ctx = p.ownRequests(p.Via(ctx), probelog.KindList) if p.DecideOnly() { return p.fetchDecide(ctx) @@ -3240,7 +3249,7 @@ func entryIn(entries []Entry, id string) (Entry, bool) { func Resolve(id string) (Provider, string, bool) { // Claude Code's mark for a model with a 1M window; it drops it before // asking, but a value in its settings still has it - id = strings.TrimSuffix(strings.TrimSpace(id), "[1m]") + id = ThroughSelf(strings.TrimSuffix(strings.TrimSpace(id), "[1m]")) if IsGroupRef(id) { // the groups' entries first: Catalog copies every entry, and was // built for each group an agent's settings name (the window's drift diff --git a/internal/provider/provider.go b/internal/provider/provider.go index b333f4fa9..e1085a7b8 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -178,6 +178,12 @@ type Provider struct { // used-up account (a switch off it, becoming its provider for it) // restart it either way: the app greys Send there (8b0132b3d). RestartApp bool `json:"restartApp,omitempty"` + // KeepSelf, on a Remote magpie that turned out to be this magpie + // (SelfAnswered), keeps it in routing anyway: left alone, such a + // provider is left out (SelfLeftOut). It is this computer's own, as + // sync's copy of the provider on the other computer points at a + // magpie that is not that one (hanslin1666 on Discord). + KeepSelf bool `json:"keepSelf,omitempty"` // MaxConcurrency is how many requests may be out at the vendor at once // on each of its keys or accounts (Discord, Lemon: a Codex account is @@ -2250,9 +2256,10 @@ func (p Provider) Ready() bool { return p.Account != nil || p.Key != "" || keyOptional(p) } -// On is whether the provider takes requests: ready, not switched off and -// not kept to its agent's own sign-in (KeptToAgent). -func (p Provider) On() bool { return p.Ready() && !p.Off && !p.KeptToAgent() } +// On is whether the provider takes requests: ready, not switched off, +// not kept to its agent's own sign-in (KeptToAgent) and not a Remote +// magpie that is this magpie (SelfLeftOut). +func (p Provider) On() bool { return p.Ready() && !p.Off && !p.KeptToAgent() && !p.SelfLeftOut() } // KeptToAgent is whether the provider is Claude's subscription with // SwitchOnly on: its accounts are Claude Code's own sign-in alone, which @@ -2282,12 +2289,12 @@ func SetOff(id string, off bool) error { func SwitchedOff(id string) (Provider, bool) { id = strings.TrimSuffix(strings.TrimSpace(id), "[1m]") if pid, _, ok := strings.Cut(id, "/"); ok { - if p, err := Find(pid); err == nil && (p.Off || p.KeptToAgent()) { + if p, err := Find(pid); err == nil && (p.Off || p.KeptToAgent() || p.SelfLeftOut()) { return *p, true } } for _, p := range All() { - if !p.Off && !p.KeptToAgent() || !p.Ready() { + if !p.Off && !p.KeptToAgent() && !p.SelfLeftOut() || !p.Ready() { continue } if slices.ContainsFunc(p.Exposed(), func(m catalog.Model) bool { return m.ID == id }) { diff --git a/internal/provider/remote_quotas.go b/internal/provider/remote_quotas.go index 6e0696895..96c936ae6 100644 --- a/internal/provider/remote_quotas.go +++ b/internal/provider/remote_quotas.go @@ -207,7 +207,7 @@ func ForgetKeptCardsForTest() { func remoteMagpies() []Provider { var out []Provider for _, p := range All() { - if p.IsRemoteMagpie() && !p.Hidden && !p.Off && p.Key != "" && p.Anthropic != "" { + if p.IsRemoteMagpie() && !p.Hidden && !p.Off && !p.SelfLeftOut() && p.Key != "" && p.Anthropic != "" { out = append(out, p) } } diff --git a/internal/provider/remote_self.go b/internal/provider/remote_self.go new file mode 100644 index 000000000..52608e4b2 --- /dev/null +++ b/internal/provider/remote_self.go @@ -0,0 +1,214 @@ +package provider + +// A Remote magpie that is this magpie itself (hanslin1666 on Discord): +// computer B uses A through a Remote magpie provider, sync carries that +// provider to A, and on A it points at A. Each of its models is one of +// A's own, a request for it a pass more through A's gateway on its way +// there, and each one stands beside the model it is in A's lists and +// groups. The list A fetches from it says so: each model's magpie_via +// ends with the magpie that listed it (catalog.ViaHere), and that is A's +// own catalog.Self. So the fetch keeps, in remote-self.json, that this +// provider at this address is this magpie, and the provider is left out +// of routing and lists (SelfLeftOut), unless the user keeps it anyway +// (KeepSelf, the editor's "Use it anyway"). +// +// The file is this computer's own: it is never in a backup or a sync, as +// B's copy of the provider points at A, which is not B. Self is made up +// again each run, so the record is what stands between runs, until the +// next fetch: one whose lister is another magpie, or one from before +// magpie_via, which names none, takes it away. An empty list or a failed +// fetch tells nothing and changes nothing. The record holds the address +// it was found at: a provider moved to another address is not this +// magpie until a fetch there says so. + +import ( + "encoding/json" + "errors" + "io/fs" + "log" + "os" + "path/filepath" + "strings" + "sync" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/filelock" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/steady" +) + +// LeaveOutSelf is whether a Remote magpie found to be this magpie is left +// out. The gateway's tests serve their Remote magpie from their own +// process, and turn it off. +var LeaveOutSelf = true + +func remoteSelfPath() string { return filepath.Join(settings.Dir(), "remote-self.json") } + +var remoteSelfMu = filelock.Mutex{Path: func() string { return remoteSelfPath() + ".lock" }} + +// remoteSelf is the file as read, by provider id the address it answered +// as this magpie at, for the settings folder it was read from. +var remoteSelf struct { + sync.RWMutex + path string + ids map[string]string +} + +// readRemoteSelf reads the file. None yet is no record; one that can't be +// read or parsed is an error. +func readRemoteSelf(path string) (map[string]string, error) { + b, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + return map[string]string{}, nil + } + if err != nil { + return nil, err + } + ids := map[string]string{} + if err := json.Unmarshal(b, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// selfAt is the address provider id was found to be this magpie at, if +// it was. A file that can't be read records nothing: the provider is +// served as it was before, until a fetch writes the file again. +func selfAt(id string) (string, bool) { + path := remoteSelfPath() + remoteSelf.RLock() + if remoteSelf.path == path { + at, ok := remoteSelf.ids[id] + remoteSelf.RUnlock() + return at, ok + } + remoteSelf.RUnlock() + remoteSelf.Lock() + defer remoteSelf.Unlock() + if remoteSelf.path != path { + ids, err := readRemoteSelf(path) + if err != nil { + log.Printf("%s: %v", path, err) + ids = map[string]string{} + } + remoteSelf.path, remoteSelf.ids = path, ids + } + at, ok := remoteSelf.ids[id] + return at, ok +} + +// anySelf says some provider was found to be this magpie: the fast way +// past ThroughSelf for everyone else. +func anySelf() bool { + selfAt("") // loaded for this settings folder + remoteSelf.RLock() + defer remoteSelf.RUnlock() + return len(remoteSelf.ids) > 0 +} + +// selfRoot is the address a record is kept by: the provider's Chat, as +// remoteMagpieEndpoints wrote it. +func (p Provider) selfRoot() string { return strings.TrimRight(strings.TrimSpace(p.Chat), "/") } + +// SelfAnswered says this Remote magpie was found to be this magpie, at +// the address it has now. +func (p Provider) SelfAnswered() bool { + if !p.IsRemoteMagpie() { + return false + } + at, ok := selfAt(p.ID) + return ok && at == p.selfRoot() +} + +// SelfLeftOut is whether the provider is left out of routing and lists as +// a Remote magpie that is this magpie, which the user didn't keep. +func (p Provider) SelfLeftOut() bool { + return LeaveOutSelf && !p.KeepSelf && p.SelfAnswered() +} + +// noteSelf keeps what a Remote magpie's fetched list says of whether it is +// this magpie: the magpie that listed a model is its magpie_via's last. +func noteSelf(p Provider, ms []catalog.Model) { + if !p.IsRemoteMagpie() || len(ms) == 0 { + return + } + self := false + for _, m := range ms { + if len(m.Via) > 0 { + self = m.Via[len(m.Via)-1] == catalog.Self() + break + } + } + at, was := selfAt(p.ID) + if self == (was && at == p.selfRoot()) { + return + } + remoteSelfMu.Lock() + defer remoteSelfMu.Unlock() + path := remoteSelfPath() + ids, err := readRemoteSelf(path) + if err != nil { + // a record a fetch made, and the next fetch makes again + log.Printf("%s: %v; written again", path, err) + ids = map[string]string{} + } + if self { + ids[p.ID] = p.selfRoot() + } else { + delete(ids, p.ID) + } + b, _ := json.MarshalIndent(ids, "", " ") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + log.Printf("%s: %v", path, err) + return + } + if err := steady.WriteFile(path, b, 0o600); err != nil { + log.Printf("%s: %v", path, err) + return + } + remoteSelf.Lock() + remoteSelf.path, remoteSelf.ids = path, ids + remoteSelf.Unlock() + if self { + log.Printf("%s: this Remote magpie is this magpie itself; left out of routing unless kept (Providers → %s → Use it anyway)", p.ID, p.Name) + } +} + +// ThroughSelf is the model id a request names with a Remote magpie that is +// this magpie, and left out, taken off the front: rem/own/m1 is own/m1 +// here, as it is on the other computer, whose agents' picks sync brings +// over (hanslin1666). +func ThroughSelf(id string) string { + if !anySelf() { + return id + } + for range catalog.MaxVia { + pid, rest, ok := strings.Cut(id, "/") + if !ok || rest == "" { + return id + } + if _, ok := selfAt(pid); !ok { + return id + } + p, err := Find(pid) + if err != nil || p.ID != pid || !p.SelfLeftOut() { + return id + } + id = rest + } + return id +} + +// SetKeepSelf keeps a Remote magpie that is this magpie in routing, or +// leaves it out again (Provider.KeepSelf). +func SetKeepSelf(id string, keep bool) error { + p, err := Find(id) + if err != nil { + return err + } + if !p.IsRemoteMagpie() { + return errors.New(p.Name + " is not a Remote magpie") + } + p.KeepSelf = keep + return Save(*p) +} diff --git a/internal/provider/remote_self_test.go b/internal/provider/remote_self_test.go new file mode 100644 index 000000000..405568e5e --- /dev/null +++ b/internal/provider/remote_self_test.go @@ -0,0 +1,154 @@ +package provider + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +// A Remote magpie's list says which magpie listed each model (the last of +// its magpie_via). One this magpie listed is this magpie: the provider is +// left out, and the record outlives the run (Self is made up again each +// one) until a list another magpie gives, or one from before magpie_via, +// says otherwise. An empty list or a failed fetch changes nothing, and a +// provider moved to another address is not this magpie there. +func TestRemoteSelfRecord(t *testing.T) { + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + var answer atomic.Value // the list the remote gives + var down atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if down.Load() { + http.Error(w, "down", http.StatusBadGateway) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, answer.Load().(string)) + })) + t.Cleanup(srv.Close) + list := func(lister string) string { + via := "" + if lister != "" { + via = `,"magpie_via":["` + lister + `"]` + } + return `{"object":"list","data":[{"id":"own/m1","object":"model"` + via + `}]}` + } + id, err := Add(Provider{ID: "rem", Name: "Rem", Preset: RemoteMagpiePreset, Chat: strings.TrimPrefix(srv.URL, "http://")}) + if err != nil { + t.Fatal(err) + } + fetch := func() Provider { + t.Helper() + p, err := Find(id) + if err != nil { + t.Fatal(err) + } + p.Fetch(context.Background()) + p, _ = Find(id) + return *p + } + answer.Store(list("another")) + if p := fetch(); p.SelfAnswered() || !p.On() { + t.Fatalf("another magpie's list: self %v, on %v", p.SelfAnswered(), p.On()) + } + if _, err := os.Stat(filepath.Join(settings.Dir(), "remote-self.json")); err == nil { + t.Error("another magpie's list wrote a record") + } + answer.Store(list(catalog.Self())) + if p := fetch(); !p.SelfAnswered() || !p.SelfLeftOut() || p.On() { + t.Fatalf("this magpie's list: self %v, left out %v, on %v", p.SelfAnswered(), p.SelfLeftOut(), p.On()) + } + if got := ThroughSelf("rem/own/m1"); got != "own/m1" { + t.Errorf("ThroughSelf(rem/own/m1) = %q, want own/m1", got) + } + if got := ThroughSelf("rem/rem/own/m1"); got != "own/m1" { + t.Errorf("ThroughSelf(rem/rem/own/m1) = %q, want own/m1", got) + } + if got := ThroughSelf("other/m1"); got != "other/m1" { + t.Errorf("ThroughSelf(other/m1) = %q", got) + } + if p, ok := SwitchedOff("rem/x/y"); !ok || p.ID != "rem" { + t.Errorf("SwitchedOff(rem/x/y) = %q %v; want the left-out remote", p.ID, ok) + } + + // the record is read again in another run, from the file + remoteSelf.Lock() + remoteSelf.path = "" + remoteSelf.Unlock() + if p, _ := Find(id); !p.SelfAnswered() { + t.Fatal("the record didn't outlive the run") + } + // an empty list and a failed fetch tell nothing + answer.Store(`{"object":"list","data":[]}`) + if p := fetch(); !p.SelfAnswered() { + t.Error("an empty list took the record away") + } + down.Store(true) + if p := fetch(); !p.SelfAnswered() { + t.Error("a failed fetch took the record away") + } + down.Store(false) + // moved to another address: not this magpie there + p, _ := Find(id) + moved := *p + moved.Chat = "http://192.0.2.1:3425/v1" + if moved.SelfAnswered() { + t.Error("a provider at another address is taken for this magpie") + } + // a magpie from before magpie_via names none: no longer this one + answer.Store(list("")) + if p := fetch(); p.SelfAnswered() || !p.On() { + t.Errorf("a list from before magpie_via: self %v, on %v", p.SelfAnswered(), p.On()) + } + if got := ThroughSelf("rem/own/m1"); got != "rem/own/m1" { + t.Errorf("ThroughSelf after the record went = %q", got) + } +} + +// Use it anyway is this computer's own: sync brings the provider from the +// computer it is not this magpie on, and a backup put back here keeps it. +func TestMirrorKeepsKeepSelf(t *testing.T) { + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + if err := Save(Provider{ID: "rem", Name: "Rem", Preset: RemoteMagpiePreset, Chat: "http://192.0.2.1:3425/v1", Key: "k", KeepSelf: true}); err != nil { + t.Fatal(err) + } + other := Provider{ID: "rem", Name: "Rem renamed", Preset: RemoteMagpiePreset, Chat: "http://192.0.2.1:3425/v1", Key: "k"} + fresh := Provider{ID: "rem2", Name: "Rem 2", Preset: RemoteMagpiePreset, Chat: "http://192.0.2.2:3425/v1", Key: "k", KeepSelf: true} + if err := Mirror([]Provider{other, fresh}, nil); err != nil { + t.Fatal(err) + } + ps, _ := Stored() + if len(ps) != 2 || ps[0].Name != other.Name || !ps[0].KeepSelf || ps[1].KeepSelf { + for _, p := range ps { + t.Logf("%s %q KeepSelf %v", p.ID, p.Name, p.KeepSelf) + } + t.Fatal("mirrored: want the other's name, this computer's KeepSelf, none on the new one") + } + if _, _, err := Restore([]Provider{other, {ID: "rem3", Name: "Rem 3", Preset: RemoteMagpiePreset, Chat: "http://192.0.2.3:3425/v1", Key: "k", KeepSelf: true}}); err != nil { + t.Fatal(err) + } + ps, _ = Stored() + for _, p := range ps { + if p.ID == "rem" && !p.KeepSelf || p.ID == "rem3" && p.KeepSelf { + t.Errorf("restored %s: KeepSelf %v", p.ID, p.KeepSelf) + } + } +}