Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

usage: times and days follow the viewer's time zone, not the server's (Outvi V, Discord)

yetonee00fbdbbc74f
diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js
index 8df9b833f..642bb13af 100644
--- a/internal/gui/assets/plugins/usage/page.js
+++ b/internal/gui/assets/plugins/usage/page.js
@@ -3,6 +3,15 @@
// first page.
const PERIODS = [["today", "Today"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]];
+// The reader's time zone, which magpie reads the period's days, the chart's
+// hours and a picked day in: magpie web may be read from another zone than
+// the computer's, whose days put a call at 9:00 in UTC+8 under 1:00 (Outvi V
+// on Discord). None, and magpie reads its own.
+function usageZone() {
+ try { return Intl.DateTimeFormat().resolvedOptions().timeZone || ""; } catch { return ""; }
+}
+const usageZoneQ = () => (usageZone() ? "&tz=" + encodeURIComponent(usageZone()) : "");
+
// asked: the reader opened the page, so a Claude account's usage is read
// at once, by running Claude Code's own /usage, rather than when its last
// reading is due (every 5 to 15 minutes, at random, once Claude Code was used).
@@ -19,7 +28,7 @@ async function loadUsage(asked) {
renderUsageLoading();
if (!asked) loadQuotas();
const p = period, read = ++usageRead;
- const next = await api("usage?period=" + encodeURIComponent(p));
+ const next = await api("usage?period=" + encodeURIComponent(p) + usageZoneQ());
if (read !== usageRead || view !== "usage" || usageTab !== "usage" || period !== p) return;
usage = next;
renderUsage();
@@ -693,6 +702,7 @@ function ledLeave() {
function ledParams(extra) {
const q = new URLSearchParams({ period });
+ if (usageZone()) q.set("tz", usageZone());
if (ledDay) q.set("day", ledDay);
if (ledAgent) q.set("agent", ledAgent);
if (ledPurpose) q.set("purpose", ledPurpose);
@@ -3258,7 +3268,7 @@ function refreshUsage(now = false) {
else if (usage && performance.now() - quotasAsked > 60e3) { quotasAsked = performance.now(); loadQuotas(); }
if (usage) {
const p = period, read = ++usageRead;
- const u = await api("usage?period=" + encodeURIComponent(p));
+ const u = await api("usage?period=" + encodeURIComponent(p) + usageZoneQ());
if (read === usageRead && view === "usage" && usageTab === "usage" && p === period) {
if (JSON.stringify(u) !== JSON.stringify(usage)) { usage = u; renderUsage(); }
// this read claimed the newest one: a pick it superseded had put the
diff --git a/internal/gui/tests/usage-stale-answer.test.cjs b/internal/gui/tests/usage-stale-answer.test.cjs
index ea17548d5..8402dcd78 100644
--- a/internal/gui/tests/usage-stale-answer.test.cjs
+++ b/internal/gui/tests/usage-stale-answer.test.cjs
@@ -62,6 +62,7 @@ const resolvers = []; // the answers, held until the test gives them
function api(path) {
return new Promise((res, rej) => { reads.push(path); resolvers.push({ path, res, rej }); });
}
+function usageZoneQ() { return ""; } // the reader's zone: usage-viewer-zone.test.cjs
function renderUsage() { drawn.push({ period, usage: usage && usage.tag }); }
function renderUsageTab() {}
function renderUsageEvery() {}
@@ -187,6 +188,7 @@ const resolvers = []; // the answers, held until the test gives them
function api(path) {
return new Promise((res, rej) => { reads.push(path); resolvers.push({ path, res, rej }); });
}
+function usageZoneQ() { return ""; } // the reader's zone: usage-viewer-zone.test.cjs
// the page's own element: what the loading flag is read and written through
function $(sel) {
return {
diff --git a/internal/gui/usage.go b/internal/gui/usage.go
index 77a9725d3..836e52bdd 100644
--- a/internal/gui/usage.go
+++ b/internal/gui/usage.go
@@ -31,10 +31,10 @@ type (
)
var (
- usageState = usageapi.Page
+ usageState = usageapi.PageIn
ledgerPage = usageapi.LedgerPage
periodOf = usageapi.PeriodOf
- ledgerFilter = usageapi.FilterOf
+ ledgerFilter = usageapi.FilterIn
)
func init() {
@@ -98,19 +98,20 @@ func requestContent(agent, session string, from, to, at time.Time) contentJSON {
func usageRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/usage", func(rw http.ResponseWriter, r *http.Request) {
- writeJSON(rw, usageState(periodOf(r.URL.Query().Get("period"))))
+ // the days and hours of the reader's zone, which the page names
+ writeJSON(rw, usageState(periodOf(r.URL.Query().Get("period")), usageapi.ZoneOf(r)))
})
// the ledger: the period's calls, newest first, a page at a time
mux.HandleFunc("GET /api/usage/requests", func(rw http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
offset, _ := strconv.Atoi(q.Get("offset"))
limit, _ := strconv.Atoi(q.Get("limit"))
- writeJSON(rw, ledgerPage(periodOf(q.Get("period")), ledgerFilter(q), offset, limit))
+ writeJSON(rw, ledgerPage(periodOf(q.Get("period")), ledgerFilter(r), offset, limit))
})
// the heatmap (#1369): the last 53 weeks a day each, of the requests the
// page's filters keep, read from the same index as the page
mux.HandleFunc("GET /api/usage/heatmap", func(rw http.ResponseWriter, r *http.Request) {
- writeJSON(rw, usage.HeatmapOf(ledgerFilter(r.URL.Query())))
+ writeJSON(rw, usage.HeatmapOf(ledgerFilter(r)))
})
// what was said in one request, read from the agent's session file when the
// row is opened, between two times (the call's own, or a gateway request's
@@ -135,9 +136,11 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/usage/requests.csv", func(rw http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
p := periodOf(q.Get("period"))
- // one moment for the rows and the day in the file's name
- now := usage.Clock()
- rows := usage.LedgerOfAt(p, ledgerFilter(q), now).Rows
+ // one moment for the rows and the day in the file's name, the
+ // reader's day
+ f := ledgerFilter(r)
+ now := usage.Clock().In(f.Zone)
+ rows := usage.LedgerOfAt(p, f, now).Rows
rw.Header().Set("Content-Type", "text/csv; charset=utf-8")
rw.Header().Set("Content-Disposition", `attachment; filename="`+csvStamp(p, q.Get("day"), now)+`.csv"`)
usage.WriteCSV(rw, rows)
@@ -146,8 +149,9 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("POST /api/usage/requests/export", func(rw http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
p := periodOf(q.Get("period"))
- now := usage.Clock()
- rows := usage.LedgerOfAt(p, ledgerFilter(q), now).Rows
+ f := ledgerFilter(r)
+ now := usage.Clock().In(f.Zone)
+ rows := usage.LedgerOfAt(p, f, now).Rows
var b bytes.Buffer
if err := usage.WriteCSV(&b, rows); err != nil {
fail(rw, err)
diff --git a/internal/gui/usage_zone_test.go b/internal/gui/usage_zone_test.go
new file mode 100644
index 000000000..6426154d8
--- /dev/null
+++ b/internal/gui/usage_zone_test.go
@@ -0,0 +1,110 @@
+package gui
+
+import (
+ "encoding/csv"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/usage"
+)
+
+// The Usage page's routes read days and hours in the zone the page names
+// in ?tz=, the browser's, not the computer's: `magpie web` read from UTC+8
+// showed a call at 9:00 under 1:00 (Outvi V on Discord). Without ?tz= the
+// computer's, as the tray and the TUI read them. Run under TZ=UTC and
+// TZ=Asia/Shanghai.
+func TestUsageRoutesReadTheViewersZone(t *testing.T) {
+ sandboxHome(t)
+ var v *time.Location
+ for _, name := range []string{"Asia/Shanghai", "America/Los_Angeles"} {
+ if z := usage.Zone(name); z != time.Local {
+ v = z
+ break
+ }
+ }
+ // a moment and a call before it on one day in v and on two in the
+ // computer's zone
+ var now, call time.Time
+ day := func(at time.Time, l *time.Location) string { return at.In(l).Format(time.DateOnly) }
+find:
+ for n := 0; n < 48; n++ {
+ now = time.Date(2026, 9, 30, n, 0, 0, 0, time.UTC)
+ for h := 1; h < 24; h++ {
+ call = now.Add(-time.Duration(h) * time.Hour)
+ if day(call, v) == day(now, v) && day(call, time.Local) != day(now, time.Local) {
+ break find
+ }
+ }
+ }
+ old := usage.Clock
+ usage.Clock = func() time.Time { return now.In(time.Local) }
+ t.Cleanup(func() { usage.Clock = old })
+ usage.Append(usage.Record{Time: call, Agent: "claude", Provider: "relay", Model: "unknown", Input: 10, Status: 200})
+
+ mux := http.NewServeMux()
+ usageRoutes(mux, folderOnly{})
+ get := func(path string, out any) string {
+ t.Helper()
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
+ if w.Code != 200 {
+ t.Fatalf("%s: %d %s", path, w.Code, w.Body)
+ }
+ if out != nil {
+ if err := json.Unmarshal(w.Body.Bytes(), out); err != nil {
+ t.Fatal(path, err)
+ }
+ }
+ return w.Body.String()
+ }
+ tz := "&tz=" + url.QueryEscape(v.String())
+ hour, date := call.In(v).Format("15"), day(call, v)
+
+ var s usageJSON
+ get("/api/usage?period=today"+tz, &s)
+ at := ""
+ for _, p := range s.Series {
+ if p.Calls > 0 {
+ at = p.Label
+ }
+ }
+ if s.Calls != 1 || at != hour {
+ t.Errorf("/api/usage in %v: %d calls at %q, want 1 at %q", v, s.Calls, at, hour)
+ }
+ s = usageJSON{}
+ if get("/api/usage?period=today", &s); s.Calls != 0 {
+ t.Errorf("/api/usage in the computer's zone: %d calls, want 0", s.Calls)
+ }
+
+ var l ledgerJSON
+ get("/api/usage/requests?period=today"+tz, &l)
+ at = ""
+ for _, p := range l.Series {
+ if p.Calls > 0 {
+ at = p.Label
+ }
+ }
+ if l.Total != 1 || at != hour {
+ t.Errorf("/api/usage/requests in %v: %d rows at %q, want 1 at %q", v, l.Total, at, hour)
+ }
+ l = ledgerJSON{}
+ if get("/api/usage/requests?period=all&day="+date+tz, &l); l.Total != 1 {
+ t.Errorf("/api/usage/requests on the reader's %s: %d rows, want 1", date, l.Total)
+ }
+
+ var h usage.Heatmap
+ get("/api/usage/heatmap?period=all"+tz, &h)
+ if h.To != day(now, v) || len(h.Days) != 1 || h.Days[0].Date != date {
+ t.Errorf("/api/usage/heatmap in %v: to %s, %+v; want to %s, the call on %s", v, h.To, h.Days, day(now, v), date)
+ }
+
+ cells, err := csv.NewReader(strings.NewReader(get("/api/usage/requests.csv?period=today"+tz, nil))).ReadAll()
+ if err != nil || len(cells) != 2 {
+ t.Errorf("CSV of the reader's today: %v, %d lines, want a row under the header", err, len(cells))
+ }
+}
diff --git a/internal/usage/cache_bounds_test.go b/internal/usage/cache_bounds_test.go
index 0918c5874..404f941d8 100644
--- a/internal/usage/cache_bounds_test.go
+++ b/internal/usage/cache_bounds_test.go
@@ -285,7 +285,7 @@ func TestUsageLargeSummaryIsCompleteAndKeptTrimmed(t *testing.T) {
t.Fatalf("large summary lost sessions: %d / %d", len(got.Sessions), got.Calls)
}
summaries.Lock()
- kept := summaries.entries[All]
+ kept := summaries.entries[summaryKey{All, time.Local}]
summaries.Unlock()
if len(kept.value.Sessions) != summaryCacheSessions || kept.value.SessionCount != summaryCacheSessions+1 {
t.Fatalf("the cache kept %d sessions of %d", len(kept.value.Sessions), kept.value.SessionCount)
@@ -329,7 +329,7 @@ func TestUsageOverBudgetPageIsCached(t *testing.T) {
equalPage(t, got, pageFromLedger(All, Filter{}, 0, 100, LedgerOf(All, Filter{})))
requestCache.Lock()
defer requestCache.Unlock()
- if _, ok := requestCache.pages[pageKey{All, Filter{}, 0, 100}]; !ok {
+ if _, ok := requestCache.pages[pageKey{All, Filter{}, 0, 100, "2026-09-30"}]; !ok {
t.Fatal("page of an over-budget history not cached")
}
}
diff --git a/internal/usage/heatmap.go b/internal/usage/heatmap.go
index b639838c4..b9dfafbb4 100644
--- a/internal/usage/heatmap.go
+++ b/internal/usage/heatmap.go
@@ -37,8 +37,8 @@ type Day struct {
Unpriced int `json:"unpriced,omitempty"`
}
-// Heatmap is the days from From to To (today), both YYYY-MM-DD in the local
-// time zone: only those with calls are listed, oldest first.
+// Heatmap is the days from From to To (today), both YYYY-MM-DD in the
+// reader's time zone (Filter.Zone): only those with calls are listed, oldest first.
type Heatmap struct {
From string `json:"from"`
To string `json:"to"`
@@ -56,10 +56,10 @@ func HeatmapOf(f Filter) Heatmap {
return Heatmap{Days: []Day{}}
}
-// heatmapOf sums the rows visit gives it by their local day, from since to
-// now's day; a row outside those days is left out.
+// heatmapOf sums the rows visit gives it by their day in now's zone (the
+// reader's), from since to now's day; a row outside those days is left out.
func heatmapOf(since, now time.Time, visit func(add func(Row))) *Heatmap {
- h := &Heatmap{From: since.Format(time.DateOnly), To: now.In(time.Local).Format(time.DateOnly), Days: []Day{}}
+ h := &Heatmap{From: since.Format(time.DateOnly), To: now.Format(time.DateOnly), Days: []Day{}}
at := map[string]*Day{}
// a day's name is made once for each day, not for each of its calls
type ymd struct{ y, yd int }
@@ -68,7 +68,7 @@ func heatmapOf(since, now time.Time, visit func(add func(Row))) *Heatmap {
if r.IsRejected() || r.Time.Before(since) {
return
}
- t := r.Time.In(time.Local)
+ t := r.Time.In(now.Location())
k := ymd{t.Year(), t.YearDay()}
d, ok := names[k]
if !ok {
diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go
index 5cbc38594..69f18c07d 100644
--- a/internal/usage/ledger.go
+++ b/internal/usage/ledger.go
@@ -53,7 +53,10 @@ func (r Record) Failed() bool { return r.Status >= 400 || r.Error != "" }
// one provider, to the failed calls, and to the rows whose models, provider, host or
// session hold Query (any case).
type Filter struct {
- Day string // YYYY-MM-DD in the chart's local time zone; "" is the whole period
+ Day string // YYYY-MM-DD in Zone; "" is the whole period
+ // Zone is the reader's time zone (Zone gives it), which the period's
+ // days, the chart's hours and Day are read in; nil is this computer's
+ Zone *time.Location
CallerKey string
RouteID int64
Model string // exact model selected in the ranking
@@ -146,7 +149,7 @@ func (f Filter) keeps(r Record) bool {
func (f Filter) keepsRecord(r Record, codexIdentity bool, subagent, parentAgent string) bool {
if f.Day != "" {
var day [len(time.DateOnly)]byte
- if string(r.Time.In(time.Local).AppendFormat(day[:0], time.DateOnly)) != f.Day {
+ if string(r.Time.In(f.loc()).AppendFormat(day[:0], time.DateOnly)) != f.Day {
return false
}
}
@@ -238,7 +241,7 @@ type Ledgered struct {
// comes with the calls the agents' session files record that the gateway did
// not see.
func LedgerOf(p Period, f Filter) Ledgered {
- return LedgerOfAt(p, f, Clock())
+ return LedgerOfAt(p, f, Clock().In(f.loc()))
}
// LedgerOfAt is LedgerOf with the period read at now, for an answer that
@@ -275,7 +278,9 @@ func gatewayRecords(since time.Time) []Record {
// Filtered narrows one snapshot without reloading either log or repricing rows.
func (l Ledgered) Filtered(f Filter) Ledgered {
- if f == (Filter{}) {
+ g := f
+ g.Zone = nil // the zone narrows nothing but through Day
+ if g == (Filter{}) {
return l
}
out := Ledgered{Rows: []Row{}, Agents: l.Agents, Providers: l.Providers}
diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go
index 971c837dc..abf374762 100644
--- a/internal/usage/request_page.go
+++ b/internal/usage/request_page.go
@@ -362,6 +362,10 @@ type pageKey struct {
Period Period
Filter Filter
Offset, Limit int
+ // Date is today in the reader's zone (Filter.Zone): the request
+ // state's key turns with this computer's day, and a reader in another
+ // zone has a today of their own
+ Date string
}
type requestIndex struct {
sync.Mutex
@@ -457,7 +461,7 @@ func readRequestState(now time.Time) requestState {
meta += fmt.Sprintf("|%x|%s", h.Sum(nil), statKey(catalog.LivePath("antigravity")))
h.Reset()
snapshot := readLogSnapshot()
- fmt.Fprint(h, meta, snapshot.version, now.Format("2006-01-02 MST"))
+ fmt.Fprint(h, meta, snapshot.version, now.In(time.Local).Format("2006-01-02 MST"))
for _, s := range sources {
fmt.Fprintf(h, "%s:%d:%d;", s.Path, s.Size, s.Modified.UnixNano())
}
@@ -479,8 +483,9 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
limit = min(limit, 500)
offset = max(0, offset)
// The time is read once, so that the rows, the chart and the day the page
- // is kept for are of one day when midnight falls while it is worked out.
- now := Clock()
+ // is kept for are of one day when midnight falls while it is worked out,
+ // and read in the reader's zone, whose days and hours the page shows.
+ now := Clock().In(f.loc())
// A replacement reader remains useful to callers supplying synthetic logs.
if LogCalls != nil {
return pageFromLedgerAt(p, f, offset, limit, LedgerOfAt(p, Filter{}, now), now)
@@ -501,7 +506,7 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
idx.pages = map[pageKey]RequestPage{}
idx.key = key
}
- q := pageKey{p, f, offset, limit}
+ q := pageKey{p, f, offset, limit, now.Format(time.DateOnly)}
if page, ok := idx.pages[q]; ok {
idx.Unlock()
return page
@@ -620,8 +625,8 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
var others []*rowChunk
var renames map[string]string
from := ""
- if !since.IsZero() {
- from = since.AddDate(0, 0, -1).Format(time.DateOnly)
+ if !since.IsZero() { // as sharedSources reads it
+ from = since.AddDate(0, 0, -2).Format(time.DateOnly)
}
for _, s := range days {
on[s.path] = true
@@ -1193,7 +1198,7 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time
}
for _, ref := range charted {
r := ref.row()
- t := r.Time.In(time.Local)
+ t := r.Time.In(now.Location())
if t.Before(chartSince) {
continue
}
diff --git a/internal/usage/shared.go b/internal/usage/shared.go
index 4972dfb31..af3b4635f 100644
--- a/internal/usage/shared.go
+++ b/internal/usage/shared.go
@@ -245,8 +245,11 @@ func sharedSources(since time.Time) (out []sharedSource, some bool) {
}
self, _ := Computer()
from := ""
- if !since.IsZero() { // a day's calls began where it was a day: one before
- from = since.AddDate(0, 0, -1).Format(time.DateOnly)
+ // A day's calls began where it was a day, and since is the reader's
+ // day, which can begin up to 26 hours from that computer's (UTC-12 and
+ // UTC+14): two days before.
+ if !since.IsZero() {
+ from = since.AddDate(0, 0, -2).Format(time.DateOnly)
}
for _, k := range kept {
c, day, _ := strings.Cut(k, "/")
diff --git a/internal/usage/summary_cache.go b/internal/usage/summary_cache.go
index 41b8f0de4..10464f971 100644
--- a/internal/usage/summary_cache.go
+++ b/internal/usage/summary_cache.go
@@ -23,9 +23,16 @@ type summaryEntry struct {
value Summary
}
+// summaryKey is a period as read in a zone: each reader's zone (Zone) has
+// days of its own, and readers in two zones don't put each other's out.
+type summaryKey struct {
+ p Period
+ zone *time.Location
+}
+
var summaries struct {
sync.Mutex
- entries map[Period]summaryEntry
+ entries map[summaryKey]summaryEntry
worked int // how many summaries were worked out, for the tests
}
@@ -40,6 +47,15 @@ func indexedSummary(p Period, now time.Time) Summary { return topSummary(p, now,
// the Usage page and the TUI, and the page was sent all 84k.
func SummarizeTop(p Period, n int) Summary { return topSummary(p, Clock(), n) }
+// SummarizeTopIn is SummarizeTop with the period's days and the chart's
+// hours read in zone (Zone gives it), the reader's: the Usage page's.
+func SummarizeTopIn(p Period, n int, zone *time.Location) Summary {
+ if zone == nil {
+ zone = time.Local
+ }
+ return topSummary(p, Clock().In(zone), n)
+}
+
func topSummary(p Period, now time.Time, n int) Summary {
p = p.shown()
snapshot := readLogSnapshot()
@@ -57,7 +73,8 @@ func topSummary(p Period, now time.Time, n int) Summary {
}
meta := usagePriceCacheKey(now)
summaries.Lock()
- old, ok := summaries.entries[p]
+ k := summaryKey{p, now.Location()}
+ old, ok := summaries.entries[k]
summaries.Unlock()
if ok && old.version == snapshot.version && old.meta == meta && (n >= 0 && n <= len(old.value.Sessions) || old.value.SessionCount == len(old.value.Sessions)) {
return topOf(cloneSummary(old.value), n)
@@ -70,10 +87,10 @@ func topSummary(p Period, now time.Time, n int) Summary {
kept = cloneSummary(kept)
summaries.Lock()
if summaries.entries == nil {
- summaries.entries = map[Period]summaryEntry{}
+ summaries.entries = map[summaryKey]summaryEntry{}
}
- if previous := summaries.entries[p]; previous.version <= snapshot.version {
- summaries.entries[p] = summaryEntry{snapshot.version, meta, kept}
+ if previous := summaries.entries[k]; previous.version <= snapshot.version {
+ summaries.entries[k] = summaryEntry{snapshot.version, meta, kept}
}
summaries.Unlock()
return topOf(value, n)
diff --git a/internal/usage/zone.go b/internal/usage/zone.go
new file mode 100644
index 000000000..7e3197c97
--- /dev/null
+++ b/internal/usage/zone.go
@@ -0,0 +1,62 @@
+package usage
+
+import (
+ "sync"
+ "time"
+)
+
+// The Usage page buckets its calls by the reader's days and hours, not the
+// computer's: `magpie web` read from across an ocean showed a call at 9:00
+// in UTC+8 under 1:00 (Outvi V on Discord). The page names its browser's
+// zone, and Zone is that zone here.
+
+var zones sync.Map // name → *time.Location, one for each name
+
+// Zone is the time zone a browser names (an IANA name such as
+// "Asia/Shanghai"), the same *time.Location for every ask of one name, so
+// that a Filter holding it is the same cache key each time. A zone that
+// keeps this computer's clock, the page on this computer, is time.Local,
+// whose answers the tray and the TUI share. An empty name or one this
+// computer doesn't know is time.Local: the computer's days, as before.
+func Zone(name string) *time.Location {
+ if name == "" || name == "Local" {
+ return time.Local
+ }
+ if l, ok := zones.Load(name); ok {
+ return l.(*time.Location)
+ }
+ loc, err := time.LoadLocation(name)
+ if err != nil {
+ return time.Local // not kept: any text can be asked for
+ }
+ if sameClock(loc, time.Local) {
+ loc = time.Local
+ }
+ l, _ := zones.LoadOrStore(name, loc)
+ return l.(*time.Location)
+}
+
+// sameClock is whether a and b tell the same offset every twelve hours
+// from three years back to a year on: the span the Usage page's days reach
+// (its heatmap is a year), and either side of every daylight-saving change
+// in it. Worked out once for each name.
+func sameClock(a, b *time.Location) bool {
+ y := time.Now().Year()
+ end := time.Date(y+2, time.January, 1, 0, 0, 0, 0, time.UTC)
+ for t := time.Date(y-3, time.January, 1, 0, 0, 0, 0, time.UTC); t.Before(end); t = t.Add(12 * time.Hour) {
+ _, oa := t.In(a).Zone()
+ _, ob := t.In(b).Zone()
+ if oa != ob {
+ return false
+ }
+ }
+ return true
+}
+
+// loc is the zone f reads its days in: the reader's, else this computer's.
+func (f Filter) loc() *time.Location {
+ if f.Zone != nil {
+ return f.Zone
+ }
+ return time.Local
+}
diff --git a/internal/usage/zone_test.go b/internal/usage/zone_test.go
new file mode 100644
index 000000000..a5410d9e9
--- /dev/null
+++ b/internal/usage/zone_test.go
@@ -0,0 +1,138 @@
+package usage
+
+import (
+ "os"
+ "testing"
+ "time"
+)
+
+// viewerZone is a zone whose clock this computer's doesn't keep: the
+// browser of `magpie web` read from elsewhere.
+func viewerZone(t *testing.T) *time.Location {
+ t.Helper()
+ for _, name := range []string{"Asia/Shanghai", "America/Los_Angeles"} {
+ if z := Zone(name); z != time.Local {
+ return z
+ }
+ }
+ t.Fatal("no zone apart from this computer's")
+ return nil
+}
+
+// zoneApart is a moment now and a call before it that fall on one day in
+// the reader's zone v and on two days in this computer's: the call is
+// today for the reader and not for the computer.
+func zoneApart(t *testing.T, v *time.Location) (now, call time.Time) {
+ t.Helper()
+ base := time.Date(2026, 9, 30, 0, 0, 0, 0, time.UTC)
+ day := func(at time.Time, l *time.Location) string { return at.In(l).Format(time.DateOnly) }
+ for n := 0; n < 48; n++ {
+ now = base.Add(time.Duration(n) * time.Hour)
+ for h := 1; h < 24; h++ {
+ call = now.Add(-time.Duration(h) * time.Hour)
+ if day(call, v) == day(now, v) && day(call, time.Local) != day(now, time.Local) {
+ return now, call
+ }
+ }
+ }
+ t.Fatalf("no moment where %v and %v keep different days", v, time.Local)
+ return
+}
+
+// The Usage page's days and hours are the reader's: a call at 9:00 in
+// UTC+8 read from a browser there shows at 09 and on that day, whatever
+// zone the computer serving the page keeps (Outvi V on Discord). Without a
+// zone, the computer's days, as before. Run under TZ=UTC and
+// TZ=Asia/Shanghai.
+func TestUsageReadsTheViewersZone(t *testing.T) {
+ pageHome(t)
+ v := viewerZone(t)
+ now, call := zoneApart(t, v)
+ holdClock(t, call)
+ Append(Record{Agent: "claude", Provider: "openai", Model: "m", Input: 10, Status: 200}) // stamped at call
+ holdClock(t, now.In(time.Local))
+
+ hour, date := call.In(v).Format("15"), call.In(v).Format(time.DateOnly)
+ labelOf := func(pts []Point, calls func(int) int) string {
+ for i, p := range pts {
+ if calls(i) > 0 {
+ return p.Label
+ }
+ }
+ return ""
+ }
+ t.Logf("computer %v, reader %v: call %v, now %v", time.Local, v, call.In(v), now.In(v))
+
+ s := SummarizeTopIn(Today, 10, v)
+ if s.Calls != 1 {
+ t.Errorf("Summary of the reader's today: %d calls, want 1", s.Calls)
+ }
+ if got := labelOf(s.Series, func(i int) int { return s.Series[i].Calls }); got != hour {
+ t.Errorf("Summary's hour: %q, want the reader's %q", got, hour)
+ }
+ if s := SummarizeTopIn(Today, 10, nil); s.Calls != 0 {
+ t.Errorf("Summary of the computer's today: %d calls, want 0", s.Calls)
+ }
+
+ f := Filter{Zone: v}
+ p := QueryPage(Today, f, 0, 10)
+ if p.Total != 1 {
+ t.Errorf("Requests in the reader's today: %d, want 1", p.Total)
+ }
+ pts := make([]Point, len(p.Series))
+ for i := range p.Series {
+ pts[i] = p.Series[i].Point
+ }
+ if got := labelOf(pts, func(i int) int { return p.Series[i].Calls }); got != hour {
+ t.Errorf("Requests chart's hour: %q, want the reader's %q", got, hour)
+ }
+ if p := QueryPage(Today, Filter{}, 0, 10); p.Total != 0 {
+ t.Errorf("Requests in the computer's today: %d, want 0", p.Total)
+ }
+ if l := LedgerOf(Today, f); len(l.Rows) != 1 {
+ t.Errorf("ledger of the reader's today: %d rows, want 1", len(l.Rows))
+ }
+ if p := QueryPage(All, Filter{Zone: v, Day: date}, 0, 10); p.Total != 1 {
+ t.Errorf("Requests on the reader's day %s: %d, want 1", date, p.Total)
+ }
+
+ // a week's chart is a day a point: the call's is the reader's day
+ dayLabel := call.In(v).Format("Jan 2")
+ w := SummarizeTopIn(Week, 10, v)
+ if got := labelOf(w.Series, func(i int) int { return w.Series[i].Calls }); got != dayLabel {
+ t.Errorf("Summary's day in the week: %q, want the reader's %q", got, dayLabel)
+ }
+ wp := QueryPage(Week, f, 0, 10)
+ wpts := make([]Point, len(wp.Series))
+ for i := range wp.Series {
+ wpts[i] = wp.Series[i].Point
+ }
+ if got := labelOf(wpts, func(i int) int { return wp.Series[i].Calls }); got != dayLabel {
+ t.Errorf("Requests chart's day in the week: %q, want the reader's %q", got, dayLabel)
+ }
+
+ h := HeatmapOf(f)
+ if h.To != now.In(v).Format(time.DateOnly) || len(h.Days) != 1 || h.Days[0].Date != date {
+ t.Errorf("heatmap: to %s, days %+v; want to %s and the call on %s", h.To, h.Days, now.In(v).Format(time.DateOnly), date)
+ }
+}
+
+// Zone is one *time.Location for each name, so a Filter holding it is one
+// cache key; a name this computer doesn't know, or one keeping its clock,
+// is this computer's own zone.
+func TestZoneNames(t *testing.T) {
+ for _, name := range []string{"", "Local", "Not/AZone", "../../etc/passwd"} {
+ if Zone(name) != time.Local {
+ t.Errorf("Zone(%q) = %v, want this computer's", name, Zone(name))
+ }
+ }
+ v := viewerZone(t)
+ if Zone(v.String()) != v {
+ t.Errorf("Zone(%q) twice gave two locations", v.String())
+ }
+ if tz := os.Getenv("TZ"); tz != "" {
+ if Zone(tz) != time.Local {
+ t.Errorf("Zone(%q), this computer's own zone, is not time.Local", tz)
+ }
+ }
+}
diff --git a/internal/usageapi/usageapi.go b/internal/usageapi/usageapi.go
index 1a60de68d..765534f24 100644
--- a/internal/usageapi/usageapi.go
+++ b/internal/usageapi/usageapi.go
@@ -6,11 +6,13 @@ package usageapi
import (
"cmp"
+ "net/http"
"net/url"
"os"
"slices"
"strconv"
"strings"
+ "time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
@@ -73,7 +75,28 @@ const PageSessions = 100
// Usage page asks for: over a long history (Vantiboo1ean, ~750k requests)
// State sent the page every one of ~84k sessions (22 MB) and worked the
// summary out again for each refresh.
-func Page(p usage.Period) Usage { return stateOf(usage.SummarizeTop(p, PageSessions)) }
+func Page(p usage.Period) Usage { return PageIn(p, nil) }
+
+// PageIn is Page with the period's days and the chart's hours in zone, the
+// reader's (ZoneOf); nil is this computer's.
+func PageIn(p usage.Period, zone *time.Location) Usage {
+ return stateOf(usage.SummarizeTopIn(p, PageSessions, zone))
+}
+
+// ZoneOf is the reader's time zone, which the Usage page names in ?tz= (its
+// browser's IANA name, as Intl gives it) for its days and hours to be the
+// reader's: magpie web may be read from another zone than the computer's
+// (Outvi V on Discord). This computer's when it names none or one unknown
+// here.
+func ZoneOf(r *http.Request) *time.Location { return usage.Zone(r.URL.Query().Get("tz")) }
+
+// FilterIn is FilterOf with the reader's zone, ZoneOf(r), which its Day and
+// the period's days are read in.
+func FilterIn(r *http.Request) usage.Filter {
+ f := FilterOf(r.URL.Query())
+ f.Zone = ZoneOf(r)
+ return f
+}
func stateOf(s usage.Summary) Usage {
out := Usage{Summary: s, Agents: []Group{}, Models: []Group{}, Accounts: []Group{}, Path: Tilde(usage.Path())}