Files
magpie/internal/usageapi/day.go
T
yetone 745d209dcf 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).
2026-11-11 17:38:42 +08:00

203 lines
6.6 KiB
Go

package usageapi
import (
"fmt"
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// One day of usage as a plugin's page reads it (usage:day): the day's
// totals, each agent's and, within each, its models', and the days before
// it that had calls, for a streak or an average day. A page that draws a
// day's statement (@magpie-community/page-day-card) reads it; nothing in it
// is a key, an account, a session or a prompt.
// DayAgents is how many agents a day lists, the most tokens first, and
// DayModels how many of an agent's models: a page draws a card, not a table.
const (
DayAgents = 12
DayModels = 12
)
// DayTotals are the counts of a day, an agent or a model.
type DayTotals struct {
Calls int `json:"calls"`
Errors int `json:"errors"`
Input int `json:"input"`
Output int `json:"output"`
CacheRead int `json:"cacheRead"`
CacheWrite int `json:"cacheWrite"`
Reasoning int `json:"reasoning"`
Cost float64 `json:"cost"` // USD at the effective price, of the priced calls
// Unpriced are calls with tokens but no known price, not in Cost
Unpriced int `json:"unpriced"`
// CacheUnknown is the prompt's tokens of calls whose vendor counts no
// cache, which a hit rate leaves out (#3464)
CacheUnknown int `json:"cacheUnknown"`
}
func dayTotals(t usage.Totals) DayTotals {
return DayTotals{
Calls: t.Calls, Errors: t.Errors, Input: t.Input, Output: t.Output,
CacheRead: t.CacheRead, CacheWrite: t.CacheWrite, Reasoning: t.Reasoning,
Cost: t.Cost, Unpriced: t.Unpriced, CacheUnknown: t.CacheUnknown,
}
}
// DayModel is a model's share of an agent's day.
type DayModel struct {
Model string `json:"model"`
Provider string `json:"provider"` // its id
ProviderName string `json:"providerName"` // as the Usage page names it
Icon string `json:"icon"` // the provider's, as the Usage page draws it
DayTotals
}
// DayAgent is an agent's day, and its models'.
type DayAgent struct {
ID string `json:"id"` // "" for calls that named no agent
Name string `json:"name"`
Icon string `json:"icon"`
DayTotals
Models []DayModel `json:"models"`
// MoreModels is how many of its models DayModels left out; their
// counts are in the agent's
MoreModels int `json:"moreModels,omitempty"`
}
// DayCount is a day that had calls.
type DayCount struct {
Date string `json:"date"`
Calls int `json:"calls"`
Tokens int `json:"tokens"` // in, out and through the cache
Cost float64 `json:"cost"`
}
// Day is a day's usage.
type Day struct {
// 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"`
MoreAgents int `json:"moreAgents,omitempty"`
// Days are the days with calls up to Date, oldest first, over the
// heatmap's span (usage.HeatmapWeeks)
Days []DayCount `json:"days"`
}
// 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) { 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
}
today := usage.Clock().In(zone).Format(time.DateOnly)
if date == "" {
date = today
}
d, err := time.ParseInLocation(time.DateOnly, date, zone)
if err != nil {
return Day{}, fmt.Errorf("no date %q: YYYY-MM-DD", date)
}
date = d.Format(time.DateOnly)
if date > today {
return Day{}, fmt.Errorf("%s is after today, %s", date, today)
}
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{From: from, Date: date, Today: today, DayTotals: dayTotals(all.Sum), Agents: []DayAgent{}, Days: []DayCount{}}
agents := clients()
face := providerFaces(provider.All())
for i, s := range all.By["agent"] {
if i == DayAgents {
out.MoreAgents = len(all.By["agent"]) - DayAgents
break
}
a := DayAgent{ID: s.ID, Name: s.ID, Icon: "generic", DayTotals: dayTotals(s.Totals), Models: []DayModel{}}
if c := agents[s.ID]; c != nil {
a.Name, a.Icon = c.Name, c.Icon
}
af := f
af.Agent = s.ID
if s.ID == "" {
// a filter of "" keeps every agent: the calls that named none
// are this group's own, and are listed by model without it
af.Agent = ""
}
var models []usage.Share
if s.ID != "" || len(all.By["agent"]) == 1 {
models = usage.QueryPage(p, af, 0, 1).By["modelAt"]
}
for j, m := range models {
if j == DayModels {
a.MoreModels = len(models) - DayModels
break
}
prov, model, _ := strings.Cut(m.ID, "/")
pf := face(prov)
a.Models = append(a.Models, DayModel{Model: model, Provider: prov, ProviderName: pf.Name, Icon: pf.Icon, DayTotals: dayTotals(m.Totals)})
}
out.Agents = append(out.Agents, a)
}
for _, h := range usage.HeatmapOf(f).Days {
if h.Date <= date && h.Calls > 0 {
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
}