Files
magpie/internal/usage/heatmap.go
T
yetone ffe493773c usage: magpie's own Test, Detect APIs and model list requests are rows of the request log, counted nowhere
neiko and gys619 on Discord: a provider's Test or Detect APIs left no
trace in Usage > Requests, so a failing test couldn't be read back.

The provider package marks the context of the editor's Test, Detect APIs
(and per-model detection) and a model list's refresh with a kind
(internal/probelog). Each request sent under the mark is written once:
by the provider's Do, or by probelog.Transport under http.DefaultClient
(netproxy.Install), whichever sends it first; the Claude Code run and
the gateway's translated test write theirs from their result. A row
keeps time, provider, account, model, host, path (no query, no
user:password), method, status, ms and the first 500 bytes of the error.

The row is usage.SourceProbe, agent "magpie", Kind provider_test /
api_detect / model_list ("Test", "Detect APIs", "Model list" in Called
for; purposes.js regenerated). The log index keeps probes apart
(logSnapshot.probes), so Visit, Load, Summarize, budgets, Vias, heatmap,
shared days, LastSeen and observers never meet one. The request page
lists them (probeChunk) and counts none: Row.IsProbe, since a packed row
keeps the row's Source and not its record's. The page shows a muted
badge "magpie's own · not counted in any total" (en, zh, zh-TW, ja, de);
no new control, no layout change.

Tests, each red on the old code:
- usage TestProbeRowsListedNotCounted: listed, clipped, and absent from
  Sum, Through, every By group, Summarize, Load, LastSeen, OwnDays and
  the observer; a provider filter lists it and sums 0.
- provider TestTestWritesItsRequestsDown / TestDetectWritesItsRequestsDown:
  every request the fake server saw is exactly one row, with the right
  kind, model and 401 text; an unmarked Do writes nothing.
- probelog TestNoteKeepsNoSecret, TestTransportOnce.
- GUI usage-ledger-probe: badge per language, both engines, 1180/420,
  light and dark, no left border, no sideways scroll.
- gui TestProviderDetectDraft now expects the log line (source probe,
  kind api_detect, no key) and leaves usage.jsonl out of the unchanged
  config comparison.

Broken by hand, each went red: request_page's uncounted check,
log_index's probe skip, Append's observer skip, Do's Taken (6 rows for
4 requests), Test's and Detect's marks, probelog's query strip,
page.js's badge (11 GUI fails).

Run at this head (on origin/main 22a7f86c9): gofmt -l clean; go vet
./..., GOOS=linux -tags nogui and GOOS=windows clean; go test -count=1
usage, probelog, netproxy, usageapi, provider and gui packages ok (the
rebase over 22a7f86c9 applied cleanly; upstream's 8b460833e chunk
cache leaves probeChunk, built per query, alone).

Run one rebase earlier (on origin/main 0b72ccbef; request_page.go
merged by hand onto 7d67910f7/66b6d6ade's per-row Totals, with
uncounted rows skipping the caller and account groups too):
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, log tee'd:
  every package ok (gateway 640s, agent 514s, provider 278s, usage 77s)
  but internal/gui's TestRestartHandsTheGatewayOver (7 of 8 requests
  answered during the restart), 3 of 3 green alone after (#3451).
- gofmt -l clean; go vet ./..., GOOS=linux -tags nogui and GOOS=windows
  go vet ./... clean.
- GUI usage-ledger-probe, usage-ledger-reported, i18n-keys,
  purpose-filter, quota-pool-model: 72/72. usage-ledger's "newest live
  route needs no return-to-live button" is red on origin/main 0b72ccbef
  alone too (#3104).
- Whole GUI suite, both engines, at the pre-rebase base 761904b5a:
  1313 tests; reds, each also red on origin/main 7b1faf99f alone:
  account-discovery "agents' sign-ins read" (#3497), builtins
  "Plugins > Built-in" (Masking page in the list, #3518 filed), and
  context-map "two tiles overlap" chromium ja 420 (#3488; 1 of 2 red on
  main alone, 3 of 3 green on this branch alone). Earlier package run:
  TestRestartHandsTheGatewayOver red under load, passes alone (#3451).
- No size budget raised.

Not tried: no real vendor account (fake servers only); a plugin's model
list, fetched in the JS plugin host, isn't written down; the real GUI
app wasn't launched (Playwright only).
2026-10-25 04:12:06 +08:00

111 lines
3.3 KiB
Go

package usage
// The heatmap (#1369): the last 53 weeks a day each, as a calendar of
// contributions lays them out, Monday on top. It is the request page's own
// index read over that span — QueryPage's cached chunks, priced once — and
// not another pass over the logs, so a page asking for it again reads only
// what changed. It counts what the Requests tab's chart counts: the rows its
// filters keep, but for the day picked, and not the calls the gateway turned
// away itself.
import (
"slices"
"time"
)
// HeatmapWeeks is how many weeks the heatmap shows, this one the last.
const HeatmapWeeks = 53
// heatmapPeriod is the span the heatmap is read over: QueryPage's period for
// it, from the Monday HeatmapWeeks-1 weeks before this week's. Not one the
// page's period switch offers.
const heatmapPeriod Period = "heatmap"
// heatmapSince is the Monday the heatmap starts on, as of now.
func heatmapSince(now time.Time) time.Time {
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
return day.AddDate(0, 0, -(int(day.Weekday())+6)%7-7*(HeatmapWeeks-1))
}
// Day is one day's calls, by the local calendar day they fell on.
type Day struct {
Date string `json:"date"` // YYYY-MM-DD
Calls int `json:"calls"`
Tokens int `json:"tokens"` // in, out and through the cache, as the chart counts them
Cost float64 `json:"cost"` // of the priced calls, USD
// Unpriced: calls with tokens but no known price, not in Cost
Unpriced int `json:"unpriced,omitempty"`
}
// 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"`
Days []Day `json:"days"`
}
// HeatmapOf is the last HeatmapWeeks weeks of the calls the filter keeps, a
// day each. The filter's Day is not one of its dimensions here: the heatmap
// is every day's.
func HeatmapOf(f Filter) Heatmap {
f.Day = ""
if h := QueryPage(heatmapPeriod, f, 0, 1).Heat; h != nil {
return *h
}
return Heatmap{Days: []Day{}}
}
// 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.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 }
names := map[ymd]string{}
visit(func(r Row) {
if r.IsRejected() || r.IsProbe() || r.Time.Before(since) {
return
}
t := r.Time.In(now.Location())
k := ymd{t.Year(), t.YearDay()}
d, ok := names[k]
if !ok {
d = t.Format(time.DateOnly)
names[k] = d
}
if d > h.To {
return
}
x := at[d]
if x == nil {
x = &Day{Date: d}
at[d] = x
}
if !r.HandedOn {
x.Calls++ // a request, not each try at it
}
x.Tokens += r.Input + r.Output + r.CacheRead + r.CacheWrite
switch {
case r.Priced:
x.Cost += r.Cost
case r.Input+r.Output > 0:
x.Unpriced++
}
})
for _, x := range at {
h.Days = append(h.Days, *x)
}
slices.SortFunc(h.Days, func(a, b Day) int {
if a.Date < b.Date {
return -1
}
if a.Date > b.Date {
return 1
}
return 0
})
return h
}