diff --git a/internal/gateway/account_proxy_test.go b/internal/gateway/account_proxy_test.go new file mode 100644 index 000000000..7bf8215cb --- /dev/null +++ b/internal/gateway/account_proxy_test.go @@ -0,0 +1,235 @@ +package gateway + +import ( + "context" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// chatgptAt stands in for the ChatGPT backend, or for a proxy in front of +// it: it notes each request's path and account (chatgpt-account-id), and +// answers a turn for acct-1 and acct-2 with their allowance used up, so a +// turn moves on through every account, and acct-3's with "pong". +type chatgptAt struct { + mu sync.Mutex + name string + got []string // " " +} + +func (c *chatgptAt) ServeHTTP(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + acct := r.Header.Get("chatgpt-account-id") + c.mu.Lock() + c.got = append(c.got, r.URL.Path+" "+acct) + c.mu.Unlock() + switch { + case strings.HasSuffix(r.URL.Path, "/responses"): + if acct != "acct-3" { + w.WriteHeader(429) + io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_in_seconds":7200}}`) + return + } + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`, + `data: {"type":"response.output_text.delta","delta":"pong via `+c.name+`"}`, + `data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`)) + case strings.HasSuffix(r.URL.Path, "/wham/usage"): + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"plan_type":"plus","rate_limit":{"primary_window":{"used_percent":10,"limit_window_seconds":18000,"reset_after_seconds":600}}}`) + default: + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"models":[]}`) + } +} + +// saw is the accounts sent a request to a path ending in suffix. +func (c *chatgptAt) saw(suffix string) []string { + c.mu.Lock() + defer c.mu.Unlock() + var out []string + for _, g := range c.got { + if path, acct, _ := strings.Cut(g, " "); strings.HasSuffix(path, suffix) { + out = append(out, acct) + } + } + return out +} + +func (c *chatgptAt) reset() { + c.mu.Lock() + c.got = nil + c.mu.Unlock() +} + +// Each of a subscription's accounts goes through its own proxy (gakki: +// 是否可以为不同的codex账号设置不同的代理): of three Codex accounts, one +// through the proxy it names, one direct though Codex and Settings both +// name one, and one, following Codex's, through Codex's — a turn that +// moves over all three, and each account's usage, alike. An account set +// back to following goes through Codex's proxy, and with Codex's cleared, +// through the global one; ftp:// is refused. +func TestAccountProxy(t *testing.T) { + codexSignedIn(t, "spare@example.com", "third@example.com") + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} { + t.Setenv(k, "") + } + own, codexs, global, vendor := &chatgptAt{name: "own"}, &chatgptAt{name: "codex's"}, &chatgptAt{name: "global"}, &chatgptAt{name: "vendor"} + var servers []*httptest.Server + for _, h := range []http.Handler{own, codexs, global, vendor} { + s := httptest.NewServer(h) + t.Cleanup(s.Close) + servers = append(servers, s) + } + ownProxy, codexProxy, globalProxy, backend := servers[0], servers[1], servers[2], servers[3] + all := []*chatgptAt{own, codexs, global, vendor} + resetAll := func() { + for _, x := range all { + x.reset() + } + } + + // the backend at a name no proxy stands in front of (loopback never + // goes through one): dialled directly, chatgpt.test is the vendor + var d net.Dialer + dial := func(ctx context.Context, network, addr string) (net.Conn, error) { + if host, _, _ := net.SplitHostPort(addr); strings.HasSuffix(host, ".test") { + addr = backend.Listener.Addr().String() + } + return d.DialContext(ctx, network, addr) + } + transport := func() *http.Transport { + return &http.Transport{Proxy: netproxy.Func, DialContext: dial, ResponseHeaderTimeout: 10 * time.Second} + } + defaultTransport := http.DefaultClient.Transport + http.DefaultClient.Transport = netproxy.Dispatch(transport()) + t.Cleanup(func() { http.DefaultClient.Transport = defaultTransport }) + was := provider.CodexBase + provider.CodexBase = "http://chatgpt.test/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + + st := settings.Load() + st.Proxy = globalProxy.URL + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + p, err := provider.Find("codex") + if err != nil { + t.Fatal(err) + } + bad := *p + bad.AccountProxies = map[string]string{"spare@example.com": "ftp://10.0.0.1:21"} + if err := provider.Save(bad); err == nil { + t.Fatal("an account's ftp:// proxy was taken") + } + p.Proxy = codexProxy.URL + p.AccountProxies = map[string]string{"Me@Example.com": " " + ownProxy.URL + " ", "spare@example.com": "direct", "third@example.com": ""} + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + if p, _ = provider.Find("codex"); p.Proxy != codexProxy.URL || len(p.AccountProxies) != 2 || + p.AccountProxies["me@example.com"] != ownProxy.URL || p.AccountProxies["spare@example.com"] != "direct" { + t.Fatalf("kept %q %v", p.Proxy, p.AccountProxies) + } + b, _ := os.ReadFile(provider.Path()) + if !strings.Contains(string(b), `"accountProxies"`) || strings.Contains(string(b), "third@example.com") { + t.Fatalf("providers.json: %s", b) + } + + // a turn over the three: acct-1 through its own proxy, acct-2 direct + // to the backend, acct-3 through Codex's + s := New() + s.client = &http.Client{Transport: netproxy.Dispatch(transport())} + turn := func() (int, string) { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"ping"}`)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String() + } + code, body := turn() + if code != 200 || !strings.Contains(body, "pong via codex's") { + t.Fatalf("turn: %d %s", code, body) + } + want := func(what, suffix string, by map[*chatgptAt][]string) { + t.Helper() + for _, x := range all { + if got := sorted(x.saw(suffix)...); !slices.Equal(got, by[x]) { + t.Fatalf("%s: %s was sent %v, want %v", what, x.name, got, by[x]) + } + } + } + want("turn", "/responses", map[*chatgptAt][]string{own: {"acct-1"}, vendor: {"acct-2"}, codexs: {"acct-3"}}) + + // each account's usage goes the same ways + usage := func() { + t.Helper() + resetAll() + for _, u := range []string{"me@example.com", "spare@example.com", "third@example.com"} { + provider.StaleAllowance("codex", u) + } + for u, q := range provider.LoginUsage(context.Background(), "codex") { + if q.Error != "" { + t.Fatalf("%s's usage: %s", u, q.Error) + } + } + } + usage() + want("usage", "/wham/usage", map[*chatgptAt][]string{own: {"acct-1"}, vendor: {"acct-2"}, codexs: {"acct-3"}}) + + // acct-1 back to following Codex's proxy; then Codex's cleared, the + // accounts following it follow the global one + p, _ = provider.Find("codex") + delete(p.AccountProxies, "me@example.com") + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + usage() + want("acct-1 following Codex's", "/wham/usage", map[*chatgptAt][]string{vendor: {"acct-2"}, codexs: sorted("acct-1", "acct-3")}) + p, _ = provider.Find("codex") + p.Proxy = "" + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + usage() + want("Codex following the global", "/wham/usage", map[*chatgptAt][]string{vendor: {"acct-2"}, global: sorted("acct-1", "acct-3")}) +} + +func sorted(s ...string) []string { slices.Sort(s); return s } + +// A Claude Code run for one of its accounts (the bridge's, a warm-up's) +// gets that account's own proxy in its *_PROXY, or else Claude's. +func TestClaudeAccountProxyEnv(t *testing.T) { + fresh(t) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"} { + t.Setenv(k, "") + } + os.MkdirAll(filepath.Dir(provider.Path()), 0o755) + os.WriteFile(provider.Path(), []byte(`{"providers":[{"id":"claude","key":"","proxy":"http://10.0.0.9:7890","accountProxies":{"a@example.com":"socks5://10.0.0.8:1080","b@example.com":"direct"}}]}`), 0o600) + env := func(user string) string { + for _, kv := range netproxy.EnvWith(claudeProxy(provider.ViaLogin(context.Background(), "claude", user)), []string{"PATH=/bin"}) { + if v, ok := strings.CutPrefix(kv, "HTTPS_PROXY="); ok { + return v + } + } + return "" + } + for user, want := range map[string]string{"A@example.com": "socks5://10.0.0.8:1080", "b@example.com": "", "c@example.com": "http://10.0.0.9:7890"} { + if got := env(user); got != want { + t.Errorf("%s: HTTPS_PROXY %q, want %q", user, got, want) + } + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 6bf19e566..a04248834 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -253,7 +253,7 @@ func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, oau args := claudeCLIArgs(model, string(mcpConfig), req.Effort, req.WebSearch) cmd := proc.CommandContext(context.Background(), binary, args...) cmd.Dir = tmp - cmd.Env = netproxy.EnvWith(provider.ProxyOf("claude"), cleanClaudeEnv(os.Environ())) + cmd.Env = netproxy.EnvWith(claudeProxy(ctx), cleanClaudeEnv(os.Environ())) if oauth != "" { // a saved account in use beside the one Claude Code is signed in to cmd.Env = append(cmd.Env, "CLAUDE_CODE_OAUTH_TOKEN="+oauth) @@ -1180,6 +1180,7 @@ func (b *subscriptionBridge) removeRun(run *subscriptionRun) { func (s *Server) serveClaudeSubscription(w http.ResponseWriter, r *http.Request, from provider.Protocol, p provider.Provider, model string, body []byte, usage *Usage) (int, string) { start := func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error) { + ctx = p.Via(ctx) // the account's own proxy, its CLI run's too owner := p.ID + "\x00" + p.Account.User if run, events := s.subscription.resume(req, owner); run != nil { return run, events, nil diff --git a/internal/gateway/claude_warmup.go b/internal/gateway/claude_warmup.go index 482056b7b..c3e20378c 100644 --- a/internal/gateway/claude_warmup.go +++ b/internal/gateway/claude_warmup.go @@ -13,6 +13,16 @@ import ( "github.com/yetone/magpie/internal/provider" ) +// claudeProxy is the proxy a Claude Code run on an account's behalf goes +// through: the one ctx names (the account's own, or its subscription's), +// else the subscription's. +func claudeProxy(ctx context.Context) string { + if c := netproxy.Choice(ctx); c != "" { + return c + } + return provider.ProxyOf("claude") +} + // warmClaude sends a Claude account one "hi" through Claude Code, as the // bridge runs it (claudeCLIArgs): none of its tools, settings or MCP // servers, nothing kept on disk, at Haiku, the least an account's window @@ -31,7 +41,7 @@ func warmClaude(ctx context.Context, oauth string) error { cmd := proc.CommandContext(ctx, binary, claudeWarmArgs()...) cmd.Dir = tmp cmd.Stdin = strings.NewReader("hi") - cmd.Env = netproxy.EnvWith(provider.ProxyOf("claude"), cleanClaudeEnv(os.Environ())) + cmd.Env = netproxy.EnvWith(claudeProxy(ctx), cleanClaudeEnv(os.Environ())) if oauth != "" { cmd.Env = append(cmd.Env, "CLAUDE_CODE_OAUTH_TOKEN="+oauth) } diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 3b9231fcd..3ebaf33c9 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -242,7 +242,7 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri } var res *http.Response for tries := 0; ; tries++ { - req, err := http.NewRequestWithContext(provider.Via(r.Context(), "codex"), r.Method, u, bytes.NewReader(body)) + req, err := http.NewRequestWithContext(provider.ViaSignedIn(r.Context(), "codex"), r.Method, u, bytes.NewReader(body)) if err != nil { writeError(w, provider.Responses, 502, err.Error()) end(502, err.Error(), 0, 0) @@ -482,7 +482,7 @@ func (s *Server) codexModels(w http.ResponseWriter, r *http.Request) { if r.URL.RawQuery != "" { u += "?" + r.URL.RawQuery } - if req, err := http.NewRequestWithContext(provider.Via(r.Context(), "codex"), http.MethodGet, u, nil); err == nil { + if req, err := http.NewRequestWithContext(provider.ViaSignedIn(r.Context(), "codex"), http.MethodGet, u, nil); err == nil { copyHeaders(req.Header, r.Header) req.Header.Del("Accept-Encoding") if res, err := s.client.Do(req); err == nil { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 9eb61d0df..ada539d07 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1383,6 +1383,12 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .editor .proxy-row .proxy-mode { flex: none; } .editor .proxy-row input.proxy-url { flex: 1 1 auto; width: auto; min-width: 0; } .editor .proxy-row input.proxy-url.off { visibility: hidden; } +/* each of a subscription's accounts with a proxy of its own: its name + over the same row as the provider's, in a quiet card, no stripes */ +.editor .acct-proxies { display: grid; gap: 8px; margin-top: 4px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); } +.editor .acct-proxy { display: grid; gap: 4px; min-width: 0; } +.editor .acct-proxy .who { font-size: 12px; font-weight: 500; color: var(--fg-2); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.editor .acct-proxies > .hint { margin-top: 0; } /* what a balance token's URL wants instead, and a balance checked in the form */ .editor .bal-fix { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin-top: 6px; font-size: 12px; line-height: 1.45; color: var(--muted); } .editor .bal-fix:empty { display: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 0bd7e4b15..ccce4f54b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -2622,7 +2622,10 @@ function proxyPicker() { } function proxyDraft(p) { const v = (p?.proxy || "").trim(); - return { proxyMode: !v ? "" : v === "direct" ? "direct" : "custom", proxyURL: v && v !== "direct" ? v : "" }; + // each account's own (accountProxies), by its name in lower case + const accountProxies = {}; + for (const [u, x] of Object.entries(p?.accountProxies || {})) accountProxies[u] = { mode: x === "direct" ? "direct" : "custom", url: x === "direct" ? "" : x }; + return { proxyMode: !v ? "" : v === "direct" ? "direct" : "custom", proxyURL: v && v !== "direct" ? v : "", accountProxies }; } // proxyOfDraft is the draft's proxy as it is saved, or null when Custom // has no address yet. @@ -2632,6 +2635,59 @@ function proxyOfDraft() { return (draft.proxyURL || "").trim() || null; } +// accountProxyPicker: one proxy per account of a subscription holding +// several (gakki: one Codex account through one proxy, another through +// another) — the provider's own (the row above), none, or its own address. +// Each account is a line of its name over the same row as the provider's, +// the address's room kept while it isn't asked for, so a pick moves +// nothing. null for a subscription with one account: the row above is its. +const ACCOUNT_PROXY_HINT = "Each account can go through a proxy of its own; Provider's proxy is the one above"; +function accountProxyPicker(a) { + const ls = [...(a?.logins || [])]; + if (ls.length < 2) return null; + ls.sort((x, y) => (y.active ? 1 : 0) - (x.active ? 1 : 0)); + draft.accountProxies = draft.accountProxies || {}; + const box = el("div", "acct-proxies"); + for (const l of ls) { + const k = l.user.toLowerCase(); + const cur = draft.accountProxies[k] || { mode: "", url: "" }; + const line = el("div", "acct-proxy"); + line.dataset.user = l.user; + const who = el("span", "who", l.user); + who.title = l.user; + const addr = input(cur.url || "", "http://127.0.0.1:7890"); + addr.className = "proxy-url"; + addr.classList.toggle("off", cur.mode !== "custom"); + addr.oninput = () => { draft.accountProxies[k] = { ...(draft.accountProxies[k] || { mode: "custom" }), url: addr.value }; }; + const seg = segs([["", t("Provider's proxy")], ["direct", t("Direct")], ["custom", t("Custom")]], cur.mode || "", (v) => { + draft.accountProxies[k] = { ...(draft.accountProxies[k] || {}), mode: v }; + addr.classList.toggle("off", v !== "custom"); + }); + seg.classList.add("proxy-mode"); + const row = el("div", "proxy-row"); + row.append(seg, addr); + line.append(who, row); + box.append(line); + } + box.append(el("div", "hint", t(ACCOUNT_PROXY_HINT))); + return box; +} +// accountProxiesOfDraft is each account's own proxy as it is saved — the +// accounts that follow the provider's left out — or { missing: user } when +// one's Custom has no address yet. +function accountProxiesOfDraft() { + const out = {}; + for (const [u, x] of Object.entries(draft.accountProxies || {})) { + if (x.mode === "direct") out[u] = "direct"; + else if (x.mode === "custom") { + const v = (x.url || "").trim(); + if (!v) return { missing: u }; + out[u] = v; + } + } + return { map: out }; +} + // Custom request headers: the draft keeps them as an ordered [name, value, // json?] list so a half-typed row (and its open JSON editor) survives a // re-render; headersOf folds that back into the object the backend stores, @@ -3139,7 +3195,11 @@ function drawEditor(p, presetID) { const cx = input(draft.contexts || "", t("e.g. 128k · or gpt-6=1m, comma separated")); ed.append(...field(t("Context window"), contextPicks(p, cx), t("How long a request the models take, told to the agents; empty leaves it to the vendor and models.dev"))); ed.append(...field(t("Fallback"), renderFallback(p), fallbackHint(p))); - ed.append(...field(t("Proxy"), proxyPicker())); + const proxies = el("div", "stack"); + proxies.append(proxyPicker()); + const perAccount = subOf(a.agent) ? accountProxyPicker(a) : null; + if (perAccount) proxies.append(perAccount); + ed.append(...field(t("Proxy"), proxies)); if (p.chat || p.responses || p.anthropic) ed.append(...field(t("Endpoints"), renderEndpoints(p, p))); const bar = el("div", "bar"); // removing only hides it from magpie; the agent stays signed in @@ -3155,7 +3215,13 @@ function drawEditor(p, presetID) { if (cx.error) return editorError(t("Context window: {v} is not a length like 128k or 1m", { v: cx.error }), "warn"); const proxy = proxyOfDraft(); if (proxy === null) { ed.querySelector(".proxy-url")?.focus(); return editorError(t("Proxy: type its address, like http://127.0.0.1:7890"), "warn"); } - saveBtn.classList.add("busy"); providerAction("save", { id: p.id, models: chosenIds(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, proxy }, t("{name} saved", { name: p.name })); }; + const own = accountProxiesOfDraft(); + if (own.missing) { + const line = [...ed.querySelectorAll(".acct-proxy")].find((x) => x.dataset.user.toLowerCase() === own.missing); + line?.querySelector(".proxy-url")?.focus({ preventScroll: true }); + return editorError(t("Proxy of {user}: type its address, like http://127.0.0.1:7890", { user: line?.dataset.user || own.missing }), "warn"); + } + saveBtn.classList.add("busy"); providerAction("save", { id: p.id, models: chosenIds(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, proxy, accountProxies: own.map }, t("{name} saved", { name: p.name })); }; bar.append(cancel, saveBtn); ed.append(bar); return ed; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2ff9f9f67..ff81f13c1 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -544,6 +544,10 @@ const I18N = { "Requests to it go direct, whatever the proxy in Settings": "发往它的请求直连,不走设置里的代理", "Requests to it go through this proxy: http://, https:// or socks5://": "发往它的请求走这个代理:http://、https:// 或 socks5://", "Proxy: type its address, like http://127.0.0.1:7890": "代理:请填写地址,例如 http://127.0.0.1:7890", + // each account's own proxy (gakki) + "Provider's proxy": "供应商代理", + "Each account can go through a proxy of its own; Provider's proxy is the one above": "每个账号可以走自己的代理;“供应商代理”即上面这一项", + "Proxy of {user}: type its address, like http://127.0.0.1:7890": "{user} 的代理:请填写地址,例如 http://127.0.0.1:7890", "Add another {name}": "再添加一个 {name}", "One more {name} provider, with its own key, headers and models": "再添加一个 {name} 供应商,使用各自的 key、请求头和模型", "e.g. {name} · Work": "例如 {name} · Work", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 71e82ac2a..c462bc9b0 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -53,6 +53,9 @@ type providerJSON struct { // the proxy its requests go through: "" the global one, "direct" // none, or an address (#237) Proxy string `json:"proxy"` + // the proxy of each of a subscription's accounts that has one of its + // own, by its name in lower case; the others follow Proxy + AccountProxies map[string]string `json:"accountProxies,omitempty"` // where a custom provider's balance is asked (see provider.Balance) BalanceURL string `json:"balanceURL,omitempty"` BalancePath string `json:"balancePath,omitempty"` @@ -201,7 +204,7 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { ID: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Host: p.Host(), Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Decide: p.Decide, Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, - Proxy: p.Proxy, Headers: p.Headers, BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL, + Proxy: p.Proxy, AccountProxies: p.AccountProxies, Headers: p.Headers, BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL, Ready: p.Ready(), Chosen: p.Models, Models: []modelJSON{}, Agents: []providerAgent{}, Fallback: p.Fallback, Routing: p.Routing, Affinity: p.Affinity, Unlisted: p.Unlisted, Off: p.Off, Contexts: p.Contexts, } @@ -539,6 +542,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } else if old != nil { in.Proxy = old.Proxy } + // each account's own proxy likewise: {} clears them + if in.AccountProxies == nil && old != nil { + in.AccountProxies = old.AccountProxies + } if in.Key == "" && old != nil { in.Key = old.Key } diff --git a/internal/gui/tests/account-proxy.test.cjs b/internal/gui/tests/account-proxy.test.cjs new file mode 100644 index 000000000..ff84b9304 --- /dev/null +++ b/internal/gui/tests/account-proxy.test.cjs @@ -0,0 +1,176 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Each account of a subscription with several has a proxy of its own +// (gakki: 是否可以为不同的codex账号设置不同的代理): Codex's editor has, under +// its Proxy row, a line per account — Provider's proxy | Direct | Custom — +// opening on what each has; Save posts accountProxies with each account +// that doesn't follow Codex's, and Custom with no address is refused +// before anything is posted. A pick moves nothing and the page stays where +// it is. A subscription with one account has no such lines. In English +// and Chinese. +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 codex = { + id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { + agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", + logins: [ + { user: "spare@example.com", plan: "PLUS", on: true }, + { user: "me@example.com", plan: "PLUS", active: true, on: true }, + { user: "Third@Example.com", plan: "PRO", on: true }, + ], + }, + proxy: "http://10.0.0.2:7890", + accountProxies: { "me@example.com": "socks5://10.0.0.5:1080", "spare@example.com": "direct" }, +}; +const claude = { + id: "claude", name: "Claude", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "claude-opus-5", name: "Claude Opus 5", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "claude", agentName: "Claude Code", user: "solo@example.com", plan: "MAX", logins: [{ user: "solo@example.com", plan: "MAX", active: true, on: true }] }, + proxy: "", +}; + +function serve(lang, posts) { + const providers = { providers: [codex, claude], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") { + posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() }); + return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { prov: "Provider's proxy", direct: "Direct", custom: "Custom", save: "Save", missing: "Proxy of Third@Example.com: type its address, like http://127.0.0.1:7890" }, + zh: { prov: "供应商代理", direct: "直连", custom: "自定义", save: "保存", missing: "Third@Example.com 的代理:请填写地址,例如 http://127.0.0.1:7890" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + const open = async (t, name, wait = ".editor .proxy-mode") => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + 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}-${name}-account-proxy.png`) }); + } + await browser.close(); + }); + const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: name }).first().click(); + await page.locator(wait).first().waitFor(); + return { page, errors, posts }; + }; + const line = (page, user) => page.locator(`.editor .acct-proxy[data-user="${user}"]`); + const mode = (page, user) => line(page, user).locator(".proxy-mode .opt.on").textContent(); + const addr = (page, user) => line(page, user).locator(".proxy-url"); + // what the page and the dialog's scrollers have scrolled + const scrolled = (page) => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" ")); + // a click on one of an account's options: it, the lines and the Save + // button left where they were, nothing scrolled + const pick = async (page, user, name) => { + const b = line(page, user).locator(".proxy-mode .opt", { hasText: name }); + await b.scrollIntoViewIfNeeded(); + await page.waitForTimeout(200); + const where = () => page.evaluate(() => [...document.querySelectorAll(".editor .acct-proxy, .editor .bar")].map((e) => Math.round(e.getBoundingClientRect().top))); + const before = await b.evaluate((e) => e.getBoundingClientRect().top), lines = await where(), sc = await scrolled(page); + await b.click(); + await page.waitForTimeout(250); + const after = await b.evaluate((e) => e.getBoundingClientRect().top); + assert(Math.abs(after - before) <= 1, `${user} ${name} moved from ${before} to ${after}`); + assert.deepEqual(await where(), lines, `a pick of ${name} moved the lines`); + assert.equal(await scrolled(page), sc, `a pick of ${name} scrolled`); + }; + const save = async (page, posts) => { + const n = posts.length; + await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click(); + for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50); + return posts.at(-1); + }; + + test(`${engine} ${lang}: each Codex account's proxy opens as it is and is saved`, async (t) => { + const { page, errors, posts } = await open(t, "Codex", ".editor .acct-proxy"); + // the account in use first, then the others as they are listed + assert.deepEqual(await page.locator(".editor .acct-proxy").evaluateAll((ls) => ls.map((l) => l.dataset.user)), ["me@example.com", "spare@example.com", "Third@Example.com"]); + assert.equal(await mode(page, "me@example.com"), w.custom); + assert.equal(await addr(page, "me@example.com").inputValue(), "socks5://10.0.0.5:1080"); + assert(await addr(page, "me@example.com").isVisible()); + assert.equal(await mode(page, "spare@example.com"), w.direct); + assert(await addr(page, "spare@example.com").isHidden()); + assert.equal(await mode(page, "Third@Example.com"), w.prov, "an account with none follows Codex's"); + assert(await addr(page, "Third@Example.com").isHidden()); + assert.equal(await page.locator(".editor .proxy-pick .proxy-url").inputValue(), "http://10.0.0.2:7890", "Codex's own is kept above"); + + // saved untouched, it posts what it has + let saved = await save(page, posts); + assert.equal(saved.action, "save"); + assert.equal(saved.body.id, "codex"); + assert.equal(saved.body.proxy, "http://10.0.0.2:7890"); + assert.deepEqual(saved.body.accountProxies, { "me@example.com": "socks5://10.0.0.5:1080", "spare@example.com": "direct" }); + + // Custom for the third with nothing typed is refused, nothing posted + await page.locator(".row.provider", { hasText: "Codex" }).first().click(); + await line(page, "Third@Example.com").waitFor(); + await pick(page, "Third@Example.com", w.custom); + assert(await addr(page, "Third@Example.com").isVisible()); + const n = posts.length; + await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click(); + await page.locator(".editor .editor-error").waitFor(); + assert.equal(await page.locator(".editor .editor-error").textContent(), w.missing); + assert.equal(posts.length, n); + assert(await addr(page, "Third@Example.com").evaluate((e) => e === document.activeElement), "its address is focused"); + + // typed, the spare back to Codex's, the first direct + await addr(page, "Third@Example.com").fill(" http://10.0.0.7:3128 "); + await pick(page, "spare@example.com", w.prov); + await pick(page, "me@example.com", w.direct); + assert(await addr(page, "me@example.com").isHidden()); + saved = await save(page, posts); + assert.deepEqual(saved.body.accountProxies, { "me@example.com": "direct", "third@example.com": "http://10.0.0.7:3128" }); + assert.deepEqual(saved.body.models, ["gpt-6"], "its picks go with it"); + + const border = await page.evaluate(() => [...document.querySelectorAll(".acct-proxies, .acct-proxies *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1)); + assert.deepEqual(border, [], "no border stripes"); + const missing = await page.evaluate(() => [ + "Provider's proxy", + "Each account can go through a proxy of its own; Provider's proxy is the one above", + "Proxy of {user}: type its address, like http://127.0.0.1:7890", + ].filter((k) => !I18N.zh[k])); + assert.deepEqual(missing, [], "every string has its Chinese"); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: a subscription with one account has no per-account lines`, async (t) => { + const { page, errors, posts } = await open(t, "Claude"); + assert.equal(await page.locator(".editor .acct-proxies").count(), 0); + const saved = await save(page, posts); + assert.equal(saved.body.id, "claude"); + assert.deepEqual(saved.body.accountProxies, {}); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/netproxy/netproxy.go b/internal/netproxy/netproxy.go index bdc623d4a..5db2062a6 100644 --- a/internal/netproxy/netproxy.go +++ b/internal/netproxy/netproxy.go @@ -58,6 +58,10 @@ func With(ctx context.Context, choice string) context.Context { return context.WithValue(ctx, choiceKey{}, choice) } +// Choice is the proxy ctx names (With), "" when it names none — for a CLI +// run on a provider's behalf, whose *_PROXY is set from it (EnvWith). +func Choice(ctx context.Context) string { return choiceOf(ctx) } + func choiceOf(ctx context.Context) string { if ctx == nil { return "" diff --git a/internal/provider/claude_warmup.go b/internal/provider/claude_warmup.go index cca616f3d..c8ce0f259 100644 --- a/internal/provider/claude_warmup.go +++ b/internal/provider/claude_warmup.go @@ -37,6 +37,8 @@ func claudeWarmUsage(ctx context.Context) map[string]SubscriptionQuota { // Claude Code is signed in to. func warmClaudeLogin(send func(ctx context.Context, oauth string) error) func(context.Context, string) error { return func(ctx context.Context, user string) error { + // the account's own proxy, which send's Claude Code runs with too + ctx = ViaLogin(ctx, "claude", user) ls := Logins("claude") i := slices.IndexFunc(ls, func(l Login) bool { return strings.EqualFold(l.User, user) }) if i < 0 { diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.go index a2941b930..57e38cd1c 100644 --- a/internal/provider/codex_models.go +++ b/internal/provider/codex_models.go @@ -183,7 +183,8 @@ func codexFetchSaved(ctx context.Context) { } user := l.User sign := codexSign(func(ctx context.Context) (string, string, error) { return savedLoginToken(ctx, "codex", user) }) - if ms, err := codexModels(ctx, sign); err == nil { + // through the account's own proxy, if it has one + if ms, err := codexModels(ViaLogin(ctx, "codex", user), sign); err == nil { catalog.SaveLive(accountModels("codex", user), CodexBase, ms) } } diff --git a/internal/provider/codex_resets.go b/internal/provider/codex_resets.go index a25f3be6b..e5608bb07 100644 --- a/internal/provider/codex_resets.go +++ b/internal/provider/codex_resets.go @@ -147,10 +147,11 @@ func (o ResetOutcome) Text() string { // last longer goes before it. It can't be undone: callers ask first. The // account's usage is read afresh after. func UseCodexReset(ctx context.Context, user string) (ResetOutcome, error) { - user, tok, accountID, err := codexUserToken(ctx, user) + user, tok, accountID, err := codexUserToken(ViaLogin(ctx, "codex", user), user) if err != nil { return ResetOutcome{}, err } + ctx = ViaLogin(ctx, "codex", user) // through the account's own proxy base := strings.TrimSuffix(CodexBase, "/codex") // which of them to spend is named, as Codex itself does: left to the // vendor, it may be one that lasts longer @@ -162,7 +163,7 @@ func UseCodexReset(ctx context.Context, user string) (ResetOutcome, error) { if credit == "" { return ResetOutcome{Code: "no_credit"}, nil } - out, err := consumeCodexReset(Via(ctx, "codex"), base, tok, accountID, credit, newRedeemID()) + out, err := consumeCodexReset(ctx, base, tok, accountID, credit, newRedeemID()) if err != nil { return out, err } diff --git a/internal/provider/codex_warmup.go b/internal/provider/codex_warmup.go index 51320f691..b1ea88607 100644 --- a/internal/provider/codex_warmup.go +++ b/internal/provider/codex_warmup.go @@ -346,7 +346,7 @@ func warmCodexLogin(ctx context.Context, user string) error { if err != nil { return err } - return warmCodex(Via(ctx, "codex"), codexSign(token), model, effort) + return warmCodex(ViaLogin(ctx, "codex", user), codexSign(token), model, effort) } // warmModel is the model a warm-up asks, and at what effort: the account's diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index 6e5c751b0..0b30c8e26 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -97,6 +97,7 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota } func loginQuota(ctx context.Context, l Login) SubscriptionQuota { + ctx = ViaLogin(ctx, l.Agent, l.User) // asked through the account's own proxy if l.Agent == "qoder" { return qoderLoginQuota(ctx, l) } diff --git a/internal/provider/logins_on.go b/internal/provider/logins_on.go index daa4e45d9..b376ef287 100644 --- a/internal/provider/logins_on.go +++ b/internal/provider/logins_on.go @@ -148,6 +148,7 @@ func savedLoginToken(ctx context.Context, agent, user string) (tok, accountID st // refuses is kept on the account as lapsed, until one goes through or it is // signed in again. func renewSavedLogin(ctx context.Context, agent, user string, force bool) (tok, accountID string, err error) { + ctx = ViaLogin(ctx, agent, user) // refreshed through the account's own proxy savedTokenMu.Lock() defer savedTokenMu.Unlock() loginsMu.Lock() diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 1dfacba17..cad9b82e9 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -100,6 +100,11 @@ type Provider struct { // "direct" none, anything else the proxy's address (http://, https://, // socks5://; host:port means http). Signed-in accounts keep it too. Proxy string `json:"proxy,omitempty"` + // AccountProxies is, for a subscription holding several accounts + // (Codex's, Claude Code's…), the proxy of each account that has one + // of its own, by its name in lower case, as Proxy takes one; an + // account not in it follows Proxy (see ProxyChoice). + AccountProxies map[string]string `json:"accountProxies,omitempty"` // BalanceURL, when set, is where the vendor tells what is left on a // key, asked with the key the way a chat request carries it; BalancePath @@ -224,7 +229,7 @@ func All() []Provider { } pk := picks[a.ID] a.Models, a.Unlisted, a.Off, a.Fallback, a.Routing, a.Affinity, a.Contexts, a.Family = pk.Models, pk.Unlisted, pk.Off, pk.Fallback, pk.Routing, pk.Affinity, pk.Contexts, pk.Family - a.Proxy = pk.Proxy + a.Proxy, a.AccountProxies = pk.Proxy, pk.AccountProxies if a.ID == "cursor" { // picked before its efforts were one model a.Models = cursorPicks(a.Models) } @@ -307,6 +312,9 @@ func Save(p Provider) error { if err := settings.CheckProxy(p.Proxy); err != nil { return err } + if err := checkAccountProxies(p.AccountProxies); err != nil { + return err + } if p.Name == "" { p.Name = p.ID } @@ -320,8 +328,9 @@ func Save(p Provider) error { if p.ID == "kiro" { key = p.Key } - p = Provider{ID: p.ID, Key: key, Models: p.Models, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Affinity: p.Affinity, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID)} + p = Provider{ID: p.ID, Key: key, Models: p.Models, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Affinity: p.Affinity, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID)} } else { + p.AccountProxies = nil // a provider of a key has no accounts to proxy apart if slices.Contains(accountIDs, p.ID) && !stored(p.ID) { // taken, it would hide that subscription once signed in return fmt.Errorf("%q is the id of the %s subscription; pick another name", p.ID, p.ID) @@ -521,6 +530,7 @@ func normalize(p Provider) Provider { p.Name = strings.TrimSpace(p.Name) p.Key = strings.TrimSpace(p.Key) p.Proxy = strings.TrimSpace(p.Proxy) + p.AccountProxies = normalAccountProxies(p.AccountProxies) for _, u := range []*string{&p.Chat, &p.Responses, &p.Anthropic, &p.Decide, &p.Website, &p.KeysURL} { *u = strings.TrimRight(strings.TrimSpace(*u), "/") if *u != "" && !strings.Contains(*u, "://") { diff --git a/internal/provider/proxy.go b/internal/provider/proxy.go index 322f6c822..83f33c51e 100644 --- a/internal/provider/proxy.go +++ b/internal/provider/proxy.go @@ -2,29 +2,123 @@ package provider import ( "context" + "fmt" + "strings" "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/settings" ) // Via is ctx for requests made on the provider's behalf: they go through -// its own proxy (Proxy), or the global one when it has none. +// its own proxy (ProxyChoice), or the global one when it has none. func (p Provider) Via(ctx context.Context) context.Context { - return netproxy.With(ctx, p.Proxy) + return netproxy.With(ctx, p.ProxyChoice()) +} + +// ProxyChoice is the proxy requests made on the provider's behalf go +// through, as netproxy.With takes it: for one account of a subscription +// that holds several, that account's own (AccountProxies), else the +// provider's (Proxy); "" follows the global one. An account in use beside +// the agent's own is made afresh by some agents (AlsoOn), without the +// provider's settings: those are read from providers.json. +func (p Provider) ProxyChoice() string { + if p.Account == nil { + return p.Proxy + } + own, prov := p.AccountProxies, p.Proxy + if own == nil && prov == "" { + if s, ok := storedPicks(p.ID); ok { + own, prov = s.AccountProxies, s.Proxy + } + } + if v := own[accountKey(p.Account.User)]; v != "" { + return v + } + return prov } // ProxyOf is the own proxy of the provider or signed-in account with id, // "" when it follows the global one. func ProxyOf(id string) string { - for _, p := range load().Providers { - if p.ID == id { - return p.Proxy - } + if s, ok := storedPicks(id); ok { + return s.Proxy } return "" } +// ProxyOfLogin is the proxy requests made on behalf of the account user +// of the subscription id go through (gakki: one Codex account through one +// proxy, another through another): the account's own, or else the +// subscription's (ProxyOf); "" follows the global one. +func ProxyOfLogin(id, user string) string { + s, ok := storedPicks(id) + if !ok { + return "" + } + if v := s.AccountProxies[accountKey(user)]; v != "" { + return v + } + return s.Proxy +} + // Via is ctx for requests made on behalf of the provider or signed-in // account with id (see Provider.Via). func Via(ctx context.Context, id string) context.Context { return netproxy.With(ctx, ProxyOf(id)) } + +// ViaLogin is ctx for requests made on behalf of the account user of the +// subscription id (ProxyOfLogin). +func ViaLogin(ctx context.Context, id, user string) context.Context { + return netproxy.With(ctx, ProxyOfLogin(id, user)) +} + +// ViaSignedIn is ctx for requests made with the sign-in an agent has now +// (Codex's own, relayed as it came): through the proxy of the account it +// is signed in to. +func ViaSignedIn(ctx context.Context, id string) context.Context { + if l, ok := liveLogin(id); ok { + return ViaLogin(ctx, id, l.User) + } + return Via(ctx, id) +} + +func storedPicks(id string) (Provider, bool) { + for _, p := range load().Providers { + if p.ID == id { + return p, true + } + } + return Provider{}, false +} + +// accountKey is how an account is known in AccountProxies: its name as the +// accounts list shows it, in lower case, as accounts are told apart. +func accountKey(user string) string { return strings.ToLower(strings.TrimSpace(user)) } + +// normalAccountProxies is m as it is kept: keys in lower case, addresses +// trimmed, accounts following the provider's proxy left out; nil for none. +func normalAccountProxies(m map[string]string) map[string]string { + var out map[string]string + for u, v := range m { + u, v = accountKey(u), strings.TrimSpace(v) + if u == "" || v == "" { + continue + } + if out == nil { + out = map[string]string{} + } + out[u] = v + } + return out +} + +// checkAccountProxies refuses an account's proxy Settings would refuse. +func checkAccountProxies(m map[string]string) error { + for u, v := range m { + if err := settings.CheckProxy(v); err != nil { + return fmt.Errorf("%s: %w", u, err) + } + } + return nil +} diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index b33d449fa..5b2053218 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -194,6 +194,9 @@ func fetchSubscriptionUsage() []SubscriptionQuota { proxies[p.ID] = p.Proxy } via := func(id string) context.Context { return netproxy.With(ctx0, proxies[id]) } + // and one account of several through its own, if it has one (perLogin + // and loginQuota ask each so) + viaLogin := func(id, user string) context.Context { return ViaLogin(ctx0, id, user) } hidden := map[string]bool{} for _, p := range load().Providers { hidden[p.ID] = p.Hidden || p.Off // switched off: not asked either @@ -203,11 +206,11 @@ func fetchSubscriptionUsage() []SubscriptionQuota { if ls := accountsOf("claude"); len(ls) > 1 { fetches = append(fetches, perLogin(via("claude"), ls, "Claude Code", "claude-color")...) } else { - fetches = append(fetches, withUser(p.Account.User, func() SubscriptionQuota { return claudeSubscriptionUsage(via("claude")) })) + fetches = append(fetches, withUser(p.Account.User, func() SubscriptionQuota { return claudeSubscriptionUsage(viaLogin("claude", p.Account.User)) })) } } if user, plan, ok := cursorIdentity(); ok && !hidden["cursor"] { - fetches = append(fetches, withUser(user, func() SubscriptionQuota { return cursorSubscriptionUsage(via("cursor"), plan) })) + fetches = append(fetches, withUser(user, func() SubscriptionQuota { return cursorSubscriptionUsage(viaLogin("cursor", user), plan) })) } if _, ok := grokAccount(); ok && !hidden["grok"] { fetches = append(fetches, func() SubscriptionQuota { return grokSubscriptionUsage(via("grok")) }) @@ -218,7 +221,7 @@ func fetchSubscriptionUsage() []SubscriptionQuota { fetches = append(fetches, perLogin(via("codex"), ls, "Codex", "codex-color")...) } else { auth := filepath.Join(home, ".codex", "auth.json") - fetches = append(fetches, withUser(p.Account.User, func() SubscriptionQuota { return codexSubscriptionUsage(via("codex"), auth) })) + fetches = append(fetches, withUser(p.Account.User, func() SubscriptionQuota { return codexSubscriptionUsage(viaLogin("codex", p.Account.User), auth) })) } } cfg := os.Getenv("XDG_CONFIG_HOME") @@ -229,7 +232,7 @@ func fetchSubscriptionUsage() []SubscriptionQuota { if ls := copilotLoginList(); len(ls) > 1 { fetches = append(fetches, perLogin(via("copilot"), ls, "Copilot", "githubcopilot")...) } else { - fetches = append(fetches, withUser(app.User, func() SubscriptionQuota { return copilotSubscriptionUsage(via("copilot"), app.Token) })) + fetches = append(fetches, withUser(app.User, func() SubscriptionQuota { return copilotSubscriptionUsage(viaLogin("copilot", app.User), app.Token) })) } } } @@ -263,7 +266,7 @@ func fetchSubscriptionUsage() []SubscriptionQuota { continue } for _, l := range googleLogins(agent) { - fetches = append(fetches, func() SubscriptionQuota { return l.acct.quota(via(agent), l.Plan) }) + fetches = append(fetches, func() SubscriptionQuota { return l.acct.quota(viaLogin(agent, l.User), l.Plan) }) } } out := make([]SubscriptionQuota, len(fetches))