Files
magpie/internal/usageapi/day_test.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

93 lines
3.6 KiB
Go

package usageapi
import (
"encoding/json"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/testenv"
"github.com/yetone/magpie/internal/usage"
)
// usage:day (a plugin page's day statement) is the day asked for, in the
// reader's zone: its totals, each agent's and each agent's models', the
// days before it with calls, and nothing of an account, a key or a
// session. A day after today is refused, as is a date that isn't one.
func TestDayOf(t *testing.T) {
// a usage log of its own: the package's other tests read the shared one
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()
midnight := time.Date(y, m, d, 0, 0, 0, 0, time.Local)
// between midnight and now: today's, whenever the test runs
at := midnight.Add(now.Sub(midnight) / 2)
yesterday := midnight.Add(-12 * time.Hour)
for _, r := range []usage.Record{
{Time: at, Agent: "claude", Provider: "anthropic", Model: "claude-x", Input: 100, Output: 10, CacheRead: 300, ProviderAccount: "me@example.com", CallerKeyName: "secret-key"},
{Time: at, Agent: "claude", Provider: "deepseek", Model: "deepseek-y", Input: 50, Output: 5},
{Time: at, Agent: "codex", Provider: "openai", Model: "gpt-z", Input: 10, Output: 1},
{Time: yesterday, Agent: "codex", Provider: "openai", Model: "gpt-z", Input: 7, Output: 1},
} {
usage.Append(r)
}
today := now.Format(time.DateOnly)
day, err := DayOf("", time.Local)
if err != nil {
t.Fatal(err)
}
if day.Date != today || day.Today != today {
t.Fatalf("date %s, today %s, want %s", day.Date, day.Today, today)
}
if day.Calls != 3 || day.Input != 160 || day.Output != 16 || day.CacheRead != 300 {
t.Errorf("totals %+v", day.DayTotals)
}
if len(day.Agents) != 2 || day.Agents[0].ID != "claude" || day.Agents[0].Name != "Claude Code" || day.Agents[1].ID != "codex" || day.Agents[0].Icon != "claude-color" || day.Agents[1].Name != "codex" || day.Agents[1].Icon != "generic" {
t.Fatalf("agents %+v", day.Agents)
}
if a := day.Agents[0]; a.Calls != 2 || len(a.Models) != 2 || a.Models[0].Model != "claude-x" || a.Models[0].Provider != "anthropic" || a.Models[1].Model != "deepseek-y" || a.Models[1].ProviderName != "DeepSeek" {
t.Errorf("claude's models %+v", a.Models)
}
if a := day.Agents[1]; a.Calls != 1 || len(a.Models) != 1 || a.Models[0].Model != "gpt-z" {
t.Errorf("codex's day %+v", a)
}
if len(day.Days) != 2 || day.Days[0].Date != yesterday.Format(time.DateOnly) || day.Days[1].Date != today || day.Days[1].Calls != 3 {
t.Errorf("days %+v", day.Days)
}
b, _ := json.Marshal(day)
for _, s := range []string{"me@example.com", "secret-key"} {
if strings.Contains(string(b), s) {
t.Errorf("the day carries %q: %s", s, b)
}
}
// yesterday: codex alone, and the days up to it only
day, err = DayOf(yesterday.Format(time.DateOnly), time.Local)
if err != nil {
t.Fatal(err)
}
if day.Calls != 1 || len(day.Agents) != 1 || day.Agents[0].ID != "codex" || len(day.Days) != 1 {
t.Errorf("yesterday %+v", day)
}
if _, err := DayOf(now.AddDate(0, 0, 1).Format(time.DateOnly), time.Local); err == nil {
t.Error("tomorrow was read")
}
for _, bad := range []string{"today", "2026-13-01", "../x"} {
if _, err := DayOf(bad, time.Local); err == nil {
t.Errorf("%q was read", bad)
}
}
}