Files
magpie/internal/gui/pageday.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

114 lines
3.2 KiB
Go

package gui
import (
"encoding/base64"
"io/fs"
"os"
"path"
"strings"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
"github.com/yetone/magpie/internal/usageapi"
)
// The usage:day read (plugin.PageReads): a day of usage for a plugin's
// page, by agent and by model, with the logos the Usage page draws for
// them. A page loads nothing but its own files and data: pictures
// (pagePolicy), so each logo comes as a data: URL, once for each name.
// pageIcon is a logo as a page draws it: Mono a one-colour mark the page
// fills with its text colour, as the window's mask icons are (app.js's
// icon), else a picture drawn as it is.
type pageIcon struct {
Src string `json:"src"`
Mono bool `json:"mono,omitempty"`
}
// maxPageIcon is the largest logo a read carries: a picture of the user's
// own past it is drawn as the generic one.
const maxPageIcon = 256 << 10
// pageIconOf is the logo named name, as app.js's icon finds it: a picture
// the user gave a provider (file:…), else the bundled SVG or PNG; ok is
// false for "generic", "" and a name with no file.
func pageIconOf(name string) (pageIcon, bool) {
if name == "" || name == "generic" {
return pageIcon{}, false
}
if own, ok := strings.CutPrefix(name, "file:"); ok {
f, _ := provider.IconServed(own)
if f == "" {
return pageIcon{}, false
}
b, err := os.ReadFile(f)
if err != nil || len(b) > maxPageIcon {
return pageIcon{}, false
}
return pageIcon{Src: dataURL(own, b)}, true
}
// a URL or a path is no bundled name (app.js draws it as generic)
if strings.ContainsAny(name, ":/\\") {
return pageIcon{}, false
}
for _, ext := range []string{".svg", ".png"} {
b, err := fs.ReadFile(assets, "assets/icons/"+name+ext)
if err != nil || len(b) > maxPageIcon {
continue
}
return pageIcon{Src: dataURL(name+ext, b), Mono: ext == ".svg" && !strings.HasSuffix(name, "-color")}, true
}
return pageIcon{}, false
}
func dataURL(name string, b []byte) string {
ctype := "image/svg+xml"
switch strings.ToLower(path.Ext(name)) {
case ".png":
ctype = "image/png"
case ".jpg", ".jpeg":
ctype = "image/jpeg"
case ".webp":
ctype = "image/webp"
}
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).
func pageDay(params map[string]any) (any, error) {
date, _ := params["date"].(string)
tz, _ := params["tz"].(string)
d, err := usageapi.DayOf(date, usage.Zone(tz))
if err != nil {
return nil, err
}
icons := map[string]pageIcon{}
want := func(name string) {
if _, ok := icons[name]; ok {
return
}
if ic, ok := pageIconOf(name); ok {
icons[name] = ic
}
}
for _, a := range d.Agents {
want(a.Icon)
for _, m := range a.Models {
want(m.Icon)
}
}
// a cost as Settings shows it: in USD, or in CNY at the rate known now
cur := settings.Load().Currency
if cur == "" {
cur = "usd"
}
return struct {
usageapi.Day
Icons map[string]pageIcon `json:"icons"`
Currency string `json:"currency"`
Rate float64 `json:"rate"` // CNY per USD, 0 when unknown
}{d, icons, cur, currentFX().Rate}, nil
}