cli, usage: magpie usage takes --last <dur> and --days <n>, a window ending now, with or without --csv and --account (#2075, tinysnake, fcy222fcy)

today, 7d and 30d begin at a local midnight, so a caller wanting "the
last few hours" just after midnight had to take 7d's CSV, seven days of
rows for one. `magpie usage [--csv [--account <name>]] --last 24h` (any
Go duration, 90m) or `--days 1.5` now reads a window that began that
long ago; the presets are unchanged.

From fcy222fcy's branch (usage-rolling-window, 60472c661): a rolling
window is a period "last:<dur>" (usage.LastOf / Period.Last) that Since,
Known, shown and the chart's timeline answer for, so the ledger, Direct
and the summary read the same window.

Review fixes on top:
- a summary of a rolling window is worked out each time, like a picked
  range: kept, its start didn't move with the clock while the log
  stayed the same (reachable through the web API's ?period=last:24h);
- the CSV export's file name has no colon from "last:24h0m0s", which
  Windows refuses;
- `--last 24h 7d` is refused rather than silently taking --last;
- --days refuses NaN, Inf and over a century;
- the help line and docs/reference.md name the flags.

Run: new TestRollingWindowIsNotKeptStale fails with the cache fix taken
out ("an hour later: 1 calls, want 0"); TestCSVStamp fails without the
colon fix ("magpie-requests-last:24h0m0s-2026-09-30");
TestUsageRollingWindowRejectsJunk fails without the preset/--days
checks; TestUsageRollingWindow and the new ...WithAccount fail (3 rows,
want 2) with Since moved back. go test -tags nogui ./internal/usage/...
./internal/cli/... ./internal/usageapi/... ./internal/gui/... in a
sandbox HOME: ok. gofmt -l clean; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows; go build darwin, linux nogui, windows.
Real use: the built binary on a sandbox HOME with a generated 50,000-call
7-day usage.jsonl: --csv 7d 47,233 rows / 6.97 MB; today 4,376; --last
24h 7,140 / 1.05 MB; --last 90m 444; --days 1.5 10,712; --account me@x
--last 24h 3,570 (that account's half); oldest row of each at the
window's start.
Not tried: the full go test ./... suite; the process still parses the
whole usage.jsonl into its in-memory index on each run (as every period
does), so the cut is in rows decoded and written, not bytes read.

Co-authored-by: fchengyan <3181088318@qq.com>
This commit is contained in:
yetone
2026-10-14 15:26:28 +08:00
co-authored by fchengyan
parent 0ad9661b60
commit 62378c5f84
10 changed files with 357 additions and 10 deletions
+4
View File
@@ -280,6 +280,10 @@ account, a plugin's and a vendor whose own client magpie goes as
(OpenCode, Cline, Kilo, another magpie) keep the User-Agent their sign-in
sends, and don't take it.
`magpie usage` (and `--csv`) takes `today`, `7d`, `30d` or `all`, each from a
local midnight, or a window ending now: `--last 24h` (any Go duration, `90m`)
or `--days 1.5`; the CSV then holds that window's calls only (#2075).
`magpie usage` also lists **upstream provider keys** to help check upstream bills.
Each request records the fingerprint and saved name of the key that actually
served it, including image calls and account/key failover. The CSV adds
+1
View File
@@ -120,6 +120,7 @@ const usage = `magpie — one place to pick every agent's model
magpie mcp image the image and video generation MCP server an agent is given from the library (stdio)
magpie usage [today|7d|30d|all] tokens and cost per agent, model and subscription account (30d)
magpie usage --csv [--account <name>] [today|7d|30d|all] every request as CSV (or one account's): the model asked for, sent and served, tokens, cost, time, status, account
magpie usage [--csv [--account <name>]] --last <dur>|--days <n> the same for a window ending now (24h, 90m, 1.5 days), not from a midnight
magpie sessions [--model <m>] [--folder <f>] [--json] the latest Claude Code, Codex, OpenCode and Pi sessions, with what each cost
magpie sessions --days N|today|all [--model <m>] [--folder <f>] [--json]
what every session spent, day by day, with the top models and folders (7 days)
+84 -3
View File
@@ -4,8 +4,10 @@ import (
"context"
"fmt"
"io"
"math"
"os"
"slices"
"strconv"
"strings"
"time"
@@ -39,13 +41,16 @@ func loadCostCurrency() {
// usageCmd: `magpie usage [today|7d|30d|all]` — tokens and cost per agent,
// model, subscription account and session; with --csv, every request of the
// period as CSV, one row each, to set beside a vendor's bill, and with
// --account <name> too, only the calls that account answered (#557)
// --account <name> too, only the calls that account answered (#557). With
// --days or --last, a rolling window ending now rather than a preset's
// calendar boundary (#2075), as magpie sessions and magpie quota history
// take --days.
func usageCmd(args []string) error {
return usageTo(os.Stdout, args)
}
func usageTo(out io.Writer, args []string) error {
const how = "usage: magpie usage [--csv [--account <name>]] [today|7d|30d|all]"
const how = "usage: magpie usage [--csv [--account <name>]] [--days <n>|--last <dur>] [today|7d|30d|all]"
asCSV := false
if i := slices.Index(args, "--csv"); i > 0 {
asCSV, args = true, slices.Delete(slices.Clone(args), i, i+1)
@@ -57,11 +62,64 @@ func usageTo(out io.Writer, args []string) error {
}
f.Account, args = args[i+1], slices.Delete(slices.Clone(args), i, i+2)
}
// a rolling window: --days takes a number of days (1, 7, even 1.5, as
// magpie quota history's does) and --last a duration (24h, 90m), both
// ending now, where the presets begin at a local midnight (#2075)
var last time.Duration
take := func(flag string, parse func(string) (time.Duration, error)) (bool, error) {
v := ""
for i := 0; i < len(args); i++ {
switch a := args[i]; {
case a == flag && i+1 < len(args):
v, args = args[i+1], slices.Delete(slices.Clone(args), i, i+2)
i--
case strings.HasPrefix(a, flag+"="):
v, args = strings.TrimPrefix(a, flag+"="), slices.Delete(slices.Clone(args), i, i+1)
i--
case a == flag || strings.HasPrefix(a, flag+"="):
return true, fmt.Errorf("%s takes a value\n%s", flag, how)
}
}
if v == "" {
return false, nil
}
d, err := parse(v)
if err != nil || d <= 0 {
return true, fmt.Errorf("%s takes a %s greater than zero, not %q\n%s", flag, strings.TrimPrefix(flag, "--"), v, how)
}
last = d
return true, nil
}
daysTaken, err := take("--days", func(v string) (time.Duration, error) {
n, err := strconv.ParseFloat(v, 64)
if err != nil || math.IsNaN(n) || n > 100*365 {
return 0, fmt.Errorf("not a number of days: %q", v)
}
return time.Duration(n * 24 * float64(time.Hour)), nil
})
if err != nil {
return err
}
if lastTaken, err := take("--last", time.ParseDuration); err != nil {
return err
} else if daysTaken && lastTaken {
return fmt.Errorf("take --days or --last, not both\n%s", how)
}
if len(args) > 2 {
return fmt.Errorf("%s", how)
}
period := stats.Month
if len(args) > 1 {
if last > 0 {
if len(args) > 1 {
// a preset beside the window: which one was meant can't be told
return fmt.Errorf("take --days/--last or a period (%s), not both\n%s", args[1], how)
}
p, ok := stats.LastOf(last)
if !ok {
return fmt.Errorf("%s", how)
}
period = p
} else if len(args) > 1 {
switch strings.ToLower(args[1]) {
case "today", "day":
period = stats.Today
@@ -86,6 +144,9 @@ func usageTo(out io.Writer, args []string) error {
// midnight falls while they are read.
s, d := stats.Summaries(period)
title := map[stats.Period]string{stats.Today: "today", stats.Week: "last 7 days", stats.Month: "last 30 days", stats.All: "all time"}[s.Period]
if dur := s.Period.Last(); dur > 0 {
title = "last " + humanWindow(dur)
}
if s.Calls == 0 && d.Calls == 0 {
fmt.Fprintln(out, muted.Render("no calls "+title+" ·"), "route an agent through magpie and its usage shows up here")
fmt.Fprintln(out, faint.Render(" "+stats.Path()))
@@ -109,6 +170,26 @@ func usageTo(out io.Writer, args []string) error {
return nil
}
// humanWindow says a rolling window's length the way a title reads it:
// whole days as days, whole hours as hours, the rest in minutes.
func humanWindow(d time.Duration) string {
switch {
case d%(24*time.Hour) == 0:
return plural(int(d/(24*time.Hour)), "day")
case d%time.Hour == 0:
return plural(int(d/time.Hour), "hour")
default:
return plural(int(d/time.Minute)+boolToInt(d%time.Minute > 0), "minute")
}
}
func boolToInt(b bool) int {
if b {
return 1
}
return 0
}
// printUsage is a summary's totals and its tables: agents, models,
// upstream keys, accounts, gateway keys and the top sessions.
func printUsage(out io.Writer, s stats.Summary, title string, names map[string]string) {
+88
View File
@@ -0,0 +1,88 @@
package cli
import (
"encoding/csv"
"strings"
"testing"
"time"
stats "github.com/yetone/magpie/internal/usage"
)
// magpie usage --last and --days read a rolling window ending now (#2075):
// what --csv rows and the summary both cover, where the presets begin at a
// local midnight.
func TestUsageRollingWindow(t *testing.T) {
groupsHome(t)
now := holdUsageClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
stats.Append(stats.Record{Time: now.Add(-time.Hour), Agent: "codex", Provider: "a", Model: "m", Input: 10, Status: 200})
stats.Append(stats.Record{Time: now.Add(-25 * time.Hour), Agent: "claude", Provider: "b", Model: "m", Input: 10, Status: 200})
var b strings.Builder
if err := usageTo(&b, []string{"usage", "--csv", "--last", "24h"}); err != nil {
t.Fatal(err)
}
recs, err := csv.NewReader(strings.NewReader(b.String())).ReadAll()
if err != nil {
t.Fatal(err)
}
if len(recs) != 2 { // the header and the call an hour old, not the one 25 hours old
t.Fatalf("%d rows, want 2:\n%s", len(recs), b.String())
}
b.Reset()
if err := usageTo(&b, []string{"usage", "--csv", "--days", "1.5"}); err != nil {
t.Fatal(err)
}
recs, _ = csv.NewReader(strings.NewReader(b.String())).ReadAll()
if len(recs) != 3 { // 36 hours: both calls
t.Fatalf("--days 1.5: %d rows, want 3", len(recs))
}
b.Reset()
if err := usageTo(&b, []string{"usage", "--last", "24h"}); err != nil {
t.Fatal(err)
}
if s := b.String(); !strings.Contains(s, "last 1 day") || !strings.Contains(s, "1 call") {
t.Errorf("summary says neither its window nor its count:\n%s", s)
}
}
func TestUsageRollingWindowRejectsJunk(t *testing.T) {
groupsHome(t)
for _, args := range [][]string{
{"usage", "--last", "abc"},
{"usage", "--last", "0s"},
{"usage", "--days", "0"},
{"usage", "--days", "-1"},
{"usage", "--days"},
{"usage", "--last"},
{"usage", "--last", "24h", "--days", "1"},
{"usage", "--last", "24h", "7d"}, // which window was meant can't be told
{"usage", "--days", "NaN"},
{"usage", "--days", "Inf"},
{"usage", "--days", "1e30"},
} {
if err := usageTo(&strings.Builder{}, args); err == nil {
t.Errorf("%v: no error", args)
}
}
}
// --last composes with --account as a preset does: the window's calls that
// account answered, and no other's (#2075, #557).
func TestUsageRollingWindowWithAccount(t *testing.T) {
groupsHome(t)
now := holdUsageClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
stats.Append(stats.Record{Time: now.Add(-time.Hour), Agent: "codex", Provider: "a", ProviderAccount: "me@x", Model: "m", Input: 10, Status: 200})
stats.Append(stats.Record{Time: now.Add(-2 * time.Hour), Agent: "codex", Provider: "a", ProviderAccount: "other@x", Model: "m", Input: 10, Status: 200})
stats.Append(stats.Record{Time: now.Add(-30 * time.Hour), Agent: "codex", Provider: "a", ProviderAccount: "me@x", Model: "m", Input: 10, Status: 200})
var b strings.Builder
if err := usageTo(&b, []string{"usage", "--csv", "--account", "me@x", "--last", "24h"}); err != nil {
t.Fatal(err)
}
recs, err := csv.NewReader(strings.NewReader(b.String())).ReadAll()
if err != nil {
t.Fatal(err)
}
if len(recs) != 2 { // the header and me@x's call an hour old
t.Fatalf("%d rows, want 2:\n%s", len(recs), b.String())
}
}
+3 -1
View File
@@ -56,7 +56,9 @@ func csvStamp(p usage.Period, day string, now time.Time) string {
if p.IsRange() { // the days picked, which already say when
return "magpie-requests-" + strings.Replace(string(p), "..", "-to-", 1)
}
return "magpie-requests-" + string(p) + "-" + now.Format(time.DateOnly)
// a rolling window ("last:24h0m0s") without the colon, which Windows
// doesn't take in a file name (#2075)
return "magpie-requests-" + strings.ReplaceAll(string(p), ":", "-") + "-" + now.Format(time.DateOnly)
}
// contentJSON is what was said in a request, or why it can't be told.
+5
View File
@@ -326,6 +326,11 @@ func TestCSVStamp(t *testing.T) {
t.Fatalf("%q: %s", day, got)
}
}
// a rolling window's name has no colon, which Windows refuses (#2075)
p, _ := usage.LastOf(24 * time.Hour)
if got := csvStamp(p, "", now); strings.ContainsAny(got, `:/\\`) {
t.Errorf("rolling window: %s", got)
}
}
// midnightUsageClock sets usage.Clock to read a tenth of a second before
+23
View File
@@ -184,6 +184,10 @@ func (p Period) Since(now time.Time) time.Time {
if first, _, ok := p.days(now.Location()); ok {
return first
}
// a rolling window ends now, so it began that long ago (#2075)
if d := p.Last(); d > 0 {
return now.Add(-d)
}
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
switch p {
case Today:
@@ -564,6 +568,25 @@ func timeline(p Period, now, first time.Time) (since time.Time, bucket string, p
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
bucket, pts = "day", []Point{}
var n int
// a rolling window ends now: an hour each of two days or less, else a
// day each from when it began (#2075)
if d := p.Last(); d > 0 {
since = now.Add(-d)
if d <= 48*time.Hour {
bucket = "hour"
for h := 0; h <= int(d.Hours()); h++ {
t := since.Add(time.Duration(h) * time.Hour)
pts = append(pts, Point{Label: t.Format("15"), Time: t})
}
} else {
n = int(d.Hours())/24 + 1
for i := 0; i < n; i++ {
t := since.AddDate(0, 0, i)
pts = append(pts, Point{Label: t.Format("Jan 2"), Time: t})
}
}
return since, bucket, pts
}
if first, last, ok := p.days(now.Location()); ok {
// a picked range: an hour each of a single day, else a day each,
// a week each (from a Monday) past 60 days as All has
+112
View File
@@ -0,0 +1,112 @@
package usage
import (
"testing"
"time"
)
// A rolling window (#2075) is a period of its own: it ends now and began
// that long ago, where the presets begin at a local midnight — what
// `magpie usage --last 24h` asks for when today is 35 minutes old and a
// preset would give a whole calendar day.
func TestRollingWindowIsAPeriod(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 10, 10, 12, 0, 0, 0, time.Local))
at := func(m time.Month, d, h int) time.Time { return time.Date(2026, m, d, h, 0, 0, 0, time.Local) }
for _, when := range []time.Time{
at(10, 9, 11), // 25 hours ago
at(10, 9, 13), // 23 hours ago
at(10, 10, 11),
} {
Append(Record{Time: when, Agent: "claude", Provider: "openai", Model: "m", Input: 10, Status: 200})
}
p, ok := LastOf(24 * time.Hour)
if !ok || !p.Known() || p.Last() != 24*time.Hour { // the period's text is its duration's own form ("last:24h0m0s"), which reads back as 24h
t.Fatalf("LastOf(24h): %q %v", p, ok)
}
if got := p.Last(); got != 24*time.Hour {
t.Errorf("Last(): %v, want 24h", got)
}
if !p.Since(now).Equal(at(10, 9, 12)) {
t.Errorf("Since: %v, want Oct 9 12:00", p.Since(now))
}
if !p.Until(now).IsZero() {
t.Errorf("Until: %v, want zero (it runs up to now)", p.Until(now))
}
s := Summarize(p)
if s.Calls != 2 || s.Period != p {
t.Errorf("Summarize(%s): %d calls, period %q; want 2", p, s.Calls, s.Period)
}
if s.Bucket != "hour" || len(s.Series) != 25 {
t.Errorf("Summarize(%s): %d %s points; want 25 hours", p, len(s.Series), s.Bucket)
}
if !s.Series[0].Time.Equal(at(10, 9, 12)) || !s.Series[24].Time.Equal(at(10, 10, 12)) {
t.Errorf("Summarize(%s): points %v..%v", p, s.Series[0].Time, s.Series[24].Time)
}
if l := LedgerOf(p, Filter{}); len(l.Rows) != 2 {
t.Errorf("LedgerOf(%s): %d rows, want 2", p, len(l.Rows))
}
if d := Direct(p); d.Period != p || !d.Since.Equal(at(10, 9, 12)) {
t.Errorf("Direct(%s): period %q since %v", p, d.Period, d.Since)
}
}
// Longer than two days, a rolling window's chart is a day each.
func TestRollingWindowOverTwoDaysIsDays(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 10, 10, 12, 0, 0, 0, time.Local))
Append(Record{Time: now.Add(-time.Hour), Agent: "claude", Provider: "openai", Model: "m", Input: 10, Status: 200})
p, _ := LastOf(72 * time.Hour)
if s := Summarize(p); s.Calls != 1 || s.Bucket != "day" || len(s.Series) != 4 {
t.Errorf("Summarize(%s): %d calls, %d %s points; want 1 in 4 days", p, s.Calls, len(s.Series), s.Bucket)
}
}
// Minutes work too, and so does a fractional day the CLI's --days builds.
func TestRollingWindowFractions(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 10, 10, 12, 0, 0, 0, time.Local))
Append(Record{Time: now.Add(-30 * time.Minute), Agent: "claude", Provider: "openai", Model: "m", Input: 10, Status: 200})
p, _ := LastOf(90 * time.Minute)
if s := Summarize(p); s.Calls != 1 || s.Bucket != "hour" || len(s.Series) != 2 {
t.Errorf("Summarize(%s): %d calls, %d %s points; want 1 in 2 hours", p, s.Calls, len(s.Series), s.Bucket)
}
if q, _ := LastOf(36 * time.Hour); q.Last() != 36*time.Hour {
t.Errorf("LastOf(36h): %v", q.Last())
}
}
func TestRollingWindowRejectsJunk(t *testing.T) {
for _, bad := range []Period{"last:0s", "last:abc", "last:-5m", "last:", "last", "90d"} {
if bad.Known() {
t.Errorf("%q is known", bad)
}
if bad.Last() != 0 {
t.Errorf("%q lasts %v", bad, bad.Last())
}
}
if p, ok := LastOf(0); ok || p != "" {
t.Errorf("LastOf(0): %q %v", p, ok)
}
if p, ok := LastOf(-time.Hour); ok || p != "" {
t.Errorf("LastOf(-1h): %q %v", p, ok)
}
}
// A rolling window's start moves with the clock while the log stays as it
// is: a summary asked again later doesn't count a call that has fallen out
// of it, as a kept summary would (#2075).
func TestRollingWindowIsNotKeptStale(t *testing.T) {
pageHome(t)
at := time.Date(2026, 10, 10, 12, 0, 0, 0, time.Local)
holdClock(t, at)
Append(Record{Time: at.Add(-30 * time.Minute), Agent: "claude", Provider: "openai", Model: "m", Input: 10, Status: 200})
p, _ := LastOf(time.Hour)
if s := SummarizeTop(p, 10); s.Calls != 1 {
t.Fatalf("at noon: %d calls, want 1", s.Calls)
}
holdClock(t, at.Add(time.Hour))
if s := SummarizeTop(p, 10); s.Calls != 0 {
t.Errorf("an hour later: %d calls, want 0 (the call is 90 minutes old)", s.Calls)
}
}
+34 -4
View File
@@ -25,6 +25,36 @@ func RangeOf(from, to string) (Period, bool) {
return Period(a.Format(time.DateOnly) + rangeSep + b.Format(time.DateOnly)), true
}
// A period can also be hours or days long, ending now (#2075): a rolling
// window, written "last:24h" or "last:90m", read from LastOf. Unlike the
// presets, which begin at a local midnight, it begins that long ago —
// what `magpie usage --last 24h` and `--days 1` ask for, where a preset
// would give a whole calendar day or week instead.
const lastSep = "last:"
// LastOf is the rolling window of d ending now; ok is false when d is
// not positive.
func LastOf(d time.Duration) (Period, bool) {
if d <= 0 {
return "", false
}
return Period(lastSep + d.String()), true
}
// Last is the length of a rolling window ("last:24h"), 0 when p is not
// one.
func (p Period) Last() time.Duration {
s, ok := strings.CutPrefix(string(p), lastSep)
if !ok {
return 0
}
d, err := time.ParseDuration(s)
if err != nil || d <= 0 {
return 0
}
return d
}
// days is the first and last day of a picked range, at midnight in loc.
func (p Period) days(loc *time.Location) (first, last time.Time, ok bool) {
from, to, found := strings.Cut(string(p), rangeSep)
@@ -45,14 +75,14 @@ func (p Period) IsRange() bool {
return ok
}
// Known is whether p is a period the usage pages answer for: a preset or a
// picked range.
// Known is whether p is a period the usage pages answer for: a preset, a
// picked range or a rolling window.
func (p Period) Known() bool {
switch p {
case Today, Week, Month, All:
return true
}
return p.IsRange()
return p.IsRange() || p.Last() > 0
}
// Until is when the period ends, as of now: the midnight after a picked
@@ -70,7 +100,7 @@ func after(until, t time.Time) bool { return !until.IsZero() && !t.Before(until)
// shown is the period a summary says it is of: the preset or range asked
// for, and All for anything else.
func (p Period) shown() Period {
if p == Today || p == Week || p == Month || p.IsRange() {
if p == Today || p == Week || p == Month || p.IsRange() || p.Last() > 0 {
return p
}
return All
+3 -2
View File
@@ -49,9 +49,10 @@ func topSummary(p Period, now time.Time, n int) Summary {
summaries.Unlock()
return summarizeFrom(p, now, snapshot.first, snapshot.keyProviders, func(fn func(Record)) { snapshot.visit(p.Since(now), fn) })
}
if p.IsRange() {
if p.IsRange() || p.Last() > 0 {
// a picked range is read afresh each time, so ranges never pile up
// in the cache (#1492)
// in the cache (#1492), and so is a rolling window, whose start
// moves with the clock though the log hasn't changed (#2075)
return topOf(work(), n)
}
meta := usagePriceCacheKey(now)