usage: traffic over time in Requests' chart, and how fast it flows now (songlairui on X)

songlairui on X asked for the gateway's bandwidth: many LLM calls, base64
images above all, weigh on the network. Each request's row already kept
its bytes up (UpBytes) and down (DownBytes), shown in its details and as
the period's "↑ · ↓" under the Requests card. What was missing was
bandwidth over time and right now.

- The Requests chart's metrics take Traffic: each hour's/day's bytes up and
  down, stacked by model, provider or agent. Its axis is in bytes ("4 MB"),
  its tooltip splits a column into "↑ up · ↓ down", and the ranking's
  values are bytes with the same split under each. A period with none
  says "No traffic counted in this period". A chart point's Part now
  carries up_bytes/down_bytes, from rows (Part.add) and from the request
  page's cells (Part.plus). The cells already kept Totals, so no cache
  version bump is needed.
- While requests are in flight, the Requests card says how fast traffic
  flows now: "↑ 1.0 MB/s · ↓ 40 KB/s", over the last ~3s, read from the
  new GET /api/usage/traffic a second apart. That route reports the
  gateway's running totals (Server.Traffic) and its requests in flight.
  The totals are atomics added where a row's bytes are added (sentUp,
  downCount.Read). So a stream counts as it arrives, nothing is buffered
  or scanned, and the totals and rows count the same bytes once. Polling
  runs only while Usage → Requests is shown and the window is visible.
  The line goes when nothing is in flight and nothing flowed. When another
  magpie serves the gateway, the route answers {} and the page shows no
  rate.

A Codex turn on the Responses WebSocket (7c1dc198d) is in the totals as
its row is: what the socket was written. The HTTP body sentUp counted is
taken back when the transport chooses the socket (toSocket) and given back
if the turn falls to HTTP after all (toHTTP), so the totals equal the sum
of the rows either way (TestTrafficCountsWhatTheSocketSent, kept and
refused).

Not counted, as before: Claude bridge turns (no HTTP to the vendor). A
plugin's row counts the local hop to the plugin host. An upload is counted
when its try is sent, so a large body shows as a burst in the live rate.
docs/subsystems/gateway-sessions.md has a Bandwidth section.

Run (mote; first at this change on da8480326, then again on 16a2dfac9):
- go test -count=1 -run 'Traffic|Socket|UpBytes|Ledger|Series'
  ./internal/gateway ./internal/usage ./internal/gui: ok.
- Broken by hand, each red, then restored: the down tally in downCount,
  the up tally in addUp, Part.plus's bytes, Part.add's bytes, the
  toSocket call (kept socket: traffic 151020, rows 50469) and the toHTTP
  call (refused: traffic 50360, rows 100551).
- gofmt -l clean; go vet -tags production ./..., GOOS=linux and
  GOOS=windows go vet ./...: ok; darwin, linux and windows builds: ok.
- GUI (mote, this tree): i18n-keys, i18n-en-no-cjk, usage-traffic and
  request-archive-usage, 54/54 in Chromium and WebKit (usage-traffic in
  en, zh, zh-TW, ja and de); usage-traffic red with the rate line broken
  by hand. "Traffic" is in i18n.js, not the Usage plugin's: Go says it
  too, and i18n-keys was red with it in the plugin's file.
- internal/cli TestEveryRouteHasACommandOrIsNamed: ok, with GET
  /api/usage/traffic named in notYet (the full run found it red).
- On 16a2dfac9 (the pushed base): gofmt -l internal clean; go test
  -count=1 -run 'Traffic|Socket|UpBytes|Ledger|Series|
  TestEveryRouteHasACommandOrIsNamed|Budget' ./internal/gateway
  ./internal/usage ./internal/gui ./internal/cli ok; i18n-keys and
  usage-traffic 40/40.
- Not finished at the tag, still running on mote: go test ./... -timeout
  45m and the whole GUI suite (under suite.lock), and the whole
  internal/gui, internal/usage and internal/gateway packages with every
  usage* GUI file. What they find is fixed in follow-ups.
This commit is contained in:
yetone
2026-11-10 07:37:34 +08:00
parent e364d27fce
commit ca5e537ecb
18 changed files with 737 additions and 15 deletions
+22
View File
@@ -661,6 +661,28 @@ cards only, and a scope with no card answers the cards routes as held.
a key with some of a provider's models, an account-held key, a provider's
only key, and a key told nothing, each red when its check is removed.
### Bandwidth
Each gateway request's row keeps `UpBytes` (the bytes its tries put on the
wire, `sentUp`) and `DownBytes` (the bytes read from the vendors' replies,
counted per `Read` by `downCount`, so a stream is counted as it arrives and
nothing is buffered). The same two places add to the gateway's running
totals (`Server.Traffic`, atomic, in
[`upbytes.go`](../../internal/gateway/upbytes.go)), so the totals and the rows
count the same bytes once. Rows sum into `Totals` and into each chart
point's `Part` (`add` from rows, `plus` from the request page's cells).
The Requests chart's Traffic metric draws them per hour/day by model,
provider or agent. `GET /api/usage/traffic` answers the totals with the
requests in flight (`{}` when another magpie serves the gateway); the
Requests card reads it a second apart while it is shown and says
"↑ x/s · ↓ y/s" over the last ~3s while requests are in flight. Not counted:
Claude bridge turns (no HTTP to the vendor), and a plugin's row counts the
local hop to the plugin host. An upload is counted when its try is sent, so
a large body shows as a burst. `TestTrafficCountsWhatRowsCount`,
`TestTrafficCountsAStreamAsItFlows`, `TestSeriesPartsKeepBytes`,
`TestUsageTrafficSaysWhatTheGatewayCounted` and `usage-traffic.test.cjs`
cover it.
### Calls read from the agents' own files
A call an agent made without magpie reaches Usage only when its own files
+1
View File
@@ -458,6 +458,7 @@ var notYet = map[string]string{
"GET /api/usage/quotas/history/holds": U, // usage.go
"GET /api/usage/requests": U, // usage.go
"GET /api/usage/requests/content": U, // usage.go
"GET /api/usage/traffic": U, // usage.go: the live rate
"POST /api/usage/checkin-account": U, // usage.go: one account now; `magpie accounts checkin` does every account
"POST /api/usage/clear": U, // usage.go
"POST /api/usage/codex-reset": U, // usage.go
+1 -1
View File
@@ -977,7 +977,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
usage.Saw(agentOf(r))
// Codex's own turns come here from the mux, not through serve: the
// row written below sums this call's tries in its own context (#4456)
r = r.WithContext(context.WithValue(r.Context(), upBytesKey{}, &upBytes{}))
r = r.WithContext(s.countBytes(r.Context()))
w0, body0 := w, body // as they came, for the fallbacks (codexFallBack)
// Claude's blocks magpie gave Codex (claudeseal) are Claude's alone:
// to OpenAI each item is its summary, as before magpie carried them
+4
View File
@@ -160,8 +160,12 @@ func (t codexSocket) RoundTrip(req *http.Request) (*http.Response, error) {
// says a refused handshake leaves the host to HTTP for a while.
func (t codexSocket) overSocket(req *http.Request, shun bool) (*http.Response, error) {
overHTTP := false
toSocket(req.Context())
defer func() { sentOnSocket(req.Context(), !overHTTP) }()
viaHTTP := func() (*http.Response, error) {
if !overHTTP {
toHTTP(req.Context())
}
overHTTP = true
return t.next.RoundTrip(req)
}
+1 -1
View File
@@ -455,7 +455,7 @@ func (s *Server) dsResolve(ctx context.Context, p provider.Provider, to provider
up += len(im.b64) / 4 * 3
}
if u := upBytesOf(ctx); u != nil {
u.wire += up
u.addUp(up)
u.saved -= up // and are what the files cost it
}
}
+3 -1
View File
@@ -601,6 +601,8 @@ type Server struct {
requestLimits requestLimits
// what a restart would cut short (busy.go)
busyCounters
// every request's bytes up and down, as they go (Traffic)
traffic traffic
// when Antigravity last turned away the system prompt it refuses
// (UnixNano, 0 for never): while that is recent, a group skips it for
// such a request when someone is left after it (antigravityForeseen)
@@ -2355,7 +2357,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// what the request's tries send up to the vendor is summed in its
// context, where forwardOnce and codexBackend add each try's bytes,
// for the ledger row to read (#4456)
r = r.WithContext(context.WithValue(r.Context(), upBytesKey{}, &upBytes{}))
r = r.WithContext(s.countBytes(r.Context()))
defer func() { watched.end(call, time.Since(start).Milliseconds()) }()
switch call.Kind {
case "web_search":
+199
View File
@@ -0,0 +1,199 @@
package gateway
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// The gateway's running byte counts (Server.Traffic, which Usage's live
// rate reads) take what each request's row takes, a refused try's bytes
// too, whole or streamed, and nothing twice (songlairui on X: how much
// bandwidth the gateway is using).
func TestTrafficCountsWhatRowsCount(t *testing.T) {
for _, stream := range []bool{false, true} {
t.Run(map[bool]string{false: "whole", true: "stream"}[stream], func(t *testing.T) {
fresh(t)
overloaded := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, `{"error":{"message":"overloaded"}}`)
}))
t.Cleanup(overloaded.Close)
ok := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
if stream {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":"hello"}}]}`, `data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`, `data: [DONE]`))
return
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, chatOK)
}))
t.Cleanup(ok.Close)
for _, p := range []provider.Provider{
{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, Chat: overloaded.URL + "/v1"},
{ID: "b", Name: "B", Key: "k", Models: []string{"m"}, Chat: ok.URL + "/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
if got := s.Traffic(); got != (Traffic{}) {
t.Fatalf("a new gateway has counted %+v", got)
}
code, body := postAs(t, s, "", fmt.Sprintf(`{"model":"group/g","stream":%v,"messages":[{"role":"user","content":"hi"}]}`, stream))
if code != 200 || !strings.Contains(body, "hello") {
t.Fatalf("%d %s", code, body)
}
route := lastRoute(s).ID
row := rowOf(t, func(u usage.Record) bool { return u.RouteID == route })
if row.UpBytes == 0 || row.DownBytes == 0 {
t.Fatalf("row: up %d, down %d", row.UpBytes, row.DownBytes)
}
if got := s.Traffic(); got.Up != int64(row.UpBytes) || got.Down != int64(row.DownBytes) {
t.Fatalf("traffic %+v; the row: up %d, down %d", got, row.UpBytes, row.DownBytes)
}
})
}
}
// A reply is counted as it streams in, not when it ends: while the
// vendor holds its stream open after the first event, the gateway's down
// count already has that event's bytes.
func TestTrafficCountsAStreamAsItFlows(t *testing.T) {
fresh(t)
first := `data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":"hello"}}]}` + "\n\n"
rest := sse(`data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`, `data: [DONE]`)
release := make(chan struct{})
vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, first)
w.(http.Flusher).Flush()
select {
case <-release:
case <-r.Context().Done():
return
}
io.WriteString(w, rest)
}))
t.Cleanup(vendor.Close)
var once bool
free := func() {
if !once {
once = true
close(release)
}
}
t.Cleanup(free)
if err := provider.Save(provider.Provider{ID: "b", Name: "B", Key: "k", Models: []string{"m"}, Chat: vendor.URL + "/v1"}); err != nil {
t.Fatal(err)
}
s := New()
done := make(chan struct{})
go func() {
defer close(done)
postAs(t, s, "", `{"model":"b/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
}()
deadline := time.Now().Add(10 * time.Second)
for s.Traffic().Down < int64(len(first)) {
if time.Now().After(deadline) {
free()
<-done
t.Fatalf("mid-stream traffic %+v; the vendor had sent %d bytes", s.Traffic(), len(first))
}
time.Sleep(5 * time.Millisecond)
}
mid := s.Traffic()
if mid.Up == 0 {
t.Fatalf("mid-stream traffic %+v: nothing counted up", mid)
}
free()
<-done
if end := s.Traffic(); end.Down != mid.Down+int64(len(rest)) {
t.Fatalf("traffic mid-stream %+v, at the end %+v; the rest was %d bytes", mid, end, len(rest))
}
}
// A Codex turn on the Responses WebSocket is in the gateway's count as
// what the socket was written, as its row is, not the HTTP body built
// before the transport chose the socket; one that went over HTTP after a
// refused handshake is in it as that body (#5781's 13 MB rows, live).
func TestTrafficCountsWhatTheSocketSent(t *testing.T) {
for _, tc := range []struct {
name string
f *fakeSocketBackend
}{
{"kept socket", &fakeSocketBackend{keep: true}},
{"refused, over HTTP", &fakeSocketBackend{refuse: http.StatusForbidden, whole: true}},
} {
t.Run(tc.name, func(t *testing.T) {
socketOn(t)
f := tc.f
f.frames = keptReply(f)
chatgpt(t, f.ServeHTTP)
s := New()
start := time.Now()
big := strings.Replace(userPing, "ping", strings.Repeat("x", 50_000), 1)
for _, body := range []string{
keptTurn("conv-1", "gpt-5.5-ws", big),
keptTurn("conv-1", "gpt-5.5-ws", big, asstPong, userAgain),
} {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer chatgpt-token-acct-1")
req.Header.Set("chatgpt-account-id", "acct-1")
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
}
var rows []usage.Record
for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) {
rows = rows[:0]
for _, r := range usage.Load(start) {
if r.Time.After(start) && r.Model == "gpt-5.5-ws" {
rows = append(rows, r)
}
}
if len(rows) >= 2 || time.Now().After(deadline) {
break
}
}
if len(rows) != 2 {
t.Fatalf("%d rows, want 2", len(rows))
}
up := 0
for _, r := range rows {
up += r.UpBytes
}
posts, sockets := f.counts()
if f.refuse == 0 && (posts != 0 || sockets != 2) || f.refuse != 0 && posts != 2 {
t.Fatalf("%d posts, %d socket turns", posts, sockets)
}
if got := s.Traffic().Up; got != int64(up) || up == 0 {
t.Fatalf("traffic up %d; the rows: %d", got, up)
}
if f.refuse == 0 {
if want := len(f.turn(0).msg) + len(f.turn(1).msg); up != want {
t.Fatalf("rows and traffic up %d; the socket was written %d", up, want)
}
} else if up < 100_000 {
t.Fatalf("rows and traffic up %d; two HTTP bodies of over 50,000 went", up)
}
})
}
}
+64 -1
View File
@@ -32,6 +32,46 @@ type upBytes struct {
socket bool
// ws is what the socket was written for that try so far (wroteSocket)
ws int
// tally is the gateway's own count of every request's bytes, which
// each try's are added to as they are to this row's (Traffic)
tally *traffic
}
// traffic is what all of a gateway's requests sent up to their vendors and
// read back, since it started: the bytes their ledger rows sum, counted as
// they go, so a request still streaming is in it already. Read twice a
// moment apart, it is how fast the gateway's upstream traffic flows now.
type traffic struct{ up, down atomic.Int64 }
// Traffic is a gateway's bytes up and down so far (traffic).
type Traffic struct {
Up int64 `json:"up"`
Down int64 `json:"down"`
}
// Traffic says how many bytes the gateway's requests have sent up to their
// vendors and read back since it started, tries and streams included.
func (s *Server) Traffic() Traffic {
return Traffic{Up: s.traffic.up.Load(), Down: s.traffic.down.Load()}
}
// countBytes is the context a request's tries add their bytes in (upBytes),
// each also added to the gateway's own count (Traffic).
func (s *Server) countBytes(ctx context.Context) context.Context {
return context.WithValue(ctx, upBytesKey{}, &upBytes{tally: &s.traffic})
}
// addUp adds n bytes sent up to the row's and to the gateway's count.
func (u *upBytes) addUp(n int) {
u.wire += n
u.tallyUp(n)
}
// tallyUp adds n bytes sent up to the gateway's count alone (Traffic).
func (u *upBytes) tallyUp(n int) {
if u.tally != nil && n != 0 {
u.tally.up.Add(int64(n))
}
}
type upBytesKey struct{}
@@ -47,7 +87,7 @@ func upBytesOf(ctx context.Context) *upBytes {
// is assembled after the last try came back — so no lock.
func sentUp(ctx context.Context, wire, plain int) {
if u := upBytesOf(ctx); u != nil {
u.wire += wire
u.addUp(wire)
u.plain = plain
u.last, u.socket, u.ws = wire, false, 0
}
@@ -59,6 +99,26 @@ func sentUp(ctx context.Context, wire, plain int) {
func wroteSocket(ctx context.Context, n int) {
if u := upBytesOf(ctx); u != nil {
u.ws += n
u.tallyUp(n)
}
}
// toSocket is that the try sentUp last counted goes to the Responses
// WebSocket, which writes its own messages (wroteSocket) in place of the
// HTTP body: the gateway's count (Traffic) takes that body back at once,
// so a kept socket's turn isn't a burst of the whole conversation in the
// live rate, and gives it again if the turn goes over HTTP after all
// (toHTTP). The row's own sum is settled once, at the end (sentOnSocket).
func toSocket(ctx context.Context) {
if u := upBytesOf(ctx); u != nil {
u.tallyUp(-u.last)
}
}
// toHTTP is that a try toSocket took goes over HTTP after all.
func toHTTP(ctx context.Context) {
if u := upBytesOf(ctx); u != nil {
u.tallyUp(u.last)
}
}
@@ -104,6 +164,9 @@ type downCount struct {
func (d *downCount) Read(b []byte) (int, error) {
n, err := d.ReadCloser.Read(b)
d.u.down.Add(int64(n))
if d.u.tally != nil {
d.u.tally.down.Add(int64(n))
}
return n, err
}
+5
View File
@@ -1374,6 +1374,9 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske
.led-strip .sub.parts > span, .kpi small.parts > span { display: inline-block; max-width: 100%; vertical-align: bottom; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* the traffic line's parts read whole: one wider than the card wraps in itself, never cut (matrix0487) */
.led-strip .sub.led-io > span { white-space: normal; }
/* how fast the traffic flows now, while requests are in flight */
.led-strip .sub.led-rate { color: var(--fg-2); }
.led-strip .sub.led-rate[hidden] { display: none; }
/* not the tile's label: .kpi span is its small capitals */
.kpi small.parts > span { margin-top: 0; font: inherit; letter-spacing: normal; text-transform: none; color: inherit; }
.led-strip .led-jump { text-align: start; font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; text-decoration: underline dotted; text-underline-offset: 2px; }
@@ -1420,6 +1423,8 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske
.led-chart .tip i { width: 7px; height: 7px; border-radius: 2px; flex: none; }
.led-chart .tip em { margin-left: auto; padding-left: 12px; font-style: normal; font-variant-numeric: tabular-nums; }
.led-chart .tip .sum { margin-top: 3px; padding-top: 3px; border-top: 1px solid var(--line-2); color: var(--muted); }
/* traffic: under its total, what went up and what came back */
.led-chart .tip .io { color: var(--muted); }
/* speed: name, speed and first token in columns, the name whole (#2343) */
.led-chart .tip.speed { display: grid; grid-template-columns: 7px minmax(0, 1fr) auto auto; column-gap: 6px; align-items: center; max-width: min(400px, 100%); }
.led-chart .tip.speed b { grid-column: 1 / -1; }
+19 -9
View File
@@ -18845,16 +18845,19 @@ function ledGroupSpeed(x) {
}
// their mean wait for the first token, 0 for none
const ledTTFT = (x) => x?.timed > 0 ? x.ttft_ms / x.timed : 0;
// the bytes a point, a share or a part sent up and read back
const ledBytes = (x) => (+x?.up_bytes || 0) + (+x?.down_bytes || 0);
// a metric's value of a point or a share, as the chart counts it
const ledValue = (m, x) => m === "speed" ? ledSpeed(x) : m === "cost" ? +x.cost || 0 : m === "calls" ? +x.calls || 0 : allTokens(x);
const ledValue = (m, x) => m === "speed" ? ledSpeed(x) : m === "traffic" ? ledBytes(x) : m === "cost" ? +x.cost || 0 : m === "calls" ? +x.calls || 0 : allTokens(x);
// of a share in the ranking: a speed is what its row says first, the one of
// more replies (ledGroupSpeed)
const ledRankValue = (m, x) => m === "speed" ? ledGroupSpeed(x)?.v || 0 : ledValue(m, x);
// of a point's part, which has its calls, tokens, cost and speed
const ledPart = (m, x) => m === "speed" ? ledSpeed(x) : m === "cost" ? +x.cost || 0 : m === "calls" ? +x.calls || 0 : +x.tokens || 0;
// a metric as its axis and its values say it
const ledFormat = (m, v) => m === "cost" ? ledMoney(v) : (m === "speed" ? ledNum : fmtN)(Math.round(v));
const ledFormatLong = (m, v) => m === "speed" ? (v > 0 ? t("{n} tok/s", { n: ledNum(Math.round(v)) }) : "—") : m === "cost" ? (fmtCost({ cost: v, unpriced: 0 }) || "—") : ledNum(Math.round(v));
const ledPart = (m, x) => m === "speed" ? ledSpeed(x) : m === "traffic" ? ledBytes(x) : m === "cost" ? +x.cost || 0 : m === "calls" ? +x.calls || 0 : +x.tokens || 0;
// a metric as its axis and its values say it: bytes as "2.5 MB", an
// axis's round "4 MB" without its ".0"
const ledFormat = (m, v) => m === "cost" ? ledMoney(v) : m === "traffic" ? fmtBytes(Math.round(v)).replace(/\.0 /, " ") : (m === "speed" ? ledNum : fmtN)(Math.round(v));
const ledFormatLong = (m, v) => m === "speed" ? (v > 0 ? t("{n} tok/s", { n: ledNum(Math.round(v)) }) : "—") : m === "cost" ? (fmtCost({ cost: v, unpriced: 0 }) || "—") : m === "traffic" ? fmtBytes(Math.round(v)) : ledNum(Math.round(v));
// an axis's top with four steps under it: round numbers, the top at least the largest value
function ledAxis(max) {
@@ -18916,7 +18919,7 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) {
const speed = metric === "speed";
const max = Math.max(0, ...totals, ...(speed ? pts.flatMap((p) => Object.values(p.by?.[split] || {}).map(ledSpeed)) : []));
if (!(max > 0)) {
plot.append(el("div", "none", t(metric === "cost" ? "No known price for these requests" : speed ? "No streamed replies timed in this period" : "Nothing in this period")));
plot.append(el("div", "none", t(metric === "cost" ? "No known price for these requests" : speed ? "No streamed replies timed in this period" : metric === "traffic" ? "No traffic counted in this period" : "Nothing in this period")));
return;
}
const topV = ledAxis(max);
@@ -19002,7 +19005,7 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) {
plot.append(g, tip);
const name = (c) => t(c.name || c.id || "—");
// counts short, as the axis says them (skyhuang1994)
const val = (v) => speed || metric === "cost" ? ledFormatLong(metric, v) : ledFormat(metric, v);
const val = (v) => speed || metric === "cost" || metric === "traffic" ? ledFormatLong(metric, v) : ledFormat(metric, v);
const at = (e) => {
const r = g.getBoundingClientRect();
const i = Math.max(0, Math.min(n - 1, Math.floor(((e.clientX - r.left) / r.width * W - M.l) / slot)));
@@ -19033,6 +19036,12 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) {
sum.append(el("span", "", t("Total")), el("em", "", val(totals[i]) + (calls ? " · " + calls : "")));
}
tip.append(sum);
// traffic: of it, what went up and what came back
if (metric === "traffic" && totals[i] > 0) {
const io = el("div", "io");
io.append(el("span", ""), el("em", "", "↑ " + fmtBytes(p.up_bytes || 0) + " · ↓ " + fmtBytes(p.down_bytes || 0)));
tip.append(io);
}
tip.hidden = false;
const x = M.l + slot * (i + 0.5), w = tip.offsetWidth;
tip.style.left = Math.max(0, x + 14 + w > W ? x - w - 14 : x + 14) + "px";
@@ -19082,7 +19091,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
if (x.icon && split !== "model") l1.append(icon(x.icon));
const nm = el("span", "rk-nm", t(x.name || x.id || "—"));
nm.title = t(x.name || x.id || "");
const long = ledFormatLong(metric, v), val = el("span", "rk-val", metric == "speed" ? gs?.text || "—" : metric == "cost" ? long : ledFormat(metric, v));
const long = ledFormatLong(metric, v), val = el("span", "rk-val", metric == "speed" ? gs?.text || "—" : metric == "cost" || metric == "traffic" ? long : ledFormat(metric, v));
val.title = metric == "speed" ? gs?.title || "" : long;
l1.append(nm, val);
const bar = el("div", "rk-bar"), fill = el("i");
@@ -19090,6 +19099,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
fill.style.background = color;
bar.append(fill);
const more = [];
if (metric === "traffic") more.push("↑ " + fmtBytes(x.up_bytes || 0) + " · ↓ " + fmtBytes(x.down_bytes || 0));
if (metric !== "calls") more.push(t(x.calls === 1 ? "{n} request" : "{n} requests", { n: fmtN(x.calls) }));
if (metric !== "tokens") more.push(t("{n} tokens", { n: fmtN(allTokens(x)) }));
if (metric !== "cost" && x.cost) more.push("≈" + fmtCost(x));
@@ -19115,7 +19125,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
for (const x of top) box.append(one(x, x.color));
if (rest.length) {
const tot = rest.reduce((acc, x) => {
for (const k of ["calls", "errors", "loops", "input", "output", "cache_read", "cache_write", "cache_unknown", "cache_unknown_calls", "cost", "credits", "credited", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n"]) acc[k] = (acc[k] || 0) + (x[k] || 0);
for (const k of ["calls", "errors", "loops", "input", "output", "cache_read", "cache_write", "cache_unknown", "cache_unknown_calls", "cost", "credits", "credited", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n", "up_bytes", "down_bytes"]) acc[k] = (acc[k] || 0) + (x[k] || 0);
return acc;
}, { id: "\0other", name: t("Other ({n})", { n: rest.length }) });
box.append(one(tot, "var(--faint)", true));
+8
View File
@@ -4120,6 +4120,8 @@ const I18N = {
"Output speed": "输出速度",
"Output tokens a second after the first, over the streamed replies": "流式回复从首字起每秒输出的 token 数",
"No streamed replies timed in this period": "这段时间没有可计时的流式回复",
"No traffic counted in this period": "这段时间没有计入流量",
"Traffic": "流量",
"A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "有推理的回复只算正文部分,从首个正文起计:推理在流里出现前就已写完",
"No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "没有正文时,仅在可见推理持续流式输出时将其计入速度;隐藏推理不显示速度",
"Cache": "缓存",
@@ -8900,6 +8902,8 @@ const I18N = {
"Output speed": "輸出速度",
"Output tokens a second after the first, over the streamed replies": "流式回覆從首字起每秒輸出的 token 數",
"No streamed replies timed in this period": "這段時間沒有可計時的流式回覆",
"No traffic counted in this period": "這段時間沒有計入流量",
"Traffic": "流量",
"A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "有推理的回覆只算正文部分,從首個正文起計:推理在流裡出現前就已寫完",
"No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "沒有正文時,僅在可見推理持續串流輸出時將其計入速度;隱藏推理不顯示速度",
"Cache": "快取",
@@ -13694,6 +13698,8 @@ const I18N = {
"Output speed": "出力速度",
"Output tokens a second after the first, over the streamed replies": "ストリーミング応答で、最初のトークン以降に毎秒出力されたトークン数",
"No streamed replies timed in this period": "この期間に計測できたストリーミング応答はありません",
"No traffic counted in this period": "この期間に数えた通信量はありません",
"Traffic": "通信量",
"A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "推論した応答は、最初の本文からの回答部分のみ数えます。推論はストリームに出る前に書き終わっています",
"No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "本文がない場合、継続的にストリームされた可視の推論のみ速度に含めます。非表示の推論には速度を表示しません",
"Cache": "キャッシュ",
@@ -18503,6 +18509,8 @@ const I18N = {
"Output speed": "Ausgabetempo",
"Output tokens a second after the first, over the streamed replies": "Ausgabe-Token pro Sekunde nach dem ersten, über die gestreamten Antworten",
"No streamed replies timed in this period": "In diesem Zeitraum wurde keine gestreamte Antwort gemessen",
"No traffic counted in this period": "In diesem Zeitraum wurde kein Datenverkehr gezählt",
"Traffic": "Datenverkehr",
"A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "Eine Antwort mit Reasoning zählt nur ihre Antwort ab dem ersten Text: Das Reasoning entstand, bevor der Stream es zeigte",
"No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "Ohne Antworttext zählt Reasoning nur bei sichtbar gestreamter Ausgabe; verborgenes Reasoning hat kein Tempo",
"Cache": "Cache",
@@ -4,6 +4,7 @@ magpie.strings({
zh: {
"Saved by image files": "图片文件省下",
"{n} saved by image files": "图片文件省下 {n}",
"{n}/s": "{n}/s",
"{size} ({n} image)": "{size}({n} 张)",
"{size} ({n} images)": "{size}({n} 张)",
"Show in Overview": "在概览中显示",
@@ -252,6 +253,7 @@ magpie.strings({
"zh-TW": {
"Saved by image files": "圖片檔案省下",
"{n} saved by image files": "圖片檔案省下 {n}",
"{n}/s": "{n}/s",
"{size} ({n} image)": "{size}({n} 張)",
"{size} ({n} images)": "{size}({n} 張)",
"Show in Overview": "在概覽中顯示",
@@ -500,6 +502,7 @@ magpie.strings({
ja: {
"Saved by image files": "画像ファイルで節約",
"{n} saved by image files": "画像ファイルで {n} 節約",
"{n}/s": "{n}/s",
"{size} ({n} image)": "{size}({n} 枚)",
"{size} ({n} images)": "{size}({n} 枚)",
"Show in Overview": "概要に表示",
@@ -748,6 +751,7 @@ magpie.strings({
de: {
"Saved by image files": "Durch Bilddateien gespart",
"{n} saved by image files": "{n} durch Bilddateien gespart",
"{n}/s": "{n}/s",
"{size} ({n} image)": "{size} ({n} Bild)",
"{size} ({n} images)": "{size} ({n} Bilder)",
"Show in Overview": "In der Übersicht einblenden",
+64 -2
View File
@@ -1203,7 +1203,7 @@ const LED_PAGE = 100;
let ledMetric = "tokens", ledSplit = "model";
try {
const m = localStorage.getItem("magpie.ledMetric");
if (["tokens", "cost", "calls", "speed"].includes(m)) ledMetric = m;
if (["tokens", "cost", "calls", "speed", "traffic"].includes(m)) ledMetric = m;
} catch {}
// Columns or lines (molvqingtai on Discord), kept per viewer as the metric
// is; anything but "line", or a read that fails, is columns.
@@ -1732,7 +1732,9 @@ function ledContentBox(c) {
// tab draws the same from the same answer.
// the window's chart can also say how fast the replies came (#860)
const LED_TREND = [...LED_METRICS, ["speed", "Speed"]];
// and how many bytes went up to the vendors and came back (songlairui on
// X: a lot of calls with base64 images weigh on the network)
const LED_TREND = [...LED_METRICS, ["speed", "Speed"], ["traffic", "Traffic"]];
// "modelAt" is a model at the provider it went to, so one model's speed at
// each provider is ranked side by side (inaction on Discord); "callerKey"
// the gateway key that made it, "none" for calls with none, offered while
@@ -1847,6 +1849,8 @@ function renderLedgerDash(l) {
io.title = t("Sent upstream") + ": " + ledNum(l.up_bytes || 0) + " B\n" + t("Received") + ": " + ledNum(l.down_bytes || 0) + " B";
strip.lastChild.append(io);
}
// and how fast it flows now, while requests are in flight (ledFlow)
strip.lastChild.append(ledFlowLine());
const c = fmtCost(l);
// the count in the words the quick panel uses too, the whole sentence on
// hover (tenacious_eagle on Discord)
@@ -1868,6 +1872,64 @@ function renderLedgerDash(l) {
drawLedTrend();
}
// ---- how fast the gateway's traffic flows now
//
// Under the period's "↑ up · ↓ down", while requests are in flight: the
// bytes the gateway's requests sent up and read back in the last few
// seconds, a second apart, as "↑ 1.2 MB/s · ↓ 40 KB/s" (songlairui on X).
// The gateway counts them as they go (/api/usage/traffic), a stream's
// reply as it comes, so nothing waits for a request to end. Read only
// while the Requests are looked at; nothing shown when another magpie
// serves the gateway, or when nothing is in flight and nothing flowed.
const LED_FLOW_EVERY = 1000, LED_FLOW_SPAN = 3000;
const ledFlow = { samples: [], timer: 0, text: "", reading: false };
function ledFlowLine() {
const s = el("span", "sub led-rate");
s.hidden = !ledFlow.text;
s.textContent = ledFlow.text;
ledFlowStart();
return s;
}
function ledFlowShow(text) {
ledFlow.text = text;
for (const s of document.querySelectorAll("#ledKpi .led-rate")) {
if (s.textContent !== text) s.textContent = text;
s.hidden = !text;
}
}
const ledFlowOn = () => view === "usage" && usageTab === "requests" && !document.hidden;
function ledFlowStart() {
if (ledFlow.timer || !ledFlowOn()) return;
ledFlow.timer = setInterval(ledFlowTick, LED_FLOW_EVERY);
ledFlowTick();
}
function ledFlowStop() {
clearInterval(ledFlow.timer);
ledFlow.timer = 0;
ledFlow.samples = [];
ledFlowShow("");
}
async function ledFlowTick() {
if (!ledFlowOn()) return ledFlowStop();
if (ledFlow.reading) return;
ledFlow.reading = true;
let x;
try { x = await api("usage/traffic"); } catch { x = null; } finally { ledFlow.reading = false; }
if (!ledFlow.timer) return;
if (!(x?.up >= 0 && x?.down >= 0)) { ledFlow.samples = []; return ledFlowShow(""); }
const now = performance.now(), ss = ledFlow.samples;
// a gateway started again counts from 0: what came before is gone
if (ss.length && (x.up < ss.at(-1).up || x.down < ss.at(-1).down)) ss.length = 0;
ss.push({ at: now, up: x.up, down: x.down });
while (ss.length > 2 && now - ss[1].at >= LED_FLOW_SPAN) ss.shift();
const a = ss[0], dt = (now - a.at) / 1000;
const up = dt > 0 ? (x.up - a.up) / dt : 0, down = dt > 0 ? (x.down - a.down) / dt : 0;
if (!(x.requests > 0) && !(up > 0) && !(down > 0)) return ledFlowShow("");
const rate = (v) => t("{n}/s", { n: fmtBytes(Math.round(v)) });
ledFlowShow(dt > 0 ? "↑ " + rate(up) + " · ↓ " + rate(down) : "");
}
document.addEventListener("visibilitychange", () => { if (document.hidden) ledFlowStop(); else if ($("#ledKpi .led-rate")) ledFlowStart(); });
// the chart's two looks, as a pair of icons beside the metrics: columns
// (the default) or lines
const LED_STYLES = [["bars", "Bar chart", "M3.5 13V8.5M8 13V3.5M12.5 13V6.5"], ["line", "Line chart", "M2.5 11.5 6 7.5l3 2.5 4.5-6"]];
+224
View File
@@ -0,0 +1,224 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The Usage page's Requests show the gateway's bandwidth (songlairui on X:
// many calls with base64 images weigh on the network). The chart's metrics
// take Traffic: columns of each hour's bytes up and down, stacked by model,
// an axis in bytes, a tooltip that splits a column into "↑ up · ↓ down",
// and a ranking whose values are bytes with the same split under each; a
// period with no bytes says so. Under the Requests card, while requests are
// in flight, "↑ 1.0 MB/s · ↓ 40 KB/s" says how fast traffic flows now, read
// from /api/usage/traffic a second apart; it goes when the gateway is idle,
// says nothing when another magpie serves the gateway ({}), and the page
// stops asking once the Requests aren't looked at. At 1180 and 420 wide the
// page never scrolls sideways. Chromium and WebKit, every language; no
// backend, the API is faked.
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 reader = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const midnight = new Date();
midnight.setHours(0, 0, 0, 0);
// a day by the hour, from 02:00: glm-5 sends 2 MB up and reads 400 KB back
// an hour, kimi half that
const GLM = { up_bytes: 2_000_000, down_bytes: 400_000 }, KIMI = { up_bytes: 1_000_000, down_bytes: 200_000 };
function page(bytes) {
const series = Array.from({ length: 24 }, (_, h) => {
const on = h >= 2 ? 1 : 0;
const part = (b) => ({ calls: 10 * on, tokens: 5000 * on, cost: 0, ...(bytes ? { up_bytes: b.up_bytes * on, down_bytes: b.down_bytes * on } : {}) });
const glm = part(GLM), kimi = part(KIMI);
return {
label: String(h), time: new Date(midnight.getTime() + h * 3600e3).toISOString(), calls: 20 * on, errors: 0, input: 10000 * on, output: 0, cache_read: 0, cache_write: 0, cost: 0,
...(bytes ? { up_bytes: 3_000_000 * on, down_bytes: 600_000 * on } : {}),
by: { model: { "glm-5": glm, kimi }, provider: { zcode: glm }, agent: { claude: glm } },
};
});
const share = (id, b) => ({ id, name: id, calls: 220, errors: 0, input: 110000, output: 0, cache_read: 0, cache_write: 0, cost: 0, ...(bytes ? { up_bytes: b.up_bytes * 22, down_bytes: b.down_bytes * 22 } : {}) });
return {
period: "today", rows: [], offset: 0, total: 440, calls: 440, errors: 0, input: 220000, output: 0, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0, unpriced: 0, bucket: "hour", series,
...(bytes ? { up_bytes: 66_000_000, down_bytes: 13_200_000 } : {}),
by: { model: [share("glm-5", GLM), share("kimi", KIMI)], provider: [share("zcode", GLM)], agent: [share("claude", GLM)] },
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], providers: [{ id: "zcode", name: "ZCode", icon: "generic" }],
};
}
// the gateway's counters: flowing (1 MB/s up, 40 KB/s down, two requests
// in flight), idle (still, none in flight) or served elsewhere ({})
function gatewayAt(state) {
const t0 = Date.now();
let frozen = null;
return () => {
if (state.mode === "elsewhere") return {};
if (state.mode === "idle") return { ...(frozen ||= { up: 0, down: 0 }), requests: 0 };
const ms = Date.now() - t0;
frozen = { up: ms * 1000, down: ms * 40 };
return { ...frozen, requests: 2 };
};
}
function server(lang, bytes, state) {
const traffic = gatewayAt(state);
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:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: { rate: 7.2, at: new Date().toISOString() } });
if (url.pathname === "/api/usage/traffic") { state.asked++; return json(traffic()); }
if (url.pathname === "/api/usage/requests") return json(page(bytes));
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage") return json({ calls: 1, errors: 0, input: 1, output: 1, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], agents: [], models: [] });
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
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 L = {
en: { traffic: "Traffic", none: "No traffic counted in this period" },
zh: { traffic: "流量", none: "这段时间没有计入流量" },
"zh-TW": { traffic: "流量", none: "這段時間沒有計入流量" },
ja: { traffic: "通信量", none: "この期間に数えた通信量はありません" },
de: { traffic: "Datenverkehr", none: "In diesem Zeitraum wurde kein Datenverkehr gezählt" },
};
async function open(browser, lang, width, bytes, state) {
const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
const p = await ctx.newPage();
const errors = [];
p.setDefaultTimeout(5000);
p.setDefaultNavigationTimeout(60000);
p.on("pageerror", (e) => errors.push(e.message));
await p.route("**/*", server(lang, bytes, state));
await p.goto("http://magpie.test/");
await p.locator('[data-view="usage"]').first().click();
await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
await p.locator("#ledChart svg").waitFor();
return { ctx, p, errors };
}
// "↑ 1.0 MB/s · ↓ 40 KB/s" as bytes a second, up and down
function rates(s) {
const m = /^↑ ([\d.]+) (B|KB|MB)\/s · ↓ ([\d.]+) (B|KB|MB)\/s$/.exec(s);
assert(m, "the rate line: " + s);
const k = { B: 1, KB: 1e3, MB: 1e6 };
return [+m[1] * k[m[2]], +m[3] * k[m[4]]];
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the gateway's traffic in Requests", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const shots = process.env.ARTIFACT_DIR;
if (shots) await fs.mkdir(shots, { recursive: true });
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
const w = L[lang];
for (const width of [1180, 420]) {
await t.test(lang + " " + width, async () => {
const state = { mode: "flowing", asked: 0 };
const { ctx, p, errors } = await open(browser, lang, width, true, state);
try {
// how fast it flows now, under the Requests card
const rate = p.locator("#ledKpi .led-rate:not([hidden])");
await rate.waitFor();
const [up, down] = rates((await rate.textContent()).trim());
assert(up > 0.7e6 && up < 1.3e6, `up ${up} B/s, the gateway sends 1 MB/s`);
assert(down > 28e3 && down < 52e3, `down ${down} B/s, the gateway reads 40 KB/s`);
// the chart's Traffic
const pill = p.locator("#ledMetric .opt").nth(4);
assert.equal((await pill.textContent()).trim(), w.traffic);
await reader.click(p, pill);
await p.locator("#ledChart svg rect.col").first().waitFor();
const axis = await p.locator("#ledChart svg text.axis[text-anchor=end]").allTextContents();
assert.equal(axis.length, 5, "five side labels: " + axis);
for (const a of axis) assert.match(a, /^\d+(\.\d)? (B|KB|MB)$/, "an axis label in bytes");
assert(axis.includes("4 MB"), "the top of 3.6 MB an hour: " + axis);
// a column's tooltip: its total, and of it what went up and came back
await reader.inView(p, p.locator("#ledChart svg"));
const box = await p.locator("#ledChart svg").boundingBox();
await p.mouse.move(box.x + box.width * 0.62, box.y + box.height / 2);
await p.locator("#ledChart .tip").waitFor();
assert.equal((await p.locator("#ledChart .tip .io em").textContent()).trim(), "↑ 3.0 MB · ↓ 600 KB");
assert((await p.locator("#ledChart .tip").textContent()).includes("3.6 MB"), "the column's total");
await p.mouse.move(1, 1);
// the ranking: bytes, the most first, split up and down
const rk = p.locator("#ledRank .rk");
assert.deepEqual((await rk.locator(".rk-val").allTextContents()).map((s) => s.trim()), ["53 MB", "26 MB"]);
const sub = (await rk.locator(".rk-b").allTextContents()).map((s) => s.split(" · ").slice(0, 2).join(" · "));
assert.deepEqual(sub, ["↑ 44 MB · ↓ 8.8 MB", "↑ 22 MB · ↓ 4.4 MB"]);
const sideways = await p.evaluate(() => [document.documentElement.scrollWidth - innerWidth, ...[...document.querySelectorAll("#ledKpi .blk, #ledMetric")].map((b) => b.scrollWidth - b.clientWidth)]);
assert(sideways.every((n) => n <= 1), `scrolls sideways: ${sideways}`);
if (shots) await p.locator(".led-trend").screenshot({ path: path.join(shots, `traffic-${engine}-${lang}-${width}.png`) });
assert.deepEqual(errors, []);
} finally {
await ctx.close();
}
});
}
// a period with no bytes counted says so
await t.test(lang + " none", async () => {
const { ctx, p, errors } = await open(browser, lang, 1180, false, { mode: "flowing", asked: 0 });
try {
await reader.click(p, p.locator("#ledMetric .opt").nth(4));
assert.equal((await p.locator("#ledChart .none").textContent()).trim(), w.none);
assert.deepEqual(errors, []);
} finally {
await ctx.close();
}
});
}
// the gateway goes idle: once the last flow has left the few seconds
// the rate is read over, the line goes
await t.test("idle", async () => {
const state = { mode: "flowing", asked: 0 };
const { ctx, p, errors } = await open(browser, "en", 1180, true, state);
try {
await p.locator("#ledKpi .led-rate:not([hidden])").waitFor();
state.mode = "idle";
await p.locator("#ledKpi .led-rate[hidden]").waitFor({ state: "attached", timeout: 10000 });
assert.equal((await p.locator("#ledKpi .led-rate").textContent()), "");
// and it comes back when requests flow again
state.mode = "flowing";
await p.locator("#ledKpi .led-rate:not([hidden])").waitFor({ timeout: 10000 });
// leaving the Requests stops the asking
await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(0).click();
await p.waitForFunction(() => !document.querySelector("#ledKpi .led-rate:not([hidden])") || document.querySelector("#ledKpi").offsetParent === null);
const asked = state.asked;
await p.waitForTimeout(2500);
assert(state.asked - asked <= 1, `asked ${state.asked - asked} times after leaving the Requests`);
assert.deepEqual(errors, []);
} finally {
await ctx.close();
}
});
// another magpie serves the gateway: no rate, nothing made up
await t.test("served elsewhere", async () => {
const state = { mode: "elsewhere", asked: 0 };
const { ctx, p, errors } = await open(browser, "en", 1180, true, state);
try {
// three answers read, each of them {}
for (const end = Date.now() + 10000; state.asked < 3; await p.waitForTimeout(100)) assert(Date.now() < end, `asked ${state.asked} times`);
assert.equal(await p.locator("#ledKpi .led-rate:not([hidden])").count(), 0);
assert.deepEqual(errors, []);
} finally {
await ctx.close();
}
});
});
}
+24
View File
@@ -15,6 +15,7 @@ import (
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
"github.com/yetone/magpie/internal/settings"
@@ -184,6 +185,12 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
limit, _ := strconv.Atoi(q.Get("limit"))
writeJSON(rw, ledgerPage(periodOf(q.Get("period")), ledgerFilter(r), offset, limit))
}))
// the gateway's bytes up and down so far and its requests in flight,
// which the Requests read a moment apart for how fast its traffic flows
// now; {} when another magpie serves the gateway
mux.HandleFunc("GET /api/usage/traffic", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, trafficNow())
})
// 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", coldTurn(func(rw http.ResponseWriter, r *http.Request) {
@@ -438,3 +445,20 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
writeJSON(rw, out)
})
}
// trafficJSON is the gateway's bytes so far (gateway.Traffic) with its
// requests in flight; all left out when this process serves no gateway.
type trafficJSON struct {
*gateway.Traffic
Requests *int `json:"requests,omitempty"`
}
// trafficNow is what /api/usage/traffic answers.
func trafficNow() trafficJSON {
gw := served.Load()
if gw == nil {
return trafficJSON{}
}
t, n := gw.Traffic(), gw.Busy().Requests
return trafficJSON{Traffic: &t, Requests: &n}
}
+34
View File
@@ -0,0 +1,34 @@
package gui
import (
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/gateway"
)
// /api/usage/traffic answers the gateway's bytes so far and its requests
// in flight, which the Requests read a moment apart for how fast traffic
// flows now; {} when this process serves no gateway, so the page shows no
// rate rather than a made-up zero.
func TestUsageTrafficSaysWhatTheGatewayCounted(t *testing.T) {
h := builtinHome(t)
get := func() string {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/api/usage/traffic", nil))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
return strings.TrimSpace(rec.Body.String())
}
prev := served.Swap(nil)
t.Cleanup(func() { served.Store(prev) })
if b := get(); b != "{}" {
t.Fatalf("no gateway served here: %s", b)
}
served.Store(gateway.New())
if b := get(); b != `{"up":0,"down":0,"requests":0}` {
t.Fatalf("a gateway served here: %s", b)
}
}
+8
View File
@@ -1145,6 +1145,10 @@ type Part struct {
TTFT int64 `json:"ttft_ms,omitempty"`
DecodeMs int64 `json:"decode_ms,omitempty"`
DecodeOut int `json:"decode_out,omitempty"`
// the bytes its requests sent up and read back (Totals.UpBytes), for
// a chart of the traffic over time
UpBytes int64 `json:"up_bytes,omitempty"`
DownBytes int64 `json:"down_bytes,omitempty"`
}
// add counts a row in the part.
@@ -1156,6 +1160,8 @@ func (p *Part) add(r Row) {
if r.Priced {
p.Cost += r.Cost
}
p.UpBytes += int64(r.UpBytes)
p.DownBytes += int64(r.DownBytes)
if r.TTFT > 0 && r.Answered() {
p.Timed++
p.TTFT += r.TTFT
@@ -1176,6 +1182,8 @@ func (p *Part) plus(d *Totals) {
p.TTFT += d.TTFT
p.DecodeMs += d.DecodeMs
p.DecodeOut += d.DecodeOut
p.UpBytes += d.UpBytes
p.DownBytes += d.DownBytes
}
// SeriesPoint is a point of the timeline with its calls told apart, by each
+52
View File
@@ -0,0 +1,52 @@
package usage
import (
"testing"
"time"
)
// A point of the chart tells each part's bytes up and down apart, as it
// does tokens, for Requests' Traffic chart to stack them (songlairui on
// X): from the rows (LedgerSeries, Part.add) and from the request page's
// cells (Part.plus) alike, and the point's own sums have them all.
func TestSeriesPartsKeepBytes(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
records := []Record{
{Time: now, Provider: "a", Agent: "codex", Model: "m", Input: 10, UpBytes: 1000, DownBytes: 300, Status: 200},
{Time: now, Provider: "a", Agent: "codex", Model: "m", Input: 10, UpBytes: 2000, DownBytes: 400, Status: 200},
{Time: now, Provider: "b", Agent: "claude", Model: "n", Input: 10, UpBytes: 50, DownBytes: 7, Status: 500},
}
gateway := &rowChunk{}
all := Ledgered{}
for i, r := range records {
row := Row{Record: r}
gateway.add(row, "", int64(i), false)
all.Rows = append(all.Rows, row)
}
for name, page := range map[string]RequestPage{
"compact": buildRequestPage(Today, Filter{}, 0, 100, gateway, nil),
"ledger": pageFromLedger(Today, Filter{}, 0, 100, all),
} {
t.Run(name, func(t *testing.T) {
var up, down int64
parts := map[string]Part{}
for _, pt := range page.Series {
up += pt.UpBytes
down += pt.DownBytes
for id, p := range pt.By["provider"] {
q := parts[id]
q.UpBytes += p.UpBytes
q.DownBytes += p.DownBytes
parts[id] = q
}
}
if up != 3050 || down != 707 {
t.Fatalf("the points' own sums: up %d, down %d", up, down)
}
if a, b := parts["a"], parts["b"]; a.UpBytes != 3000 || a.DownBytes != 700 || b.UpBytes != 50 || b.DownBytes != 7 {
t.Fatalf("the providers' parts: %+v", parts)
}
})
}
}