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).
This commit is contained in:
@@ -1433,8 +1433,10 @@ Cost: `observe` takes the row's lock and the trace's, neither held while
|
||||
anything blocks. A whole JSON reply (its first byte `{` or `[`) is counted
|
||||
in bytes only, never copied or decoded; a stream is cut into lines in
|
||||
place, only a line cut by the end of a write is copied, and a line over
|
||||
1 MiB is passed over. The ChatGPT backend's chain (`codex_backend.go`)
|
||||
writes past the capture writer and is not counted.
|
||||
1 MiB is passed over. The ChatGPT backend's chain (`codex_backend.go`,
|
||||
`codexUpstreamOn`) writes past the capture writer, so it begins a
|
||||
`liveRow` of its own and calls `observe` on each chunk it copies, as the
|
||||
Responses protocol.
|
||||
|
||||
The page ([`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js),
|
||||
`liveParts`, `paintLive`) shows the numbers on a request in flight's row
|
||||
@@ -1444,6 +1446,42 @@ the request is done. `TestLiveCountsARealStream` and the other tests in
|
||||
[`live_test.go`](../../internal/gateway/live_test.go), and
|
||||
`routing-live-bytes.test.cjs`.
|
||||
|
||||
### A session's output speed
|
||||
|
||||
The Sessions page draws each session's output speed over its last two
|
||||
minutes, the way a token speed chart does
|
||||
([`session_speed.go`](../../internal/gateway/session_speed.go)).
|
||||
`counted()` opens the session's track (`curveMeter.open`, by the
|
||||
request's agent and `sessionOf` id; none without a session) for as long
|
||||
as the request is in flight, and `liveRow.observe` adds the content bytes
|
||||
it counts to it (`curveMeter.add`). A track keeps a ring of 120 seconds:
|
||||
the bytes of each second, and whether anything of the session's was in
|
||||
flight in it. A second with nothing in flight is a gap (`null` on the
|
||||
curve): the agent was running a tool, or waiting. Tokens are the bytes
|
||||
at the rate `liveRates` learned for the provider and model (`rate`);
|
||||
until it has one the curve is in bytes, `rated` is false and every
|
||||
number is 0, never a guess.
|
||||
|
||||
A round is the run of requests with no pause over `curveRound` (2 min)
|
||||
between them; its average (over the seconds it wrote in), peak (of a 3
|
||||
second moving average) and output are kept. A track idle over
|
||||
`curveForget` (10 min) is dropped, and at most `curveMost` (256) are kept.
|
||||
The meter's lock is never held while anything blocks; `add` is a map
|
||||
lookup and an add.
|
||||
|
||||
`GET /api/speeds` (`internal/gui/sessions_manage.go`, not under
|
||||
`/api/sessions`, so a poll never counts as reading the agents' sessions)
|
||||
returns `[]gateway.Speed`, newest first. `/api/sessions/manage` gives each
|
||||
native row its other gateway keys (`keys`, `sessions.GatewayKeys` past the
|
||||
first) so a row finds its speed by any of them. The page
|
||||
([`plugins/sessions/client.js`](../../internal/gui/assets/plugins/sessions/client.js),
|
||||
`speedCell`, `openSpeed`) reads it once a second only while it is shown
|
||||
and the window is in sight, and draws a row's curve and tokens a second
|
||||
now (the round's average once nothing is in flight); a click opens the
|
||||
round's numbers and its gaps. Tests: [`session_speed_test.go`](../../internal/gateway/session_speed_test.go)
|
||||
(`TestSessionCurveFromARealStream`, `TestSessionCurveFromCodexOwnSignIn`)
|
||||
and `sessions-speed.test.cjs`.
|
||||
|
||||
## Turning provider search off
|
||||
|
||||
[Settings](../../internal/settings/settings.go)' `searcher: "off"` disables magpie's provider-assisted search,
|
||||
|
||||
@@ -48,6 +48,8 @@ type inflight struct {
|
||||
unrouted *unroutedHold
|
||||
// tr: the trace its routes are in, for the phase they say (under mu)
|
||||
tr *trace
|
||||
// curves: the speed meter its reply is counted in (under mu)
|
||||
curves *curveMeter
|
||||
// redaction: its maskings, their phase and time (redact_phase.go)
|
||||
redaction redaction
|
||||
// live: its reply counted as it reaches the agent (live.go)
|
||||
|
||||
@@ -85,10 +85,15 @@ func (s *Server) counted(h http.Handler) http.Handler {
|
||||
}
|
||||
s.inFlight.Add(1)
|
||||
r, done := s.active.add(r)
|
||||
shut := func() {}
|
||||
if f := inflightOf(r.Context()); f != nil {
|
||||
f.mu.Lock()
|
||||
f.tr = &s.trace
|
||||
f.curves = &s.curves
|
||||
f.mu.Unlock()
|
||||
// the session's curve counts it in flight, its tool gaps
|
||||
// being the time between
|
||||
shut = s.curves.open(f.agent, f.session)
|
||||
}
|
||||
w, r, unwatch := s.watchUnrouted(w, r, inflightOf(r.Context()))
|
||||
defer func() {
|
||||
@@ -99,6 +104,7 @@ func (s *Server) counted(h http.Handler) http.Handler {
|
||||
defer panic(p)
|
||||
}
|
||||
unwatch()
|
||||
shut()
|
||||
done()
|
||||
s.lastDone.Store(time.Now().UnixNano())
|
||||
if f := inflightOf(r.Context()); f != nil && f.agent == "codex" {
|
||||
@@ -124,6 +130,8 @@ type busyCounters struct {
|
||||
codexDone atomic.Int64 // unix ns
|
||||
// handing back what requests left once it rests (idle_memory.go)
|
||||
idle idleMemory
|
||||
// each session's output speed, for the Sessions page (session_speed.go)
|
||||
curves curveMeter
|
||||
}
|
||||
|
||||
// parked is how many runs wait on their caller's tool results.
|
||||
|
||||
@@ -1078,6 +1078,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
effort := "" // the reasoning Codex asked for, which goes on as it is
|
||||
end := func(status int, msg string, tokens, out int) {}
|
||||
var tools *toolScan // whether the reply calls a tool, for a turn's end
|
||||
var live *liveRow // the reply counted as it reaches Codex (live.go)
|
||||
if rest != "/responses" {
|
||||
// no route of its own (a compaction, a memory): recorded alone
|
||||
noteMasked(r, "chat", maskedHits, sentOf(maskedHits, body), 0, "openai", modelOf(body))
|
||||
@@ -1114,6 +1115,8 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
s.trace.update(tr, func(t *Route) { t.Masked = m })
|
||||
}
|
||||
first.onFirst = s.trace.firstContent(tr)
|
||||
live = liveBegin(inflightOf(r.Context()), model, provider.Responses)
|
||||
live.routed("openai", model)
|
||||
promptRead := s.inspectPrompt(tr, provider.Responses, body, body, sentWhole)
|
||||
end = func(status int, msg string, tokens, out int) {
|
||||
ms := time.Since(start).Milliseconds()
|
||||
@@ -1526,6 +1529,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
}
|
||||
m, werr := out.Write(buf[:n])
|
||||
passed += int64(m)
|
||||
live.observe(buf[:m])
|
||||
if werr != nil {
|
||||
writeErr = werr
|
||||
break
|
||||
@@ -1627,6 +1631,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
if line := codexEndedEarly(res, sniff, call.Model, callerOf(r).agent, began, passed, readErr, writeErr, r.Context()); line != "" {
|
||||
log.Print(line)
|
||||
}
|
||||
live.finish(call.Status >= 400, uu.Output)
|
||||
end(call.Status, call.Error, uu.Input+uu.Output+uu.CacheRead+uu.CacheWrite, uu.Output)
|
||||
call.Route = tr.ID
|
||||
call.Masked = s.trace.maskedOf(tr)
|
||||
|
||||
@@ -33,6 +33,8 @@ type liveRow struct {
|
||||
f *inflight
|
||||
// tr: f's trace, nil when its routes are in none
|
||||
tr *trace
|
||||
// curves: f's session speed meter, nil when it has none
|
||||
curves *curveMeter
|
||||
}
|
||||
|
||||
// liveBegin starts counting f's reply, from is the agent's protocol, which
|
||||
@@ -43,9 +45,9 @@ func liveBegin(f *inflight, model string, from provider.Protocol) *liveRow {
|
||||
return nil
|
||||
}
|
||||
f.mu.Lock()
|
||||
tr := f.tr
|
||||
tr, curves := f.tr, f.curves
|
||||
f.mu.Unlock()
|
||||
l := &liveRow{f: f, tr: tr, model: model, counter: liveContentCounter{proto: from}}
|
||||
l := &liveRow{f: f, tr: tr, curves: curves, model: model, counter: liveContentCounter{proto: from}}
|
||||
f.live.Store(l)
|
||||
return l
|
||||
}
|
||||
@@ -68,10 +70,12 @@ func (l *liveRow) observe(p []byte) {
|
||||
if !commentOnly(p) {
|
||||
l.contentAt = time.Now().UnixMilli()
|
||||
}
|
||||
was := l.counter.total
|
||||
l.counter.add(p)
|
||||
bytes, contentAt, content := l.bytes, l.contentAt, l.counter.total
|
||||
provider, model := l.provider, l.model
|
||||
l.mu.Unlock()
|
||||
l.curves.add(l.f.agent, l.f.session, provider, model, content-was)
|
||||
l.tell(bytes, contentAt, provider, model, content)
|
||||
}
|
||||
|
||||
|
||||
@@ -89,3 +89,18 @@ func resetRates() {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// curveMeter keeps each session's output speed, a second at a time, for
|
||||
// the Sessions page's curve: how many tokens a second the model wrote to
|
||||
// the agent over the last curveSpan seconds, and the seconds nothing of
|
||||
// the session's was in flight, when the agent ran a tool or waited on
|
||||
// its user. It counts what liveRow counts, a reply's content as it
|
||||
// reaches the agent, and reads it as tokens at the rate liveRates learned
|
||||
// for the model that wrote it. A session whose model has no rate yet has
|
||||
// the curve's shape and no numbers.
|
||||
//
|
||||
// It is kept in memory only. A session is dropped curveForget after its
|
||||
// last request ended, and a pause longer than curveRound with nothing in
|
||||
// flight starts a new round, whose average, peak and output are counted
|
||||
// again from 0.
|
||||
//
|
||||
// add runs on every write of a stream, a few array writes under a lock
|
||||
// nothing blocks under.
|
||||
const (
|
||||
curveSpan = 120 // seconds of curve kept
|
||||
curveForget = 10 * time.Minute
|
||||
curveRound = 2 * time.Minute
|
||||
curveMost = 256 // sessions kept, the least recently heard dropped
|
||||
// curveSmooth: seconds a peak and the current speed are averaged over,
|
||||
// as bytes come in network-sized bursts
|
||||
curveSmooth = 3
|
||||
)
|
||||
|
||||
type curveKey struct{ agent, session string }
|
||||
|
||||
type curveTrack struct {
|
||||
// bytes and live: the content bytes of each second, and whether
|
||||
// anything of the session's was in flight in it, at sec % curveSpan
|
||||
bytes [curveSpan]int64
|
||||
live [curveSpan]bool
|
||||
// at: the latest second the ring holds; heard: when the session last
|
||||
// had something in flight (unix s), for curveForget and curveRound
|
||||
at, heard int64
|
||||
open int
|
||||
// provider and model: the last pair that wrote, whose rate reads the
|
||||
// bytes as tokens
|
||||
provider, model string
|
||||
// the round: its content bytes, the seconds it wrote in, its best
|
||||
// smoothed second, and when it began (unix s)
|
||||
roundBytes, roundSecs, roundPeak, roundAt int64
|
||||
}
|
||||
|
||||
type curveMeter struct {
|
||||
mu sync.Mutex
|
||||
m map[curveKey]*curveTrack
|
||||
// now is the clock, time.Now outside tests
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func (m *curveMeter) clock() int64 {
|
||||
if m.now != nil {
|
||||
return m.now().Unix()
|
||||
}
|
||||
return time.Now().Unix()
|
||||
}
|
||||
|
||||
// track is k's, made when it isn't there yet; under mu.
|
||||
func (m *curveMeter) track(k curveKey, now int64) *curveTrack {
|
||||
if m.m == nil {
|
||||
m.m = map[curveKey]*curveTrack{}
|
||||
}
|
||||
t := m.m[k]
|
||||
if t == nil {
|
||||
if len(m.m) >= curveMost {
|
||||
m.dropOldest()
|
||||
}
|
||||
t = &curveTrack{at: now, heard: now, roundAt: now}
|
||||
m.m[k] = t
|
||||
}
|
||||
t.advance(now)
|
||||
return t
|
||||
}
|
||||
|
||||
func (m *curveMeter) dropOldest() {
|
||||
var oldest curveKey
|
||||
at := int64(math.MaxInt64)
|
||||
for k, t := range m.m {
|
||||
if t.open == 0 && t.heard < at {
|
||||
oldest, at = k, t.heard
|
||||
}
|
||||
}
|
||||
if at != math.MaxInt64 {
|
||||
delete(m.m, oldest)
|
||||
}
|
||||
}
|
||||
|
||||
// advance moves the ring on to now: each second after the last it holds
|
||||
// is empty, live if something was in flight all along. A pause longer
|
||||
// than curveRound with nothing in flight begins a new round.
|
||||
func (t *curveTrack) advance(now int64) {
|
||||
if now <= t.at {
|
||||
return
|
||||
}
|
||||
if t.open == 0 && now-t.heard > int64(curveRound/time.Second) {
|
||||
t.roundBytes, t.roundSecs, t.roundPeak, t.roundAt = 0, 0, 0, now
|
||||
}
|
||||
// the last second held is whole now, and so are the few after it
|
||||
// whose smoothed speed still reaches back to it: each may be a peak
|
||||
t.peak(t.at)
|
||||
last := t.at
|
||||
for s := max(t.at+1, now-curveSpan+1); s <= now; s++ {
|
||||
i := s % curveSpan
|
||||
t.bytes[i], t.live[i] = 0, t.open > 0
|
||||
}
|
||||
t.at = now
|
||||
for s := last + 1; s < now && s < last+curveSmooth; s++ {
|
||||
t.peak(s)
|
||||
}
|
||||
}
|
||||
|
||||
// peak counts the whole second s toward the round's peak.
|
||||
func (t *curveTrack) peak(s int64) {
|
||||
if s < t.roundAt {
|
||||
return
|
||||
}
|
||||
if v := t.smoothed(s); v > t.roundPeak {
|
||||
t.roundPeak = v
|
||||
}
|
||||
}
|
||||
|
||||
// smoothed is the bytes a second over the curveSmooth seconds up to s,
|
||||
// the seconds nothing was in flight left out: 0 when none was.
|
||||
func (t *curveTrack) smoothed(s int64) int64 {
|
||||
var sum, n int64
|
||||
for d := int64(0); d < curveSmooth; d++ {
|
||||
at := s - d
|
||||
if at <= t.at-curveSpan || at < t.roundAt {
|
||||
break
|
||||
}
|
||||
if i := at % curveSpan; t.live[i] {
|
||||
sum += t.bytes[i]
|
||||
n++
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
return sum / n
|
||||
}
|
||||
|
||||
// open counts a request of the session's in flight until the func it
|
||||
// answers is called. A request with no session is not a session's.
|
||||
func (m *curveMeter) open(agent, session string) func() {
|
||||
if m == nil || session == "" {
|
||||
return func() {}
|
||||
}
|
||||
k := curveKey{agent, session}
|
||||
m.mu.Lock()
|
||||
now := m.clock()
|
||||
t := m.track(k, now)
|
||||
t.open++
|
||||
t.heard = now
|
||||
t.live[now%curveSpan] = true
|
||||
m.mu.Unlock()
|
||||
return func() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
now := m.clock()
|
||||
t := m.m[k]
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
t.advance(now)
|
||||
t.open = max(t.open-1, 0)
|
||||
t.heard = now
|
||||
}
|
||||
}
|
||||
|
||||
// add counts n content bytes written now by provider's model.
|
||||
func (m *curveMeter) add(agent, session, provider, model string, n int64) {
|
||||
if m == nil || session == "" || n <= 0 {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
now := m.clock()
|
||||
t := m.track(curveKey{agent, session}, now)
|
||||
i := now % curveSpan
|
||||
if t.bytes[i] == 0 {
|
||||
t.roundSecs++
|
||||
}
|
||||
t.bytes[i] += n
|
||||
t.live[i] = true
|
||||
t.roundBytes += n
|
||||
if provider != "" && model != "" {
|
||||
t.provider, t.model = provider, model
|
||||
}
|
||||
}
|
||||
|
||||
// Speed is a session's output speed for the Sessions page. Tokens a
|
||||
// second are estimates (liveRates); Rated is false while the session's
|
||||
// model has no rate yet, and then every number is 0 and Curve holds
|
||||
// content bytes a second instead, for its shape alone.
|
||||
type Speed struct {
|
||||
Agent string `json:"agent"`
|
||||
Session string `json:"session"`
|
||||
// Live: a request of the session's is in flight now
|
||||
Live bool `json:"live"`
|
||||
Rated bool `json:"rated"`
|
||||
// Now: tokens a second over the last few whole seconds, 0 when
|
||||
// nothing is in flight
|
||||
Now float64 `json:"now"`
|
||||
// Avg, Peak and Output are the round's: tokens a second over the
|
||||
// seconds it wrote in, its best few seconds, and its output tokens
|
||||
Avg float64 `json:"avg"`
|
||||
Peak float64 `json:"peak"`
|
||||
Output int64 `json:"output"`
|
||||
// Curve: the last curveSpan whole seconds, oldest first, nil for a
|
||||
// second with nothing of the session's in flight
|
||||
Curve []*float64 `json:"curve"`
|
||||
// Idle: seconds since its last request ended, when nothing is in
|
||||
// flight
|
||||
Idle int64 `json:"idle,omitempty"`
|
||||
}
|
||||
|
||||
// Speeds are the sessions heard in the last curveForget, the most
|
||||
// recently heard first.
|
||||
func (s *Server) Speeds() []Speed { return s.curves.speeds() }
|
||||
|
||||
func (m *curveMeter) speeds() []Speed {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
m.mu.Lock()
|
||||
now := m.clock()
|
||||
type got struct {
|
||||
k curveKey
|
||||
t curveTrack
|
||||
heard int64
|
||||
}
|
||||
var gs []got
|
||||
for k, t := range m.m {
|
||||
t.advance(now)
|
||||
if t.open == 0 && now-t.heard > int64(curveForget/time.Second) {
|
||||
delete(m.m, k)
|
||||
continue
|
||||
}
|
||||
gs = append(gs, got{k, *t, t.heard})
|
||||
}
|
||||
m.mu.Unlock()
|
||||
sort.Slice(gs, func(i, j int) bool {
|
||||
if gs[i].heard != gs[j].heard {
|
||||
return gs[i].heard > gs[j].heard
|
||||
}
|
||||
return gs[i].k.agent+gs[i].k.session < gs[j].k.agent+gs[j].k.session
|
||||
})
|
||||
out := make([]Speed, 0, len(gs))
|
||||
for _, g := range gs {
|
||||
out = append(out, g.t.speed(g.k, now))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// speed reads t at now, the second now itself not whole yet.
|
||||
func (t *curveTrack) speed(k curveKey, now int64) Speed {
|
||||
sp := Speed{Agent: k.agent, Session: k.session, Live: t.open > 0}
|
||||
rate, rated := liveRates.rate(t.provider, t.model)
|
||||
sp.Rated = rated
|
||||
if !rated {
|
||||
rate = 1
|
||||
}
|
||||
tok := func(b float64) float64 { return math.Round(b*rate*10) / 10 }
|
||||
sp.Curve = make([]*float64, curveSpan)
|
||||
for d := int64(0); d < curveSpan; d++ {
|
||||
s := now - curveSpan + d
|
||||
if s <= t.at-curveSpan || s < 0 {
|
||||
continue
|
||||
}
|
||||
if i := s % curveSpan; t.live[i] {
|
||||
v := tok(float64(t.bytes[i]))
|
||||
sp.Curve[d] = &v
|
||||
}
|
||||
}
|
||||
if !rated {
|
||||
return sp
|
||||
}
|
||||
if sp.Live {
|
||||
sp.Now = tok(float64(t.smoothed(now - 1)))
|
||||
} else {
|
||||
sp.Idle = now - t.heard
|
||||
}
|
||||
if t.roundSecs > 0 {
|
||||
sp.Avg = tok(float64(t.roundBytes) / float64(t.roundSecs))
|
||||
}
|
||||
sp.Peak = tok(float64(max(t.roundPeak, t.smoothed(now-1))))
|
||||
sp.Output = int64(math.Round(float64(t.roundBytes) * rate))
|
||||
return sp
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// curveClock is a meter's clock the test moves by hand.
|
||||
type curveClock struct{ at atomic.Int64 }
|
||||
|
||||
func (c *curveClock) now() time.Time { return time.Unix(c.at.Load(), 0) }
|
||||
func (c *curveClock) tick(d int64) { c.at.Add(d) }
|
||||
|
||||
func meterAt(start int64) (*curveMeter, *curveClock) {
|
||||
c := &curveClock{}
|
||||
c.at.Store(start)
|
||||
return &curveMeter{now: c.now}, c
|
||||
}
|
||||
|
||||
// learnRate teaches liveRates tokens-per-byte for a pair, past liveRateMin.
|
||||
func learnRate(provider, model string, bytes int64, output int) {
|
||||
for range liveRateMin {
|
||||
liveRates.learn(provider, model, bytes, output)
|
||||
}
|
||||
}
|
||||
|
||||
func onlySpeed(t *testing.T, m *curveMeter) Speed {
|
||||
t.Helper()
|
||||
sp := m.speeds()
|
||||
if len(sp) != 1 {
|
||||
t.Fatalf("speeds %+v, want one session", sp)
|
||||
}
|
||||
return sp[0]
|
||||
}
|
||||
|
||||
// The curve is tokens a second over whole seconds, a gap where nothing of
|
||||
// the session's was in flight (a tool ran), and the round's average over
|
||||
// the seconds it wrote in, its peak and its output.
|
||||
func TestSessionCurveCountsSecondsAndGaps(t *testing.T) {
|
||||
freshRates(t)
|
||||
learnRate("p", "m", 400, 100) // a byte is a quarter token
|
||||
m, c := meterAt(1_000_000)
|
||||
|
||||
shut := m.open("claude", "s1")
|
||||
for range 5 {
|
||||
m.add("claude", "s1", "p", "m", 400)
|
||||
c.tick(1)
|
||||
}
|
||||
shut()
|
||||
c.tick(10) // the agent runs a tool
|
||||
shut = m.open("claude", "s1")
|
||||
for range 3 {
|
||||
m.add("claude", "s1", "p", "m", 800)
|
||||
c.tick(1)
|
||||
}
|
||||
|
||||
sp := onlySpeed(t, m)
|
||||
if !sp.Live || !sp.Rated {
|
||||
t.Fatalf("live %v rated %v", sp.Live, sp.Rated)
|
||||
}
|
||||
if len(sp.Curve) != curveSpan {
|
||||
t.Fatalf("curve has %d seconds", len(sp.Curve))
|
||||
}
|
||||
tail := sp.Curve[curveSpan-19:]
|
||||
var got []string
|
||||
for _, v := range tail {
|
||||
if v == nil {
|
||||
got = append(got, "-")
|
||||
} else {
|
||||
got = append(got, strconv.FormatFloat(*v, 'f', -1, 64))
|
||||
}
|
||||
}
|
||||
// 5 seconds at 100, the second the first request ended in (live, 0),
|
||||
// 9 seconds of nothing in flight, then 3 at 200
|
||||
want := "100 100 100 100 100 0 - - - - - - - - - 200 200 200"
|
||||
if g := strings.Join(got[1:], " "); g != want {
|
||||
t.Fatalf("curve tail\n got %s\nwant %s", g, want)
|
||||
}
|
||||
if sp.Now != 200 {
|
||||
t.Errorf("now %v, want 200", sp.Now)
|
||||
}
|
||||
if want := float64(5*400+3*800) / 8 / 4; sp.Avg != want {
|
||||
t.Errorf("avg %v, want %v", sp.Avg, want)
|
||||
}
|
||||
if sp.Peak != 200 {
|
||||
t.Errorf("peak %v, want 200", sp.Peak)
|
||||
}
|
||||
if sp.Output != 1100 {
|
||||
t.Errorf("output %v, want 1100", sp.Output)
|
||||
}
|
||||
|
||||
shut()
|
||||
c.tick(4)
|
||||
sp = onlySpeed(t, m)
|
||||
if sp.Live || sp.Now != 0 || sp.Idle != 4 {
|
||||
t.Fatalf("after the turn: live %v now %v idle %v", sp.Live, sp.Now, sp.Idle)
|
||||
}
|
||||
}
|
||||
|
||||
// roundBytes is the content bytes a session's round has so far.
|
||||
func (m *curveMeter) roundBytes(session string) int64 {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for k, t := range m.m {
|
||||
if k.session == session {
|
||||
return t.roundBytes
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// A model with no rate yet has the curve's shape in bytes and no numbers:
|
||||
// a guess would be a wrong number on the page.
|
||||
func TestSessionCurveUnratedHasNoNumbers(t *testing.T) {
|
||||
freshRates(t)
|
||||
m, c := meterAt(2_000_000)
|
||||
shut := m.open("codex", "s2")
|
||||
defer shut()
|
||||
m.add("codex", "s2", "openai", "gpt", 300)
|
||||
c.tick(1)
|
||||
sp := onlySpeed(t, m)
|
||||
if sp.Rated || sp.Now != 0 || sp.Avg != 0 || sp.Peak != 0 || sp.Output != 0 {
|
||||
t.Fatalf("unrated speed has numbers: %+v", sp)
|
||||
}
|
||||
if v := sp.Curve[curveSpan-1]; v == nil || *v != 300 {
|
||||
t.Fatalf("unrated curve's last second %v, want its 300 bytes", v)
|
||||
}
|
||||
}
|
||||
|
||||
// A pause past curveRound with nothing in flight starts a new round; one
|
||||
// past curveForget drops the session. A request with no session has no
|
||||
// curve.
|
||||
func TestSessionCurveRoundsAndForgets(t *testing.T) {
|
||||
freshRates(t)
|
||||
learnRate("p", "m", 100, 100)
|
||||
m, c := meterAt(3_000_000)
|
||||
shut := m.open("a", "s")
|
||||
m.add("a", "s", "p", "m", 1000)
|
||||
c.tick(1)
|
||||
shut()
|
||||
c.tick(int64(curveRound/time.Second) + 1)
|
||||
shut = m.open("a", "s")
|
||||
m.add("a", "s", "p", "m", 10)
|
||||
c.tick(1)
|
||||
shut()
|
||||
sp := onlySpeed(t, m)
|
||||
if sp.Output != 10 || sp.Peak != 10 || sp.Avg != 10 {
|
||||
t.Fatalf("new round kept the old one's numbers: %+v", sp)
|
||||
}
|
||||
m.open("a", "")()
|
||||
m.add("a", "", "p", "m", 10)
|
||||
if len(m.speeds()) != 1 {
|
||||
t.Fatal("a request with no session got a curve")
|
||||
}
|
||||
c.tick(int64(curveForget/time.Second) + 1)
|
||||
if sp := m.speeds(); len(sp) != 0 {
|
||||
t.Fatalf("a session quiet past curveForget is kept: %+v", sp)
|
||||
}
|
||||
}
|
||||
|
||||
// A long tool run moves the ring on without going through every second
|
||||
// in between, and leaves it all gap.
|
||||
func TestSessionCurveLongGap(t *testing.T) {
|
||||
freshRates(t)
|
||||
learnRate("p", "m", 100, 100)
|
||||
m, c := meterAt(4_000_000)
|
||||
shut := m.open("a", "s")
|
||||
m.add("a", "s", "p", "m", 50)
|
||||
shut()
|
||||
c.tick(int64(curveRound/time.Second) - 1)
|
||||
m.open("a", "s")
|
||||
c.tick(1)
|
||||
sp := onlySpeed(t, m)
|
||||
for i, v := range sp.Curve[:curveSpan-1] {
|
||||
if v != nil {
|
||||
t.Fatalf("second %d of a long gap is %v, want a gap", i, *v)
|
||||
}
|
||||
}
|
||||
if sp.Peak != 50 || sp.Output != 50 {
|
||||
t.Fatalf("the round before the gap is lost: %+v", sp)
|
||||
}
|
||||
}
|
||||
|
||||
// Through the whole gateway: a session's streamed reply is on its curve,
|
||||
// in flight while it streams and not after.
|
||||
func TestSessionCurveFromARealStream(t *testing.T) {
|
||||
freshRates(t)
|
||||
learnRate("live", "m", 6, 6) // a content byte is a token
|
||||
release := make(chan struct{})
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("content-type", "text/event-stream")
|
||||
io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"content\":\"abcd\"}}]}\n\n")
|
||||
w.(http.Flusher).Flush()
|
||||
<-release
|
||||
io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"content\":\"ef\"}}]}\n\n")
|
||||
io.WriteString(w, "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":6,\"total_tokens\":9}}\n\ndata: [DONE]\n\n")
|
||||
}))
|
||||
defer up.Close()
|
||||
var once atomic.Bool
|
||||
free := func() {
|
||||
if once.CompareAndSwap(false, true) {
|
||||
close(release)
|
||||
}
|
||||
}
|
||||
defer free()
|
||||
if err := provider.Save(provider.Provider{ID: "live", Name: "Live", Chat: up.URL + "/v1", Key: "k", Models: []string{"m"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
clock := &curveClock{}
|
||||
clock.at.Store(5_000_000)
|
||||
s.curves.now = clock.now
|
||||
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"live/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
|
||||
req.Header.Set("content-type", "application/json")
|
||||
req.Header.Set(SessionHeader, "sess-e2e")
|
||||
rec := httptest.NewRecorder()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
}()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
if sp := s.Speeds(); len(sp) == 1 && sp[0].Live {
|
||||
if s.curves.roundBytes("sess-e2e") == 4 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
free()
|
||||
t.Fatalf("the first content never reached the session's curve: %+v", s.Speeds())
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if sp := s.Speeds()[0]; sp.Session != "sess-e2e" || !sp.Live {
|
||||
t.Fatalf("mid-stream %+v", sp)
|
||||
}
|
||||
free()
|
||||
<-done
|
||||
clock.tick(1)
|
||||
sp := s.Speeds()
|
||||
if len(sp) != 1 || sp[0].Live || !sp[0].Rated || sp[0].Output != 6 {
|
||||
t.Fatalf("after the reply: %+v", sp)
|
||||
}
|
||||
if v := sp[0].Curve[curveSpan-1]; v == nil || *v != 6 {
|
||||
t.Fatalf("the reply's second on the curve is %v, want 6 tokens", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Codex's own sign-in is served apart from serve: its reply is on the
|
||||
// session's curve too.
|
||||
func TestSessionCurveFromCodexOwnSignIn(t *testing.T) {
|
||||
setup(t, provider.Chat, &fake{t: t})
|
||||
freshRates(t)
|
||||
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(
|
||||
`data: {"type":"response.output_text.delta","delta":"hello"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9,"output_tokens":5}}}`))
|
||||
})
|
||||
s := New()
|
||||
clock := &curveClock{}
|
||||
clock.at.Store(6_000_000)
|
||||
s.curves.now = clock.now
|
||||
for range liveRateMin + 1 {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`))
|
||||
req.Header.Set("Authorization", "Bearer chatgpt-token")
|
||||
req.Header.Set("session_id", "codex-sess")
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
clock.tick(1)
|
||||
sp := s.Speeds()
|
||||
if len(sp) != 1 || sp[0].Session != "codex-sess" || !sp[0].Rated {
|
||||
t.Fatalf("speeds %+v", sp)
|
||||
}
|
||||
// four replies of five content bytes, each five tokens
|
||||
if sp[0].Output != 20 {
|
||||
t.Fatalf("output %d, want 20", sp[0].Output)
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,15 @@ magpie.plugin("sessions", (ctx) => {
|
||||
const MAX_DEPTH = 8;
|
||||
let loading = 0;
|
||||
let fitObserver = null;
|
||||
// Each session's output speed as the gateway counts it (/api/speeds,
|
||||
// gateway/session_speed.go), by "agent|session", read once a second
|
||||
// while the page is in sight and drawn on its rows: a curve of the last
|
||||
// two minutes, tokens a second now, and the round's numbers in a
|
||||
// popover. A session the gateway hasn't served lately has none.
|
||||
let speeds = new Map();
|
||||
let speedT = 0;
|
||||
let speedBusy = false;
|
||||
let speedPop = null; // { anchor, draw } of the popover open
|
||||
let focus = null; // { agent, id, until }: a session to bring into sight once drawn
|
||||
let recordingBusy = false;
|
||||
// the agents picked in the consent (RustCats on X), by id, and whether
|
||||
@@ -171,7 +180,7 @@ magpie.plugin("sessions", (ctx) => {
|
||||
if (n !== loading) return;
|
||||
failed = e.message;
|
||||
}
|
||||
if (view === "sessions") draw();
|
||||
if (view === "sessions") { draw(); speedsOn(); }
|
||||
if (n === loading) fillSoon();
|
||||
}
|
||||
|
||||
@@ -521,7 +530,7 @@ magpie.plugin("sessions", (ctx) => {
|
||||
tr.setAttribute("aria-pressed", String(trashOn));
|
||||
tr.append(svg(TRASH, 13, 1.4), el("span", "", t("Trash")));
|
||||
if (data?.trash.length) tr.append(el("em", "", String(data.trash.length)));
|
||||
tr.onclick = () => { trashOn = !trashOn; selecting = false; picked.clear(); draw(); };
|
||||
tr.onclick = () => { trashOn = !trashOn; selecting = false; picked.clear(); draw(); speedsOn(); };
|
||||
// which agents' history is read is Settings › Privacy's (the scattered
|
||||
// settings audit after netube99 on X); gateway mode reads none there
|
||||
const go = el("button", "text sm-toset");
|
||||
@@ -1060,6 +1069,7 @@ magpie.plugin("sessions", (ctx) => {
|
||||
if (hit) who.append(hitLine(hit));
|
||||
// what it spent, as the Usage page's list shows it
|
||||
r.append(who, ...sessSpent(s));
|
||||
r.append(speedCell(s));
|
||||
const lane = lanes();
|
||||
if (s.resume) {
|
||||
const res = el("button", "sess-resume", t("Resume"));
|
||||
@@ -1654,6 +1664,154 @@ magpie.plugin("sessions", (ctx) => {
|
||||
return out;
|
||||
}
|
||||
|
||||
// speedOf is the speed of a row's session: of any of the keys the
|
||||
// gateway may know it by (s.keys, sessions.GatewayKeys), the one in
|
||||
// flight, else the one heard from last
|
||||
function speedOf(s) {
|
||||
let best = null;
|
||||
for (const k of [s.agent + "|" + s.id, ...(s.keys || [])]) {
|
||||
const sp = speeds.get(k);
|
||||
if (sp && (!best || sp.live && !best.live || sp.live === best.live && sp.idle < best.idle)) best = sp;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
const rateText = (v) => String(Math.round(v));
|
||||
// rateParts is "{n} tok/s" in the reader's language, in the parts around n
|
||||
const rateParts = () => t("{n} tok/s", { n: "\u0000" }).split("\u0000");
|
||||
const NS = "http://www.w3.org/2000/svg";
|
||||
function sv(tag, attrs) {
|
||||
const n = document.createElementNS(NS, tag);
|
||||
for (const k in attrs) n.setAttribute(k, attrs[k]);
|
||||
return n;
|
||||
}
|
||||
// curveShape lays a curve (a value a second, null where nothing of the
|
||||
// session's was in flight) on a 300-wide box h high: the runs of seconds
|
||||
// with a value, the gaps between two runs, and where the last value is
|
||||
function curveShape(curve, h) {
|
||||
const vals = curve || [], n = vals.length;
|
||||
const max = Math.max(1, ...vals.filter((v) => v != null));
|
||||
const x = (i) => n > 1 ? i * 300 / (n - 1) : 300;
|
||||
const y = (v) => +(h - 2 - v / max * (h - 8)).toFixed(1);
|
||||
const runs = [], gaps = [];
|
||||
let run = null, last = -1;
|
||||
vals.forEach((v, i) => {
|
||||
if (v == null) { if (run) runs.push(run); run = null; return; }
|
||||
if (!run && last >= 0 && i - last > 1) gaps.push({ from: x(last), to: x(i), secs: i - last - 1 });
|
||||
(run ||= []).push([+x(i).toFixed(1), y(v)]);
|
||||
last = i;
|
||||
});
|
||||
if (run) runs.push(run);
|
||||
// a lone second is a short stroke, not nothing
|
||||
for (const r of runs) if (r.length === 1) r.push([Math.min(300, r[0][0] + 2.5), r[0][1]]);
|
||||
return { runs, gaps, end: last === n - 1 && last >= 0 ? { x: x(last), y: y(vals[last]) } : null };
|
||||
}
|
||||
// curveSvg draws it: the line, a dashed baseline over each gap, and
|
||||
// under the line a light fill in the popover
|
||||
function curveSvg(curve, w, h, fill) {
|
||||
const shape = curveShape(curve, h);
|
||||
const g = sv("svg", { width: w, height: h, viewBox: `0 0 300 ${h}`, preserveAspectRatio: "none", "aria-hidden": "true", class: "sm-curve" });
|
||||
const pts = (r) => r.map((p) => p.join(",")).join(" ");
|
||||
for (const r of shape.runs) {
|
||||
if (fill) g.append(sv("path", { class: "sm-curve-fill", d: `M${r[0][0]},${h} L${pts(r).replaceAll(" ", " L")} L${r[r.length - 1][0]},${h} Z` }));
|
||||
g.append(sv("polyline", { class: "sm-curve-line", points: pts(r), "vector-effect": "non-scaling-stroke" }));
|
||||
}
|
||||
for (const gap of shape.gaps) g.append(sv("line", { class: "sm-curve-gap", x1: gap.from, x2: gap.to, y1: h - 1, y2: h - 1, "vector-effect": "non-scaling-stroke" }));
|
||||
return { svg: g, shape };
|
||||
}
|
||||
// speedCell is a row's speed: its curve and tokens a second now, or the
|
||||
// round's average once nothing is in flight; a button that opens the
|
||||
// round's numbers. Hidden while the session has no speed.
|
||||
function speedCell(s) {
|
||||
const b = el("button", "sm-speed");
|
||||
b.type = "button";
|
||||
b.sess = s;
|
||||
b.setAttribute("aria-haspopup", "dialog");
|
||||
b.setAttribute("aria-expanded", "false");
|
||||
b.onclick = (e) => { e.stopPropagation(); openSpeed(b); };
|
||||
fillSpeed(b);
|
||||
return b;
|
||||
}
|
||||
function fillSpeed(b) {
|
||||
const sp = speedOf(b.sess);
|
||||
const drawn = sp && (sp.live || sp.rated && sp.avg > 0 || sp.curve?.some((v) => v != null));
|
||||
b.hidden = !drawn;
|
||||
if (!drawn) { b.replaceChildren(); return; }
|
||||
const parts = [];
|
||||
if (sp.curve?.some((v) => v != null)) parts.push(curveSvg(sp.curve, 88, 24, false).svg);
|
||||
const v = el("span", "sm-speed-val" + (sp.live ? " live" : ""));
|
||||
if (!sp.rated) v.textContent = "—";
|
||||
else if (sp.live) { const [pre, post] = rateParts(); v.append(pre, el("b", "", rateText(sp.now)), el("small", "", post)); }
|
||||
else v.textContent = t("Avg {n} tok/s", { n: rateText(sp.avg) });
|
||||
parts.push(v);
|
||||
b.replaceChildren(...parts);
|
||||
b.setAttribute("aria-label", t("Output speed") + ": " + v.textContent);
|
||||
}
|
||||
function speedPopBody(sp) {
|
||||
const head = el("div", "sm-sp-head");
|
||||
const [pre, post] = rateParts();
|
||||
head.append(pre, el("span", "sm-sp-big", sp.rated ? rateText(sp.live ? sp.now : sp.avg) : "—"), el("span", "sm-sp-unit", post.trim()));
|
||||
const chart = el("div", "sm-sp-chart");
|
||||
const { svg: g, shape } = curveSvg(sp.curve, 308, 72, true);
|
||||
chart.append(g);
|
||||
// a gap inside the round is the agent at work between two requests
|
||||
for (const gap of shape.gaps) {
|
||||
if (gap.secs < 3 || gap.to - gap.from < 40) continue;
|
||||
const l = el("span", "sm-sp-gap", t("Tool {n}s", { n: gap.secs }));
|
||||
l.style.left = `calc(${gap.from / 3}% + 4px)`;
|
||||
chart.append(l);
|
||||
}
|
||||
if (sp.live && shape.end) {
|
||||
const d = el("span", "sm-sp-dot");
|
||||
d.style.top = (shape.end.y - 3.5) + "px";
|
||||
chart.append(d);
|
||||
}
|
||||
const stats = el("div", "sm-sp-stats");
|
||||
const rate = (n) => sp.rated ? t("{n} tok/s", { n: rateText(n) }) : "—";
|
||||
for (const [k, v] of [["Round average", rate(sp.avg)], ["Fastest second", rate(sp.peak)], ["Out so far", sp.rated ? t("{n} tokens", { n: fmtN(sp.output) }) : "—"]]) {
|
||||
const c = el("div", "");
|
||||
c.append(el("span", "sm-sp-k", t(k)), el("span", "sm-sp-v", v));
|
||||
stats.append(c);
|
||||
}
|
||||
return [head, chart, stats];
|
||||
}
|
||||
function openSpeed(b) {
|
||||
if (speedPop?.anchor === b) return closeProtoMenu();
|
||||
closeProtoMenu();
|
||||
const box = el("div", "pop sm-speed-pop");
|
||||
box.setAttribute("role", "dialog");
|
||||
box.setAttribute("aria-label", t("Output speed"));
|
||||
const draw = () => {
|
||||
const sp = speedOf(b.sess);
|
||||
if (!sp || !b.isConnected) return closeProtoMenu();
|
||||
box.replaceChildren(...speedPopBody(sp));
|
||||
};
|
||||
draw();
|
||||
document.body.append(box);
|
||||
placeMenu(box, b, "right");
|
||||
b.classList.add("open");
|
||||
b.setAttribute("aria-expanded", "true");
|
||||
holdMenu(box, b, () => {}, (e) => { if (scrollCloses(box, e)) closeProtoMenu(); }, () => { speedPop = null; });
|
||||
speedPop = { anchor: b, draw };
|
||||
}
|
||||
const speedsShown = () => view === "sessions" && !document.hidden && !trashOn;
|
||||
async function speedTick() {
|
||||
if (!speedsShown()) { clearInterval(speedT); speedT = 0; return; }
|
||||
if (speedBusy) return;
|
||||
speedBusy = true;
|
||||
try {
|
||||
const list = await api("speeds");
|
||||
speeds = new Map((Array.isArray(list) ? list : []).map((sp) => [sp.agent + "|" + sp.session, sp]));
|
||||
} catch { return; } finally { speedBusy = false; }
|
||||
page?.querySelectorAll(".sm-speed").forEach(fillSpeed);
|
||||
speedPop?.draw();
|
||||
}
|
||||
function speedsOn() {
|
||||
if (speedT || !speedsShown()) return;
|
||||
speedT = setInterval(speedTick, 1000);
|
||||
speedTick();
|
||||
}
|
||||
document.addEventListener("visibilitychange", speedsOn);
|
||||
|
||||
ctx.slots.add("page", {
|
||||
key: "sessions",
|
||||
title: "Sessions",
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
// kernel adds them to i18n.js's (magpie.strings).
|
||||
magpie.strings({
|
||||
zh: {
|
||||
"Avg {n} tok/s": "平均 {n} token/秒",
|
||||
"Tool {n}s": "工具 {n} 秒",
|
||||
"Round average": "本轮平均",
|
||||
"Fastest second": "峰值",
|
||||
"Out so far": "已输出",
|
||||
"Show your agents' sessions?": "显示智能体的会话吗?",
|
||||
"magpie reads no agent's session history until you allow it. Pick the agents whose sessions this page may show; what magpie's gateway served is counted either way. You can change this in Settings › Privacy.": "在你允许之前,magpie 不读取任何智能体的会话历史。选择本页可以显示哪些智能体的会话;magpie 网关处理过的请求照常计入。之后可在 设置 › 隐私 中更改。",
|
||||
"No agent's sessions were found on this computer yet.": "这台电脑上还没有找到任何智能体的会话。",
|
||||
@@ -92,6 +97,11 @@ magpie.strings({
|
||||
"Searched what was said in the latest {n} of {total} sessions.": "已搜索最近 {n} 个会话的对话内容(共 {total} 个)。",
|
||||
},
|
||||
"zh-TW": {
|
||||
"Avg {n} tok/s": "平均 {n} token/秒",
|
||||
"Tool {n}s": "工具 {n} 秒",
|
||||
"Round average": "本輪平均",
|
||||
"Fastest second": "峰值",
|
||||
"Out so far": "已輸出",
|
||||
"Show your agents' sessions?": "顯示智慧體的會話嗎?",
|
||||
"magpie reads no agent's session history until you allow it. Pick the agents whose sessions this page may show; what magpie's gateway served is counted either way. You can change this in Settings › Privacy.": "在你允許之前,magpie 不讀取任何智慧體的會話歷史。選擇本頁可以顯示哪些智慧體的會話;magpie 閘道處理過的請求照常計入。之後可在 設定 › 隱私 中變更。",
|
||||
"No agent's sessions were found on this computer yet.": "這台電腦上還沒有找到任何智慧體的會話。",
|
||||
@@ -182,6 +192,11 @@ magpie.strings({
|
||||
"Searched what was said in the latest {n} of {total} sessions.": "已搜尋最近 {n} 個會話的對話內容(共 {total} 個)。",
|
||||
},
|
||||
ja: {
|
||||
"Avg {n} tok/s": "平均 {n} トークン/秒",
|
||||
"Tool {n}s": "ツール {n} 秒",
|
||||
"Round average": "このターンの平均",
|
||||
"Fastest second": "ピーク",
|
||||
"Out so far": "出力済み",
|
||||
"Show your agents' sessions?": "エージェントのセッションを表示しますか?",
|
||||
"magpie reads no agent's session history until you allow it. Pick the agents whose sessions this page may show; what magpie's gateway served is counted either way. You can change this in Settings › Privacy.": "許可するまで、magpie はどのエージェントのセッション履歴も読みません。このページに表示してよいエージェントを選んでください。magpie のゲートウェイが処理したリクエストはどちらでも集計されます。あとから 設定 › プライバシー で変更できます。",
|
||||
"No agent's sessions were found on this computer yet.": "このコンピュータにはまだエージェントのセッションが見つかりません。",
|
||||
@@ -272,6 +287,11 @@ magpie.strings({
|
||||
"Searched what was said in the latest {n} of {total} sessions.": "最新 {n} 件の会話の内容を検索しました(全 {total} 件)。",
|
||||
},
|
||||
de: {
|
||||
"Avg {n} tok/s": "Ø {n} Token/s",
|
||||
"Tool {n}s": "Tool {n} s",
|
||||
"Round average": "Ø dieser Runde",
|
||||
"Fastest second": "Spitze",
|
||||
"Out so far": "Ausgegeben",
|
||||
"Show your agents' sessions?": "Sitzungen deiner Agenten anzeigen?",
|
||||
"magpie reads no agent's session history until you allow it. Pick the agents whose sessions this page may show; what magpie's gateway served is counted either way. You can change this in Settings › Privacy.": "magpie liest den Sitzungsverlauf keines Agenten, bis du es erlaubst. Wähle die Agenten, deren Sitzungen diese Seite zeigen darf; was das Gateway von magpie bedient hat, wird so oder so gezählt. Ändern kannst du das unter Einstellungen › Datenschutz.",
|
||||
"No agent's sessions were found on this computer yet.": "Auf diesem Computer wurden noch keine Sitzungen von Agenten gefunden.",
|
||||
|
||||
@@ -181,3 +181,35 @@ body.window .row.sm-sub-row { min-height: 42px; padding-left: calc(14px + var(--
|
||||
.sm-consent-row .lib-switch { flex: none; cursor: pointer; padding: 0; border: 0; }
|
||||
.sm-consent-row .lib-switch:disabled { opacity: .5; cursor: default; }
|
||||
.sm-consent-acts { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; margin-top: 4px; }
|
||||
/* a session's output speed (session_speed.go): its last two minutes and
|
||||
tokens a second now, opening the round's numbers */
|
||||
.row.sm-sess .sm-speed { flex: none; display: inline-flex; align-items: center; gap: 10px; height: 30px; padding: 0 8px; border: 0; border-radius: 7px; background: none; color: var(--muted); font: inherit; font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; transition: background-color .15s ease; }
|
||||
.row.sm-sess .sm-speed[hidden] { display: none; }
|
||||
@media (hover: hover) and (pointer: fine) { .row.sm-sess .sm-speed:hover { background: var(--pill); } }
|
||||
.row.sm-sess .sm-speed.open { background: var(--pill); }
|
||||
.row.sm-sess .sm-speed:active { transform: scale(.97); }
|
||||
.sm-speed .sm-curve { display: block; flex: none; }
|
||||
.sm-speed-val { min-width: 72px; text-align: right; }
|
||||
.sm-speed-val.live { color: var(--fg); }
|
||||
.sm-speed-val b { font-size: 13px; font-weight: 600; }
|
||||
.sm-speed-val small { font-size: 11px; color: var(--muted); }
|
||||
.sm-curve-line { fill: none; stroke: var(--accent); stroke-width: 1.5; stroke-linejoin: round; }
|
||||
.sm-curve-fill { fill: var(--accent); fill-opacity: .08; }
|
||||
.sm-curve-gap { stroke: var(--faint); stroke-width: 1.5; stroke-dasharray: 3 3; }
|
||||
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .sm-curve-fill { fill-opacity: .1; } }
|
||||
:root[data-theme="dark"] .sm-curve-fill { fill-opacity: .1; }
|
||||
/* a narrow list keeps the number and leaves the curve to the popover */
|
||||
@container sm-tree (width < 620px) { .sm-speed .sm-curve { display: none; } .sm-speed-val { min-width: 0; } }
|
||||
.pop.sm-speed-pop { width: min(340px, calc(100vw - 16px)); max-height: none; padding: 14px 16px; gap: 10px; transform-origin: right top; font-variant-numeric: tabular-nums; }
|
||||
.pop.sm-speed-pop.up { transform-origin: right bottom; }
|
||||
.sm-sp-head { display: flex; align-items: baseline; gap: 6px; }
|
||||
.sm-sp-big { font-size: 28px; font-weight: 600; letter-spacing: -.02em; color: var(--fg); }
|
||||
.sm-sp-unit { font-size: 12px; color: var(--muted); }
|
||||
.sm-sp-chart { position: relative; height: 72px; }
|
||||
.sm-sp-chart .sm-curve { width: 100%; }
|
||||
.sm-sp-gap { position: absolute; bottom: 8px; font-size: 10.5px; color: var(--muted); white-space: nowrap; pointer-events: none; }
|
||||
.sm-sp-dot { position: absolute; right: -4px; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 2px var(--card); }
|
||||
.sm-sp-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; padding-top: 10px; border-top: 1px solid var(--line-2); }
|
||||
.sm-sp-stats > div { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||
.sm-sp-k { font-size: 11px; color: var(--muted); }
|
||||
.sm-sp-v { font-size: 13px; font-weight: 500; color: var(--fg); white-space: nowrap; }
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
@@ -37,6 +38,18 @@ type manageAgentJSON struct {
|
||||
type managedJSON struct {
|
||||
sessions.Managed
|
||||
Via []usage.Via `json:"via,omitempty"`
|
||||
// Keys: the gateway's other "agent|id" keys for it than its own
|
||||
// (sessions.GatewayKeys), for the page to find its speed by
|
||||
Keys []string `json:"keys,omitempty"`
|
||||
}
|
||||
|
||||
// otherKeys are s's gateway keys but its own agent|id.
|
||||
func otherKeys(s sessions.Session) []string {
|
||||
k := sessions.GatewayKeys(s)
|
||||
if len(k) < 2 {
|
||||
return nil
|
||||
}
|
||||
return k[1:]
|
||||
}
|
||||
|
||||
// listedGateway are the gateway sessions the session lists show: not those
|
||||
@@ -115,6 +128,17 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
writeJSON(rw, map[string]bool{"recording": settings.Load().GatewayConversations})
|
||||
})
|
||||
// speeds: each session's output speed now (gateway.Speeds), for the
|
||||
// page's curves while it is open. Not under /api/sessions, which
|
||||
// holds the session files' warm-up for a page that reads them: this
|
||||
// is asked every second and reads none.
|
||||
mux.HandleFunc("GET /api/speeds", func(rw http.ResponseWriter, r *http.Request) {
|
||||
sp := []gateway.Speed{}
|
||||
if gw := served.Load(); gw != nil {
|
||||
sp = append(sp, gw.Speeds()...)
|
||||
}
|
||||
writeJSON(rw, sp)
|
||||
})
|
||||
// manage is the agents with sessions, and every session of ?agent=
|
||||
// (the one with the most when none is named), and the trash.
|
||||
mux.HandleFunc("GET /api/sessions/manage", func(rw http.ResponseWriter, r *http.Request) {
|
||||
@@ -220,7 +244,7 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {
|
||||
vias := usage.Vias(since.Add(-time.Minute))
|
||||
for _, s := range list {
|
||||
s.Path = tilde(s.Path)
|
||||
out.Sessions = append(out.Sessions, managedJSON{Managed: s, Via: viaOf(vias, s.Session)})
|
||||
out.Sessions = append(out.Sessions, managedJSON{Managed: s, Via: viaOf(vias, s.Session), Keys: otherKeys(s.Session)})
|
||||
}
|
||||
sizes := sessions.GatewaySizes()
|
||||
for _, g := range gateway {
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A session the gateway is serving shows its output speed on its Sessions
|
||||
// row: a curve of the last two minutes and tokens a second now, read from
|
||||
// /api/speeds once a second; a click opens the round's numbers, with the
|
||||
// gap where a tool ran. A session known by another key (s.keys) gets its
|
||||
// speed too; a model with no rate yet shows "—", never a guess; a session
|
||||
// with no speed has no cell. Every language, Chromium and WebKit, wide and
|
||||
// narrow.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const at = (min) => new Date(Date.now() - min * 60e3).toISOString();
|
||||
const sess = (id, min, extra = {}) => ({
|
||||
agent: "claude", id, cwd: "/work/app", title: "Session " + id, start: at(min + 5), last: at(min),
|
||||
models: [{ model: "claude-opus-5-5", priced: true, input: 1000, output: 200, calls: 4 }],
|
||||
input: 1000, output: 200, cost: 0.1, messages: 12, size: 4096, files: 1, deletable: true,
|
||||
resume: `claude --resume ${id}`, path: `~/.claude/projects/x/${id}.jsonl`, ...extra,
|
||||
});
|
||||
// 120 seconds: 20 at 100, a 30 second gap, then 70 rising to the last at `now`
|
||||
function curve(now) {
|
||||
const c = [];
|
||||
for (let i = 0; i < 120; i++) c.push(i < 20 ? null : i < 40 ? 100 : i < 70 ? null : 100 + (i - 70) * (now - 100) / 49);
|
||||
return c;
|
||||
}
|
||||
|
||||
function serve(lang, reads) {
|
||||
const sessions = [sess("s-1", 0), sess("s-2", 1, { keys: ["claude|other-key"] }), sess("s-3", 30)];
|
||||
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/sessions/manage") {
|
||||
return json({
|
||||
agents: [{ agent: "claude", count: sessions.length, deletable: true, name: "Claude Code", icon: "claudecode-color" }],
|
||||
agent: "claude", sessions, terminal: true, trash: [], trashDir: "~/trash",
|
||||
});
|
||||
}
|
||||
if (url.pathname === "/api/speeds") {
|
||||
reads.n++;
|
||||
const now = reads.n < 3 ? 128 : 140;
|
||||
return json([
|
||||
{ agent: "claude", session: "s-1", live: true, rated: true, now, avg: 109.4, peak: 315, output: 3700, curve: curve(now), idle: 0 },
|
||||
{ agent: "claude", session: "other-key", live: false, rated: false, now: 0, avg: 0, peak: 0, output: 0, curve: curve(300).map((v, i) => i < 110 ? v : null), idle: 12 },
|
||||
]);
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { nav: "Sessions", unit: "tok/s", avg: "Round average", peak: "Fastest second", written: "Out so far", gap: "Tool 30s" },
|
||||
zh: { nav: "会话", unit: "token/秒", avg: "本轮平均", peak: "峰值", written: "已输出", gap: "工具 30 秒" },
|
||||
"zh-TW": { nav: "會話", unit: "token/秒", avg: "本輪平均", peak: "峰值", written: "已輸出", gap: "工具 30 秒" },
|
||||
ja: { nav: "セッション", unit: "トークン/秒", avg: "このターンの平均", peak: "ピーク", written: "出力済み", gap: "ツール 30 秒" },
|
||||
de: { nav: "Sitzungen", unit: "Token/s", avg: "Ø dieser Runde", peak: "Spitze", written: "Ausgegeben", gap: "Tool 30 s" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
test(`${engine} ${lang}: a session's speed on its row and in its popover`, async (t) => {
|
||||
const w = words[lang];
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width: 1100, height: 700 }, reducedMotion: "reduce" })).newPage();
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-sessions-speed.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page.setDefaultTimeout(8000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const reads = { n: 0 };
|
||||
await page.route("**/*", serve(lang, reads));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
assert.equal(reads.n, 0, "/api/speeds is read before the Sessions page is shown");
|
||||
await page.locator("#nav").getByRole("button", { name: w.nav, exact: true }).click();
|
||||
const row = (id) => page.locator(`#view-sessions .row.sm-sess[data-id="${id}"]`);
|
||||
const cell = row("s-1").locator(".sm-speed");
|
||||
await cell.locator(".sm-speed-val b").filter({ hasText: "128" }).waitFor();
|
||||
assert.equal((await cell.locator(".sm-speed-val small").textContent()).trim(), w.unit);
|
||||
assert.equal(await cell.locator("svg.sm-curve polyline").count(), 2, "two runs of seconds");
|
||||
assert.equal(await cell.locator("svg.sm-curve line.sm-curve-gap").count(), 1, "one gap");
|
||||
// another key of the session's, a model with no rate: the shape, no number
|
||||
const other = row("s-2").locator(".sm-speed");
|
||||
await other.waitFor();
|
||||
assert.equal(await other.locator(".sm-speed-val").textContent(), "—");
|
||||
assert.ok(await other.locator("svg.sm-curve").count());
|
||||
assert.equal(await row("s-3").locator(".sm-speed").isHidden(), true, "a session with no speed shows none");
|
||||
|
||||
// the popover: the number now, the curve, the tool's gap and the round
|
||||
await cell.click();
|
||||
const pop = page.locator(".pop.sm-speed-pop");
|
||||
await pop.waitFor();
|
||||
assert.equal(await cell.getAttribute("aria-expanded"), "true");
|
||||
assert.equal(await pop.locator(".sm-sp-unit").textContent(), w.unit);
|
||||
assert.match(await pop.locator(".sm-sp-big").textContent(), /^(128|140)$/);
|
||||
assert.equal(await pop.locator(".sm-sp-gap").textContent(), w.gap);
|
||||
assert.equal(await pop.locator(".sm-sp-dot").count(), 1, "a live session's last second is marked");
|
||||
const stats = await pop.locator(".sm-sp-k").allTextContents();
|
||||
assert.deepEqual(stats, [w.avg, w.peak, w.written]);
|
||||
const vals = await pop.locator(".sm-sp-v").allTextContents();
|
||||
assert.match(vals[0], /109/);
|
||||
assert.match(vals[1], /315/);
|
||||
assert.match(vals[2], /3[.,]?7/);
|
||||
// it follows the next reads, open
|
||||
await pop.locator(".sm-sp-big").filter({ hasText: "140" }).waitFor();
|
||||
const box = await pop.boundingBox(), vw = page.viewportSize().width;
|
||||
assert.ok(box.x >= 0 && box.x + box.width <= vw, `popover inside the window: ${JSON.stringify(box)}`);
|
||||
await page.keyboard.press("Escape");
|
||||
await pop.waitFor({ state: "detached" });
|
||||
assert.equal(await cell.getAttribute("aria-expanded"), "false");
|
||||
|
||||
// narrow: the number stays, nothing runs past the row
|
||||
for (const width of [720, 520, 380]) {
|
||||
await page.setViewportSize({ width, height: 700 });
|
||||
await page.waitForFunction(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true)))));
|
||||
const m = await row("s-1").evaluate((r) => {
|
||||
const b = r.getBoundingClientRect();
|
||||
return [...r.children].filter((c) => c.offsetParent && (c.getBoundingClientRect().right > b.right + 1 || c.getBoundingClientRect().left < b.left - 1)).map((c) => c.className);
|
||||
});
|
||||
assert.deepEqual(m, [], `at ${width}px past the row's edge`);
|
||||
assert.ok(await cell.locator(".sm-speed-val").isVisible(), `at ${width}px the number shows`);
|
||||
}
|
||||
|
||||
// off the page, no more reads
|
||||
await page.setViewportSize({ width: 1100, height: 700 });
|
||||
await page.locator("#nav").getByRole("button").first().click();
|
||||
await page.waitForTimeout(300);
|
||||
const was = reads.n;
|
||||
await page.waitForTimeout(2500);
|
||||
assert.ok(reads.n <= was + 1, `read ${reads.n - was} times off the page`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user