Files
magpie/internal/usageapi/day.go
T
yetone 623e797fde plugin pages: read a day's usage and share a picture they drew
A plugin's page can now read one day's usage and share an image it
drew. This is for the day card (JungleyYeh on X asked for a "daily AI
statement"); the card itself is an optional community plugin,
@magpie-community/page-day-card.

- A page that asks for the "usage:day" read gets that day as
  magpie.read("usage:day", {date, tz}): totals, each agent and its
  models, the streak and the average active day (usageapi/day.go,
  gui/pageday.go). The Plugins page names the read before it is granted.
- magpie.image.copy(png) and magpie.image.save(png, name) share a PNG
  of at most 16 MB. In the window they go through
  POST /api/plugin-pages/image (pageimage.go): copy puts the picture on
  the clipboard (clipimage.go: osascript PNGf on macOS, PowerShell
  PNG + Bitmap on Windows, wl-copy or xclip on Linux), and save writes
  it to Downloads under a name made safe. In magpie web, the browser
  saves or copies the picture itself.
- The window's side, pageshare.js, is imported the first time a page
  shares a picture. The core grows by its one call only, paid for by
  comments cut, so the budget is not raised.

Tests:
- New: TestDayOf, TestPluginPageReadsADay, TestPluginPageSharesAPicture,
  TestPageImageName and TestClipImageCommand. plugin-page.test.cjs
  covers the bridge, both engines and a refused SVG.

What was run (mote):
- gofmt, plus go vet on darwin, linux and windows: clean.
- Full go test ./... at the pre-rebase base: 369 packages ok, 3 FAILs.
  - TestEveryRouteHasACommandOrIsNamed and TestCoreScriptBudget were
    this change's own reds. The new route now has a parity entry, and
    the share code moved into lazy pageshare.js with no raise.
  - TestGatewayModeStatsNameTheGatewaySessions is #5690, the red in the
    first hour of the day (it ran at 00:32).
- GUI suite (affected and plugin files, both engines): 1160 of 1179
  passed. Every red is filed and none touches this change:
  - i18n-keys "a plugin's words are its own": #5332, #5426, #5482.
  - page-width-steady: #5013.
  - plugin-card-update in WebKit: #3079.
  - plugin-move-unserved "Try again": #4410.
- At this head, after the rebase on bc8b01d60:
  - gofmt clean; go vet ./internal/... on darwin, linux (nogui) and
    windows ok.
  - internal/usageapi, internal/plugin and internal/cli ok.
  - internal/gui: TestCoreScriptBudget, the TestPluginPage* tests and
    the TestPageImage/TestClipImage tests pass.
  - plugin-page and old-webkit (both engines): 12 of 12.

Real use:
- A sandbox HOME with a copy of real usage, through the real GUI
  server, in Chromium and WebKit, light and dark, en/zh/zh-TW/ja/de, at
  420 and 1100 px. The card showed 87.9M tokens, $9.85 and 4076 calls
  with a 22-day streak.
- Picking an earlier day and WebKit's Copy ("Copied") worked, with no
  page errors.
- Not tried at push: Chromium's Copy (its headless clipboard was
  denied) and magpie web's Save as a captured download. A second real
  run that grants both was still queued on mote's suite lock.
- Clipboard: checked live on macOS (osascript) and Windows
  (PowerShell). Not tried live on Linux: WSLg had no display.
2026-11-09 23:19:14 +08:00

155 lines
4.9 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 {
Date string `json:"date"` // YYYY-MM-DD, in the zone asked for
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) {
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)
}
p, _ := usage.RangeOf(date, date)
f := usage.Filter{Zone: zone}
all := usage.QueryPage(p, f, 0, 1)
out := Day{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})
}
}
return out, nil
}