Files
magpie/internal/usage/gateway_sessions.go
T
yetone 60f896031e usage: a client the user counts as an agent is counted as it on Usage and Sessions (#1958, NorethSea)
NorethSea's bridge (hermes-codex-thread-bridge) starts Codex's
app-server under a User-Agent of its own, so its calls were a row
apart from Codex on Usage, and its threads weren't Codex's in Sessions.
Rather than learn one bridge's name, the user says which agent a client
counts as.

- settings: clientAgents, client name (lowercased) -> agent id.
  ClientAgentsNow reads just that field through filememo, so a pass over
  the ledger costs a stat.
- usage: ReportedAs(ua) is AgentOf, then the user's mapping. It is used
  for what is reported only: the summary, the agents list and filters,
  request rows and pages, priced blocks, direct, Vias and gateway
  sessions. The gateway's routing, keys and caps still go by AgentOf,
  the client's own name. The mapping is read once per ledger pass
  (readLogSnapshot) and is part of the keys of the summary price cache,
  the vias cache and the request page cache, so a change redraws the
  history already counted. A request row keeps the client's own name in
  a new "client" field, shown as "Client" in its details.
- gui: POST /api/usage/arrange takes {count:{client,as}}. It refuses a
  client magpie already knows as an agent, "other" or magpie's own, and
  an "as" that isn't a known agent or is magpie. as "" counts it on its
  own again. /api/settings keeps the mapping it doesn't send. On the
  Usage page an unknown client's "…" offers "Count as an agent…" (a
  picker of the known agents), the agent's row says "with <client>",
  and the agent's "…" offers "Count <client> on its own". Strings are
  in all 5 languages.

Run:
- go test -count=1 ./internal/usage ./internal/settings ./internal/gui: ok.
- TestClientCountedAsAgent goes red with reportedAs broken, and with the
  mapping left out of the vias key or the request page key. With the
  summary key alone left out it stays green, because the settings stat
  already moves it.
- TestUsageArrangeCountClient and TestSettingsSaveKeepsWhatItDoesNotSend
  (ClientAgents added) pass.
- Playwright usage-count-client.test.cjs (new) and usage-agents-hide
  (its menu now has two items for an unknown client) pass in Chromium
  and WebKit, in all 5 languages, at 1100 and 420: 54/54. With
  countable() forced false, the new test goes red.
- gofmt -l is clean. go vet is clean for darwin, linux -tags nogui and
  windows.

Not tried: a real hermes bridge (the records' UA is from the issue), and
the Client line in a request's details has no GUI test.
2026-10-13 18:17:47 +08:00

306 lines
8.7 KiB
Go

package usage
import (
"slices"
"sort"
"sync"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/sessions"
)
// GatewaySessionWindow returns gateway sessions and their daily usage for a
// local-date range. It is kept separate from the GUI conversion so callers
// can use the same single usage-log snapshot for list and stats.
func GatewaySessionWindow(since time.Time) ([]GatewaySession, []GatewayDayUsage) {
return gatewaySessionSnapshot(since, nil)
}
func GatewaySessionWindowExcept(since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage) {
return gatewaySessionSnapshot(since, nativeKeys)
}
type GatewayDayUsage struct {
Date, Agent, Model string
sessions.Tokens
Cost float64
Priced bool
}
// GatewaySession is a read-only projection of requests served by this
// gateway. Its identity is the agent name and the session id supplied by the
// client. Unidentified requests and generated recording identities are left out.
type GatewaySession struct {
Agent string `json:"agent"`
ID string `json:"id"`
Start time.Time `json:"start"`
Last time.Time `json:"last"`
Models []GatewayModel `json:"models"`
Daily []GatewayDayUsage `json:"-"`
sessions.Tokens
Cost float64 `json:"cost"`
Unpriced int `json:"unpriced"`
}
type GatewayModel struct {
Model string `json:"model"`
sessions.Tokens
Cost float64 `json:"cost"`
Priced bool `json:"priced"`
}
// GatewaySessions aggregates one usage snapshot without reading routing
// history or agent files. NativeKeys contains identities already represented
// by local session files and is used to suppress the duplicate projection.
func GatewaySessions(since time.Time, nativeKeys map[string]bool) []GatewaySession {
e := gatewayProjection(since)
out := make([]GatewaySession, 0, len(e.sessions))
for _, s := range e.sessions {
if !nativeKeys[s.Agent+"|"+s.ID] {
out = append(out, cloneGatewaySession(s))
}
}
return out
}
func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySession, bool) {
if id == "" {
return GatewaySession{}, false
}
agent = ReportedAs(agent)
if nativeKeys[agent+"|"+id] {
return GatewaySession{}, false
}
entry := gatewayProjection(time.Time{})
i, ok := entry.byID[agent+"|"+id]
if !ok {
return GatewaySession{}, false
}
return cloneGatewaySession(entry.sessions[i]), true
}
type gatewayProjectionEntry struct {
version uint64
meta string
since time.Time
sessions []GatewaySession
byID map[string]int
}
var gatewayCache struct {
sync.Mutex
entries []gatewayProjectionEntry
}
// Retain a few window projections, not one copy for every native exclusion set.
// The log snapshot version also detects rewrites and changes of config directory.
func gatewayProjection(since time.Time) gatewayProjectionEntry {
snapshot := readLogSnapshot()
meta := usagePriceCacheKey(time.Now())
gatewayCache.Lock()
defer gatewayCache.Unlock()
for _, e := range gatewayCache.entries {
if e.version == snapshot.version && e.meta == meta && e.since.Equal(since) {
return e
}
}
ss, _ := buildGatewaySessions(snapshot, since, nil)
e := gatewayProjectionEntry{version: snapshot.version, meta: meta, since: since, sessions: ss, byID: make(map[string]int, len(ss))}
for i, s := range ss {
e.byID[s.Agent+"|"+s.ID] = i
}
// A failed or partial read must be retried, not published as current.
if snapshot.info != nil && snapshot.off == snapshot.info.Size() {
gatewayCache.entries = slices.DeleteFunc(gatewayCache.entries, func(old gatewayProjectionEntry) bool {
return old.version != e.version || old.meta != e.meta || old.since.Equal(since)
})
if len(gatewayCache.entries) >= 4 {
gatewayCache.entries = gatewayCache.entries[1:]
}
gatewayCache.entries = append(gatewayCache.entries, e)
}
return e
}
func cloneGatewaySession(s GatewaySession) GatewaySession {
s.Models, s.Daily = slices.Clone(s.Models), slices.Clone(s.Daily)
return s
}
func gatewaySessionSnapshot(since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage) {
out := GatewaySessions(since, nativeKeys)
return out, gatewayDays(out)
}
func gatewayDays(ss []GatewaySession) []GatewayDayUsage {
type key struct{ date, agent, model string }
groups := map[key]GatewayDayUsage{}
for _, s := range ss {
for _, d := range s.Daily {
k := key{d.Date, d.Agent, d.Model}
v, ok := groups[k]
if !ok {
v.Date, v.Agent, v.Model, v.Priced = d.Date, d.Agent, d.Model, true
}
v.Input += d.Input
v.Output += d.Output
v.CacheRead += d.CacheRead
v.CacheWrite += d.CacheWrite
v.CacheWrite1h += d.CacheWrite1h
v.Cost += d.Cost
v.Priced = v.Priced && d.Priced
groups[k] = v
}
}
out := make([]GatewayDayUsage, 0, len(groups))
for _, d := range groups {
out = append(out, d)
}
sort.Slice(out, func(i, j int) bool {
a, b := out[i], out[j]
if a.Date != b.Date {
return a.Date < b.Date
}
if a.Agent != b.Agent {
return a.Agent < b.Agent
}
return a.Model < b.Model
})
return out
}
func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage) {
priceOf := pricer()
type key struct{ agent, id string }
groups := map[key]*GatewaySession{}
models := map[key]map[string]*GatewayModel{}
type dayKey struct{ date, agent, model string }
daily := map[dayKey]*GatewayDayUsage{}
perSession := map[key]map[dayKey]*GatewayDayUsage{}
snapshot.visit(since, func(r Record) {
if r.IsRejected() || r.IsReported() || r.Session == "" {
return
}
a := ReportedAs(r.Agent)
k := key{a, r.Session}
if nativeKeys != nil && nativeKeys[a+"|"+r.Session] {
return
}
s := groups[k]
if s == nil {
s = &GatewaySession{Agent: a, ID: r.Session, Models: []GatewayModel{}}
groups[k] = s
models[k] = map[string]*GatewayModel{}
perSession[k] = map[dayKey]*GatewayDayUsage{}
}
if s.Start.IsZero() || r.Time.Before(s.Start) {
s.Start = r.Time
}
if end := r.Time.Add(time.Duration(max(0, r.Millis)) * time.Millisecond); end.After(s.Last) {
s.Last = end
}
p := priceOf(r)
cost, priced := 0.0, true
if r.Input+r.Output > 0 {
if p == nil {
priced = false
} else {
cost = r.CostAt(*p)
}
}
tokens := sessions.Tokens{Input: r.Input, Output: r.Output, CacheRead: r.CacheRead, CacheWrite: r.CacheWrite, CacheWrite1h: r.CacheWrite1h}
dk := dayKey{r.Time.In(time.Local).Format(time.DateOnly), a, r.Model}
for _, kept := range []map[dayKey]*GatewayDayUsage{daily, perSession[k]} {
d := kept[dk]
if d == nil {
d = &GatewayDayUsage{Date: dk.date, Agent: a, Model: r.Model, Priced: true}
kept[dk] = d
}
d.Input += tokens.Input
d.Output += tokens.Output
d.CacheRead += tokens.CacheRead
d.CacheWrite += tokens.CacheWrite
d.CacheWrite1h += tokens.CacheWrite1h
d.Cost += cost
d.Priced = d.Priced && priced
}
s.Input += r.Input
s.Output += r.Output
s.CacheRead += r.CacheRead
s.CacheWrite += r.CacheWrite
s.CacheWrite1h += r.CacheWrite1h
m := models[k][r.Model]
if m == nil {
m = &GatewayModel{Model: r.Model, Priced: true}
models[k][r.Model] = m
}
m.addRecord(r, p)
})
for k, s := range groups {
for _, d := range perSession[k] {
s.Daily = append(s.Daily, *d)
}
sort.Slice(s.Daily, func(i, j int) bool {
if s.Daily[i].Date != s.Daily[j].Date {
return s.Daily[i].Date < s.Daily[j].Date
}
return s.Daily[i].Model < s.Daily[j].Model
})
for _, m := range models[k] {
s.Models = append(s.Models, *m)
s.Cost += m.Cost
if !m.Priced && m.Input+m.Output > 0 {
s.Unpriced++
}
}
sort.Slice(s.Models, func(i, j int) bool {
a, b := s.Models[i], s.Models[j]
if a.Input+a.Output != b.Input+b.Output {
return a.Input+a.Output > b.Input+b.Output
}
return a.Model < b.Model
})
}
out := make([]GatewaySession, 0, len(groups))
for _, s := range groups {
out = append(out, *s)
}
sort.Slice(out, func(i, j int) bool {
if !out[i].Last.Equal(out[j].Last) {
return out[i].Last.After(out[j].Last)
}
return out[i].Agent+"|"+out[i].ID < out[j].Agent+"|"+out[j].ID
})
days := make([]GatewayDayUsage, 0, len(daily))
for _, d := range daily {
days = append(days, *d)
}
sort.Slice(days, func(i, j int) bool {
if days[i].Date != days[j].Date {
return days[i].Date < days[j].Date
}
if days[i].Agent != days[j].Agent {
return days[i].Agent < days[j].Agent
}
return days[i].Model < days[j].Model
})
return out, days
}
func (m *GatewayModel) addRecord(r Record, p *catalog.Price) {
m.Input += r.Input
m.Output += r.Output
m.CacheRead += r.CacheRead
m.CacheWrite += r.CacheWrite
m.CacheWrite1h += r.CacheWrite1h
if r.Input+r.Output == 0 {
return
}
if p == nil {
m.Priced = false
return
}
m.Cost += r.CostAt(*p)
}