providers: Copy all keys, and magpie provider keys, carry a provider's keys to another magpie

@emilochen on X asked to batch-export one provider's keys, to sync them
between a local and a cloud magpie. Each key row could copy only its own
key (#1480), and nothing printed them all.

- A provider with two or more keys gets a "Copy all N keys" row under
  Add another key. It asks provider/key with allKeys (provider.AllKeys:
  the main key and every listed key, deduplicated, turned-off ones too)
  and copies them one a line, for the other magpie's Paste several
  (keys/import). The secret goes only to the clipboard on the click,
  through the page's copy(); nothing logs it, and the route sits behind
  the GUI API's existing local/origin guards. A signed-in account has
  no keys and is refused.
- The row is drawn by keyrates.js (copyAllKeysRow), already imported
  when a provider with two or more keys opens; keyRateField now takes
  which of its parts to draw. It has its own class, keys-copy-all, not
  .add, since ~21 GUI tests take .acc.add as the one adding row.
  TestCoreScriptBudget's core budget goes up by the 72 bytes left in
  app.js (the placing line and the helper's new argument); app.js stays
  under its own budget.
- CLI: `magpie provider keys <id>` prints the keys one a line;
  `magpie provider keys <id> add [key… | -]` adds them from words or
  stdin (SplitKeys + AddKeys), so
  `magpie provider keys relay | ssh cloud magpie provider keys relay add`
  works. A word starting with "-" is refused, never taken as a key.
- Strings in en, zh, zh-TW, ja, de.

Related: #5387 (sharing saved providers through magpie:// links), not
closed by this.

Run on mote (mote-run) at this tree on 11ddf076b (debc80271, its new parent, changes LESSONS.md only):
- gofmt -l internal/: clean. go vet (darwin) ./internal/provider
  ./internal/gui ./internal/cli; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; GOOS=linux go build -tags nogui and
  GOOS=windows go build: ok.
- go test -count=1 ./internal/provider ./internal/cli: ok;
  ./internal/gui: ok (TestCoreScriptBudget included, after the budget
  change).
- GUI, Chromium + WebKit: key-copy-all (en/zh/zh-TW/ja/de × 900/420px),
  api-key-usage, i18n-keys, key-price-rate, key-copy, key-weight,
  click-scroll: 104/104. key-copy-all again in WebKit twice: 15/15 each.
- GUI, 43 key/provider/i18n files at the change vs the same files at
  untouched 11ddf076b: the only new reds were api-key-usage's key-row
  count (it counted .acc:not(.add); now leaves keys-copy-all out). The
  other 67 reds are the same on the base and filed: #5835 key-switch,
  #6414 key-balance-card de, #6424 key-box-once, #5866 signin-proxy
  380, #6444 api-key-theme, #4126 key-replace 420, #4673
  provider-typed, #6416 key-import Paste several, and #6628 (filed now)
  login-export's Export row count.

Broken by hand: key-copy-all.test.cjs at untouched 11ddf076b assets
fails 10 of 15 in WebKit (the 5 that pass are "one key has no Copy
all"). The Go tests can't build on the old code (AllKeys, keysCmd).

Not tried: the real app and the system clipboard, the Windows and
Linux boxes, a real cloud/headless magpie over ssh, and the full Go
suite (mote and mica were both over their load limits; the three
touched packages and cross-OS vet ran instead).
This commit is contained in:
yetone
2026-11-14 16:34:10 +08:00
parent debc80271f
commit 07a62b3739
15 changed files with 414 additions and 12 deletions
+1 -1
View File
@@ -40,7 +40,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). Requests that miss a build together (a write drops what is held) wait for the first one's build and take it, unless a write came while it was built; a wait is bounded (`heldWait`), so a caller never waits for good. Before, each built again behind `logins.json`'s lock, and requests sat past the 30s unrouted deadline (#5104: `TestLoginsMissedTogetherListedOnce`, `TestHeldWaiterBuildsAgainAfterAWrite`, `TestHeldWaiterNeverStuck`). `OwnPaused` is held the same way, once a request. | [`provider.go`](../../internal/provider/provider.go) |
| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models <id> none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). Codex's own list at `/backend-api/codex/models` drops the ChatGPT account's visible models too, as spawn_agent's list of them does, and the list's ETag changes so a running Codex asks again (`CodexNativePicked` in [`codex_models.go`](../../internal/provider/codex_models.go), #2530); the hidden ones Codex runs jobs of its own on (codex-auto-review, gpt-reserve) and other providers' models stay. The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. With nothing picked and Select none off, Best in family (`BestInFamily`, `magpie provider models <id> best`, the editor's fourth option, Steven on Discord) serves only the newest model of each family the vendor lists, up to 24: the family is the id with its version numbers taken out, a dated snapshot counts as its alias, and sizes and suffixes (-mini, -pro, -8b) stay in the name (`FamilyOf`, `BestInFamily` in [`family.go`](../../internal/catalog/family.go)). A newer one the vendor lists later takes the old one's place with nothing saved. Codex's own list narrows the same way (`CodexNativePicked`). An older one named by its `provider/model` id is still served, as an unpicked one is under Picked only. A pick or Select none clears it, and a file without `bestInFamily` reads as before. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models for `pickWait` (an hour) from when the last one left (`DelistedAt`, `waitsForPicks`), not the vendor's list; after that, or for picks set aside before `DelistedAt` was kept, the picks are taken as gone for good and the list is served as if none were picked, while they still come back with a list that has them. WorkBuddy AI took its Free plan's deepseek-v4.1-flash off its list for hy3, and an account whose one pick it was got no model in the agents' picker, its row reading "1 image model" (maxleebeta on Discord). `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. Devin's picks and set-aside picks are read without Adaptive and Fusion, in any case (`withoutDevinRouters` in `normalize`): the built-in listed them before it served Devin's chat API (ce8d0e065), which answers either with 502 "no API providers are available", and picks saved then were served as the user's own models after the move to the plugin, which lists neither (`TestDevinRouterPicksNotServed`). `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone`, `TestPicksGoneForGoodServeTheList` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no `RefreshEvery` is fetched every 10m (`RemoteMagpieEvery`, `RefreshSchedule`), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; `off` set on it is kept as `"off"` and asks it only when told (`TestRemoteMagpieListFollowsTheOtherMagpie`). The gateway also follows each Remote magpie's list as it changes there (KaCli on Discord: a route or group changed on the server reached the agents on the computer using it only on the next 10m): `KeepRemoteListsFollowed` keeps one long-poll per Remote magpie, a `GET /v1/models` with `X-Magpie-List-Wait` and the `If-None-Match` of its last answer, and on a new ETag fetches the list through the same `RefetchTaking`, so `catalog.Touched` rewrites the agents' configs within a second or two. A magpie from before answers at once with no ETag; it is left to the schedule and asked to wait again after an hour. One set to `off` is not followed (`TestRemoteMagpieListFollowed`, `TestRemoteMagpieOldListNotFollowed`, `TestRemoteMagpieOffNotFollowed` in [`remote_follow_test.go`](../../internal/provider/remote_follow_test.go)). | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`remote_follow.go`](../../internal/provider/remote_follow.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`): Anthropic, Chat, Responses or a custom provider's Gemini API (corddis_114 on Discord). `WithKey` leaves it that protocol's URL only, and the gateway puts the key that suits the model first (`keyFit`: Claude to the Anthropic key, GPT to a Chat or Responses one, Gemini to the Gemini one; `TestKeyMadeForGemini`, `TestKeyProtocolGemini`, `key-gemini.test.cjs`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. Each Fetch models carries each key's list into the models it serves (`refreshKeyModels` in [`key_models_refresh.go`](../../internal/provider/key_models_refresh.go)): a key with a list of its own gains what its list gained and loses what it lost, keeping what the user ticked or un-ticked; a key on All models (the provider's first, one added before per-key lists, one whose list wasn't read in time when added) is given its own list when that list leaves out a model the other keys list. A key the user set to All models (`accountmodels` with none) is marked in `AccountModelsAll` and stays so; the editor's save keeps it. A key set to All models before the mark was kept has none, and is narrowed once to its list on the next Fetch (young02036 on Discord, `TestFetchTicksEachKeysListOnAllModels`, `TestFetchModelsTicksEveryKeysModels`). | [`keys.go`](../../internal/provider/keys.go), [`key_models_refresh.go`](../../internal/provider/key_models_refresh.go) |
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`): Anthropic, Chat, Responses or a custom provider's Gemini API (corddis_114 on Discord). `WithKey` leaves it that protocol's URL only, and the gateway puts the key that suits the model first (`keyFit`: Claude to the Anthropic key, GPT to a Chat or Responses one, Gemini to the Gemini one; `TestKeyMadeForGemini`, `TestKeyProtocolGemini`, `key-gemini.test.cjs`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. Each Fetch models carries each key's list into the models it serves (`refreshKeyModels` in [`key_models_refresh.go`](../../internal/provider/key_models_refresh.go)): a key with a list of its own gains what its list gained and loses what it lost, keeping what the user ticked or un-ticked; a key on All models (the provider's first, one added before per-key lists, one whose list wasn't read in time when added) is given its own list when that list leaves out a model the other keys list. A key the user set to All models (`accountmodels` with none) is marked in `AccountModelsAll` and stays so; the editor's save keeps it. A key set to All models before the mark was kept has none, and is narrowed once to its list on the next Fetch (young02036 on Discord, `TestFetchTicksEachKeysListOnAllModels`, `TestFetchModelsTicksEveryKeysModels`). Every key goes out at once, one a line, for another magpie to take in (@emilochen on X: one provider's keys from this computer to a magpie in the cloud): `AllKeys` gives the keys alone, on and off, in the list's order, each once; their names, protocols and plans stay behind. The editor's *Copy all N keys* (shown with more than one key, under *Add another key*, drawn by keyrates.js; `provider/key` with `allKeys`) copies them to the clipboard for the other magpie's *Paste several*, and `magpie provider keys <id>` prints them to stdout for `magpie provider keys <id> add`, which reads them from stdin or as words (a flag is never a key). Nothing logs them (`TestAllKeys`, `TestCopyAllKeysPastesInto`, `TestKeysCmd`, `key-copy-all.test.cjs`). | [`keys.go`](../../internal/provider/keys.go), [`key_models_refresh.go`](../../internal/provider/key_models_refresh.go) |
| Accounts at once | `MaxAccounts *int` is the user's own count of keys or accounts taking requests at the same time: nil takes the plugin's (`PluginAtOnce`: `maxAccounts` on the plugin's auth hook or package.json `magpie`, host.js `atOnceOf`), 0 is no limit, saved clamped to 0..`MaxLimit`; a subscription's is kept with its picks (`withPicks`). `AtOnce()` answers the one in force, `SetAtOnce` sets it (`magpie provider at-once`, the editor's Accounts at once; GUI save leaves it as it was when the body has none). The gateway's use is in [gateway routing](gateway-routing.md) (`TestAtOnce`, `TestAtOnceSave`, `TestAtOnceCmd`). | [`concurrency.go`](../../internal/provider/concurrency.go) |
| A provider with no key | A provider of the user's own saves, imports and is `Ready` with no key when it is a preset with `NoKey` or its host is on this computer or the user's own network (`keyOptional`, `ownNetwork`): localhost, a loopback, private, link-local or carrier-grade NAT (Tailscale's 100.64/10) address, or a `.local` name, read from the URL alone with no lookup. A company's keyless relay at a LAN address is taken as a local server is (iSnow_999 on X: a Codex relay at http://<LAN IP>:8080 was left out of a CC Switch import as "it has no API key"); a keyless address on the internet still needs its key. With no key it is asked as one on 127.0.0.1 is: a Responses request carries no `Authorization`. | [`provider.go`](../../internal/provider/provider.go), [`importapps.go`](../../internal/provider/importapps.go), [`import_lan_test.go`](../../internal/provider/import_lan_test.go) |
| A key a provider | One vendor's keys saved a provider each — an app that keeps an entry a key, as CC Switch does, imported (yuluo_yx on X: "NVIDIA #001" to "#600" at one address, "Mistral #0001"…) — are folded into one provider with those keys (`FoldCopies` at start-up, `foldAdded` after `ImportFromApps`): hundreds of copies listed every model hundreds of times in every agent's picker and found group, and 3,000 made `/api/state` 86 MB. At start-up only copies by name are folded: a base name and that name with a number after it (`copyBase`: " #12", or `freeName`'s " 2"), one at least numbered; an import folds what it added whatever their names. Either way they must be alike in all but their key (`foldShape`: the provider with its id, name, keys and on/off left out), what the settings say of their models (`modelPrefs`) and where they are named (`foldRefs`: Visible, the agents' picked, hidden and ordered models, the groups, the providers falling back to them), so one key shown to one agent and another to another stays apart. Not folded: a subscription's, a hidden one, one without a key, Vertex, one with a StepFun sign-in of its own. The first on, in the providers' order, takes the rest in; its name becomes the base and its key is named its old name. Each other is a key in order, named its name, off if it was off (all off: the provider is off, its keys on); its id goes in `Was`, so its calls count with the provider by their key (`ProviderKeyID` is the key's fingerprint, unchanged) and a model picked by the old id still reaches it. Group members, rules, weights and fallbacks naming them name the provider once; their per-model settings and fetched lists go; balance and window history kept by their id moves to their key's name (`foldHistories`). A providers.json that doesn't parse is left alone. It runs at every start and writes nothing when there is nothing to fold. `TestFoldCopies`, `TestFoldCopiesIntoOneOn`, `TestFoldCopiesUnreadable`, `TestImportFoldsAKeyAnEntry`. | [`fold.go`](../../internal/provider/fold.go), [`importapps.go`](../../internal/provider/importapps.go), [`main.go`](../../internal/cli/main.go) |
+71
View File
@@ -0,0 +1,71 @@
package cli
import (
"fmt"
"io"
"os"
"strings"
"github.com/yetone/magpie/internal/provider"
)
const keysUsage = "magpie provider keys <id> [add [key… | -]]"
// keysCmd prints every key a provider holds, one a line and nothing else,
// or adds keys: given as words, or one a line on stdin (-, or none given).
// So one provider's keys go from one magpie to another (@emilochen on X:
// this computer's to a magpie in the cloud):
//
// magpie provider keys relay | ssh cloud magpie provider keys relay add
//
// What is printed is the keys themselves, asked for by name; they go to
// stdout alone, never to a log.
func keysCmd(rest []string, in io.Reader, out io.Writer) error {
if len(rest) < 1 || strings.HasPrefix(rest[0], "-") {
return fmt.Errorf("%s", keysUsage)
}
if len(rest) == 1 {
keys, err := provider.AllKeys(rest[0])
if err != nil {
return err
}
for _, k := range keys {
fmt.Fprintln(out, k)
}
return nil
}
if rest[1] != "add" {
return fmt.Errorf("%s", keysUsage)
}
words := rest[2:]
var text string
if len(words) == 0 || len(words) == 1 && words[0] == "-" {
b, err := io.ReadAll(io.LimitReader(in, 8<<20))
if err != nil {
return err
}
text = string(b)
} else {
for _, w := range words {
// a flag is never a key (--help)
if strings.HasPrefix(w, "-") {
return fmt.Errorf("%s", keysUsage)
}
}
text = strings.Join(words, "\n")
}
p, err := provider.Find(rest[0])
if err != nil {
return err
}
added, had, err := provider.AddKeys(p.ID, provider.SplitKeys(text), "")
if err != nil {
return err
}
msg := fmt.Sprintf("%d keys added to %s", added, p.Name)
if had > 0 {
msg += muted.Render(fmt.Sprintf(" · %d already there", had))
}
fmt.Fprintln(os.Stderr, green.Render("✓"), msg)
return nil
}
+55
View File
@@ -0,0 +1,55 @@
package cli
import (
"bytes"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// magpie provider keys prints every key, one a line and nothing else, and
// keys … add takes them from stdin or as words (@emilochen on X: one
// provider's keys to a magpie in the cloud). A flag is never a key, and
// nothing is written for one.
func TestKeysCmd(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("DSH_HOME", "")
for _, p := range []provider.Provider{
{ID: "relay", Name: "Relay", Key: "k1", KeyName: "Team", Chat: "http://127.0.0.1:1/v1", Keys: []provider.KeyAccount{{Key: "k2", Off: true}, {Name: "Spare", Key: "k3"}}},
{ID: "cloud", Name: "Cloud", Key: "k9", Chat: "http://127.0.0.1:1/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
var out bytes.Buffer
if err := keysCmd([]string{"relay"}, nil, &out); err != nil {
t.Fatal(err)
}
if out.String() != "k1\nk2\nk3\n" {
t.Fatalf("printed %q", out.String())
}
if err := keysCmd([]string{"cloud", "add"}, strings.NewReader(out.String()), &bytes.Buffer{}); err != nil {
t.Fatal(err)
}
if err := keysCmd([]string{"cloud", "add", "k4", "k1"}, nil, &bytes.Buffer{}); err != nil {
t.Fatal(err)
}
if got, _ := provider.AllKeys("cloud"); !slices.Equal(got, []string{"k9", "k1", "k2", "k3", "k4"}) {
t.Fatalf("cloud holds %q", got)
}
for _, bad := range [][]string{{}, {"--help"}, {"cloud", "--help"}, {"cloud", "add", "--help"}, {"cloud", "add", "k5", "-x"}, {"nope"}} {
if err := keysCmd(bad, strings.NewReader(""), &bytes.Buffer{}); err == nil {
t.Fatalf("%v taken", bad)
}
}
if got, _ := provider.AllKeys("cloud"); len(got) != 5 {
t.Fatalf("a refused call wrote %q", got)
}
}
+4
View File
@@ -76,6 +76,8 @@ const providerUsage = `usage:
asked once, nothing read into them, no other provider tried;
errors=magpie, the default, has magpie handle them
magpie provider key <id> <key> change the API key
magpie provider keys <id> [add [key…|-]] print every key, one a line, or add keys (as words,
or one a line on stdin), to carry them to another magpie
magpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon
magpie provider fallback <id> <provider/model>… where requests go when it's out of quota or down (none clears)
magpie provider models <id> [ids…] fetch the vendor's model list, or choose which models to expose:
@@ -688,6 +690,8 @@ func providerCmd(args []string) error {
return spendCapCmd(rest)
case "key-rate", "key-rates":
return keyRateCmd(rest)
case "keys":
return keysCmd(rest, os.Stdin, os.Stdout)
case "account-weight", "account-weights":
return accountWeightCmd(rest)
case "queue":
+6 -6
View File
@@ -3004,12 +3004,12 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.acc.new { animation: sub-in .3s var(--ease-out); }
.acc.new .dot { animation: copy-pop .3s var(--ease-out); }
@keyframes sub-in { from { opacity: 0; transform: translateY(-4px); background: var(--pill-hover); } }
.acc.add { width: 100%; color: var(--fg-2); background: none; border: 0 solid var(--line-2); cursor: default; }
.acc + .acc.add { border-top-width: 1px; }
.acc.add .dot { box-shadow: inset 0 0 0 1.5px var(--faint); border-radius: 50%; }
.acc.add .n { font-weight: 450; }
.acc.add:hover { background: var(--card-2); color: var(--fg); }
.acc.add:hover .dot { box-shadow: inset 0 0 0 1.5px var(--fg); color: var(--fg); }
.acc.add, .acc.keys-copy-all { width: 100%; color: var(--fg-2); background: none; border: 0 solid var(--line-2); cursor: default; }
.acc + .acc.add, .acc + .acc.keys-copy-all { border-top-width: 1px; }
.acc.add .dot, .acc.keys-copy-all .dot { box-shadow: inset 0 0 0 1.5px var(--faint); border-radius: 50%; }
.acc.add .n, .acc.keys-copy-all .n { font-weight: 450; }
.acc.add:hover, .acc.keys-copy-all:hover { background: var(--card-2); color: var(--fg); }
.acc.add:hover .dot, .acc.keys-copy-all:hover .dot { box-shadow: inset 0 0 0 1.5px var(--fg); color: var(--fg); }
/* a long list of keys, folded (361 on Discord): All N keys opens it on a
filter, removing many at once, and a page of rows */
+6 -2
View File
@@ -8231,8 +8231,9 @@ function accountProxiesOfDraft() {
return { map: out };
}
// a key's own price rate (@tnt12231 on X), in keyrates.js
const keyRateField = (p, at = el("span")) => p?.keyList?.length > 1 ? (import("./keyrates.js").then(() => at.replaceWith(...keyPriceRateField(p)), () => {}), [at]) : [];
// a key's own price rate (@tnt12231 on X), in keyrates.js, and any other
// part keyrates.js draws for a provider with two or more keys (f)
const keyRateField = (p, f = "keyPriceRateField", at = el("span")) => p?.keyList?.length > 1 ? (import("./keyrates.js").then(() => at.replaceWith(...window[f](p)), () => {}), [at]) : [];
// headers as ordered [name, value, json?] rows that survive a redraw; headersOf folds them back
function headerRows(obj) {
@@ -15136,6 +15137,9 @@ function renderKeyAccounts(p) {
queueMicrotask(() => key.focus());
} else {
list.append(addRow(t("Add another key"), () => { addingKey = { id: p.id, name: "", key: "" }; renderProviders(); }));
// every key at once, one a line, for another magpie's Paste several
// (@emilochen on X): the row is drawn by keyrates.js (copyAllKeysRow)
list.append(...keyRateField(p, "copyAllKeysRow"));
}
// rows folded away keep their places when the shown ones are dragged
if (fold.folded) list.accountOrder = p.keyList.map((k) => k.id);
+8
View File
@@ -2321,6 +2321,8 @@ const I18N = {
"The first is tried first; the other {n} are added to its accounts": "第一个优先使用,其余 {n} 个加为它的账号",
"Add many keys at once, one a line or separated by commas": "一次添加多个密钥,每行一个或用逗号分隔",
"Add another key": "添加另一个密钥",
"Copy all {n} keys": "全部复制({n} 个密钥)",
"{n} keys copied, one a line — paste them into Paste several in another magpie": "已复制 {n} 个密钥,每行一个 — 在另一台 magpie 的“批量粘贴”里粘贴即可",
"Add a key": "添加密钥",
"Name (optional), e.g. Team": "名称(可选),例如 团队",
"Name, e.g. Personal or Team": "名称,例如 个人 或 团队",
@@ -7579,6 +7581,8 @@ const I18N = {
"The first is tried first; the other {n} are added to its accounts": "第一個優先使用,其餘 {n} 個加為它的帳號",
"Add many keys at once, one a line or separated by commas": "一次新增多個金鑰,每行一個或用逗號分隔",
"Add another key": "新增另一個金鑰",
"Copy all {n} keys": "全部複製({n} 個金鑰)",
"{n} keys copied, one a line — paste them into Paste several in another magpie": "已複製 {n} 個金鑰,每行一個 — 在另一台 magpie 的「批次貼上」裡貼上即可",
"Add a key": "新增金鑰",
"Name (optional), e.g. Team": "名稱(可選),例如 團隊",
"Name, e.g. Personal or Team": "名稱,例如 個人 或 團隊",
@@ -12812,6 +12816,8 @@ const I18N = {
"The first is tried first; the other {n} are added to its accounts": "最初のキーを優先し、残りの {n} 個はアカウントとして追加します",
"Add many keys at once, one a line or separated by commas": "複数のキーを一度に追加(1 行に 1 つ、またはカンマ区切り)",
"Add another key": "別のキーを追加",
"Copy all {n} keys": "{n} 個のキーをすべてコピー",
"{n} keys copied, one a line — paste them into Paste several in another magpie": "{n} 個のキーを 1 行に 1 つずつコピーしました — 別の magpie の「まとめて貼り付け」に貼り付けてください",
"Add a key": "キーを追加",
"Name (optional), e.g. Team": "名前(任意)、例:チーム",
"Name, e.g. Personal or Team": "名前、例:個人 または チーム",
@@ -18076,6 +18082,8 @@ const I18N = {
"The first is tried first; the other {n} are added to its accounts": "Der erste wird zuerst versucht; die anderen {n} kommen als seine Konten dazu",
"Add many keys at once, one a line or separated by commas": "Viele Schlüssel auf einmal hinzufügen, einer pro Zeile oder durch Kommas getrennt",
"Add another key": "Weiteren Schlüssel hinzufügen",
"Copy all {n} keys": "Alle {n} Schlüssel kopieren",
"{n} keys copied, one a line — paste them into Paste several in another magpie": "{n} Schlüssel kopiert, einer pro Zeile — in einem anderen magpie unter „Mehrere einfügen“ einfügen",
"Add a key": "Schlüssel hinzufügen",
"Name (optional), e.g. Team": "Name (optional), z. B. Team",
"Name, e.g. Personal or Team": "Name, z. B. Privat oder Team",
+13
View File
@@ -63,3 +63,16 @@ window.keysTag = function (p, m) {
tag.title = t("Listed by {keys} only", { keys: names.join(", ") + (n > names.length ? " …" : "") });
return tag;
};
// Copy all keys (@emilochen on X): every key of the provider, one a line,
// for Paste several in another magpie; each key's row still copies its
// own. Not .add: that is the one row that adds.
window.copyAllKeysRow = function (p) {
const all = addRow(t("Copy all {n} keys", { n: p.keyList.length }), async () => {
try {
const r = await api("provider/key", { id: p.id, allKeys: true });
copy(r.key, "", null, t("{n} keys copied, one a line — paste them into Paste several in another magpie", { n: r.count }));
} catch (err) { statusErr(err); }
}, COPY_ICON);
all.classList.replace("add", "keys-copy-all");
return [all];
};
+1 -1
View File
@@ -18,7 +18,7 @@ import (
// `git log -L` of this file.
const (
appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had
coreScriptBudget = 1_269_857 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to
coreScriptBudget = 1_269_929 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to; +72 for Copy all keys (emilochen on X): its row in keyrates.js, imported when a provider with two or more keys opens through keyRateField, now told which of its parts to draw, and what is left is the one line that places it
)
// codeBytes is how many bytes of b are code: its blank lines, its lines
+49
View File
@@ -51,3 +51,52 @@ func TestEachKeyCopiesItsOwn(t *testing.T) {
t.Errorf("a key it hasn't: %q (%d)", got, code)
}
}
// Copy all keys (@emilochen on X) asks provider/key with allKeys and gets
// every key, one a line, off ones too, which keys/import in another
// provider takes as they are.
func TestCopyAllKeysPastesInto(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", os.Getenv("HOME"))
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
mux := http.NewServeMux()
providerRoutes(mux, nil)
post := func(path, body string) (int, string) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", path, strings.NewReader(body)))
return w.Code, w.Body.String()
}
for _, p := range []string{"relay", "cloud"} {
key := `"sk-a, sk-b, sk-c"`
if p == "cloud" {
key = `"sk-z"`
}
if code, body := post("/api/provider/save", `{"id":"`+p+`","name":"`+p+`","chat":"http://127.0.0.1:1/v1","key":`+key+`,"new":true}`); code != 200 {
t.Fatalf("save %s: %d %s", p, code, body)
}
}
if code, body := post("/api/keys/off", `{"id":"relay","ref":"`+provider.KeyID("sk-b")+`"}`); code != 200 {
t.Fatalf("off: %d %s", code, body)
}
code, body := post("/api/provider/key", `{"id":"relay","allKeys":true}`)
var out struct {
Key string
Count int
}
json.Unmarshal([]byte(body), &out)
if code != 200 || out.Key != "sk-a\nsk-b\nsk-c" || out.Count != 3 {
t.Fatalf("all keys: %d %q %d", code, out.Key, out.Count)
}
in, _ := json.Marshal(map[string]string{"id": "cloud", "key": out.Key})
if code, body := post("/api/keys/import", string(in)); code != 200 {
t.Fatalf("import: %d %s", code, body)
}
if got, _ := provider.AllKeys("cloud"); strings.Join(got, ",") != "sk-z,sk-a,sk-b,sk-c" {
t.Fatalf("cloud holds %q", got)
}
if code, _ := post("/api/provider/key", `{"id":"gone","allKeys":true}`); code == 200 {
t.Fatal("a provider it hasn't answered 200")
}
}
+15 -1
View File
@@ -1968,6 +1968,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// the provider's (#474)
Account string `json:"account"`
Allow []string `json:"allow"`
// AllKeys, for key: every key the provider holds, one a line,
// for Copy all keys (provider.AllKeys)
AllKeys bool `json:"allKeys"`
// Cap, for accountcap: the share (1–99) of its windows the
// account is used to at most, 0 for no cap; for windowcap, the
// share of Window alone (1–99, 100 for none on it), 0 to have
@@ -2682,7 +2685,18 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// the saved key, for the editor's Show button; it never
// leaves this machine (the panel is served on loopback).
// With Account, the key of that id: each of several keys'
// rows copies its own (#1480).
// rows copies its own (#1480). With AllKeys, every one of
// them, one a line, as Paste several takes them in another
// magpie (@emilochen on X); never logged.
if req.AllKeys {
keys, err := provider.AllKeys(in.ID)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, map[string]any{"key": strings.Join(keys, "\n"), "count": len(keys)})
return
}
if req.Account != "" {
k, err := provider.KeyOf(in.ID, req.Account)
if err != nil {
+1 -1
View File
@@ -97,7 +97,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
: { addButton: "Add", first: "Make first", remove: "Remove", failed: "Failed", all: "All gateway keys" };
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "Relay" }).click();
assert.equal(await page.locator(".accts .acc:not(.add)").count(), 2);
assert.equal(await page.locator(".accts .acc:not(.add):not(.keys-copy-all)").count(), 2);
await page.locator(".accts .acc.add").click();
await page.locator(".acc.adding .kf input").nth(0).fill("Backup");
await page.locator(".acc.adding .kf input").nth(1).fill("test-new");
+128
View File
@@ -0,0 +1,128 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Copy all keys (@emilochen on X: one provider's keys from this computer to
// a magpie in the cloud): a key provider with more than one key has Copy all
// N keys under Add another key. It asks provider/key with allKeys and copies
// what comes back, one a line, through magpie's clipboard, and says how many
// went and where to paste them. One key has no such row; each row's own
// Copy stays. Add another key is still the one row that adds. The page
// doesn't scroll. Every language, wide and narrow.
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 KEYS = "sk-one\nsk-two\nsk-three";
const relay = (n) => ({
id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "big", name: "", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "",
keyList: [
{ id: "aaaaaaaaaa", name: "Team", masked: "sk-…one", on: true, active: true },
{ id: "bbbbbbbbbb", name: "", masked: "sk-…two", on: false },
{ id: "cccccccccc", name: "", masked: "sk-…ree", on: true },
].slice(0, n),
});
function serve(lang, n, posts) {
const providers = { providers: [relay(n)], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
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/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/provider/key" && route.request().method() === "POST") {
const body = route.request().postDataJSON();
posts.push({ path: url.pathname, body });
return json(body.allKeys ? { key: KEYS, count: 3 } : { key: "sk-one" });
}
if (url.pathname === "/api/copy" && route.request().method() === "POST") {
posts.push({ path: url.pathname, body: route.request().postDataJSON() });
return route.fulfill({ status: 204, body: "" });
}
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 words = {
en: { all: "Copy all 3 keys", another: "Add another key", note: "3 keys copied, one a line — paste them into Paste several in another magpie" },
zh: { all: "全部复制(3 个密钥)", another: "添加另一个密钥", note: "已复制 3 个密钥,每行一个 — 在另一台 magpie 的“批量粘贴”里粘贴即可" },
"zh-TW": { all: "全部複製(3 個金鑰)", another: "新增另一個金鑰", note: "已複製 3 個金鑰,每行一個 — 在另一台 magpie 的「批次貼上」裡貼上即可" },
ja: { all: "3 個のキーをすべてコピー", another: "別のキーを追加", note: "3 個のキーを 1 行に 1 つずつコピーしました — 別の magpie の「まとめて貼り付け」に貼り付けてください" },
de: { all: "Alle 3 Schlüssel kopieren", another: "Weiteren Schlüssel hinzufügen", note: "3 Schlüssel kopiert, einer pro Zeile — in einem anderen magpie unter „Mehrere einfügen“ einfügen" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
for (const width of [900, 420]) {
const open = async (t, n, name) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
let page;
t.after(async () => {
if (process.env.ARTIFACT_DIR && page) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name}-key-copy-all.png`) });
}
await browser.close();
});
page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(15000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", serve(lang, n, posts));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "Relay" }).first().click();
await page.locator(".editor .accts .acc.add").waitFor();
return { page, errors, posts };
};
const scrolled = (page) => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.classList[0]}:${e.scrollTop}`)].join(" "));
test(`${engine} ${lang} ${width}px: Copy all keys copies every key, one a line`, async (t) => {
const { page, errors, posts } = await open(t, 3, "three");
const all = page.locator(".editor .accts .acc.keys-copy-all");
assert.equal(await all.count(), 1);
assert.equal((await all.textContent()).trim(), w.all);
// under Add another key, which stays the one row that adds
assert.equal(await page.locator(".editor .accts .acc.add").count(), 1);
assert.equal((await page.locator(".editor .accts .acc.add").textContent()).trim(), w.another);
assert.ok(await all.evaluate((e) => e.previousElementSibling?.classList.contains("add")), "not right under Add another key");
// the label fits on its row, narrow too
assert.ok(await all.evaluate((e) => e.scrollWidth <= e.clientWidth + 1), "the label overflows its row");
// in view first: Playwright scrolls to what it clicks, the page must not
await all.scrollIntoViewIfNeeded();
const sc = await scrolled(page);
await all.click();
for (let i = 0; i < 200 && posts.length < 2; i++) await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(posts, [
{ path: "/api/provider/key", body: { id: "relay", allKeys: true } },
{ path: "/api/copy", body: { text: KEYS } },
]);
await page.waitForFunction((note) => document.querySelector("#status")?.textContent.trim() === note, w.note);
assert.equal(await scrolled(page), sc, "a click scrolled");
// the label stays: the toast says it went
assert.equal((await all.textContent()).trim(), w.all);
assert.deepEqual(errors, []);
});
if (width === 900) {
test(`${engine} ${lang}: one key has no Copy all`, async (t) => {
const { page, errors } = await open(t, 1, "one");
assert.equal(await page.locator(".editor .accts .acc.keys-copy-all").count(), 0);
assert.deepEqual(errors, []);
});
}
}
}
}
+30
View File
@@ -268,6 +268,36 @@ func SplitKeys(text string) []string {
return out
}
// AllKeys is every key a provider holds, on or off, in the order its
// list shows them, each once: what Copy all keys and `magpie provider
// keys <id>` give, one a line, for another magpie's Paste several or
// `magpie provider keys <id> add` to take (@emilochen on X: one
// provider's keys from this computer to a magpie in the cloud). Only
// the keys go: their names, protocols and plans are this magpie's.
// A signed-in account has none to give.
func AllKeys(id string) ([]string, error) {
p, err := Find(id)
if err != nil {
return nil, err
}
if p.Account != nil {
return nil, errors.New("a signed-in account has no keys")
}
var out []string
seen := map[string]bool{}
add := func(k string) {
if k = strings.TrimSpace(k); k != "" && !seen[k] {
seen[k] = true
out = append(out, k)
}
}
add(p.Key)
for _, k := range p.Keys {
add(k.Key)
}
return out, nil
}
// AddKeys saves several keys at once, on, after the ones the provider has,
// with the protocol given: those it has already are passed over. added is
// how many were new, had how many it had.
+26
View File
@@ -3,6 +3,7 @@ package provider
import (
"path/filepath"
"reflect"
"strings"
"testing"
)
@@ -62,3 +63,28 @@ func TestAddKeys(t *testing.T) {
t.Fatalf("rest key %q", p.RestKey(k))
}
}
// AllKeys gives every key a provider holds, on or off, in its list's
// order, each once, for another magpie to take in with SplitKeys
// (@emilochen on X); a signed-in account has none.
func TestAllKeys(t *testing.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: "bulk", Name: "Bulk", Chat: "https://example.invalid/v1", Key: "k1", KeyName: "Team",
Keys: []KeyAccount{{Key: "k2", Off: true}, {Name: "Spare", Key: "k3", Protocol: Anthropic}, {Key: "k1"}}}); err != nil {
t.Fatal(err)
}
got, err := AllKeys("bulk")
if want := []string{"k1", "k2", "k3"}; err != nil || !reflect.DeepEqual(got, want) {
t.Fatalf("got %q, %v", got, err)
}
if !reflect.DeepEqual(SplitKeys(strings.Join(got, "\n")), got) {
t.Fatal("what it gives is not what Paste several reads")
}
if _, err := AllKeys("nope"); err == nil {
t.Fatal("no provider: no error")
}
}