provider, gui: a routing group is shared as text and imported into another magpie (laincatx on X)
A group row's menu has Copy to share: the group as JSON marked "magpie": "routing-group" with a format version (provider.ShareGroup), holding its members as it names them, patterns, routing, rules, classifier and settings. A group holds provider/model ids only, so no key, account or address goes with it; derived matches and the found/hidden/off flags stay behind. The Routing page's Import (by New group) opens a box the text is pasted into, words or a code fence around it allowed. POST /api/groups/import (provider.ImportGroup) adds it under a free name, never over a group. A member whose provider the importer has is kept; else the same model under one of their providers (listed as used instead); else it is left out and listed, with the rules that send to it and its off/fast place; a classifier gone takes the intent rules and auto effort. Nothing is added when no member is left. Other text, a newer format or none is refused in the reader's language (provider.ShareError, code "share"). Run: - go test -tags nogui ./... (gateway failed once on a full disk, then passed alone); new TestSharedGroupRoundTrip/MissingMembers/BadText and TestGroupShareAndImport; the version check broken by hand turns them red - gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; go build - group-share.test.cjs in chromium and webkit, en/zh/zh-TW/ja/de, 420px; every group-*, settings-groups, filter-ime, panel-routing GUI test (210 pass); routing-* (550/557: webkit fold tests timed out only under --test-concurrency=6 and pass alone; a webkit routing-* run under the same load fails one test on origin/main too, a different one each run) - real use: the owner's 12 groups from a sandbox copy of providers.json each shared (no key in the text) and imported back whole
This commit is contained in:
@@ -30,7 +30,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`plugins_cli.go`](../../plugins_cli.go) |
|
||||
| Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../accounts_cli.go) |
|
||||
| Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). | [`codex_switch.go`](../../internal/provider/codex_switch.go) |
|
||||
| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). Members are `provider/model[:effort]`. A group can nest another (`group/<id>`); `SaveGroup` refuses loops. `Match` takes a glob or `re:` pattern (#766). A found group follows its providers: one switched off or removed leaves it, and one on again is back. A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go) |
|
||||
| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). Members are `provider/model[:effort]`. A group can nest another (`group/<id>`); `SaveGroup` refuses loops. `Match` takes a glob or `re:` pattern (#766). A found group follows its providers: one switched off or removed leaves it, and one on again is back. A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches and found/hidden/off flags stay behind. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) |
|
||||
| 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. 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. 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 `<remote>/~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=<remote>/~keys&user=<key name>`). 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`). 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 opened 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. | [`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 prices (a remote request without a valid key never reaches the list: `lanGuard` refuses it). 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`, asked with `X-Magpie-Drawers` (`DrawersHeader`), 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). A remote from before this sends no tiers, and its models are offered none, as before. | [`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) |
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"regexp"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -1876,6 +1877,13 @@ func fail(rw http.ResponseWriter, err error) {
|
||||
if errors.As(err, &signedIn) {
|
||||
out["code"], out["agent"], out["user"] = "signed_in", signedIn.Agent, signedIn.User
|
||||
}
|
||||
// a text that isn't a group to import (laincatx on X), said in the
|
||||
// reader's language
|
||||
var share *provider.ShareError
|
||||
if errors.As(err, &share) {
|
||||
out["code"], out["share"] = "share", share.Why
|
||||
out["format"], out["models"] = strconv.Itoa(share.Format), strings.Join(share.Models, ", ")
|
||||
}
|
||||
// an agent's npm update, or RTK's winget, that needed an administrator
|
||||
// and didn't get one, said in the reader's language
|
||||
var admin *agent.AdminError
|
||||
|
||||
@@ -114,6 +114,16 @@ async function api(path, body, heads, signal) {
|
||||
err.code = data.code;
|
||||
err.message = t("{agent} is signed in to {user} now: sign it in to another of its accounts first (Use on that account), then remove this one", { agent: { codex: "Codex", claude: "Claude Code" }[data.agent] || data.agent, user: data.user });
|
||||
}
|
||||
// a text Import can't add as a routing group (laincatx on X)
|
||||
if (data?.code === "share") {
|
||||
err.code = data.code;
|
||||
err.message = {
|
||||
newer: t("This group was shared from a newer magpie (format {n}): update magpie to import it", { n: data.format }),
|
||||
no_format: t("This shared group says no format it is in: copy it again with Copy to share"),
|
||||
unreadable: t("This shared group can't be read: copy it again with Copy to share"),
|
||||
none_here: t("None of the group's models is in your magpie: {models}", { models: data.models }),
|
||||
}[data.share] || t("This is not a routing group shared from magpie: copy one with Copy to share in a group's menu");
|
||||
}
|
||||
// an agent's npm update whose global folder (Program Files) needs an
|
||||
// administrator, or RTK's winget for every user, the prompt declined or
|
||||
// not to be had (新v学员 on Discord): what to do, in the reader's language
|
||||
|
||||
@@ -1787,6 +1787,22 @@ const I18N = {
|
||||
"A new provider with {name}'s URLs, key, headers, models and balance settings, to change before adding": "新建供应商,沿用 {name} 的地址、Key、请求头、模型和余额设置,添加前可修改",
|
||||
"{name} copy": "{name} 副本",
|
||||
"Duplicated {name}": "已复制 {name}",
|
||||
"Copy to share": "分享为文字",
|
||||
"{name} as text to paste into another magpie: its models, routing and rules, no key": "把 {name} 复制成文字,粘贴到另一个 magpie:带上模型、路由和规则,不带密钥",
|
||||
"{name} copied: paste it into Import on another magpie's Routing page": "已复制 {name}:在另一个 magpie 的路由页点「导入」粘贴即可",
|
||||
"Add a routing group someone shared from their magpie": "添加别人从他们的 magpie 分享的路由组",
|
||||
"Paste a group copied with Copy to share": "粘贴用「分享为文字」复制的路由组",
|
||||
"A routing group shared from magpie": "从 magpie 分享的路由组",
|
||||
"Paste a routing group someone shared from their magpie: its models, routing and rules come with it, never a key": "粘贴别人从 magpie 分享的路由组:模型、路由和规则都会带上,密钥从不随之分享",
|
||||
"Not in your magpie, left out: {models}": "你的 magpie 里没有,已略过:{models}",
|
||||
"The same model from your own provider: {models}": "换成你自己服务商的同一模型:{models}",
|
||||
"1 rule left out with them": "1 条规则随之略过",
|
||||
"{n} rules left out with them": "{n} 条规则随之略过",
|
||||
"This group was shared from a newer magpie (format {n}): update magpie to import it": "这个路由组来自更新版本的 magpie(格式 {n}):请先更新 magpie 再导入",
|
||||
"This shared group says no format it is in: copy it again with Copy to share": "这个分享的路由组没写明格式:请用「分享为文字」重新复制",
|
||||
"This shared group can't be read: copy it again with Copy to share": "这个分享的路由组读不出来:请用「分享为文字」重新复制",
|
||||
"None of the group's models is in your magpie: {models}": "这个路由组的模型在你的 magpie 里一个都没有:{models}",
|
||||
"This is not a routing group shared from magpie: copy one with Copy to share in a group's menu": "这不是从 magpie 分享的路由组:请在路由组的菜单里用「分享为文字」复制",
|
||||
"Hard to strong, easy to cheap": "难题给强模型,简单的给便宜模型",
|
||||
"A hard task goes to the strongest model, an easy one and compaction to a cheap one": "难的任务交给最强的模型,简单的任务和压缩交给便宜模型",
|
||||
"Cheap first": "便宜优先",
|
||||
@@ -6024,6 +6040,22 @@ const I18N = {
|
||||
"A new provider with {name}'s URLs, key, headers, models and balance settings, to change before adding": "新增供應商,沿用 {name} 的位址、Key、請求頭、模型和餘額設定,新增前可修改",
|
||||
"{name} copy": "{name} 副本",
|
||||
"Duplicated {name}": "已複製 {name}",
|
||||
"Copy to share": "分享為文字",
|
||||
"{name} as text to paste into another magpie: its models, routing and rules, no key": "把 {name} 複製成文字,貼到另一個 magpie:帶上模型、路由和規則,不帶金鑰",
|
||||
"{name} copied: paste it into Import on another magpie's Routing page": "已複製 {name}:在另一個 magpie 的路由頁點「匯入」貼上即可",
|
||||
"Add a routing group someone shared from their magpie": "新增別人從他們的 magpie 分享的路由組",
|
||||
"Paste a group copied with Copy to share": "貼上用「分享為文字」複製的路由組",
|
||||
"A routing group shared from magpie": "從 magpie 分享的路由組",
|
||||
"Paste a routing group someone shared from their magpie: its models, routing and rules come with it, never a key": "貼上別人從 magpie 分享的路由組:模型、路由和規則都會帶上,金鑰從不隨之分享",
|
||||
"Not in your magpie, left out: {models}": "你的 magpie 裡沒有,已略過:{models}",
|
||||
"The same model from your own provider: {models}": "換成你自己服務商的同一模型:{models}",
|
||||
"1 rule left out with them": "1 條規則隨之略過",
|
||||
"{n} rules left out with them": "{n} 條規則隨之略過",
|
||||
"This group was shared from a newer magpie (format {n}): update magpie to import it": "這個路由組來自較新版本的 magpie(格式 {n}):請先更新 magpie 再匯入",
|
||||
"This shared group says no format it is in: copy it again with Copy to share": "這個分享的路由組沒寫明格式:請用「分享為文字」重新複製",
|
||||
"This shared group can't be read: copy it again with Copy to share": "這個分享的路由組讀不出來:請用「分享為文字」重新複製",
|
||||
"None of the group's models is in your magpie: {models}": "這個路由組的模型在你的 magpie 裡一個都沒有:{models}",
|
||||
"This is not a routing group shared from magpie: copy one with Copy to share in a group's menu": "這不是從 magpie 分享的路由組:請在路由組的選單裡用「分享為文字」複製",
|
||||
"Hard to strong, easy to cheap": "難題給強模型,簡單的給便宜模型",
|
||||
"A hard task goes to the strongest model, an easy one and compaction to a cheap one": "困難的任務交給最強的模型,簡單的任務和壓縮交給便宜模型",
|
||||
"Cheap first": "便宜優先",
|
||||
@@ -10239,6 +10271,22 @@ const I18N = {
|
||||
"A new provider with {name}'s URLs, key, headers, models and balance settings, to change before adding": "{name} の URL、キー、ヘッダー、モデル、残高設定を引き継いだ新しいプロバイダです。追加前に変更できます",
|
||||
"{name} copy": "{name} のコピー",
|
||||
"Duplicated {name}": "{name} を複製しました",
|
||||
"Copy to share": "共有用にコピー",
|
||||
"{name} as text to paste into another magpie: its models, routing and rules, no key": "{name} を別の magpie に貼り付けるテキストとして:モデル、ルーティング、ルールを含み、キーは含みません",
|
||||
"{name} copied: paste it into Import on another magpie's Routing page": "{name} をコピーしました:別の magpie のルーティングページで「インポート」に貼り付けてください",
|
||||
"Add a routing group someone shared from their magpie": "誰かが自分の magpie から共有したルーティンググループを追加",
|
||||
"Paste a group copied with Copy to share": "「共有用にコピー」でコピーしたグループを貼り付け",
|
||||
"A routing group shared from magpie": "magpie から共有されたルーティンググループ",
|
||||
"Paste a routing group someone shared from their magpie: its models, routing and rules come with it, never a key": "誰かが magpie から共有したルーティンググループを貼り付けます:モデル、ルーティング、ルールが含まれ、キーは決して含まれません",
|
||||
"Not in your magpie, left out: {models}": "この magpie にないため除外:{models}",
|
||||
"The same model from your own provider: {models}": "自分のプロバイダーの同じモデルを使用:{models}",
|
||||
"1 rule left out with them": "1 件のルールも一緒に除外",
|
||||
"{n} rules left out with them": "{n} 件のルールも一緒に除外",
|
||||
"This group was shared from a newer magpie (format {n}): update magpie to import it": "このグループは新しい magpie から共有されました(形式 {n}):インポートするには magpie を更新してください",
|
||||
"This shared group says no format it is in: copy it again with Copy to share": "この共有グループには形式が書かれていません:「共有用にコピー」でもう一度コピーしてください",
|
||||
"This shared group can't be read: copy it again with Copy to share": "この共有グループを読み取れません:「共有用にコピー」でもう一度コピーしてください",
|
||||
"None of the group's models is in your magpie: {models}": "このグループのモデルはどれもこの magpie にありません:{models}",
|
||||
"This is not a routing group shared from magpie: copy one with Copy to share in a group's menu": "magpie から共有されたルーティンググループではありません:グループのメニューの「共有用にコピー」でコピーしてください",
|
||||
"Hard to strong, easy to cheap": "難しい作業は強いモデル、簡単な作業は安いモデルへ",
|
||||
"A hard task goes to the strongest model, an easy one and compaction to a cheap one": "難しいタスクは最強のモデルへ、簡単なタスクと圧縮は安いモデルへ",
|
||||
"Cheap first": "安いモデル優先",
|
||||
@@ -14473,6 +14521,22 @@ const I18N = {
|
||||
"A new provider with {name}'s URLs, key, headers, models and balance settings, to change before adding": "Ein neuer Anbieter mit URLs, Schlüssel, Headern, Modellen und Guthaben-Einstellungen von {name}, vor dem Hinzufügen änderbar",
|
||||
"{name} copy": "{name} Kopie",
|
||||
"Duplicated {name}": "{name} dupliziert",
|
||||
"Copy to share": "Zum Teilen kopieren",
|
||||
"{name} as text to paste into another magpie: its models, routing and rules, no key": "{name} als Text zum Einfügen in ein anderes magpie: Modelle, Routing und Regeln, kein Schlüssel",
|
||||
"{name} copied: paste it into Import on another magpie's Routing page": "{name} kopiert: auf der Routing-Seite eines anderen magpie unter Importieren einfügen",
|
||||
"Add a routing group someone shared from their magpie": "Eine Routing-Gruppe hinzufügen, die jemand aus seinem magpie geteilt hat",
|
||||
"Paste a group copied with Copy to share": "Eine mit „Zum Teilen kopieren“ kopierte Gruppe einfügen",
|
||||
"A routing group shared from magpie": "Eine aus magpie geteilte Routing-Gruppe",
|
||||
"Paste a routing group someone shared from their magpie: its models, routing and rules come with it, never a key": "Eine Routing-Gruppe einfügen, die jemand aus magpie geteilt hat: Modelle, Routing und Regeln kommen mit, nie ein Schlüssel",
|
||||
"Not in your magpie, left out: {models}": "Nicht in deinem magpie, weggelassen: {models}",
|
||||
"The same model from your own provider: {models}": "Dasselbe Modell von deinem eigenen Anbieter: {models}",
|
||||
"1 rule left out with them": "1 Regel mit ihnen weggelassen",
|
||||
"{n} rules left out with them": "{n} Regeln mit ihnen weggelassen",
|
||||
"This group was shared from a newer magpie (format {n}): update magpie to import it": "Diese Gruppe wurde aus einem neueren magpie geteilt (Format {n}): aktualisiere magpie, um sie zu importieren",
|
||||
"This shared group says no format it is in: copy it again with Copy to share": "Diese geteilte Gruppe nennt kein Format: kopiere sie erneut mit „Zum Teilen kopieren“",
|
||||
"This shared group can't be read: copy it again with Copy to share": "Diese geteilte Gruppe ist nicht lesbar: kopiere sie erneut mit „Zum Teilen kopieren“",
|
||||
"None of the group's models is in your magpie: {models}": "Keines der Modelle dieser Gruppe ist in deinem magpie: {models}",
|
||||
"This is not a routing group shared from magpie: copy one with Copy to share in a group's menu": "Das ist keine aus magpie geteilte Routing-Gruppe: kopiere eine mit „Zum Teilen kopieren“ im Menü einer Gruppe",
|
||||
"Hard to strong, easy to cheap": "Schweres zum starken, Leichtes zum günstigen Modell",
|
||||
"A hard task goes to the strongest model, an easy one and compaction to a cheap one": "Eine schwere Aufgabe geht an das stärkste Modell, eine leichte und die Kompaktierung an ein günstiges",
|
||||
"Cheap first": "Günstig zuerst",
|
||||
|
||||
@@ -663,6 +663,14 @@ button.rt-session { cursor: pointer; }
|
||||
added in a click (provider.Templates) */
|
||||
.rt-gtpl { padding: 10px 12px 12px; display: grid; gap: 8px; }
|
||||
.rt-gtpl-head { font-size: 12px; color: var(--muted); }
|
||||
/* Import a group (laincatx on X): the text pasted, then what came of it */
|
||||
.rt-gimport { padding: 10px 12px 12px; display: grid; gap: 8px; min-width: 0; border-bottom: 1px solid var(--line); }
|
||||
.rt-gimport-text { width: 100%; box-sizing: border-box; min-height: 72px; padding: 7px 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font-family: var(--code-font, var(--code)); font-size: 12px; line-height: 1.45; resize: vertical; outline: none; overflow-wrap: anywhere; }
|
||||
.rt-gimport-text:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
|
||||
.rt-gimport .acts { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
|
||||
.rt-gimport-done { font-size: 12.5px; font-weight: 600; }
|
||||
.rt-gimport-missing, .rt-gimport-note { font-size: 12px; line-height: 1.45; color: var(--muted); overflow-wrap: anywhere; }
|
||||
.rt-gimport-missing { color: var(--danger, #d66); }
|
||||
.rt-gtpl-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 8px; }
|
||||
.rt-gtpl-card { display: flex; flex-direction: column; gap: 4px; min-width: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; }
|
||||
.rt-gtpl-card .hd { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
|
||||
@@ -3174,6 +3174,14 @@
|
||||
gQ.autocomplete = "off";
|
||||
gQ.oninput = () => renderGroups();
|
||||
gQ.onkeydown = (e) => { if (e.key === "Escape" && gQ.value) { e.stopPropagation(); gQ.value = ""; renderGroups(); } };
|
||||
// gImport: Import a group's box (laincatx on X): the text pasted, kept
|
||||
// in the page across redraws as gQ is, and what the import added and
|
||||
// left out once it has; null while closed
|
||||
let gImport = null;
|
||||
const gImportText = el("textarea", "rt-gimport-text");
|
||||
gImportText.spellcheck = false;
|
||||
gImportText.rows = 4;
|
||||
gImportText.onkeydown = (e) => { if (e.key === "Escape") { e.stopPropagation(); closeImport(); } };
|
||||
// groupMatches: every word of the filter in the group's name, id, or a
|
||||
// member's id or label (its provider and model names)
|
||||
function groupMatches(g, words) {
|
||||
@@ -3203,6 +3211,12 @@
|
||||
const own = all.some((g) => !g.auto), tpls = groups.templates || [];
|
||||
if (!gSel) {
|
||||
if (own && tpls.length) head.push(templateButton(tpls));
|
||||
const imp = el("button", "text rt-gimportbtn", t("Import"));
|
||||
imp.type = "button";
|
||||
imp.title = t("Add a routing group someone shared from their magpie");
|
||||
imp.setAttribute("aria-expanded", gImport ? "true" : "false");
|
||||
imp.onclick = () => gImport ? closeImport() : openImport();
|
||||
head.push(imp);
|
||||
// several removed at once: pick them, then Remove
|
||||
if (all.length > 1) {
|
||||
const pick = el("button", "text rt-gselect", t("Select"));
|
||||
@@ -3223,6 +3237,7 @@
|
||||
const rows = [];
|
||||
if (!gSel && !own && !words.length && tpls.length) rows.push(templateCards(tpls));
|
||||
if (gSel) rows.push(selectBar(shown));
|
||||
if (gImport && !gSel) rows.push(importBox());
|
||||
if (gEdit && !gEdit.id) rows.push(groupEditor(null));
|
||||
for (const g of shown) rows.push(gSel ? pickedRow(g) : gEdit?.id === g.id ? groupEditor(g) : groupRow(g));
|
||||
if (!rows.length && all.length) rows.push(el("div", "none rt-gnone", t("No group or model matches “{q}”", { q: gQ.value.trim() })));
|
||||
@@ -3250,9 +3265,78 @@
|
||||
h.append(b);
|
||||
rows.push(h);
|
||||
}
|
||||
gList.replaceChildren(...rows);
|
||||
// the import box's text stays in the page as the list is drawn again
|
||||
replaceKeeping(gList, rows);
|
||||
renderPools();
|
||||
}
|
||||
// Copy to share (laincatx on X): the group as text, its models, routing
|
||||
// and rules and no key (provider.ShareGroup), for anyone to paste into
|
||||
// their magpie's Import
|
||||
async function shareGroup(g) {
|
||||
try {
|
||||
const st = await api("groups/share", { id: g.id });
|
||||
await copy(st.shared, g.name, null, t("{name} copied: paste it into Import on another magpie's Routing page", { name: g.name }));
|
||||
} catch (e) { status(e.message, "err"); }
|
||||
}
|
||||
async function openImport() {
|
||||
if (groupDirty() && !(await confirmDiscard())) return;
|
||||
gEdit = null; gSel = null;
|
||||
gImport = {};
|
||||
gImportText.value = "";
|
||||
renderGroups();
|
||||
gImportText.focus({ preventScroll: true });
|
||||
}
|
||||
function closeImport() {
|
||||
gImport = null;
|
||||
gImportText.value = "";
|
||||
renderGroups();
|
||||
}
|
||||
// importBox: paste a shared group, Import adds it; then what was added,
|
||||
// and what of it this magpie has none of, until Done
|
||||
let gImportBox = null;
|
||||
function importBox() {
|
||||
gImportBox ||= el("div", "rt-gimport");
|
||||
const box = gImportBox, res = gImport.res;
|
||||
const parts = [];
|
||||
if (!res) {
|
||||
gImportText.placeholder = t("Paste a group copied with Copy to share");
|
||||
gImportText.setAttribute("aria-label", t("A routing group shared from magpie"));
|
||||
const go = el("button", "text primary rt-gimport-go", t("Import"));
|
||||
go.type = "button";
|
||||
go.onclick = async () => {
|
||||
const text = gImportText.value;
|
||||
if (!text.trim()) { gImportText.focus({ preventScroll: true }); return; }
|
||||
go.disabled = true;
|
||||
try {
|
||||
groups = await api("groups/import", { text });
|
||||
gImport = { res: groups.imported };
|
||||
gImportText.value = "";
|
||||
status(t("Added {name}", { name: groups.imported.name }), "ok");
|
||||
renderGroups();
|
||||
load(); // the gateway's model list, the agents' pickers
|
||||
} catch (e) { go.disabled = false; status(e.message, "err"); }
|
||||
};
|
||||
const no = el("button", "text", t("Cancel"));
|
||||
no.type = "button";
|
||||
no.onclick = closeImport;
|
||||
const acts = el("div", "acts");
|
||||
acts.append(go, no);
|
||||
parts.push(el("div", "rt-gtpl-head", t("Paste a routing group someone shared from their magpie: its models, routing and rules come with it, never a key")), gImportText, acts);
|
||||
} else {
|
||||
parts.push(el("div", "rt-gimport-done", t("Added {name}", { name: res.name })));
|
||||
if (res.missing?.length) parts.push(el("div", "rt-gimport-missing", t("Not in your magpie, left out: {models}", { models: res.missing.join(", ") })));
|
||||
if (res.instead?.length) parts.push(el("div", "rt-gimport-note", t("The same model from your own provider: {models}", { models: res.instead.join(", ") })));
|
||||
if (res.rules) parts.push(el("div", "rt-gimport-note", t(res.rules === 1 ? "1 rule left out with them" : "{n} rules left out with them", { n: res.rules })));
|
||||
const done = el("button", "text", t("Done"));
|
||||
done.type = "button";
|
||||
done.onclick = closeImport;
|
||||
const acts = el("div", "acts");
|
||||
acts.append(done);
|
||||
parts.push(acts);
|
||||
}
|
||||
replaceKeeping(box, parts);
|
||||
return box;
|
||||
}
|
||||
// a template's name and what it does, in the user's language
|
||||
// (provider.TemplateNames)
|
||||
const TPL = {
|
||||
@@ -3553,6 +3637,9 @@
|
||||
// change without touching the one agents use (lc on Discord)
|
||||
{ name: "Duplicate", icon: COPY_ICON, sep: true, tip: t("A copy of {name} with its models, routing and rules, listed after it", { name: g.name }),
|
||||
run: async () => { if (!groupDirty() || await confirmDiscard()) groupAction("copy", { id: g.id, name: t("{name} copy", { name: g.name }) }, t("Duplicated {name}", { name: g.name })); } },
|
||||
// the group as text for someone else's magpie (laincatx on X)
|
||||
{ name: "Copy to share", icon: OUT, tip: t("{name} as text to paste into another magpie: its models, routing and rules, no key", { name: g.name }),
|
||||
run: () => shareGroup(g) },
|
||||
]);
|
||||
}
|
||||
// nextTo: where a group moved one up (-1) or down goes, among them all:
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// laincatx on X: the Routing view's Copy to share answers the group as
|
||||
// text with no key in it, and Import a group adds it back as a group of
|
||||
// the user's, saying what it left out; text that is no shared group is
|
||||
// refused in words.
|
||||
func TestGroupShareAndImport(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())
|
||||
const key = "sk-gui-share-secret-42"
|
||||
if err := provider.Save(provider.Provider{ID: "a", Name: "a", Key: key, Chat: "http://127.0.0.1:1/v1", Models: []string{"m1", "m2"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{ID: "duo", Name: "Duo", Members: []string{"a/m1", "a/m2"}, Routing: provider.Ordered,
|
||||
Rules: []provider.Rule{{Use: "a/m2", Compact: true}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
groupRoutes(mux)
|
||||
post := func(action string, body any) (int, groupsJSON, string) {
|
||||
raw, _ := json.Marshal(body)
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/groups/"+action, strings.NewReader(string(raw))))
|
||||
var st groupsJSON
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &st)
|
||||
return w.Code, st, w.Body.String()
|
||||
}
|
||||
|
||||
code, st, body := post("share", map[string]string{"id": "duo"})
|
||||
if code != 200 || !strings.Contains(st.Shared, `"routing-group"`) {
|
||||
t.Fatalf("share: %d %s", code, body)
|
||||
}
|
||||
if strings.Contains(st.Shared, key) {
|
||||
t.Fatalf("the shared text has the provider's key: %s", st.Shared)
|
||||
}
|
||||
|
||||
// the same text with a member this magpie has no provider of
|
||||
shared := strings.Replace(st.Shared, `"members":["a/m1","a/m2"]`, `"members":["a/m1","a/m2","gone/m9"]`, 1)
|
||||
if shared == st.Shared {
|
||||
t.Fatalf("the members aren't spelt as expected: %s", st.Shared)
|
||||
}
|
||||
code, st, body = post("import", map[string]string{"text": shared})
|
||||
if code != 200 || st.Imported == nil || st.Imported.ID != "duo-2" || strings.Join(st.Imported.Missing, ",") != "gone/m9" {
|
||||
t.Fatalf("import: %d %s", code, body)
|
||||
}
|
||||
g, _, ok := provider.FindGroup("group/duo-2")
|
||||
if !ok || strings.Join(g.Members, ",") != "a/m1,a/m2" || len(g.Rules) != 1 {
|
||||
t.Fatalf("imported %+v", g)
|
||||
}
|
||||
if !strings.Contains(body, `"duo-2"`) {
|
||||
t.Fatalf("the answer doesn't list the group added: %s", body)
|
||||
}
|
||||
|
||||
// why, for the page to say in the reader's language
|
||||
if code, _, body = post("import", map[string]string{"text": "a group, honest"}); code == 200 || !strings.Contains(body, "not a routing group shared from magpie") ||
|
||||
!strings.Contains(body, `"share":"not_shared"`) {
|
||||
t.Fatalf("bad text: %d %s", code, body)
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -29,6 +29,12 @@ type groupsJSON struct {
|
||||
// Templates: groups for common needs made of the user's own models,
|
||||
// which the page adds in a click (provider.Templates)
|
||||
Templates []provider.Template `json:"templates"`
|
||||
// Shared: share's answer, the group as text to paste into another
|
||||
// magpie (provider.ShareGroup)
|
||||
Shared string `json:"shared,omitempty"`
|
||||
// Imported: import's answer, the group added and what of the text
|
||||
// this magpie has none of (provider.ImportGroup)
|
||||
Imported *provider.Imported `json:"imported,omitempty"`
|
||||
}
|
||||
|
||||
type groupJSON struct {
|
||||
@@ -300,6 +306,8 @@ func groupRoutes(mux *http.ServeMux) {
|
||||
// template: which one, saved under the group's name
|
||||
// (provider.AddTemplate)
|
||||
Kind string `json:"kind"`
|
||||
// import: a group shared as text (provider.ShareGroup)
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
fail(rw, err)
|
||||
@@ -308,6 +316,8 @@ func groupRoutes(mux *http.ServeMux) {
|
||||
in := body.Group
|
||||
var err error
|
||||
var moved []agent.Move
|
||||
var shared string
|
||||
var imported *provider.Imported
|
||||
switch r.PathValue("action") {
|
||||
case "found":
|
||||
// off, an agent set to a found group is moved to its model
|
||||
@@ -339,6 +349,14 @@ func groupRoutes(mux *http.ServeMux) {
|
||||
case "copy":
|
||||
// a group as it is, under name (provider.CopyGroup)
|
||||
_, err = provider.CopyGroup(in.ID, in.Name)
|
||||
case "share":
|
||||
// the group as text for another magpie: no key goes with it
|
||||
shared, err = provider.ShareGroup(in.ID)
|
||||
case "import":
|
||||
var res provider.Imported
|
||||
if res, err = provider.ImportGroup(body.Text); err == nil {
|
||||
imported = &res
|
||||
}
|
||||
case "template":
|
||||
_, err = provider.AddTemplate(body.Kind, in.Name)
|
||||
case "switch":
|
||||
@@ -355,7 +373,7 @@ func groupRoutes(mux *http.ServeMux) {
|
||||
return
|
||||
}
|
||||
st := groupsState()
|
||||
st.Moved = moved
|
||||
st.Moved, st.Shared, st.Imported = moved, shared, imported
|
||||
writeJSON(rw, st)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// laincatx on X: a routing group is shared as text. Its row's menu has
|
||||
// Copy to share, which asks groups/share for the group's text and copies
|
||||
// it; Import by New group opens a box the text is pasted into, which posts
|
||||
// groups/import and says what was added, what of it the user has none of,
|
||||
// what came from their own provider instead and how many rules went with
|
||||
// them, until Done. The text typed stays in the box as the list is drawn
|
||||
// again. A text that is no shared group is refused in the reader's
|
||||
// language. No click moves the page. At 420px, in every language,
|
||||
// Chromium and WebKit.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const models = [
|
||||
{ id: "a/m", name: "m", providerName: "A", icon: "generic" },
|
||||
{ id: "a/x", name: "x", providerName: "A", icon: "generic" },
|
||||
];
|
||||
const info = (ids) => ids.map((id) => ({ id, ready: true }));
|
||||
const group = (id, name, members, more = {}) => ({ id, name, members, ready: true, memberInfo: info(members), ...more });
|
||||
|
||||
const words = {
|
||||
en: { share: "Copy to share", copied: "One copied", imp: "Import", added: "Added One 2", missing: "Not in your magpie, left out: gone/y", instead: "The same model from your own provider: relay/x → a/x", rules: "2 rules left out with them", bad: "This is not a routing group shared from magpie", done: "Done" },
|
||||
zh: { share: "分享为文字", copied: "已复制 One", imp: "导入", added: "已添加 One 2", missing: "你的 magpie 里没有,已略过:gone/y", instead: "换成你自己服务商的同一模型:relay/x → a/x", rules: "2 条规则随之略过", bad: "这不是从 magpie 分享的路由组", done: "完成" },
|
||||
"zh-TW": { share: "分享為文字", copied: "已複製 One", imp: "匯入", added: "已新增 One 2", missing: "你的 magpie 裡沒有,已略過:gone/y", instead: "換成你自己服務商的同一模型:relay/x → a/x", rules: "2 條規則隨之略過", bad: "這不是從 magpie 分享的路由組", done: "完成" },
|
||||
ja: { share: "共有用にコピー", copied: "One をコピーしました", imp: "インポート", added: "One 2", missing: "この magpie にないため除外:gone/y", instead: "自分のプロバイダーの同じモデルを使用:relay/x → a/x", rules: "2 件のルールも一緒に除外", bad: "magpie から共有されたルーティンググループではありません", done: "完了" },
|
||||
de: { share: "Zum Teilen kopieren", copied: "One kopiert", imp: "Importieren", added: "One 2", missing: "Nicht in deinem magpie, weggelassen: gone/y", instead: "Dasselbe Modell von deinem eigenen Anbieter: relay/x → a/x", rules: "2 Regeln mit ihnen weggelassen", bad: "Das ist keine aus magpie geteilte Routing-Gruppe", done: "Fertig" },
|
||||
};
|
||||
const KEYS = ["Copy to share", "{name} as text to paste into another magpie: its models, routing and rules, no key",
|
||||
"{name} copied: paste it into Import on another magpie's Routing page", "Add a routing group someone shared from their magpie",
|
||||
"Paste a group copied with Copy to share", "A routing group shared from magpie",
|
||||
"Paste a routing group someone shared from their magpie: its models, routing and rules come with it, never a key",
|
||||
"Not in your magpie, left out: {models}", "The same model from your own provider: {models}", "1 rule left out with them",
|
||||
"{n} rules left out with them", "This group was shared from a newer magpie (format {n}): update magpie to import it",
|
||||
"This shared group says no format it is in: copy it again with Copy to share", "This shared group can't be read: copy it again with Copy to share",
|
||||
"None of the group's models is in your magpie: {models}",
|
||||
"This is not a routing group shared from magpie: copy one with Copy to share in a group's menu", "Import", "Added {name}", "Done", "Cancel"];
|
||||
const SHARED = '{"magpie":"routing-group","version":1,"group":{"name":"One","members":["a/x","a/m"]}}';
|
||||
|
||||
function serve(lang, posts) {
|
||||
let list = [
|
||||
group("one", "One", ["a/x", "a/m"], { routing: "order", rules: [{ use: "a/m", agents: ["codex"] }] }),
|
||||
group("two", "Two", ["a/m"]),
|
||||
];
|
||||
const groups = () => ({ models, pools: [], deciders: [], found: true, groups: list });
|
||||
const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
const json = (data) => r.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) return new Promise(() => {});
|
||||
return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json(groups());
|
||||
if (url.pathname === "/api/groups/share") {
|
||||
posts.push(["share", JSON.parse(r.request().postData() || "{}")]);
|
||||
return json({ ...groups(), shared: SHARED });
|
||||
}
|
||||
if (url.pathname === "/api/copy") {
|
||||
posts.push(["copy", JSON.parse(r.request().postData() || "{}").text]);
|
||||
return json({});
|
||||
}
|
||||
if (url.pathname === "/api/groups/import") {
|
||||
const { text } = JSON.parse(r.request().postData() || "{}");
|
||||
posts.push(["import", text]);
|
||||
if (!text.includes("routing-group")) return r.fulfill({ status: 400, json: { error: "this is not a routing group shared from magpie", code: "share", share: "not_shared", format: "0", models: "" } });
|
||||
list = [...list, group("one-2", "One 2", ["a/x"])];
|
||||
return json({ ...groups(), imported: { id: "one-2", name: "One 2", missing: ["gone/y"], instead: ["relay/x → a/x"], rules: 2 } });
|
||||
}
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await r.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const listed = (page) => page.locator(".rt-groups > .rt-group").evaluateAll((rs) => rs.map((r) => r.dataset.id));
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang}: a routing group is copied to share and imported`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width: 420, height: 1800 }, reducedMotion: "reduce" })).newPage();
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-group-share.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posts = [];
|
||||
// WebKit reports a ResizeObserver round left to the next frame as a
|
||||
// page error; see group-duplicate.test.cjs
|
||||
page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); });
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
await page.locator(".rt-groups > .rt-group").nth(1).waitFor();
|
||||
// tall enough that the import box is in view unscrolled in every
|
||||
// language: a scroll closes the menu, and the page settles its own
|
||||
// scroll as it loads
|
||||
await page.waitForTimeout(500);
|
||||
const at = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => [e.id || e.className, e.scrollTop]).join(";") + "|" + scrollX);
|
||||
const before = await at();
|
||||
const status = (m) => page.waitForFunction((m) => document.querySelector("#status").textContent.includes(m), m);
|
||||
|
||||
// Copy to share: the group's text, copied
|
||||
await page.locator(".rt-group[data-id=one] .main").click({ button: "right" });
|
||||
const menu = page.locator(".row-menu");
|
||||
await menu.waitFor();
|
||||
const box = await menu.boundingBox();
|
||||
assert(box.x >= 0 && box.x + box.width <= 420, `menu off the window: ${JSON.stringify(box)}`);
|
||||
await menu.getByRole("menuitem", { name: w.share, exact: true }).click();
|
||||
await status(w.copied);
|
||||
assert.deepEqual(posts, [["share", { id: "one" }], ["copy", SHARED]]);
|
||||
assert.equal(await page.locator(".rt-gedit").count(), 0, "sharing opened the editor");
|
||||
posts.length = 0;
|
||||
|
||||
// Import: a box the text is pasted into, kept as the list is redrawn
|
||||
const imp = page.locator(".rt-gimportbtn");
|
||||
assert.equal((await imp.textContent()).trim(), w.imp);
|
||||
await imp.click();
|
||||
const text = page.locator(".rt-gimport-text");
|
||||
await text.waitFor();
|
||||
const ib = await page.locator(".rt-gimport").boundingBox();
|
||||
assert(ib.x >= 0 && ib.x + ib.width <= 420, `import box off the window: ${JSON.stringify(ib)}`);
|
||||
await text.fill("a group, honest");
|
||||
await page.locator(".rt-gfilter").fill("o");
|
||||
await page.locator(".rt-gfilter").fill("");
|
||||
assert.equal(await text.inputValue(), "a group, honest", "the redraw lost the text");
|
||||
await page.locator(".rt-gimport-go").click();
|
||||
await status(w.bad);
|
||||
assert.equal(await page.locator(".rt-gimport-text").count(), 1, "a refused text closed the box");
|
||||
|
||||
await text.fill("```\n" + SHARED + "\n```");
|
||||
await page.locator(".rt-gimport-go").click();
|
||||
await page.locator(".rt-gimport-done").waitFor();
|
||||
assert((await page.locator(".rt-gimport-done").textContent()).includes(w.added));
|
||||
assert.equal(await page.locator(".rt-gimport-missing").textContent(), w.missing);
|
||||
const notes = await page.locator(".rt-gimport-note").allTextContents();
|
||||
assert.deepEqual(notes, [w.instead, w.rules]);
|
||||
assert.deepEqual(await listed(page), ["one", "two", "one-2"]);
|
||||
assert.equal(posts[1][1], "```\n" + SHARED + "\n```");
|
||||
await page.locator(".rt-gimport").getByRole("button", { name: w.done, exact: true }).click();
|
||||
assert.equal(await page.locator(".rt-gimport").count(), 0, "Done left the box");
|
||||
|
||||
assert.equal(await at(), before, "a click moved the page");
|
||||
if (lang !== "en") {
|
||||
const missing = await page.evaluate(([l, ks]) => ks.filter((k) => !I18N[l][k]), [lang, KEYS]);
|
||||
assert.deepEqual(missing, [], `every string has its ${lang}`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A routing group shared as text (laincatx on X): one group's routing,
|
||||
// rules and members, copied from one magpie and pasted into another. It
|
||||
// says what it is (ShareMark) and in which format (ShareVersion), so a
|
||||
// magpie can tell it from any other text and one made by a newer magpie
|
||||
// from one it can read.
|
||||
const (
|
||||
ShareMark = "routing-group"
|
||||
ShareVersion = 1
|
||||
)
|
||||
|
||||
// SharedGroup is the text a group is shared as.
|
||||
type SharedGroup struct {
|
||||
Magpie string `json:"magpie"`
|
||||
Version int `json:"version"`
|
||||
Group Group `json:"group"`
|
||||
}
|
||||
|
||||
// ShareGroup is group id as text to paste into another magpie: its
|
||||
// members as it names them, its patterns, routing, rules, classifier,
|
||||
// effort, context, levels, fast and off members. A group holds no key or
|
||||
// account of its own, only provider/model ids, so nothing secret goes with
|
||||
// it; what is derived (the models its patterns match now, found, hidden,
|
||||
// switched off) stays behind.
|
||||
func ShareGroup(id string) (string, error) {
|
||||
all := Groups()
|
||||
i := slices.IndexFunc(all, func(g Group) bool { return g.ID == id && !g.Hidden })
|
||||
if i < 0 {
|
||||
return "", fmt.Errorf("no group %q", id)
|
||||
}
|
||||
// a copy shares nothing with the group read: the rules' time windows
|
||||
// are pointers
|
||||
raw, err := json.Marshal(all[i])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var g Group
|
||||
if err := json.Unmarshal(raw, &g); err != nil {
|
||||
return "", err
|
||||
}
|
||||
g.Members, g.Match = ownMembers(g)
|
||||
g.Matched = nil
|
||||
g.Auto, g.Hidden, g.Disabled = false, false, false
|
||||
out, err := json.Marshal(SharedGroup{Magpie: ShareMark, Version: ShareVersion, Group: g})
|
||||
return string(out), err
|
||||
}
|
||||
|
||||
// ShareError is why a text can't be imported as a group, by Why, for the
|
||||
// GUI to say in the reader's language: "not_shared" (no group shared from
|
||||
// magpie), "newer" (a format past ShareVersion, in Format), "no_format",
|
||||
// "unreadable" (Err), "none_here" (none of its models here, in Models).
|
||||
type ShareError struct {
|
||||
Why string
|
||||
Format int
|
||||
Models []string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *ShareError) Error() string {
|
||||
switch e.Why {
|
||||
case "newer":
|
||||
return fmt.Sprintf("this group was shared from a newer magpie (format %d): update magpie to import it", e.Format)
|
||||
case "no_format":
|
||||
return "this shared group says no format it is in: copy it again with Copy to share"
|
||||
case "unreadable":
|
||||
return fmt.Sprintf("this shared group can't be read: %v", e.Err)
|
||||
case "none_here":
|
||||
return "none of the group's models is in your magpie: " + strings.Join(e.Models, ", ")
|
||||
}
|
||||
return "this is not a routing group shared from magpie: copy one with Copy to share in a group's menu"
|
||||
}
|
||||
|
||||
func (e *ShareError) Unwrap() error { return e.Err }
|
||||
|
||||
// Imported is what ImportGroup made of a shared group.
|
||||
type Imported struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
// Missing are the models and groups the text names that this magpie
|
||||
// has none of, left out of the group: members, and the classifier.
|
||||
Missing []string `json:"missing,omitempty"`
|
||||
// Instead are the members this magpie has under another provider: the
|
||||
// same model (AutoGroupOf), "shared → here".
|
||||
Instead []string `json:"instead,omitempty"`
|
||||
// Rules is how many of the group's rules were left out with the
|
||||
// member they send to, or the classifier their intent needs.
|
||||
Rules int `json:"rules,omitempty"`
|
||||
}
|
||||
|
||||
// ReadShared reads a shared group's text, as copied or pasted from a chat:
|
||||
// the object may have words or a code fence around it.
|
||||
func ReadShared(text string) (SharedGroup, error) {
|
||||
var s SharedGroup
|
||||
start, end := strings.Index(text, "{"), strings.LastIndex(text, "}")
|
||||
notOne := &ShareError{Why: "not_shared"}
|
||||
if start < 0 || end < start {
|
||||
return s, notOne
|
||||
}
|
||||
var probe struct {
|
||||
Magpie string `json:"magpie"`
|
||||
Version int `json:"version"`
|
||||
Group json.RawMessage `json:"group"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(text[start:end+1]), &probe); err != nil || probe.Magpie != ShareMark {
|
||||
return s, notOne
|
||||
}
|
||||
switch {
|
||||
case probe.Version > ShareVersion:
|
||||
return s, &ShareError{Why: "newer", Format: probe.Version}
|
||||
case probe.Version < 1:
|
||||
return s, &ShareError{Why: "no_format"}
|
||||
}
|
||||
if err := json.Unmarshal(probe.Group, &s.Group); err != nil {
|
||||
return s, &ShareError{Why: "unreadable", Err: err}
|
||||
}
|
||||
s.Magpie, s.Version = probe.Magpie, probe.Version
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// ImportGroup adds the group a shared text holds as a group of the
|
||||
// user's, named as it was shared and numbered past a name or id in use,
|
||||
// so it never replaces a group there is. It is listed last. A member this
|
||||
// magpie has no provider of is the same model under one it has, where it
|
||||
// serves it (Instead), else left out (Missing), and with it the rules that
|
||||
// send to it and its place among the fast and off members. Nothing is
|
||||
// added when none of its members is left.
|
||||
func ImportGroup(text string) (Imported, error) {
|
||||
s, err := ReadShared(text)
|
||||
if err != nil {
|
||||
return Imported{}, err
|
||||
}
|
||||
g := s.Group
|
||||
entries := providerEntries()
|
||||
all := Groups()
|
||||
var res Imported
|
||||
// what each member the text names is here: itself, another provider's
|
||||
// same model, or "" for none
|
||||
here := map[string]string{}
|
||||
place := func(m string) string {
|
||||
m = strings.TrimSpace(m)
|
||||
if to, ok := here[m]; ok {
|
||||
return to
|
||||
}
|
||||
to := memberHere(entries, all, m)
|
||||
here[m] = to
|
||||
switch {
|
||||
case to == "":
|
||||
res.Missing = append(res.Missing, m)
|
||||
case to != m:
|
||||
res.Instead = append(res.Instead, m+" → "+to)
|
||||
}
|
||||
return to
|
||||
}
|
||||
members, match := ownMembers(g)
|
||||
g.Members = nil
|
||||
for _, m := range members {
|
||||
if to := place(m); to != "" && !slices.Contains(g.Members, to) {
|
||||
g.Members = append(g.Members, to)
|
||||
}
|
||||
}
|
||||
g.Match, g.Matched = match, nil
|
||||
if len(g.Members) == 0 && len(g.Match) == 0 {
|
||||
return res, &ShareError{Why: "none_here", Models: res.Missing}
|
||||
}
|
||||
kept := func(list []string) []string {
|
||||
var out []string
|
||||
for _, m := range list {
|
||||
if to := here[strings.TrimSpace(m)]; to != "" && !slices.Contains(out, to) {
|
||||
out = append(out, to)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
g.Off, g.Fast = kept(g.Off), slices.DeleteFunc(kept(g.Fast), func(f string) bool {
|
||||
// the same model under another provider may have no fast mode
|
||||
model, _ := memberEffortIn(entries, f)
|
||||
p, id, ok := resolveIn(entries, model)
|
||||
return ok && !CanFast(p, id)
|
||||
})
|
||||
if g.Routing != Manual && len(g.Off) == len(g.Members) {
|
||||
g.Off = nil // the ones it sent to are gone: those left are on
|
||||
}
|
||||
g.Pick = here[strings.TrimSpace(g.Pick)]
|
||||
if c := strings.TrimSpace(g.Classifier); c != "" {
|
||||
if g.Classifier = place(c); g.Classifier == GroupPrefix+g.ID {
|
||||
g.Classifier = ""
|
||||
}
|
||||
}
|
||||
// a rule sends to a model the group names, or one its patterns match
|
||||
// here
|
||||
in := append(slices.Clone(g.Members), matchesIn(entries, g)...)
|
||||
var rules []Rule
|
||||
for _, r := range g.Rules {
|
||||
use := here[strings.TrimSpace(r.Use)]
|
||||
if _, named := here[strings.TrimSpace(r.Use)]; !named && !IsPattern(r.Use) {
|
||||
// a rule may send to a model a pattern matches: one this
|
||||
// magpie has, or none
|
||||
use = memberHere(entries, all, r.Use)
|
||||
}
|
||||
if use == "" || !slices.Contains(in, use) || (r.Intent != "" && g.Classifier == "") {
|
||||
res.Rules++
|
||||
continue
|
||||
}
|
||||
r.Use = use
|
||||
rules = append(rules, r)
|
||||
}
|
||||
g.Rules = rules
|
||||
if g.Classifier == "" {
|
||||
g.Effort = "" // nothing to rate a turn with
|
||||
}
|
||||
name := strings.TrimSpace(g.Name)
|
||||
if name == "" {
|
||||
name = "Shared group"
|
||||
}
|
||||
g.Name, g.ID = freeGroupName(all, name, "")
|
||||
g.Auto, g.Hidden, g.Disabled = false, false, false
|
||||
if err := SaveGroup(g); err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.ID, res.Name = g.ID, g.Name
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// memberHere is what member m of a shared group is in this magpie: m
|
||||
// itself when it has the provider (or the group), else the same model
|
||||
// (AutoGroupOf) under the first provider here that serves it, in the
|
||||
// Providers order; "" when none does. A member's own effort goes with it.
|
||||
func memberHere(entries []Entry, all []Group, m string) string {
|
||||
m = strings.TrimPrefix(strings.TrimSpace(m), "magpie/")
|
||||
model, effort := memberEffortIn(entries, m)
|
||||
if gid, ok := strings.CutPrefix(model, GroupPrefix); ok {
|
||||
if slices.ContainsFunc(all, func(g Group) bool { return g.ID == gid && !g.Hidden }) {
|
||||
return m
|
||||
}
|
||||
return ""
|
||||
}
|
||||
pid, id, ok := strings.Cut(model, "/")
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if _, err := Find(pid); err == nil || isModel(entries, model) {
|
||||
return m
|
||||
}
|
||||
same := AutoGroupOf(pid, id)
|
||||
for _, e := range entries {
|
||||
if e.Group == "" && AutoGroupOf(e.Provider.ID, e.Model) == same {
|
||||
return WithMemberEffort(e.ID, effort)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func shareHome(t *testing.T, ps ...Provider) {
|
||||
t.Helper()
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", t.TempDir())
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
for _, p := range ps {
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sharedAt(t *testing.T, id string) Group {
|
||||
t.Helper()
|
||||
g, _, ok := FindGroup(GroupPrefix + id)
|
||||
if !ok {
|
||||
t.Fatalf("no group %q", id)
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
// laincatx on X: a routing group is shared as text and pasted into
|
||||
// another magpie. What goes is the group's routing, rules and members,
|
||||
// never a key; pasted back, it is the same group under a name of its own.
|
||||
func TestSharedGroupRoundTrip(t *testing.T) {
|
||||
const secret = "sk-shared-secret-0123456789"
|
||||
shareHome(t,
|
||||
Provider{ID: "a", Name: "A", Key: secret, Chat: "http://127.0.0.1:1/v1", Models: []string{"x", "small"}},
|
||||
Provider{ID: "b", Name: "B", Key: secret + "-b", Chat: "http://127.0.0.1:1/v1", Models: []string{"x"}},
|
||||
)
|
||||
g := Group{Name: "Smart", Members: []string{"a/x:high", "b/x", "a/small"}, Routing: Ordered, Affinity: "session",
|
||||
Patience: 90, Off: []string{"b/x"}, Classifier: "a/small", Levels: []string{"low", "high"},
|
||||
Rules: []Rule{
|
||||
{Use: "a/small", Compact: true},
|
||||
{Use: "a/small", Intent: "a quick question"},
|
||||
{Use: "a/x:high", Tokens: 50000, Agents: []string{"codex"}},
|
||||
{Use: "b/x", Time: &TimeWindow{From: "22:00", To: "08:00", Days: []string{"fri"}}},
|
||||
}}
|
||||
if err := SaveGroup(g); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text, err := ShareGroup("smart")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(text, secret) || strings.Contains(text, "127.0.0.1") {
|
||||
t.Fatalf("the shared text carries a provider's key or address: %s", text)
|
||||
}
|
||||
if !strings.Contains(text, `"magpie":"routing-group"`) || !strings.Contains(text, `"version":1`) {
|
||||
t.Fatalf("the shared text doesn't say what it is: %s", text)
|
||||
}
|
||||
|
||||
// pasted from a chat, with words and a code fence around it
|
||||
res, err := ImportGroup("here's mine:\n```json\n" + text + "\n```\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.ID != "smart-2" || res.Name != "Smart 2" || len(res.Missing) != 0 || len(res.Instead) != 0 || res.Rules != 0 {
|
||||
t.Fatalf("imported %+v, want Smart 2 whole", res)
|
||||
}
|
||||
src, got := sharedAt(t, "smart"), sharedAt(t, "smart-2")
|
||||
if !slices.Equal(got.Members, src.Members) || !slices.Equal(got.Off, src.Off) || !slices.Equal(got.Levels, src.Levels) ||
|
||||
got.Routing != src.Routing || got.Affinity != src.Affinity || got.Patience != src.Patience || got.Classifier != src.Classifier {
|
||||
t.Fatalf("imported %+v\nfrom %+v", got, src)
|
||||
}
|
||||
a, _ := json.Marshal(src.Rules)
|
||||
b, _ := json.Marshal(got.Rules)
|
||||
if string(a) != string(b) {
|
||||
t.Fatalf("rules %s, want %s", b, a)
|
||||
}
|
||||
// the one shared is left as it was
|
||||
if len(Groups()) < 2 || sharedAt(t, "smart").Name != "Smart" {
|
||||
t.Fatal("the shared group changed")
|
||||
}
|
||||
}
|
||||
|
||||
// A member whose provider the importer doesn't have is the same model
|
||||
// under one they have, else left out and named, with the rules that send
|
||||
// to it; a rule by intent goes when its classifier does.
|
||||
func TestSharedGroupMissingMembers(t *testing.T) {
|
||||
shareHome(t, Provider{ID: "mine", Name: "Mine", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"x"}})
|
||||
text, _ := json.Marshal(SharedGroup{Magpie: ShareMark, Version: ShareVersion, Group: Group{
|
||||
ID: "theirs", Name: "Theirs", Members: []string{"relay/x", "gone/y", "group/nested"}, Routing: Ordered,
|
||||
Off: []string{"gone/y"}, Classifier: "gone/judge",
|
||||
Rules: []Rule{
|
||||
{Use: "gone/y", Tokens: 1000},
|
||||
{Use: "relay/x", Agents: []string{"claude"}},
|
||||
{Use: "relay/x", Intent: "hard"},
|
||||
},
|
||||
}})
|
||||
res, err := ImportGroup(string(text))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := []string{"gone/y", "group/nested", "gone/judge"}; !slices.Equal(res.Missing, want) {
|
||||
t.Errorf("missing %v, want %v", res.Missing, want)
|
||||
}
|
||||
if want := []string{"relay/x → mine/x"}; !slices.Equal(res.Instead, want) {
|
||||
t.Errorf("instead %v, want %v", res.Instead, want)
|
||||
}
|
||||
if res.Rules != 2 {
|
||||
t.Errorf("rules left out %d, want 2: the one to gone/y and the one by intent", res.Rules)
|
||||
}
|
||||
g := sharedAt(t, res.ID)
|
||||
if !slices.Equal(g.Members, []string{"mine/x"}) || len(g.Off) != 0 || g.Classifier != "" || len(g.Rules) != 1 || g.Rules[0].Use != "mine/x" {
|
||||
t.Fatalf("imported %+v", g)
|
||||
}
|
||||
|
||||
// nothing of it here: nothing is added, and the reader is told why
|
||||
none, _ := json.Marshal(SharedGroup{Magpie: ShareMark, Version: ShareVersion, Group: Group{Name: "N", Members: []string{"gone/y"}}})
|
||||
n := len(Groups())
|
||||
if _, err := ImportGroup(string(none)); err == nil || !strings.Contains(err.Error(), "gone/y") {
|
||||
t.Fatalf("none here: %v", err)
|
||||
}
|
||||
if len(Groups()) != n {
|
||||
t.Fatal("a group was added with none of its models")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedGroupBadText(t *testing.T) {
|
||||
shareHome(t, Provider{ID: "a", Name: "A", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"x"}})
|
||||
for _, c := range []struct{ text, says string }{
|
||||
{"", "not a routing group shared from magpie"},
|
||||
{"hello {not json}", "not a routing group shared from magpie"},
|
||||
{`{"magpie":"something-else","version":1,"group":{"members":["a/x"]}}`, "not a routing group shared from magpie"},
|
||||
{`{"magpie":"routing-group","version":2,"group":{"members":["a/x"]}}`, "newer magpie (format 2)"},
|
||||
{`{"magpie":"routing-group","group":{"members":["a/x"]}}`, "no format"},
|
||||
{`{"magpie":"routing-group","version":1,"group":{"members":"a/x"}}`, "can't be read"},
|
||||
} {
|
||||
if _, err := ImportGroup(c.text); err == nil || !strings.Contains(err.Error(), c.says) {
|
||||
t.Errorf("ImportGroup(%q) = %v, want an error saying %q", c.text, err, c.says)
|
||||
}
|
||||
}
|
||||
if len(Groups()) != 0 {
|
||||
t.Fatalf("bad text added %v", Groups())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user