From 745d209dcf5f4d9b7feee416e1848e33502834e6 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 17:38:32 +0800 Subject: [PATCH] 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). --- docs/subsystems/plugin-runtime.md | 2 +- internal/gui/pageday.go | 9 ++-- internal/gui/pageimage_test.go | 14 +++++++ internal/usageapi/day.go | 56 +++++++++++++++++++++++-- internal/usageapi/day_test.go | 68 +++++++++++++++++++++++++++++++ 5 files changed, 141 insertions(+), 8 deletions(-) diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index fbaa557be..a7a746c63 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -272,7 +272,7 @@ still means off; a page is its own plugin's to turn on and off. | Usage observer | `export function onUsage(row, options)` gets each usage row of an allow-list (no bodies, prompts or ids), from a bounded queue off the request path: a full queue drops and counts, and a request never waits. 250ms each, fail open. | `plugins/middleware` ("JS gateway plugins", from the same module as its [middleware](gateway-middleware.md)) | [`points.go`](../../internal/middleware/points.go) | | Search API | Its `search` hook's entries, each a web search API in Settings › Web search (`:`), asked in the search APIs' order with a quarter of a search's time. An entry with a key, none (`keyOptional`) or the user's address (`url`), or one with `auth` naming a provider the plugin's own `auth` hook signs in to: it takes no key, asks that provider's accounts that are on in the order its model requests take them, and its `ctx.getAuth()` is the one account chosen, renewed first within the search's time; a refusal rests the account for search only. Off, no search asks it. | `plugins/search` (Web search, Essential) | [Plugin tools](plugin-tools.md) ("Search APIs from a plugin"), [provider plugins](provider-plugins.md) | | Tool | Its OpenCode `tool` hook's tools, offered to every agent by magpie's MCP server at `/mcp/magpie/tools`, each named `_`, each call held to the calling key's limit and run in the host within 55s. Off, no tool is listed and a call says the plugin is off. | `plugins/tools` ("Plugin tools", Essential; `InUse` counts the plugins on that give tools, from `plugin-tools.json`), `gwtool.PluginTools` | [Plugin tools](plugin-tools.md) | -| A page in the window | `magpie.page {title, file, icon}` and `magpie.permissions` in package.json, installed from npm, GitHub or a folder like any plugin (`plugin.WindowPage`: `file` an .html inside the plugin, the icon in the page's folder, reads kept to `plugin.PageReads`). An on plugin's page gets a tab in the sidebar's Plugins group, after the built-in pages (`pluginpages.js`, a kernel `page` part). It runs in an iframe sandboxed to `allow-scripts`, its files served from `/_magpie/plugin//` (an HMAC of the spec with a secret of this run) under a policy of `sandbox allow-scripts`, its own folder only, `connect-src 'none'`. The frame talks to the window by `postMessage`: the window answers only its own frame (`ev.source`), with the theme, its own options (`/api/plugin-pages/options`, at most once a second, saved without restarting the host for a page-only plugin) and the reads it declared (`/api/plugin-pages/read`, checked again by the server): `usage:summary` (totals and the top 20 models), `usage:day` (`pageDay`, `usageapi.DayOf`: one day, `{date, tz}` with today by default and a day after today refused, its totals, its first 12 agents by tokens with each one's first 12 models and providers, the days up to it that had calls over the heatmap's span, the agents' and providers' logos as data: pictures, `pageIconOf`, and Settings' currency and rate) and `providers:list` (ids and names). Nothing secret is readable, since a page can still send its frame to another site. A page can share a picture it drew (`magpie.image.copy(png)`, `magpie.image.save(png, name)`, a PNG Blob of 16MB at most): its sandbox has no download or clipboard, and the app's window copies text only, so the window hands the base64 PNG to `/api/plugin-pages/image` (`pageimage.go`), which checks the page is one magpie shows, that it is a PNG of 8192px a side at most, and twice a second at most a page, then puts it on the system clipboard with the system's own tool (`clipimage.go`: osascript's `«class PNGf»`, PowerShell's `Clipboard.SetDataObject` with PNG and a bitmap, `wl-copy` or `xclip`, the file's path always an argument) or saves it in Downloads under a name never over a file there. In `magpie web` the server is another computer: the browser's window downloads it and uses `navigator.clipboard` itself. The window's side is `pageshare.js`, imported the first time a page shares a picture, so it weighs nothing on the core. Tests: `TestDayOf`, `TestPluginPageReadsADay`, `TestPluginPageSharesAPicture`, `TestPageImageName`, `TestClipImageCommand`, `plugin-page.test.cjs` (image.copy and image.save). The day card (`@magpie-community/page-day-card`) reads `usage:day`. `noFramedAPI` turns away every `/api/` request a sandboxed frame or another site can send (`Origin: null`, `Sec-Fetch-Dest` a frame, a cross-site subresource), since the desktop window's API has no key; `webGuard` lets the prefix through without the cookie the frame never sends, and the token is the key. A page that throws, or doesn't say hello in 10s, is broken through the kernel (`ctx.broke`), with Try again. The frame is made the first time the page is opened. When the reader goes to another page it is told (`{event: "visibility", data: {visible: false}}`, the bridge's `magpie.visible` and `magpie.onVisibility(fn)`), since a frame in a hidden view isn't hidden to itself, and told again on coming back. A page left 10 minutes (`IDLE_MS`) has its frame let go, with its scripts, timers and connections, and loads again when it is next opened; `magpie.page.keepAlive: true` (`plugin.PageSpec.KeepAlive`, anything but `true` is false) keeps it however long, for a page that works while no one looks at it. Tests: `TestWindowPanels` (keepAlive), `plugin-page-idle.test.cjs`. The Plugins page shows the page and its reads on the row before the plugin is on. A plugin that is only a page is in-magpie-only: no Bun host starts for it. A page whose plugin also has a part for the host (a local service its page goes to, as Magiczerowxy/magpie-chat's does) starts the host when its HTML is served, if none is up (`pageHost`, `plugin.Warm`), waiting up to 7s: the host otherwise starts only on a call, so after a Restart (a plugin installed, updated or set, a Bun update) or a crash the page's service was down, and WebKit leaves a frame that navigates to a refused address on its old document with no error. A page reaches its service through magpie too, when the plugin declares it (`magpie.page.service {port, option}`, `plugin.ServiceSpec`: the port, or the plugin option named, from its plugins.json `options`): in `magpie web`, where 127.0.0.1 is the viewer's own computer, not the server (aigcfree on Discord: a server behind nginx, a Windows PC's browser, "127.0.0.1 refused to connect"), `/api/plugin-pages` gives the page a `service` under its token, `_magpie/service/`, and the bridge hands it to the frame as `magpie.service`, an absolute address (the desktop window gets none, and the page goes to 127.0.0.1 as before; a slot page gets none). `servePageService` reverse-proxies it to 127.0.0.1:: Host set to the service's own (its rebinding check), the window's cookie taken off, Origin only absent or `null` (403 otherwise), Set-Cookie dropped, everything it sends sandboxed (`sandbox allow-scripts; frame-ancestors 'self'`, `Referrer-Policy: no-referrer`), streamed as it comes (`FlushInterval -1`, `X-Accel-Buffering: no` on an event stream, which `webCompressed` never gzips), a redirect to its own address made relative, and the gateway's port never served (a request from this server is loopback, which the gateway takes without a key). The way in is the page's: the token, which only a signed-in `/api` hands out, behind `AllowGuard`; the service stays on loopback. Its entry starts the host as the page's HTML does, and a service not up yet answers its frame with a 502 page that tries again in 2s. The chat page (`@magpie-community/page-chat` 0.1.1) goes to `magpie.service` when given one, else 127.0.0.1, and asks its `api/…` by relative address. Tests: `TestPluginPageServiceListedToBrowserOnly`, `TestPluginPageServiceSpec`, `TestPluginPageServiceProxied`, `TestPluginPageServiceDown`, `TestServiceLocation`, `plugin-page.test.cjs` (`magpie.service`). Discover lists a market entry of `kind: "page"` under Pages with the Page chip, and a GitHub repository tagged `magpie-plugin` whose package.json has `magpie.page.file` as a Page (`TaggedRepos`, which then checks that file is committed, as it does a provider's entry; `TestTaggedRepos`, `plugin-kinds-discover.test.cjs`). Tests: `TestWindowPageStaysInside`, `TestPluginPageServedShutIn`, `TestPluginPageReadsWhatItDeclared`, `TestPluginPageNoAPI`, `TestPluginPageWebGuard`, `TestPluginPageStartsItsHost`, `plugin-page.test.cjs`. Example: `internal/gui/testdata/page-plugin`. A magpie that serves no pages (a command such as `magpie plugin update`, `servesPages` in `internal/cli`) starts its host with each service its plugin's option moves on a free port of its own (`plugin.ServePages`, `hostOptions`): a plugin that waits on its port, as page-chat does, loads at once beside the app's host holding it, and doesn't go on trying for it to take it when the app's host restarts (#5187). A service no option moves is started as before. Tests: `TestHostServingNoPagesLeavesHeldPort`, `TestHostOptionsMoveOnlyTheService`, `TestServesPages`. | the window, no built-in plugin: the page is the plugin's own on/off | [`page.go`](../../internal/plugin/page.go), [`pluginpage.go`](../../internal/gui/pluginpage.go), [`pagebridge.js`](../../internal/gui/pagebridge.js), [`pluginpages.js`](../../internal/gui/assets/pluginpages.js) | +| A page in the window | `magpie.page {title, file, icon}` and `magpie.permissions` in package.json, installed from npm, GitHub or a folder like any plugin (`plugin.WindowPage`: `file` an .html inside the plugin, the icon in the page's folder, reads kept to `plugin.PageReads`). An on plugin's page gets a tab in the sidebar's Plugins group, after the built-in pages (`pluginpages.js`, a kernel `page` part). It runs in an iframe sandboxed to `allow-scripts`, its files served from `/_magpie/plugin//` (an HMAC of the spec with a secret of this run) under a policy of `sandbox allow-scripts`, its own folder only, `connect-src 'none'`. The frame talks to the window by `postMessage`: the window answers only its own frame (`ev.source`), with the theme, its own options (`/api/plugin-pages/options`, at most once a second, saved without restarting the host for a page-only plugin) and the reads it declared (`/api/plugin-pages/read`, checked again by the server): `usage:summary` (totals and the top 20 models), `usage:day` (`pageDay`, `usageapi.SpanOf`: one day, `{date, from, tz}` with today by default and a day after today refused; a `from` (a date, or `all` for the first day with calls) makes it the days from there to `date`, `from` in the answer, and a `from` after `date` is refused, its totals, its first 12 agents by tokens with each one's first 12 models and providers, the days up to it that had calls over the heatmap's span, the agents' and providers' logos as data: pictures, `pageIconOf`, and Settings' currency and rate) and `providers:list` (ids and names). Nothing secret is readable, since a page can still send its frame to another site. A page can share a picture it drew (`magpie.image.copy(png)`, `magpie.image.save(png, name)`, a PNG Blob of 16MB at most): its sandbox has no download or clipboard, and the app's window copies text only, so the window hands the base64 PNG to `/api/plugin-pages/image` (`pageimage.go`), which checks the page is one magpie shows, that it is a PNG of 8192px a side at most, and twice a second at most a page, then puts it on the system clipboard with the system's own tool (`clipimage.go`: osascript's `«class PNGf»`, PowerShell's `Clipboard.SetDataObject` with PNG and a bitmap, `wl-copy` or `xclip`, the file's path always an argument) or saves it in Downloads under a name never over a file there. In `magpie web` the server is another computer: the browser's window downloads it and uses `navigator.clipboard` itself. The window's side is `pageshare.js`, imported the first time a page shares a picture, so it weighs nothing on the core. Tests: `TestDayOf`, `TestPluginPageReadsADay`, `TestPluginPageSharesAPicture`, `TestPageImageName`, `TestClipImageCommand`, `plugin-page.test.cjs` (image.copy and image.save). The day card (`@magpie-community/page-day-card`) reads `usage:day`. `noFramedAPI` turns away every `/api/` request a sandboxed frame or another site can send (`Origin: null`, `Sec-Fetch-Dest` a frame, a cross-site subresource), since the desktop window's API has no key; `webGuard` lets the prefix through without the cookie the frame never sends, and the token is the key. A page that throws, or doesn't say hello in 10s, is broken through the kernel (`ctx.broke`), with Try again. The frame is made the first time the page is opened. When the reader goes to another page it is told (`{event: "visibility", data: {visible: false}}`, the bridge's `magpie.visible` and `magpie.onVisibility(fn)`), since a frame in a hidden view isn't hidden to itself, and told again on coming back. A page left 10 minutes (`IDLE_MS`) has its frame let go, with its scripts, timers and connections, and loads again when it is next opened; `magpie.page.keepAlive: true` (`plugin.PageSpec.KeepAlive`, anything but `true` is false) keeps it however long, for a page that works while no one looks at it. Tests: `TestWindowPanels` (keepAlive), `plugin-page-idle.test.cjs`. The Plugins page shows the page and its reads on the row before the plugin is on. A plugin that is only a page is in-magpie-only: no Bun host starts for it. A page whose plugin also has a part for the host (a local service its page goes to, as Magiczerowxy/magpie-chat's does) starts the host when its HTML is served, if none is up (`pageHost`, `plugin.Warm`), waiting up to 7s: the host otherwise starts only on a call, so after a Restart (a plugin installed, updated or set, a Bun update) or a crash the page's service was down, and WebKit leaves a frame that navigates to a refused address on its old document with no error. A page reaches its service through magpie too, when the plugin declares it (`magpie.page.service {port, option}`, `plugin.ServiceSpec`: the port, or the plugin option named, from its plugins.json `options`): in `magpie web`, where 127.0.0.1 is the viewer's own computer, not the server (aigcfree on Discord: a server behind nginx, a Windows PC's browser, "127.0.0.1 refused to connect"), `/api/plugin-pages` gives the page a `service` under its token, `_magpie/service/`, and the bridge hands it to the frame as `magpie.service`, an absolute address (the desktop window gets none, and the page goes to 127.0.0.1 as before; a slot page gets none). `servePageService` reverse-proxies it to 127.0.0.1:: Host set to the service's own (its rebinding check), the window's cookie taken off, Origin only absent or `null` (403 otherwise), Set-Cookie dropped, everything it sends sandboxed (`sandbox allow-scripts; frame-ancestors 'self'`, `Referrer-Policy: no-referrer`), streamed as it comes (`FlushInterval -1`, `X-Accel-Buffering: no` on an event stream, which `webCompressed` never gzips), a redirect to its own address made relative, and the gateway's port never served (a request from this server is loopback, which the gateway takes without a key). The way in is the page's: the token, which only a signed-in `/api` hands out, behind `AllowGuard`; the service stays on loopback. Its entry starts the host as the page's HTML does, and a service not up yet answers its frame with a 502 page that tries again in 2s. The chat page (`@magpie-community/page-chat` 0.1.1) goes to `magpie.service` when given one, else 127.0.0.1, and asks its `api/…` by relative address. Tests: `TestPluginPageServiceListedToBrowserOnly`, `TestPluginPageServiceSpec`, `TestPluginPageServiceProxied`, `TestPluginPageServiceDown`, `TestServiceLocation`, `plugin-page.test.cjs` (`magpie.service`). Discover lists a market entry of `kind: "page"` under Pages with the Page chip, and a GitHub repository tagged `magpie-plugin` whose package.json has `magpie.page.file` as a Page (`TaggedRepos`, which then checks that file is committed, as it does a provider's entry; `TestTaggedRepos`, `plugin-kinds-discover.test.cjs`). Tests: `TestWindowPageStaysInside`, `TestPluginPageServedShutIn`, `TestPluginPageReadsWhatItDeclared`, `TestPluginPageNoAPI`, `TestPluginPageWebGuard`, `TestPluginPageStartsItsHost`, `plugin-page.test.cjs`. Example: `internal/gui/testdata/page-plugin`. A magpie that serves no pages (a command such as `magpie plugin update`, `servesPages` in `internal/cli`) starts its host with each service its plugin's option moves on a free port of its own (`plugin.ServePages`, `hostOptions`): a plugin that waits on its port, as page-chat does, loads at once beside the app's host holding it, and doesn't go on trying for it to take it when the app's host restarts (#5187). A service no option moves is started as before. Tests: `TestHostServingNoPagesLeavesHeldPort`, `TestHostOptionsMoveOnlyTheService`, `TestServesPages`. | the window, no built-in plugin: the page is the plugin's own on/off | [`page.go`](../../internal/plugin/page.go), [`pluginpage.go`](../../internal/gui/pluginpage.go), [`pagebridge.js`](../../internal/gui/pagebridge.js), [`pluginpages.js`](../../internal/gui/assets/pluginpages.js) | `plugins/middleware` is now "JS gateway plugins". Apply registers the chain and `usage.Observe(middleware.Points())`; off, no JS middleware, strategy or `onUsage` runs, and a pool routed by a JS strategy is its listed order. `InUse` is unchanged. ([`middleware.go`](../../plugins/middleware/middleware.go)) diff --git a/internal/gui/pageday.go b/internal/gui/pageday.go index 7f1de7b67..70fb717a7 100644 --- a/internal/gui/pageday.go +++ b/internal/gui/pageday.go @@ -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 } diff --git a/internal/gui/pageimage_test.go b/internal/gui/pageimage_test.go index 8f1dd996f..ce40d3967 100644 --- a/internal/gui/pageimage_test.go +++ b/internal/gui/pageimage_test.go @@ -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) } diff --git a/internal/usageapi/day.go b/internal/usageapi/day.go index 909ab257f..b79d8fcf9 100644 --- a/internal/usageapi/day.go +++ b/internal/usageapi/day.go @@ -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 } diff --git a/internal/usageapi/day_test.go b/internal/usageapi/day_test.go index b081a02b0..0a20dbb9c 100644 --- a/internal/usageapi/day_test.go +++ b/internal/usageapi/day_test.go @@ -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]) + } + } +}