Files
magpie/internal/cli/statusline_cli.go
T
yetone 1dfa284840 usage: a plugin's row of text alone shows its text, not "· 100% left"
AutoClaw's 积分余额, Cline's balance, Cursor's Auto + Composer note and
the other plugin rows that are only words come to magpie as a window set
aside with a display and nothing counted (used 0, no amount, no limit).
Every surface read that used 0 as a share: the usage card said
"1,234 积分 · 100% left" (or "· 0% used") beside an empty meter, the
panel drew an empty ring, the TUI an empty bar, `magpie accounts` and
`magpie quota` "积分余额 0% (1,234 积分)", and the status line
"积分余额 0%".

provider: QuotaWindow.Text (json "text") marks such a row in
quotaOfPlugin: aside, a display, used/amount/limit all 0. Aside is
required: Cursor's On-demand "$0 / $20" isn't set aside and is a real
0%. QuotaSpan carries it to /api/quotas.
GUI (app.js): quotaText gives the display alone; the account row's
meter, the Usage page's track and the panel's rings leave the row out;
a panel card with only such rows shows their text on its line, as an
Unlimited card does. The tray's menu-bar text already skips aside rows.
TUI quotaCell, the CLI's quotaCell (accounts, quota) and statuslineCard
write the name and the text.

app.js stays under its budget (1,322,289, not raised; now 1,322,275):
to make room, the 8 copies of Math.max(0, Math.min(100, x)) are one
to100(x), and 8 one-line [..].filter(Boolean).join("\n") tooltips are
tipLines(..). Same results; the GUI files below cover those callers.

Readings cached before this release have no text flag and show as
before until the account is read again (a minute's cache, or Refresh).

Run, at this commit's tree (rebased on origin/main 9dc7d6eb8):
- internal/gui/tests/quota-text-row.test.cjs (new): a text row alone
  and beside a counted window, through accountQuota, panelQuotaCard,
  quotaWindows and quotaText; chromium and webkit, en and zh: 4 of 4.
- the GUI files the change reaches (quota*, usage*, panel*, tray*,
  profile*, plugin-plan, plugin-quota*, plugin-panels, api-key-usage,
  claude-usage, gateway-key-quotas, glm/opencode-go quota errors,
  routing-quota-left, gui-de/ja/zh-TW, i18n-keys; 114 files, both
  engines, 4 wide, load 130 to 200): 1433 of 1467. The reds, rerun
  alone here and with 9dc7d6eb8's own app.js: quota-count-wrap (webkit,
  #3404 #2228), usage-agents-hide (#3414 #2276), usage-checkin's Qoder
  tab (webkit, #2549), usage-fold (#3415 #2163) and usage-ledger's
  return-to-live (#3104) fail the same at both; api-key-usage failed
  once 4 wide and passes alone at both (#3589).
- go test -timeout 45m ./internal/gui/ ./internal/cli/ ./internal/tui/
  ./internal/provider/: ok (TestCoreScriptBudget included).
- gofmt -l internal/ clean; go vet on darwin, linux (nogui) and windows
  for provider, cli, tui (and gui on darwin): clean.
Broken by hand:
- app.js at HEAD under the new GUI test: red, quotaText gave
  "1,234 积分 · 0% used" / "1,234 积分 · 已用 0%".
- quotaOfPlugin's Text line removed: TestPluginTextRowIsText red.
- the CLI's quotaCell at HEAD: TestQuotaCell red ("积分余额 0% (1,234 积分)");
  statuslineCard at HEAD: red ("autoclaw-plugin 积分余额 0% 5h 40%").
- the TUI's quotaCell at HEAD: TestTextQuotaCell red
  ("积分余额 ░░░░░░░░ 1,234 积分 · 0% used").
Not tried: a real AutoClaw, Cline, Cursor, Factory or ZCode account in
the app (fixtures follow the plugins' own window shapes); the full
`go test ./...` and the whole GUI suite; the Linux and Windows apps.
2026-10-25 17:26:38 +08:00

170 lines
5.4 KiB
Go

package cli
// magpie statusline: one line for Claude Code's status line (#1997,
// kensenzhao). Claude Code runs the statusLine command on every message,
// hands it the session's JSON on stdin and shows what it prints, however
// Claude Code signs in to the gateway; the anthropic-ratelimit-* headers
// (#1257) reach it only while it is signed in to claude.ai itself, and
// tell only the one account that answered. This asks the running gateway
// for what it already holds — the session's latest route and every
// account's windows as last read (/v1/magpie/quotas?kept=1) — and asks no
// vendor itself, so it never waits on one.
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
const statuslineUsage = `usage: magpie statusline [<provider|account>…]
one line for Claude Code's status line: the model the session's latest turn went
to through magpie, then each subscription and plan magpie has, as last read: its
windows' use ("5h 62% 7d 41%"), * on the one that answered last. Accounts that
answered through magpie in the last 30 days are shown, all of them when none has;
a provider or an account's email, login or name keeps only those.
Claude Code runs it on every message with the session's JSON on stdin; put it in
~/.claude/settings.json yourself (magpie doesn't write it, a status line such as
claude-hud may hold it):
"statusLine": {"type": "command", "command": "magpie statusline"}
It asks the gateway on this computer (the port in Settings' Gateway address, or MAGPIE_ADDR), never
a vendor, and prints nothing when the gateway isn't running.`
// statuslineWait bounds each ask of the gateway: Claude Code shows the line
// only once the command ends.
const statuslineWait = time.Second
// statuslineCmd: magpie statusline [<provider|account>…]
func statuslineCmd(args []string) error {
fmt.Println(statusline(os.Stdin, args[1:], "http://"+settings.GatewayAddr(), time.Now()))
return nil
}
// statusline is the line: "" when the gateway can't be asked.
func statusline(stdin io.Reader, only []string, base string, now time.Time) string {
var in struct {
SessionID string `json:"session_id"`
}
if stdin != nil {
// Claude Code's JSON is small; a terminal's stdin with nothing
// piped in isn't waited on (read only when it is a pipe or file)
if f, ok := stdin.(*os.File); !ok || stdinPiped(f) {
_ = json.NewDecoder(io.LimitReader(stdin, 1<<20)).Decode(&in)
}
}
client := &http.Client{Timeout: statuslineWait}
var quotas struct {
Data []provider.Quota `json:"data"`
}
if !getJSON(client, base+"/v1/magpie/quotas?kept=1", &quotas) {
return ""
}
var parts []string
if in.SessionID != "" {
var route struct {
Route *struct {
Asked string `json:"asked"`
Model string `json:"model"`
} `json:"route"`
}
if getJSON(client, base+"/v1/magpie/route?session="+url.QueryEscape(in.SessionID), &route) && route.Route != nil {
if m := route.Route.Model; m != "" {
parts = append(parts, "→ "+m)
} else if route.Route.Asked != "" {
parts = append(parts, "→ "+route.Route.Asked)
}
}
}
for _, q := range statuslineCards(quotas.Data, only) {
parts = append(parts, statuslineCard(q, now))
}
return strings.Join(parts, " | ")
}
// stdinPiped: f is a pipe or a file, not a terminal waiting for typing.
func stdinPiped(f *os.File) bool {
st, err := f.Stat()
return err == nil && st.Mode()&os.ModeCharDevice == 0
}
func getJSON(c *http.Client, u string, v any) bool {
res, err := c.Get(u)
if err != nil {
return false
}
defer res.Body.Close()
return res.StatusCode == http.StatusOK && json.NewDecoder(res.Body).Decode(v) == nil
}
// statuslineCards are the subscriptions and plans with windows to show:
// those named, else those that answered through magpie lately, else all.
func statuslineCards(qs []provider.Quota, only []string) []provider.Quota {
var withWindows, served []provider.Quota
for _, q := range qs {
if q.Kind == "balance" || len(q.Windows) == 0 {
continue
}
if len(only) > 0 && !statuslineMatches(q, only) {
continue
}
withWindows = append(withWindows, q)
if q.LastServedAt != nil {
served = append(served, q)
}
}
if len(only) == 0 && len(served) > 0 {
return served
}
return withWindows
}
func statuslineMatches(q provider.Quota, only []string) bool {
for _, o := range only {
for _, v := range []string{q.Provider, q.Name, q.User, q.Alias, q.Provider + "/" + q.User} {
if v != "" && strings.EqualFold(v, o) {
return true
}
}
}
return false
}
// statuslineCard is one account: "claude a@x.com* 5h 62% 7d 41%".
func statuslineCard(q provider.Quota, now time.Time) string {
name := q.Provider
switch {
case q.Alias != "":
name += " " + q.Alias
case q.User != "":
name += " " + q.User
}
if q.Last {
name += "*"
}
short := strings.NewReplacer(" hours", "h", " hour", "h", " days", "d", " day", "d", " · ", " ")
cells := []string{name}
for _, w := range q.Windows {
n := short.Replace(w.Name)
switch {
case w.Unlimited:
cells = append(cells, n+" ∞")
case w.Text:
// a row of text alone (a plugin's balance) has no share
cells = append(cells, n+" "+w.Display)
case w.ResetsAt != nil && !w.ResetsAt.After(now):
// its window has started again since it was read
cells = append(cells, n+" 0%")
default:
cells = append(cells, fmt.Sprintf("%s %.0f%%", n, w.Used))
}
}
return strings.Join(cells, " ")
}