diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 221f6b3c2..bb09b04f9 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -218,6 +218,12 @@ body.window .field.solo { grid-column: auto; } .subscription-head { display: flex; align-items: center; gap: 7px; margin-bottom: 9px; } .subscription-head .ic { width: 17px; height: 17px; } .subscription-head b { font-size: 12.5px; font-weight: 600; } +.subscription-account { display: flex; align-items: baseline; gap: 7px; margin: 0 0 6px; font-size: 11px; color: var(--fg-2); } +.subscription-card.several .quota-windows + .subscription-account, +.subscription-card.several .subscription-error + .subscription-account, +.subscription-card.several .quota-balance + .subscription-account { margin-top: 10px; padding-top: 9px; border-top: 1px solid var(--line); } +.subscription-account .user { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.subscription-account .plan { margin-left: auto; flex: none; font-size: 10.5px; color: var(--muted); text-transform: capitalize; } .subscription-head .plan { margin-left: auto; font-size: 10.5px; color: var(--muted); text-transform: capitalize; } .quota-windows { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px 14px; } .quota-labels { display: flex; align-items: baseline; gap: 6px; margin-bottom: 4px; font-size: 10.5px; color: var(--muted); } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 71111d4e5..87b71b1f6 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -2689,40 +2689,62 @@ function renderQuotas() { return; } subscriptions.hidden = !quotas.length; + // an agent with several accounts is one card, a section per account + const groups = []; for (const sub of quotas) { - const card = el("div", "subscription-card"); + const g = sub.user && groups.find((x) => x[0].user && x[0].provider === sub.provider); + if (g) g.push(sub); else groups.push([sub]); + } + for (const subs of groups) { + const first = subs[0]; + const card = el("div", "subscription-card" + (first.user ? " several" : "")); const head = el("div", "subscription-head"); - head.append(icon(sub.icon), el("b", "", sub.name)); - if (sub.plan) head.append(el("span", "plan", sub.plan)); - else if (sub.user) head.append(el("span", "plan", sub.user)); + head.append(icon(first.icon), el("b", "", first.name)); + if (!first.user && first.plan) head.append(el("span", "plan", first.plan)); card.append(head); - if (sub.balance) { - const b = el("div", "quota-balance"); - b.append(el("span", "", t("Balance")), el("b", "", sub.balance)); - card.append(b); - } else if (sub.error) { - card.append(el("div", "subscription-error", t("Usage unavailable"))); - card.title = sub.error; - } else { - const windows = el("div", "quota-windows"); - for (const w of sub.windows) { - const quota = el("div", "quota"); - const labels = el("div", "quota-labels"); - labels.append(el("span", "", t(w.name)), el("b", "", w.display || `${Math.round(w.used)}%`)); - const track = el("div", "quota-track"); - const fill = el("i"); - fill.style.width = `${Math.max(0, Math.min(100, w.used))}%`; - track.append(fill); - quota.append(labels, track); - if (w.resetsAt) quota.title = t("Resets {when}", { when: new Date(w.resetsAt).toLocaleString() }); - windows.append(quota); + for (const sub of subs) { + if (sub.user) { + const who = el("div", "subscription-account"); + const u = el("span", "user", sub.user); + u.title = sub.user; + who.append(u); + if (sub.plan) who.append(el("span", "plan", sub.plan)); + card.append(who); } - card.append(windows); + card.append(quotaWindows(sub)); } subscriptions.append(card); } } +// quotaWindows: one account's allowance as meters, or why there are none. +function quotaWindows(sub) { + if (sub.balance) { + const b = el("div", "quota-balance"); + b.append(el("span", "", t("Balance")), el("b", "", sub.balance)); + return b; + } + if (sub.error) { + const e = el("div", "subscription-error", t("Usage unavailable")); + e.title = sub.error; + return e; + } + const windows = el("div", "quota-windows"); + for (const w of sub.windows) { + const quota = el("div", "quota"); + const labels = el("div", "quota-labels"); + labels.append(el("span", "", t(w.name)), el("b", "", w.display || `${Math.round(w.used)}%`)); + const track = el("div", "quota-track"); + const fill = el("i"); + fill.style.width = `${Math.max(0, Math.min(100, w.used))}%`; + track.append(fill); + quota.append(labels, track); + if (w.resetsAt) quota.title = t("Resets {when}", { when: new Date(w.resetsAt).toLocaleString() }); + windows.append(quota); + } + return windows; +} + function renderUsage() { const u = usage; const view = $("#view-usage"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index ab01a7118..23d1297f8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -372,6 +372,8 @@ const I18N = { "5 hours": "5 小时", "7 days · Opus": "7 天 · Opus", "7 days · Sonnet": "7 天 · Sonnet", + "Auto + Composer": "Auto + Composer", + "Total": "合计", "Usage unavailable": "暂时无法获取用量", "Resets {when}": "重置于 {when}", "Allowance": "用量额度", diff --git a/internal/provider/account_test.go b/internal/provider/account_test.go index 361358e80..cf86d4453 100644 --- a/internal/provider/account_test.go +++ b/internal/provider/account_test.go @@ -59,17 +59,19 @@ func signIn(t *testing.T) string { return home } -// isolate keeps tests off the machine's own Claude Code Keychain login and -// forgets anything a previous test cached. +// isolate keeps tests off the machine's own Claude Code and Cursor Keychain +// logins and forgets anything a previous test cached. func isolate(t *testing.T) { t.Helper() oldKeychain, oldURL, oldBase, oldExe := claudeKeychain, claudeTokenURL, claudeBase, claudeExecutable - claudeKeychain = false + oldCursor := cursorKeychain + claudeKeychain, cursorKeychain = false, false claudeExecutable = func() string { return "" } forgetClaudeCredential() forgetClaudeStatus() t.Cleanup(func() { claudeKeychain, claudeTokenURL, claudeBase, claudeExecutable = oldKeychain, oldURL, oldBase, oldExe + cursorKeychain = oldCursor forgetClaudeCredential() forgetClaudeStatus() }) diff --git a/internal/provider/cursor_usage.go b/internal/provider/cursor_usage.go new file mode 100644 index 000000000..7821fa9d2 --- /dev/null +++ b/internal/provider/cursor_usage.go @@ -0,0 +1,127 @@ +package provider + +// How much of a Cursor plan's included usage is gone, as the CLI's own +// usage view reads it: the dashboard's current period, split into what Auto +// and Composer used and what the named (API) models did. + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" +) + +// cursorBase is Cursor's API; a var so tests can point it elsewhere. +var cursorBase = "https://api2.cursor.sh" + +// cursorKeychain reads cursor-agent's token from the macOS Keychain; a var +// so tests stay off the real one. +var cursorKeychain = runtime.GOOS == "darwin" + +// cursorToken is the access token cursor-agent signed in with: in the +// Keychain on a Mac, in its auth.json elsewhere. +func cursorToken() (string, error) { + if cursorKeychain { + out, err := exec.Command("security", "find-generic-password", "-s", "cursor-access-token", "-a", "cursor-user", "-w").Output() + if tok := strings.TrimSpace(string(out)); err == nil && tok != "" { + return tok, nil + } + } + var auth struct { + AccessToken string `json:"accessToken"` + } + if path := cursorAuthPath(); path != "" && readJSON(path, &auth) && auth.AccessToken != "" { + return auth.AccessToken, nil + } + return "", errorf("cursor-agent is not signed in") +} + +// cursorAuthPath is where cursor-agent keeps its sign-in outside the Keychain. +func cursorAuthPath() string { + home, err := os.UserHomeDir() + if err != nil { + return "" + } + switch runtime.GOOS { + case "windows": + dir := os.Getenv("APPDATA") + if dir == "" { + dir = filepath.Join(home, "AppData", "Roaming") + } + return filepath.Join(dir, "Cursor", "auth.json") + case "darwin": + return filepath.Join(home, ".cursor", "auth.json") + } + dir := os.Getenv("XDG_CONFIG_HOME") + if dir == "" { + dir = filepath.Join(home, ".config") + } + return filepath.Join(dir, "cursor", "auth.json") +} + +func cursorSubscriptionUsage(ctx context.Context, plan string) SubscriptionQuota { + q := SubscriptionQuota{Provider: "cursor", Name: "Cursor", Icon: "cursor", Plan: plan, Windows: []QuotaWindow{}} + tok, err := cursorToken() + if err == nil { + q.Windows, err = cursorWindows(ctx, tok) + } + if err != nil { + q.Error = err.Error() + } + return q +} + +// cursorWindows: the plan's included usage this billing period. An +// enterprise plan reports spend instead, and gets no windows. +func cursorWindows(ctx context.Context, token string) ([]QuotaWindow, error) { + var data struct { + BillingCycleEnd string `json:"billingCycleEnd"` // epoch millis + PlanUsage *struct { + Auto float64 `json:"autoPercentUsed"` + API float64 `json:"apiPercentUsed"` + Total float64 `json:"totalPercentUsed"` + } `json:"planUsage"` + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, cursorBase+"/aiserver.v1.DashboardService/GetCurrentPeriodUsage", bytes.NewReader([]byte("{}"))) + if err != nil { + return []QuotaWindow{}, err + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Connect-Protocol-Version", "1") + res, err := http.DefaultClient.Do(req) + if err != nil { + return []QuotaWindow{}, err + } + defer res.Body.Close() + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if res.StatusCode < 200 || res.StatusCode >= 300 { + return []QuotaWindow{}, &accountStatusError{status: res.StatusCode} + } + if err := json.Unmarshal(b, &data); err != nil { + return []QuotaWindow{}, err + } + if data.PlanUsage == nil { + return []QuotaWindow{}, nil + } + var resets *time.Time + if ms, err := strconv.ParseInt(data.BillingCycleEnd, 10, 64); err == nil && ms > 0 { + t := time.UnixMilli(ms) + resets = &t + } + u := data.PlanUsage + // the two pools fit the line; the total goes in its tooltip + return []QuotaWindow{ + {Name: "Auto + Composer", Used: u.Auto, ResetsAt: resets}, + {Name: "API", Used: u.API, ResetsAt: resets}, + {Name: "Total", Used: u.Total, ResetsAt: resets}, + }, nil +} diff --git a/internal/provider/cursor_usage_test.go b/internal/provider/cursor_usage_test.go new file mode 100644 index 000000000..4ebb44b73 --- /dev/null +++ b/internal/provider/cursor_usage_test.go @@ -0,0 +1,42 @@ +package provider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +// Cursor's current period comes back as its two pools and the total, each +// resetting when the billing cycle ends. +func TestCursorWindows(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/aiserver.v1.DashboardService/GetCurrentPeriodUsage" || r.Header.Get("Authorization") != "Bearer tok" { + http.Error(rw, "no", http.StatusUnauthorized) + return + } + _ = json.NewEncoder(rw).Encode(map[string]any{ + "billingCycleEnd": "1792833042000", + "planUsage": map[string]any{"autoPercentUsed": 12.5, "apiPercentUsed": 40, "totalPercentUsed": 20}, + }) + })) + defer srv.Close() + old := cursorBase + cursorBase = srv.URL + defer func() { cursorBase = old }() + + ws, err := cursorWindows(context.Background(), "tok") + if err != nil { + t.Fatal(err) + } + if len(ws) != 3 || ws[0].Used != 12.5 || ws[1].Used != 40 || ws[2].Used != 20 { + t.Fatalf("windows = %+v", ws) + } + if ws[0].ResetsAt == nil || ws[0].ResetsAt.UnixMilli() != 1792833042000 { + t.Fatalf("resets = %v", ws[0].ResetsAt) + } + if _, err := cursorWindows(context.Background(), "bad"); err == nil { + t.Fatal("a refused token is an error") + } +} diff --git a/internal/provider/grok_usage.go b/internal/provider/grok_usage.go index f7883d9d0..270ea8d20 100644 --- a/internal/provider/grok_usage.go +++ b/internal/provider/grok_usage.go @@ -15,6 +15,9 @@ var grokBase = "https://cli-chat-proxy.grok.com/v1" func grokSubscriptionUsage(ctx context.Context) SubscriptionQuota { q := SubscriptionQuota{Provider: "grok", Name: "Grok", Icon: "xai", Windows: []QuotaWindow{}} + if c, ok := readGrokCredential(GrokHome()); ok { + q.User = c.Email + } c, err := grokAccessToken(GrokHome(), GrokExecutable(), false) if err == nil { q.Windows, err = grokWindows(ctx, c.Key) diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index 8e46623a1..92cb8639b 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -29,13 +29,21 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota return grokLoginUsage(ctx) } out := map[string]SubscriptionQuota{} - if agent != "claude" && agent != "codex" { + var logins []Login + switch agent { + case "claude", "codex": + logins = Logins(agent) + case "cursor": // one account, the one cursor-agent is signed in to + if user, plan, ok := cursorIdentity(); ok { + logins = []Login{{Agent: agent, User: user, Plan: plan, Active: true, On: true}} + } + default: return out } c := &loginUsageCache var mu sync.Mutex var wg sync.WaitGroup - for _, l := range Logins(agent) { + for _, l := range logins { key := agent + "/" + strings.ToLower(l.User) c.Lock() e, ok := c.m[key] @@ -67,6 +75,9 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota } func loginQuota(ctx context.Context, l Login) SubscriptionQuota { + if l.Agent == "cursor" { + return cursorSubscriptionUsage(ctx, l.Plan) + } q := SubscriptionQuota{Provider: l.Agent, Plan: l.Plan, Windows: []QuotaWindow{}} var tok, accountID string var err error diff --git a/internal/provider/logins_on_test.go b/internal/provider/logins_on_test.go index 83ca2e5ad..1bbbd2911 100644 --- a/internal/provider/logins_on_test.go +++ b/internal/provider/logins_on_test.go @@ -130,3 +130,36 @@ func TestLoginUsageEachAccount(t *testing.T) { t.Fatal("usage for an agent without accounts") } } + +// With several accounts, the usage page has a card for each, the one the +// agent is signed in to first. +func TestSubscriptionUsageEachAccount(t *testing.T) { + home := signIn(t) + rememberLogins(true) + codexSignIn(t, home, "work@example.com", "r-work") + rememberLogins(true) + used := map[string]float64{"acct-1": 12, "acct-work@example.com": 97} + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/backend-api/wham/usage" { + w.WriteHeader(404) + return + } + json.NewEncoder(w).Encode(map[string]any{"plan_type": "pro", "rate_limit": map[string]any{ + "primary_window": map[string]any{"used_percent": used[r.Header.Get("chatgpt-account-id")], "limit_window_seconds": 18000}}}) + })) + defer fake.Close() + old := CodexBase + CodexBase = fake.URL + "/backend-api/codex" + t.Cleanup(func() { CodexBase = old }) + + var codex []SubscriptionQuota + for _, q := range fetchSubscriptionUsage() { + if q.Provider == "codex" { + codex = append(codex, q) + } + } + if len(codex) != 2 || codex[0].User != "work@example.com" || codex[0].Windows[0].Used != 97 || + codex[1].User != "me@example.com" || codex[1].Windows[0].Used != 12 || codex[1].Name != "Codex" { + t.Fatalf("cards %+v", codex) + } +} diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index d8c85c752..0b0f54d79 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -8,6 +8,7 @@ import ( "net/http" "os" "path/filepath" + "sort" "strings" "sync" "time" @@ -104,23 +105,34 @@ func fetchSubscriptionUsage() []SubscriptionQuota { hidden[p.ID] = p.Hidden } var fetches []func() SubscriptionQuota - if _, ok := claudeAccount(); ok && !hidden["claude"] { - fetches = append(fetches, func() SubscriptionQuota { return claudeSubscriptionUsage(ctx) }) + if p, ok := claudeAccount(); ok && !hidden["claude"] { + if ls := accountsOf("claude"); len(ls) > 1 { + fetches = append(fetches, perLogin(ctx, ls, "Claude Code", "claude-color")...) + } else { + fetches = append(fetches, withUser(p.Account.User, func() SubscriptionQuota { return claudeSubscriptionUsage(ctx) })) + } + } + if user, plan, ok := cursorIdentity(); ok && !hidden["cursor"] { + fetches = append(fetches, withUser(user, func() SubscriptionQuota { return cursorSubscriptionUsage(ctx, plan) })) } if _, ok := grokAccount(); ok && !hidden["grok"] { fetches = append(fetches, func() SubscriptionQuota { return grokSubscriptionUsage(ctx) }) } if home, err := os.UserHomeDir(); err == nil { - if _, ok := codexAccount(home); ok && !hidden["codex"] { - auth := filepath.Join(home, ".codex", "auth.json") - fetches = append(fetches, func() SubscriptionQuota { return codexSubscriptionUsage(ctx, auth) }) + if p, ok := codexAccount(home); ok && !hidden["codex"] { + if ls := accountsOf("codex"); len(ls) > 1 { + fetches = append(fetches, perLogin(ctx, ls, "Codex", "codex-color")...) + } else { + auth := filepath.Join(home, ".codex", "auth.json") + fetches = append(fetches, withUser(p.Account.User, func() SubscriptionQuota { return codexSubscriptionUsage(ctx, auth) })) + } } cfg := os.Getenv("XDG_CONFIG_HOME") if cfg == "" { cfg = filepath.Join(home, ".config") } if app, ok := copilotLogin(cfg); ok && !hidden["copilot"] { - fetches = append(fetches, func() SubscriptionQuota { return copilotSubscriptionUsage(ctx, app.Token) }) + fetches = append(fetches, withUser(app.User, func() SubscriptionQuota { return copilotSubscriptionUsage(ctx, app.Token) })) } } out := make([]SubscriptionQuota, len(fetches)) @@ -133,6 +145,36 @@ func fetchSubscriptionUsage() []SubscriptionQuota { return out } +// accountsOf is every account magpie remembers for agent, the one it is +// signed in to first. +func accountsOf(agent string) []Login { + ls := Logins(agent) + sort.SliceStable(ls, func(i, j int) bool { return ls[i].Active && !ls[j].Active }) + return ls +} + +// withUser names the account a fetch is for. +func withUser(user string, f func() SubscriptionQuota) func() SubscriptionQuota { + return func() SubscriptionQuota { + q := f() + q.User = user + return q + } +} + +// perLogin fetches each account's allowance on a card of its own. +func perLogin(ctx context.Context, ls []Login, name, icon string) []func() SubscriptionQuota { + var out []func() SubscriptionQuota + for _, l := range ls { + out = append(out, func() SubscriptionQuota { + q := loginQuota(ctx, l) + q.Name, q.Icon, q.User = name, icon, l.User + return q + }) + } + return out +} + func accountJSON(ctx context.Context, url, token string, headers map[string]string, dst any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil {