usage:day takes a from: a week, a month or all time in one read (HeheLi29136651 on X)

HeheLi29136651 asked for the Day card's weekly, monthly and total bill. The
read only answered one day, so the plugin had nothing to draw. usage:day
now takes {from: "YYYY-MM-DD" | "all"} beside date: the days from there to
date, with the same totals, agents, models and days list (usageapi.SpanOf;
DayOf is SpanOf with no from). "all" starts at the first day with calls:
the ledger keeps old calls in wider buckets that start before the first
call, so From is taken from the first day the heatmap lists. A from after
date, or a date after today, is an error. Answers carry `from`, which is how
a plugin tells a magpie that has spans from one that ignores the param.

Run, on mote:
- TestSpanOf (week, month, all, all up to an earlier date, day alone,
  bad inputs) with calls 300 days back, where the bucket starts before the
  first call: red when the From correction is removed (From 2026-01-12 for
  a first call on 01-15), green with it.
- TestPluginPageReadsADay gains from "2000-01-01", from "all" and a from
  after the day.
- go vet (darwin, windows, linux -tags nogui), usageapi and internal/plugin
  tests ok.
- The plugin side (page-day-card 0.3.0) reads it: seen in the sandbox web
  instance in chromium and webkit, empty ledger only.

Not tried: a ledger with real calls end to end in the page (the plugin's
test covers the card from a made-up read), and a magpie from before this
change opening the 0.3.0 page (the code path throws "usage:day from" when
there is no `from`, and says to update).
This commit is contained in:
yetone
2026-11-11 17:38:42 +08:00
parent a94468ea5e
commit 745d209dcf
5 changed files with 141 additions and 8 deletions
File diff suppressed because one or more lines are too long
+6 -3
View File
@@ -75,12 +75,15 @@ func dataURL(name string, b []byte) string {
return "data:" + ctype + ";base64," + base64.StdEncoding.EncodeToString(b)
}
// pageDay is the usage:day read: params {date: "YYYY-MM-DD", tz: an IANA
// zone}, both optional (today, this computer's zone).
// pageDay is the usage:day read: params {date: "YYYY-MM-DD", from:
// "YYYY-MM-DD" or "all", tz: an IANA zone}, all optional (today, the day
// alone, this computer's zone): with a from it is the days from there to
// date (usageapi.SpanOf), a week's or a month's or all time's.
func pageDay(params map[string]any) (any, error) {
date, _ := params["date"].(string)
from, _ := params["from"].(string)
tz, _ := params["tz"].(string)
d, err := usageapi.DayOf(date, usage.Zone(tz))
d, err := usageapi.SpanOf(from, date, usage.Zone(tz))
if err != nil {
return nil, err
}
+14
View File
@@ -52,6 +52,20 @@ func TestPluginPageReadsADay(t *testing.T) {
if w := pagePost(h, "/api/plugin-pages/read", map[string]any{"spec": on, "read": "usage:day", "params": map[string]any{"date": "2999-01-01"}}); w.Code == 200 {
t.Errorf("a day after today: %d %s", w.Code, w.Body)
}
// a from makes it a span: a week's, a month's or all time's
for _, from := range []string{"2000-01-01", "all"} {
w := pagePost(h, "/api/plugin-pages/read", map[string]any{"spec": on, "read": "usage:day", "params": map[string]any{"from": from}})
var span map[string]any
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &span) != nil {
t.Fatalf("usage:day from %s: %d %s", from, w.Code, w.Body)
}
if f, _ := span["from"].(string); f == "" || f > day["date"].(string) {
t.Errorf("usage:day from %s has from %q: %s", from, f, w.Body)
}
}
if w := pagePost(h, "/api/plugin-pages/read", map[string]any{"spec": on, "read": "usage:day", "params": map[string]any{"from": "2999-01-01"}}); w.Code == 200 {
t.Errorf("a from after the day: %d %s", w.Code, w.Body)
}
if w := pagePost(h, "/api/plugin-pages/read", map[string]any{"spec": on, "read": "usage:summary"}); w.Code != http.StatusForbidden {
t.Errorf("a read it no longer declares: %d", w.Code)
}
+52 -4
View File
@@ -78,7 +78,10 @@ type DayCount struct {
// Day is a day's usage.
type Day struct {
Date string `json:"date"` // YYYY-MM-DD, in the zone asked for
// From is the first day of the span asked for (SpanOf), the same as
// Date for a day
From string `json:"from"`
Date string `json:"date"` // YYYY-MM-DD, in the zone asked for; a span's last day
Today string `json:"today"` // the zone's today
DayTotals
Agents []DayAgent `json:"agents"`
@@ -90,7 +93,18 @@ type Day struct {
// DayOf is the day date (YYYY-MM-DD; "" for today) in zone (nil is this
// computer's). A day after today is an error.
func DayOf(date string, zone *time.Location) (Day, error) {
func DayOf(date string, zone *time.Location) (Day, error) { return SpanOf("", date, zone) }
// SpanAll as SpanOf's from is every day there is a call for, up to date.
const SpanAll = "all"
// SpanOf is the days from from to date, both included (YYYY-MM-DD; date ""
// is today, from "" is date alone and SpanAll the first day with calls), in
// zone (nil is this computer's), as DayOf is one day: a week's, a month's or
// all time's totals and the agents and models that made them. A day after
// today is an error, as is a from after date.
func SpanOf(from, date string, zone *time.Location) (Day, error) {
span := from
if zone == nil {
zone = time.Local
}
@@ -106,10 +120,39 @@ func DayOf(date string, zone *time.Location) (Day, error) {
if date > today {
return Day{}, fmt.Errorf("%s is after today, %s", date, today)
}
p, _ := usage.RangeOf(date, date)
f := usage.Filter{Zone: zone}
var p usage.Period
switch from {
case "", date:
from = date
p, _ = usage.RangeOf(date, date)
case SpanAll:
// every day through date: the ledger's whole span is through today,
// so an earlier date is the range from the first day with calls
first := usage.QueryPage(usage.All, f, 0, 1)
from = date
for _, pt := range first.Series {
if pt.Calls > 0 {
if day := pt.Time.In(zone).Format(time.DateOnly); day < from {
from = day
}
break
}
}
p, _ = usage.RangeOf(from, date)
default:
a, err := time.ParseInLocation(time.DateOnly, from, zone)
if err != nil {
return Day{}, fmt.Errorf("no date %q: YYYY-MM-DD", from)
}
from = a.Format(time.DateOnly)
if from > date {
return Day{}, fmt.Errorf("%s is after %s", from, date)
}
p, _ = usage.RangeOf(from, date)
}
all := usage.QueryPage(p, f, 0, 1)
out := Day{Date: date, Today: today, DayTotals: dayTotals(all.Sum), Agents: []DayAgent{}, Days: []DayCount{}}
out := Day{From: from, Date: date, Today: today, DayTotals: dayTotals(all.Sum), Agents: []DayAgent{}, Days: []DayCount{}}
agents := clients()
face := providerFaces(provider.All())
@@ -150,5 +193,10 @@ func DayOf(date string, zone *time.Location) (Day, error) {
out.Days = append(out.Days, DayCount{Date: h.Date, Calls: h.Calls, Tokens: h.Tokens, Cost: h.Cost})
}
}
if span == SpanAll && len(out.Days) > 0 && out.Days[0].Date > out.From {
// the ledger keeps older calls in wider buckets, which start before
// the first call: all time begins at the first day with calls
out.From = out.Days[0].Date
}
return out, nil
}
+68
View File
@@ -90,3 +90,71 @@ func TestDayOf(t *testing.T) {
}
}
}
// usage:day with a from is the days from there to the date, a week's, a
// month's or all time's (Day card's period switch, HeheLi29136651 on X):
// one set of totals and agents over all of them, from the first day with
// calls for "all".
func TestSpanOf(t *testing.T) {
home := t.TempDir()
testenv.SetHome(t, home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
heldClients := Clients
Clients = func() []Client { return []Client{{ID: "claude", Name: "Claude Code", Icon: "claude-color"}} }
t.Cleanup(func() { Clients = heldClients })
now := time.Now()
held := usage.Clock
usage.Clock = func() time.Time { return now }
t.Cleanup(func() { usage.Clock = held })
y, m, d := now.Date()
noon := time.Date(y, m, d, 12, 0, 0, 0, time.Local)
ago := func(n int) time.Time { return noon.AddDate(0, 0, -n) }
for _, r := range []usage.Record{
{Time: ago(300), Agent: "codex", Provider: "openai", Model: "gpt-z", Input: 1000, Output: 100},
{Time: ago(20), Agent: "claude", Provider: "anthropic", Model: "claude-x", Input: 500, Output: 50},
{Time: ago(3), Agent: "claude", Provider: "anthropic", Model: "claude-x", Input: 40, Output: 4},
{Time: ago(3), Agent: "codex", Provider: "openai", Model: "gpt-z", Input: 30, Output: 3},
{Time: ago(0), Agent: "claude", Provider: "anthropic", Model: "claude-x", Input: 2, Output: 1},
} {
usage.Append(r)
}
day := func(n int) string { return ago(n).Format(time.DateOnly) }
// a week: the seven days ending today
w, err := SpanOf(day(6), "", time.Local)
if err != nil {
t.Fatal(err)
}
if w.From != day(6) || w.Date != day(0) || w.Calls != 3 || w.Input != 72 || w.Output != 8 || len(w.Agents) != 2 || w.Agents[0].ID != "claude" || w.Agents[0].Calls != 2 || w.Agents[1].Models[0].Model != "gpt-z" {
t.Errorf("week %+v", w)
}
// a month's worth reaches the call 20 days back, not the one 40 back
mo, err := SpanOf(day(29), "", time.Local)
if err != nil || mo.Calls != 4 || mo.Input != 572 {
t.Errorf("month %+v %v", mo, err)
}
// all time: from the first day with calls
all, err := SpanOf(SpanAll, "", time.Local)
if err != nil {
t.Fatal(err)
}
if all.From != day(300) || all.Date != day(0) || all.Calls != 5 || all.Input != 1572 || len(all.Days) != 4 {
t.Errorf("all %+v", all)
}
// up to an earlier date it stops there
upTo, err := SpanOf(SpanAll, day(10), time.Local)
if err != nil || upTo.From != day(300) || upTo.Date != day(10) || upTo.Calls != 2 {
t.Errorf("all to %s: %+v %v", day(10), upTo, err)
}
// no from is the day alone, as DayOf is
one, err := SpanOf("", day(3), time.Local)
if err != nil || one.From != day(3) || one.Date != day(3) || one.Calls != 2 {
t.Errorf("day %+v %v", one, err)
}
for _, bad := range [][2]string{{"nope", ""}, {day(0), day(3)}, {day(3), now.AddDate(0, 0, 1).Format(time.DateOnly)}} {
if _, err := SpanOf(bad[0], bad[1], time.Local); err == nil {
t.Errorf("from %q to %q was read", bad[0], bad[1])
}
}
}