Files
magpie/internal/gateway/live_rates.go
T
yetone e6f151507f sessions: each session's output speed, a curve of its last two minutes
The owner liked a tweet's token-speed curve and approved a mockup
(claude.ai/artifact/7mrkMKdVi6jA3HA1Z6pRr5). Each Sessions row now
shows its output speed with a small curve; clicking it opens a popover
with the current tok/s, two minutes of seconds, tool gaps, and the
round's average, fastest second and output so far. A row not live
shows "Avg {n} tok/s".

Gateway: a curveMeter (session_speed.go) on the Server counts every
reply's content bytes per agent and session, from liveRow.observe, the
same count the Live view uses, and turns them into tokens with the
learned per-model rate (tokenRates.rate). A model with no rate yet
shows the curve's shape and no number: a guess would be a wrong
number. counted() opens a session's in-flight span, so a second with
nothing in flight is a gap (a tool ran), not a zero. A pause past 2m
starts a new round; 10m of quiet forgets the session; at most 256
sessions. Codex's own sign-in (codex_backend.go) went past serve and
liveRow before; it now has a liveRow too, so its sessions are counted.

GUI: GET /api/speeds, kept out of /api/sessions* so a once-a-second
poll doesn't set off session reading. The page polls only while
Sessions is shown and visible. managedJSON gains keys, so a row
matches a session the gateway saw under another of its keys. The
curve hides below 620px.

Run (mote's sshd resets every connection today, so Linux and Windows):
- Linux (magpie-desktop, wsl-run): gofmt clean; go test -timeout 45m
  ./internal/gateway ./internal/sessions ok except
  TestGroupFailoverTimesEachTry, red once under load, 5/5 green alone
  here and on main (#5948); node --test over every sessions-*.test.cjs
  and i18n-*.test.cjs: 546/549, the reds sessions-export en in both
  engines, the same on origin/main d657e182a alone (#5947), and
  sessions-folder-paging webkit zh, green alone. sessions-speed in
  Chromium and WebKit x en, zh, zh-TW, ja, de (row, popover, live
  update, narrow width, no poll off the page).
- Windows (xiaomi-gpu, win-run), at this head: go vet ./... clean; the
  curve/live/rates/codex tests of ./internal/gateway ok; go test
  ./internal/gui ./internal/sessions ok but 12 tests, every one red the
  same on origin/main 4d95d81ea and filed (#4115, #5928, #4043, #4925,
  #5324; TestAntigravityAppFolder new as #5957). (internal/gui needs gtk4 for cgo, which
  the WSL distro lacks.)
- At the pushed head (on 6886da1ca, which changed core i18n.js and
  gateway.go), Linux: sessions-speed, i18n-keys, i18n-en-no-cjk,
  sessions-row-narrow 22/22; the gateway curve/live/rates/codex/CORS
  tests ok. The Windows run above was at 4d95d81ea.
Broken by hand: with live.go's curves.add skipped, both
TestSessionCurveFromARealStream and TestSessionCurveFromCodexOwnSignIn
went red; green once restored.

Not tried: a real agent session in the built app; macOS (mote down);
darwin vet; the full go and GUI suites (run after the push, reds
filed).
2026-11-10 20:22:17 +08:00

107 lines
2.9 KiB
Go

package gateway
import (
"sync"
"time"
)
// tokenRates learns how many output tokens a provider's model writes per
// content byte, from streamed replies whose vendor said their output
// tokens, to estimate a reply in flight before its usage comes (#4951).
// An estimate is never learned from, and under liveRateMin replies there
// is none: the page then shows no tokens rather than a guess.
//
// The rates are kept in memory only: a restart learns them again in
// liveRateMin replies, and nothing is written per request.
const (
liveRateMin = 3 // replies learned before a pair estimates
liveRateKeys = 256 // pairs kept, the least recently learned dropped
)
// rateSample is a pair's sums: estimating a ratio needs no more.
type rateSample struct {
bytes, output int64
seen int
at int64
}
type tokenRates struct {
mu sync.Mutex
m map[string]rateSample
}
// liveRates is the gateway's one: estimate runs on every write of a
// stream, a multiplication under a lock nothing blocks under.
var liveRates = &tokenRates{m: map[string]rateSample{}}
func rateKey(provider, model string) string {
if provider == "" || model == "" {
return ""
}
return provider + "/" + model
}
// estimate is content's output tokens at the pair's learned rate, rounded
// down, or 0 when it has none yet.
func (t *tokenRates) estimate(provider, model string, content int64) int {
if content <= 0 || provider == "" || model == "" {
return 0
}
t.mu.Lock()
s, ok := t.m[rateKey(provider, model)]
t.mu.Unlock()
if !ok || s.seen < liveRateMin || s.bytes <= 0 || s.output <= 0 {
return 0
}
// in floats: the sums grow with every reply, and their product with a
// long reply's content would overflow
return int(float64(content) * float64(s.output) / float64(s.bytes))
}
// learn adds one finished reply: content bytes and the vendor's output.
func (t *tokenRates) learn(provider, model string, content int64, output int) {
key := rateKey(provider, model)
if key == "" || content <= 0 || output <= 0 {
return
}
t.mu.Lock()
defer t.mu.Unlock()
s := t.m[key]
s.bytes += content
s.output += int64(output)
s.seen++
s.at = time.Now().UnixNano()
t.m[key] = s
if len(t.m) > liveRateKeys {
oldest, at := "", int64(1<<62)
for k, v := range t.m {
if v.at < at {
oldest, at = k, v.at
}
}
delete(t.m, oldest)
}
}
// resetRates forgets every rate, for a test.
func resetRates() {
liveRates.mu.Lock()
liveRates.m = map[string]rateSample{}
liveRates.mu.Unlock()
}
// rate is the pair's learned output tokens a content byte, false when it
// has none yet (as estimate).
func (t *tokenRates) rate(provider, model string) (float64, bool) {
if provider == "" || model == "" {
return 0, false
}
t.mu.Lock()
s, ok := t.m[rateKey(provider, model)]
t.mu.Unlock()
if !ok || s.seen < liveRateMin || s.bytes <= 0 || s.output <= 0 {
return 0, false
}
return float64(s.output) / float64(s.bytes), true
}