provider, gateway, gui, cli: Claude's accounts can be kept to Claude Code's own sign-in, magpie serving nothing on them (myduso)
myduso on Discord asked for an exclusive mode on Claude's subscription: switch the credentials locally and proxy no traffic, since Claude Code is used on its own and the SDK run magpie's bridge makes spends more of the allowance than the interactive client. The switch-only setting Codex has (#1907) now also takes claude. On it, Provider.KeptToAgent is true and On() false, so the gateway, catalog, groups, fallbacks, search, draw and embeddings serve nothing on the Claude accounts, and a request naming them is refused 404 saying they are kept to Claude Code's own sign-in and how to undo it (switchedOff). Switching Claude Code's sign-in when an account is used up, and reading usage, go on: both are gated by leftAlone on the raw Off, which this doesn't set. Groups magpie found keep their Claude members (heldOffEntries). Nothing is sent as Claude Code: magpie only writes and restores Claude Code's own credentials as it already did. GUI: the tick under Claude's accounts, shown with one account too, drawn by the block Codex's tick had (one block now, its strings picked by agent). app.js stays under its budget with no raise (1,311,711 of 1,311,735). CLI: magpie accounts switch-only <codex|claude> [on|off]. Docs: reference.md, subsystems/providers-accounts.md. Run on mote at this tree on 06950fbbb; then rebased onaeacc6358(two app.js comments shorter) and go test -run TestCoreScriptBudget ./internal/gui run again at the pushed head: ok. - gofmt -l internal: clean. GOOS=linux go vet -tags nogui ./internal/... and GOOS=windows go vet ./internal/...: ok. - go test -tags nogui -count=1 -timeout 45m ./internal/provider ./internal/gateway ./internal/cli ./internal/gui: all ok. - node --test (Chromium + WebKit, every language the file covers): claude-switch-only (new), switch-only, keep-login, i18n-keys, gui-ja, gui-de, gui-zh-tw: 85 of 93 in one run beside other sessions' full GUI suites (load 23-73); the 8 reds (claude-switch-only chromium en/zh, gui-de and gui-ja in both engines) were not captured, and those files then passed alone twice (35 of 35 each run). - Earlier, at ecbd694a2 (onddf31ca30): internal/agent ok; add-sheet, api-key-usage pass; account-models and account-proxy 40/40 alone after 8 browserType.launch timeouts at load 40-70 from other sessions. Broken by hand, watched red: - On() without the KeptToAgent term: TestClaudeSwitchOnlyServesNothing- AndStillSwitches and TestClaudeKeptToClaudeCodeServesNothing fail (the gateway ran Claude Code through the bridge, 200). - SetSwitchOnly refusing claude: both fail. - app.js without the claude branch: claude-switch-only 16/16 red in Chromium, switch-only (Codex) 16/16 green. Not tried: real Claude accounts or a real Claude Code (the switch itself is the existing path, tested with a fake claude in a sandbox HOME); the whole GUI suite (only the files that open Claude's or a provider's editor, plus the i18n ones); Linux and Windows test runs (vet only).
This commit is contained in:
@@ -1796,6 +1796,16 @@ start, so one already open stays on its account until it is opened again;
|
||||
a new `codex` session takes the new one. Connected to magpie, Codex's
|
||||
requests go through it as before.
|
||||
|
||||
*Only switch Claude Code's sign-in* under Providers › Claude (or `magpie
|
||||
accounts switch-only claude on`) keeps the Claude accounts to Claude
|
||||
Code alone, with one account too: magpie still moves Claude Code's own
|
||||
sign-in as above, and serves no request on them. They leave the model
|
||||
list, and a request that names them, from any agent, a group, a
|
||||
fallback or a Claude Code connected to magpie, is refused as kept to
|
||||
Claude Code, so no turn runs through Claude Code's SDK mode, which
|
||||
spends more of the allowance than Claude Code used on its own (myduso on
|
||||
Discord). Their usage is still read and shown.
|
||||
|
||||
**How often an allowance is read.** Routing uses what was read last and
|
||||
never waits for a reading, except the first one after magpie starts (3
|
||||
seconds at most). A reading over a minute old is read again in the
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -23,14 +23,14 @@ import (
|
||||
// `magpie accounts switch|forget <agent> <email>`,
|
||||
// `magpie accounts project <gemini|antigravity> <email> <project>`,
|
||||
// `magpie accounts alias <agent> <email> [<name>|--clear]`
|
||||
// `magpie accounts switch-only codex [on|off]`
|
||||
// `magpie accounts switch-only <codex|claude> [on|off]`
|
||||
// — the subscriptions magpie remembers, how much of each one's allowance is
|
||||
// used, and switching the agent between them.
|
||||
func accountsCmd(args []string) error {
|
||||
if len(args) > 1 && args[1] == "discovery" {
|
||||
return accountsDiscoveryCmd(args[2:])
|
||||
}
|
||||
const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|<plugin>] [--json] | magpie accounts add <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> | magpie accounts add copilot [--host <name>.ghe.com] | magpie accounts import <codex|claude|antigravity|factory> <file>... [--yes] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> <email> | magpie accounts switch|forget copilot <login>[@<name>.ghe.com] [--host <name>.ghe.com] | magpie accounts project <gemini|antigravity> <email> <gcp-project-id> | magpie accounts alias <agent|<plugin>> <email> [<name>|--clear] | magpie accounts switch-only codex [on|off]"
|
||||
const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|<plugin>] [--json] | magpie accounts add <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> | magpie accounts add copilot [--host <name>.ghe.com] | magpie accounts import <codex|claude|antigravity|factory> <file>... [--yes] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> <email> | magpie accounts switch|forget copilot <login>[@<name>.ghe.com] [--host <name>.ghe.com] | magpie accounts project <gemini|antigravity> <email> <gcp-project-id> | magpie accounts alias <agent|<plugin>> <email> [<name>|--clear] | magpie accounts switch-only <codex|claude> [on|off]"
|
||||
agentID := func(s string) (string, error) {
|
||||
switch strings.ToLower(s) {
|
||||
case "claude", "cc":
|
||||
@@ -868,20 +868,32 @@ func accountNamed(agent, user string) (string, error) {
|
||||
return "", fmt.Errorf("no saved %s account %q · its accounts: %q", agent, user, names)
|
||||
}
|
||||
|
||||
// switchOnlyCmd is `magpie accounts switch-only codex [on|off]`: magpie
|
||||
// only switches Codex's own sign-in to the next account with room, its
|
||||
// requests never sent through the gateway for account failover (#1907).
|
||||
// With no on or off it says which it is.
|
||||
// switchOnlyCmd is `magpie accounts switch-only <codex|claude> [on|off]`:
|
||||
// magpie only switches the agent's own sign-in to the next account with
|
||||
// room. Codex's requests are then never sent through the gateway for
|
||||
// account failover (#1907); Claude's accounts serve no request through the
|
||||
// gateway (provider.KeptToAgent, myduso on Discord). With no on or off it
|
||||
// says which it is.
|
||||
func switchOnlyCmd(args []string) error {
|
||||
const usage = "usage: magpie accounts switch-only codex [on|off]"
|
||||
if len(args) < 1 || len(args) > 2 || !strings.EqualFold(args[0], "codex") {
|
||||
const usage = "usage: magpie accounts switch-only <codex|claude> [on|off]"
|
||||
if len(args) < 1 || len(args) > 2 {
|
||||
return fmt.Errorf("%s", usage)
|
||||
}
|
||||
id := strings.ToLower(args[0])
|
||||
if id != "codex" && id != "claude" {
|
||||
return fmt.Errorf("%s", usage)
|
||||
}
|
||||
if len(args) == 1 {
|
||||
if provider.SwitchOnly("codex") {
|
||||
on := provider.SwitchOnly(id)
|
||||
switch {
|
||||
case id == "codex" && on:
|
||||
fmt.Println("on · magpie only switches Codex's sign-in; its requests go straight to OpenAI")
|
||||
} else {
|
||||
case id == "codex":
|
||||
fmt.Println("off · with more of its accounts on, Codex's requests go through magpie to fail over between them")
|
||||
case on:
|
||||
fmt.Println("on · magpie only switches Claude Code's sign-in; it serves no requests on the Claude accounts")
|
||||
default:
|
||||
fmt.Println("off · magpie serves requests on the Claude accounts that are on")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -893,15 +905,20 @@ func switchOnlyCmd(args []string) error {
|
||||
default:
|
||||
return fmt.Errorf("%s", usage)
|
||||
}
|
||||
if err := provider.SetSwitchOnly("codex", on); err != nil {
|
||||
if err := provider.SetSwitchOnly(id, on); err != nil {
|
||||
return err
|
||||
}
|
||||
// Codex's config.toml follows now, not at the next start
|
||||
// the agents' configs and model lists follow now, not at the next start
|
||||
agent.SyncCatalog()
|
||||
if on {
|
||||
switch {
|
||||
case id == "codex" && on:
|
||||
fmt.Println(green.Render("✓"), "magpie only switches Codex's sign-in to an account with room; its requests go straight to OpenAI. A Codex app or session already open stays on its account until it is opened again.")
|
||||
} else {
|
||||
case id == "codex":
|
||||
fmt.Println(green.Render("✓"), "with more of its accounts on, Codex's requests go through magpie to fail over between them again")
|
||||
case on:
|
||||
fmt.Println(green.Render("✓"), "magpie only switches Claude Code's sign-in to an account with room; it serves no requests on the Claude accounts. A Claude Code session already open stays on its account until it is started again.")
|
||||
default:
|
||||
fmt.Println(green.Render("✓"), "magpie serves requests on the Claude accounts that are on again")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -99,6 +99,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie accounts project <gemini|antigravity> <email> <project> the Google Cloud project a Google account's requests go to
|
||||
magpie accounts alias <agent> <email> [<name>|--clear] a name of your own for an account, shown on its card, in the menu bar and in magpie quota
|
||||
magpie accounts switch-only codex [on|off] only switch Codex's own sign-in to an account with room; its requests go straight to OpenAI, never through magpie
|
||||
magpie accounts switch-only claude [on|off] only switch Claude Code's own sign-in to an account with room; magpie serves no requests on the Claude accounts
|
||||
magpie claude-code [install [--yes]|remove] the Claude Code a Claude subscription runs; install downloads Anthropic's own build, checked against its manifest, for a server or container without one
|
||||
magpie plugin [add <package>|rm|update|on|off|login <provider>|logout <provider>]
|
||||
OpenCode provider plugins and pi packages: subscriptions signed in to, and served, through a plugin
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// myduso on Discord: Claude's subscription kept to Claude Code, magpie
|
||||
// only switching its sign-in. A request naming the Claude accounts runs
|
||||
// no Claude Code through the bridge and is told why, with how to undo it;
|
||||
// unticked, it is served again.
|
||||
func TestClaudeKeptToClaudeCodeServesNothing(t *testing.T) {
|
||||
claudeMadeFirst(t, false)
|
||||
s := New()
|
||||
t.Cleanup(s.subscription.abortAll)
|
||||
calls := filepath.Join(t.TempDir(), "calls")
|
||||
claudeRefuses(t, calls, "tok-none") // no account refused
|
||||
|
||||
if err := provider.SetSwitchOnly("claude", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := askClaudeModel(s, "hi")
|
||||
if rec.Code != 404 || !strings.Contains(rec.Body.String(), "kept to Claude Code's own sign-in") {
|
||||
t.Fatalf("kept to Claude Code: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if b, _ := os.ReadFile(calls); len(b) != 0 {
|
||||
t.Fatalf("Claude Code run through the bridge: %q", b)
|
||||
}
|
||||
|
||||
if err := provider.SetSwitchOnly("claude", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec := askClaudeModel(s, "again"); rec.Code != 200 || !strings.Contains(rec.Body.String(), "healthy account") {
|
||||
t.Fatalf("unticked: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -254,8 +254,12 @@ func namesInCatalog() map[string]bool {
|
||||
}
|
||||
|
||||
// switchedOff says a request for model went nowhere because p, which
|
||||
// serves it, is switched off in magpie (provider.Provider.Off).
|
||||
// serves it, is switched off in magpie (provider.Provider.Off), or kept to
|
||||
// Claude Code's own sign-in (provider.Provider.KeptToAgent).
|
||||
func switchedOff(p provider.Provider, model string) string {
|
||||
if p.KeptToAgent() {
|
||||
return fmt.Sprintf("%s's accounts are kept to Claude Code's own sign-in in Magpie, so %q is not served; untick \"Only switch Claude Code's sign-in\" under its accounts in Magpie's Providers to use it", p.Name, model)
|
||||
}
|
||||
return fmt.Sprintf("%s is switched off in Magpie, so %q is not served; switch it on again in Magpie's Providers to use it", p.Name, model)
|
||||
}
|
||||
|
||||
|
||||
@@ -13083,19 +13083,14 @@ function renderAccounts(a, p) {
|
||||
box.append(keep, as);
|
||||
list.append(box);
|
||||
}
|
||||
// with more of its accounts on, magpie sends Codex's own requests through
|
||||
// the gateway to fail over between them (#1385); this has it only switch
|
||||
// Codex's own sign-in instead, its requests going straight to OpenAI
|
||||
// (#1907: Codex Desktop and the CLI on their own subscription alone)
|
||||
if (a.agent === "codex" && several && p) {
|
||||
const box = el("div", "switch-only");
|
||||
const [only, cb] = tick(t("Only switch {agent}'s sign-in", { agent: a.agentName }), !!p.switchOnly);
|
||||
only.title = t("magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.", { agent: a.agentName });
|
||||
cb.onchange = () => accountAction("provider/switchonly", { id: p.id, switchOnly: cb.checked }, cb.checked
|
||||
? t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", { agent: a.agentName })
|
||||
: t("{agent}'s requests go through magpie to fail over to your other accounts again", { agent: a.agentName }));
|
||||
box.append(only);
|
||||
list.append(box);
|
||||
const cx = a.agent === "codex", ag = { agent: a.agentName };
|
||||
if (p && (cx && several || a.agent === "claude")) {
|
||||
const [only, cb] = tick(t("Only switch {agent}'s sign-in", ag), p.switchOnly);
|
||||
const [tip, on, off] = cx ? [t("magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.", ag), t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", ag), t("{agent}'s requests go through magpie to fail over to your other accounts again", ag)]
|
||||
: [t("magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.", ag), t("magpie serves no requests on these accounts"), t("magpie serves requests on these accounts again")];
|
||||
only.title = tip;
|
||||
cb.onchange = () => accountAction("provider/switchonly", { id: p.id, switchOnly: cb.checked }, cb.checked ? on : off);
|
||||
list.append(el("div", "switch-only", only));
|
||||
}
|
||||
// how a pool ends at its caps (plugins#349)
|
||||
const capped = (l) => accountCapOf(p, l.user) || windowCapsOf(p, l.user);
|
||||
|
||||
@@ -1614,6 +1614,9 @@ const I18N = {
|
||||
"No cap on {users}: used to 100% of each window": "{users} 没有上限:每个窗口都会用到 100%",
|
||||
"magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.": "当前账号额度用完时,magpie 改写 {agent} 自己的登录,把它切到下一个还有额度的账号,等原账号额度恢复后再切回;{agent} 的请求直接发往 OpenAI,不经过 magpie。已经打开的 {agent} 应用或会话会停留在原账号,直到重新打开。{agent} 接入 magpie 时,请求仍照常经过 magpie。",
|
||||
"magpie only switches {agent}'s sign-in; its requests go straight to OpenAI": "magpie 只切换 {agent} 的登录;它的请求直接发往 OpenAI",
|
||||
"magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.": "账号用完时,magpie 把 {agent} 自己的登录切到下一个还有额度的账号,有额度后再切回来。这些账号上的请求一概不经 magpie 处理。",
|
||||
"magpie serves no requests on these accounts": "magpie 不在这些账号上处理任何请求",
|
||||
"magpie serves requests on these accounts again": "magpie 重新在这些账号上处理请求",
|
||||
"{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} 的请求重新经过 magpie,以便转到你的其他账号",
|
||||
"the first account": "首选账号",
|
||||
"Account to stay signed in to": "始终登录的账号",
|
||||
@@ -5659,6 +5662,9 @@ const I18N = {
|
||||
"No cap on {users}: used to 100% of each window": "{users} 沒有上限:每個視窗都會用到 100%",
|
||||
"magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.": "目前帳號額度用完時,magpie 改寫 {agent} 自己的登入,把它切到下一個還有額度的帳號,等原帳號額度恢復後再切回;{agent} 的請求直接送往 OpenAI,不經過 magpie。已經開啟的 {agent} 應用程式或工作階段會停留在原帳號,直到重新開啟。{agent} 接入 magpie 時,請求仍照常經過 magpie。",
|
||||
"magpie only switches {agent}'s sign-in; its requests go straight to OpenAI": "magpie 只切換 {agent} 的登入;它的請求直接送往 OpenAI",
|
||||
"magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.": "帳號用完時,magpie 把 {agent} 自己的登入切到下一個還有額度的帳號,有額度後再切回來。這些帳號上的請求一概不經 magpie 處理。",
|
||||
"magpie serves no requests on these accounts": "magpie 不在這些帳號上處理任何請求",
|
||||
"magpie serves requests on these accounts again": "magpie 重新在這些帳號上處理請求",
|
||||
"{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} 的請求重新經過 magpie,以便轉到你的其他帳號",
|
||||
"the first account": "首選帳號",
|
||||
"Account to stay signed in to": "始終登入的帳號",
|
||||
@@ -9681,6 +9687,9 @@ const I18N = {
|
||||
"No cap on {users}: used to 100% of each window": "{users} には上限がありません:各ウィンドウを 100% まで使います",
|
||||
"magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.": "{agent} がサインイン中のアカウントの利用枠を使い切ると、magpie は {agent} 自身のサインインを書き換えて、枠の残っている次のアカウントに切り替え、元のアカウントの枠が戻ったら切り戻します。{agent} のリクエストは magpie を経由せず、OpenAI に直接送られます。すでに開いている {agent} のアプリやセッションは、開き直すまで元のアカウントのままです。{agent} を magpie に接続している場合、リクエストはこれまでどおり magpie を経由します。",
|
||||
"magpie only switches {agent}'s sign-in; its requests go straight to OpenAI": "magpie は {agent} のサインインだけを切り替えます。リクエストは OpenAI に直接送られます",
|
||||
"magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.": "アカウントを使い切ると、magpie は {agent} 自身のサインインを空きのある次のアカウントに切り替え、空きが戻ったら切り戻します。これらのアカウントのリクエストは magpie を一切通りません。",
|
||||
"magpie serves no requests on these accounts": "magpie はこれらのアカウントでリクエストを処理しません",
|
||||
"magpie serves requests on these accounts again": "magpie はこれらのアカウントで再びリクエストを処理します",
|
||||
"{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} のリクエストは再び magpie を経由し、他のアカウントへ切り替えられます",
|
||||
"the first account": "最初のアカウント",
|
||||
"Account to stay signed in to": "サインインしたままにするアカウント",
|
||||
@@ -13733,6 +13742,9 @@ const I18N = {
|
||||
"No cap on {users}: used to 100% of each window": "Kein Limit für {users}: jedes Fenster wird bis 100 % genutzt",
|
||||
"magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.": "Ist das Konto, mit dem {agent} angemeldet ist, aufgebraucht, schreibt magpie die eigene Anmeldung von {agent} auf das nächste Konto mit Kontingent um, und zurück, sobald das erste wieder Kontingent hat; die Anfragen von {agent} gehen direkt an OpenAI, nie über magpie. Eine bereits geöffnete {agent}-App oder -Sitzung bleibt beim bisherigen Konto, bis sie neu geöffnet wird. Ist {agent} mit magpie verbunden, laufen seine Anfragen wie bisher über magpie.",
|
||||
"magpie only switches {agent}'s sign-in; its requests go straight to OpenAI": "magpie wechselt nur die Anmeldung von {agent}; seine Anfragen gehen direkt an OpenAI",
|
||||
"magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.": "Ist ein Konto aufgebraucht, meldet magpie {agent} mit der eigenen Anmeldung beim nächsten Konto mit Kontingent an und wieder zurück, sobald es Kontingent hat. Über diese Konten läuft nichts durch magpie.",
|
||||
"magpie serves no requests on these accounts": "magpie bearbeitet keine Anfragen über diese Konten",
|
||||
"magpie serves requests on these accounts again": "magpie bearbeitet wieder Anfragen über diese Konten",
|
||||
"{agent}'s requests go through magpie to fail over to your other accounts again": "Die Anfragen von {agent} laufen wieder über magpie, um auf deine anderen Konten auszuweichen",
|
||||
"the first account": "dem ersten Konto",
|
||||
"Account to stay signed in to": "Konto für die dauerhafte Anmeldung",
|
||||
|
||||
@@ -218,7 +218,9 @@ type providerJSON struct {
|
||||
// first, the gateway still trying them in their order
|
||||
KeepLoginAs string `json:"keepLoginAs,omitempty"`
|
||||
// SwitchOnly: magpie only moves Codex's own sign-in between its
|
||||
// accounts, never routing its requests for failover (#1907)
|
||||
// accounts, never routing its requests for failover (#1907); on
|
||||
// Claude's, the accounts are kept to Claude Code's own sign-in and
|
||||
// serve no request through magpie (myduso on Discord)
|
||||
SwitchOnly bool `json:"switchOnly,omitempty"`
|
||||
// CapStop and CapCareful: how its accounts end at their caps
|
||||
// (plugins#349), set on their own with capstop and capcareful
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// myduso on Discord: under Claude's accounts a tick keeps them to Claude
|
||||
// Code, magpie only switching its own sign-in and serving no request on
|
||||
// them. It shows with one account too: what it stops is magpie serving
|
||||
// them, not a switch between them. Ticking it posts provider/switchonly,
|
||||
// and the redraw keeps it ticked; unticking posts it off. The page doesn't
|
||||
// move. In English, Chinese, Japanese and German, Chromium and WebKit, at
|
||||
// 1100 and 420 wide.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const claude = ({ switchOnly = false, spare = true } = {}) => ({
|
||||
id: "claude", name: "Claude", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "", switchOnly,
|
||||
models: [{ id: "claude-sonnet-5", name: "Claude Sonnet 5", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
|
||||
account: {
|
||||
agent: "claude", agentName: "Claude Code", user: "work@example.com", plan: "MAX",
|
||||
logins: [{ user: "work@example.com", plan: "MAX", active: true, on: true }].concat(spare ? [{ user: "spare@example.com", plan: "PRO", on: true }] : []),
|
||||
},
|
||||
});
|
||||
|
||||
function serve(lang, first, posts) {
|
||||
let list = [first];
|
||||
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
|
||||
const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/providers") return json(providers());
|
||||
if (url.pathname === "/api/provider/switchonly") {
|
||||
const body = route.request().postDataJSON();
|
||||
posts.push(body);
|
||||
list = [{ ...list[0], switchOnly: body.switchOnly }];
|
||||
return json(providers());
|
||||
}
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const label = {
|
||||
en: "Only switch Claude Code's sign-in",
|
||||
zh: "只切换 Claude Code 的登录",
|
||||
ja: "Claude Code のサインインだけを切り替える",
|
||||
de: "Nur die Anmeldung von Claude Code wechseln",
|
||||
};
|
||||
const strings = [
|
||||
"Only switch {agent}'s sign-in",
|
||||
"magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.",
|
||||
"magpie serves no requests on these accounts",
|
||||
"magpie serves requests on these accounts again",
|
||||
];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const width of [1100, 420]) {
|
||||
for (const lang of Object.keys(label)) {
|
||||
const open = async (t, opts) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, claude(opts), posts));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: "Claude" }).first().click();
|
||||
await page.locator(".editor .acc").first().waitFor();
|
||||
return { page, errors, posts };
|
||||
};
|
||||
|
||||
test(`${engine} ${width} ${lang}: a tick keeps Claude's accounts to Claude Code`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, {});
|
||||
const only = page.locator(".editor .accts .switch-only label");
|
||||
assert.equal((await only.textContent()).trim(), label[lang]);
|
||||
assert.ok(await only.getAttribute("title"), "it says what it does");
|
||||
assert.equal(await only.locator("input").isChecked(), false);
|
||||
if (lang === "en") {
|
||||
const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings);
|
||||
assert.deepEqual(missing, [], "every string has its translations");
|
||||
}
|
||||
await only.scrollIntoViewIfNeeded();
|
||||
const box = await only.boundingBox();
|
||||
assert.ok(box.x >= 0 && box.x + box.width <= width, `the tick fits across ${width}`);
|
||||
const scrollers = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop).concat(document.scrollingElement.scrollTop));
|
||||
const before = await scrollers();
|
||||
await only.locator("input").click();
|
||||
await page.waitForFunction(() => document.querySelector(".editor .accts .switch-only input")?.checked === true);
|
||||
assert.deepEqual(posts, [{ id: "claude", switchOnly: true }]);
|
||||
assert.deepEqual(await scrollers(), before, "the page doesn't move");
|
||||
await page.locator(".editor .accts .switch-only input").click();
|
||||
await page.waitForFunction(() => document.querySelector(".editor .accts .switch-only input")?.checked === false);
|
||||
assert.deepEqual(posts, [{ id: "claude", switchOnly: true }, { id: "claude", switchOnly: false }]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${width} ${lang}: kept to Claude Code is drawn ticked, and shown with one account`, async (t) => {
|
||||
const ticked = await open(t, { switchOnly: true });
|
||||
assert.equal(await ticked.page.locator(".editor .accts .switch-only input").isChecked(), true);
|
||||
const one = await open(t, { spare: false });
|
||||
assert.equal(await one.page.locator(".editor .accts .switch-only").count(), 1);
|
||||
assert.deepEqual([...ticked.errors, ...one.errors], []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2548,7 +2548,7 @@ func entriesOff(off func(pid, model string) bool) []Entry {
|
||||
func heldOffEntries() []Entry {
|
||||
return heldOf("off entries", func() []Entry {
|
||||
return keptOf("off entries", func() []Entry {
|
||||
return slices.Clip(entriesOf(func(p Provider) bool { return p.Ready() && p.Off }, disabledNow()))
|
||||
return slices.Clip(entriesOf(func(p Provider) bool { return p.Ready() && (p.Off || p.KeptToAgent()) }, disabledNow()))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -151,7 +151,9 @@ type Provider struct {
|
||||
// own sign-in (auth.json) to the next account with room and back:
|
||||
// Codex's requests then go straight to OpenAI, never through the
|
||||
// gateway for account failover, however many of its accounts are on
|
||||
// (#1907).
|
||||
// (#1907). On Claude's subscription it keeps the accounts to Claude
|
||||
// Code's own sign-in, which magpie still moves: the gateway serves no
|
||||
// request on them (KeptToAgent; myduso on Discord).
|
||||
SwitchOnly bool `json:"switchOnly,omitempty"`
|
||||
|
||||
// MaxConcurrency is how many requests may be out at the vendor at once
|
||||
@@ -1892,8 +1894,20 @@ func (p Provider) Ready() bool {
|
||||
return p.Account != nil || p.Key != "" || keyOptional(p)
|
||||
}
|
||||
|
||||
// On is whether the provider takes requests: ready, and not switched off.
|
||||
func (p Provider) On() bool { return p.Ready() && !p.Off }
|
||||
// On is whether the provider takes requests: ready, not switched off and
|
||||
// not kept to its agent's own sign-in (KeptToAgent).
|
||||
func (p Provider) On() bool { return p.Ready() && !p.Off && !p.KeptToAgent() }
|
||||
|
||||
// KeptToAgent is whether the provider is Claude's subscription with
|
||||
// SwitchOnly on: its accounts are Claude Code's own sign-in alone, which
|
||||
// magpie moves to the next account with room and back, and the gateway
|
||||
// sends no request to them, so none goes through Claude Code's SDK run,
|
||||
// which spends more of the allowance than Claude Code's own sessions
|
||||
// (myduso on Discord). Codex's SwitchOnly only keeps failover out of its
|
||||
// config.
|
||||
func (p Provider) KeptToAgent() bool {
|
||||
return p.SwitchOnly && p.ID == "claude" && p.Account != nil && p.Account.Agent == "claude"
|
||||
}
|
||||
|
||||
// SetOff switches a provider off, or on again (see Provider.Off). Saving
|
||||
// it brings the model lists written into agents' files up to date.
|
||||
@@ -1912,12 +1926,12 @@ func SetOff(id string, off bool) error {
|
||||
func SwitchedOff(id string) (Provider, bool) {
|
||||
id = strings.TrimSuffix(strings.TrimSpace(id), "[1m]")
|
||||
if pid, _, ok := strings.Cut(id, "/"); ok {
|
||||
if p, err := Find(pid); err == nil && p.Off {
|
||||
if p, err := Find(pid); err == nil && (p.Off || p.KeptToAgent()) {
|
||||
return *p, true
|
||||
}
|
||||
}
|
||||
for _, p := range All() {
|
||||
if !p.Off || !p.Ready() {
|
||||
if !p.Off && !p.KeptToAgent() || !p.Ready() {
|
||||
continue
|
||||
}
|
||||
if slices.ContainsFunc(p.Exposed(), func(m catalog.Model) bool { return m.ID == id }) {
|
||||
|
||||
@@ -117,15 +117,16 @@ func SetKeepLogin(id string, keep bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetSwitchOnly has magpie only move Codex's own sign-in between its
|
||||
// accounts (Provider.SwitchOnly), its requests never sent through the
|
||||
// gateway for account failover, or lets failover go through it again.
|
||||
// SetSwitchOnly has magpie only move Codex's or Claude Code's own sign-in
|
||||
// between its accounts (Provider.SwitchOnly): Codex's requests never sent
|
||||
// through the gateway for account failover, Claude's accounts serving no
|
||||
// request through the gateway (KeptToAgent). Off, both are as before.
|
||||
func SetSwitchOnly(id string, on bool) error {
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Account == nil || p.Account.Agent != p.ID || p.ID != "codex" {
|
||||
if p.Account == nil || p.Account.Agent != p.ID || p.ID != "codex" && p.ID != "claude" {
|
||||
return fmt.Errorf("magpie doesn't route %s's own requests for account failover", p.Name)
|
||||
}
|
||||
p.SwitchOnly = on
|
||||
|
||||
@@ -9,14 +9,17 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
)
|
||||
|
||||
// #1907 (foobra): Codex Desktop and the CLI on their own ChatGPT
|
||||
// subscription, two accounts, no gateway in between. Switch-only is kept on
|
||||
// Codex's subscription; with it on, the account Codex is signed in to
|
||||
// running out still signs Codex in to the next one with room, in its own
|
||||
// auth.json, and back once the first has room again. Claude Code's
|
||||
// subscription has no such setting. A providers.json that can't be read
|
||||
// auth.json, and back once the first has room again. A providers.json
|
||||
// that can't be read
|
||||
// says switch-only: the user's choice is unknown, and failover through the
|
||||
// gateway, magpie's own idea, isn't taken up on it.
|
||||
func TestCodexSwitchOnlyStillSwitchesTheSignIn(t *testing.T) {
|
||||
@@ -69,10 +72,6 @@ func TestCodexSwitchOnlyStillSwitchesTheSignIn(t *testing.T) {
|
||||
if err != nil || !p.SwitchOnly {
|
||||
t.Fatalf("Find: %+v %v", p, err)
|
||||
}
|
||||
if err := SetSwitchOnly("claude", true); err == nil {
|
||||
t.Error("switch-only set on Claude Code's subscription")
|
||||
}
|
||||
|
||||
// out: on to the spare, in Codex's own auth.json
|
||||
if to := switched(); to != "spare@example.com" || signedIn() != "r-spare" {
|
||||
t.Fatalf("switched to %q, Codex signed in with %q", to, signedIn())
|
||||
@@ -99,3 +98,104 @@ func TestCodexSwitchOnlyStillSwitchesTheSignIn(t *testing.T) {
|
||||
t.Error("an unreadable providers.json read as switch-only off")
|
||||
}
|
||||
}
|
||||
|
||||
// myduso on Discord: Claude's subscription kept to Claude Code alone.
|
||||
// magpie still signs Claude Code in to the next account with room, by
|
||||
// writing Claude Code's own sign-in, and serves nothing on the accounts:
|
||||
// they leave the catalog, a request naming them is refused as switched
|
||||
// off, and none of it is the raw Off a user's switch writes.
|
||||
func TestClaudeSwitchOnlyServesNothingAndStillSwitches(t *testing.T) {
|
||||
home := claudeHome(t)
|
||||
cred := claudeSignIn(t, home, time.Now().Add(time.Hour)) // sk-ant-oat01-old
|
||||
writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "a@example.com", "accountUuid": "u-a"}})
|
||||
rememberLogins(true)
|
||||
loginsMu.Lock()
|
||||
ls := upsertLogin(readLogins(), savedLogin{Agent: "claude", User: "b@example.com", Plan: "max", On: true, Seen: time.Now().UTC(),
|
||||
Auth: mustJSONRaw(t, map[string]any{"claudeAiOauth": map[string]any{"accessToken": "sk-ant-oat01-b", "refreshToken": "sk-ant-ort01-b",
|
||||
"expiresAt": time.Now().Add(time.Hour).UnixMilli(), "subscriptionType": "max", "scopes": []string{"user:inference", "user:profile"}}}),
|
||||
Profile: mustJSONRaw(t, map[string]any{"emailAddress": "b@example.com", "accountUuid": "u-b"})})
|
||||
if err := writeLogins(ls); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loginsMu.Unlock()
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("usage endpoint read: %s", r.URL)
|
||||
}))
|
||||
defer fake.Close()
|
||||
claudeBase = fake.URL // isolate puts it back
|
||||
os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)
|
||||
if err := os.WriteFile(catalog.CachePath(), []byte(`{"anthropic": {"models": {
|
||||
"claude-sonnet-5": {"id":"claude-sonnet-5","name":"Claude Sonnet 5","modalities":{"input":["text"],"output":["text"]}}}}}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog.Reset()
|
||||
t.Cleanup(catalog.Reset)
|
||||
if p, err := Find("claude"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if _, err := p.Fetch(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
served := func() bool {
|
||||
t.Helper()
|
||||
for _, e := range Catalog() {
|
||||
if e.Provider.ID == "claude" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
p, err := Find("claude")
|
||||
if err != nil || !p.On() || p.KeptToAgent() || !served() {
|
||||
t.Fatalf("before: %+v %v, served %v", p, err, served())
|
||||
}
|
||||
if err := SetSwitchOnly("claude", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err = Find("claude")
|
||||
if err != nil || !p.SwitchOnly || !p.KeptToAgent() || p.On() || p.Off {
|
||||
t.Fatalf("kept to Claude Code: %+v %v", p, err)
|
||||
}
|
||||
if served() {
|
||||
t.Error("the catalog still serves the Claude accounts")
|
||||
}
|
||||
if _, _, ok := Resolve("claude/claude-sonnet-5"); ok {
|
||||
t.Error("claude/claude-sonnet-5 resolves kept to Claude Code")
|
||||
}
|
||||
if _, off := SwitchedOff("claude/claude-sonnet-5"); !off {
|
||||
t.Error("a request naming the Claude accounts isn't refused as switched off")
|
||||
}
|
||||
if leftAlone("claude") {
|
||||
t.Fatal("kept to Claude Code reads as left alone: no switching, no usage")
|
||||
}
|
||||
|
||||
// spent: Claude Code's own sign-in goes on to b
|
||||
for user, u := range map[string]float64{"a@example.com": 99, "b@example.com": 10} {
|
||||
NoteClaudeLimits(user, []ClaudeLimit{{Kind: "five_hour", Used: u / 100, ResetsAt: time.Now().Add(time.Hour).Unix()}})
|
||||
}
|
||||
to, err := SwitchWhenSpent(context.Background(), "claude")
|
||||
if err != nil || to != "b@example.com" {
|
||||
t.Fatalf("switched to %q: %v", to, err)
|
||||
}
|
||||
var c map[string]any
|
||||
readJSON(cred, &c)
|
||||
if o, _ := c["claudeAiOauth"].(map[string]any); o["refreshToken"] != "sk-ant-ort01-b" {
|
||||
t.Fatalf("Claude Code is signed in with %v", o)
|
||||
}
|
||||
if p, _ := Find("claude"); !p.KeptToAgent() {
|
||||
t.Fatal("kept to Claude Code lost on a switch")
|
||||
}
|
||||
|
||||
if err := SetSwitchOnly("claude", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, _ := Find("claude"); !p.On() || !served() {
|
||||
t.Fatalf("off again: %+v, served %v", p, served())
|
||||
}
|
||||
if _, off := SwitchedOff("claude/claude-sonnet-5"); off {
|
||||
t.Error("still refused as switched off")
|
||||
}
|
||||
if _, _, ok := Resolve("claude/claude-sonnet-5"); !ok {
|
||||
t.Error("claude/claude-sonnet-5 doesn't resolve unticked")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user