usage: the Requests card's up arrow opens what the bytes sent upstream were made of
theforeveriris (X, 2121408745616162998) saw 8169 requests send 8.6 GB up and 1.0 GB down and wanted to know why. About 1 MB a request is normal: every request sends the whole conversation again, with the system prompt and the tools' definitions. This shows it. Gateway: promptOf, which already parses the body off the request path, now also counts the bytes of the system prompt, the tool definitions and images in the body it read. upParts scales those to the wire bytes and puts them on Record.UpParts. Nothing new runs on the request path, and a body that isn't parsed stays "Not measured". Usage: a packed row keeps the mix in 255ths under flag rowUpParts (32768); the row stays 152 bytes. Totals gain up_calls, up_measured, up_system, up_tools and up_images, and Shares carry up_bytes and up_calls by agent and by model. settledCountVersion goes 4 -> 5, so settled days are counted again once on the next start. GUI (Usage -> Requests): the "↑ 8.6 GB" on the Requests card is a button that opens a "Sent upstream" card: the average per request, one sentence on why, a bar and legend for Conversation / Tool definitions / System prompt / Images / Not measured, and the top 8 agents and models with bytes sent and per request. The open state is kept; × closes it. A request's details get a "Made of" line. zh, zh-TW, ja, de strings. Entrance is 200ms ease-out, no movement under reduced motion. Run (mote, at this head on27e43ed26): - go test ./internal/usage ./internal/usageapi: ok - go test -run 'Prompt|UpParts|UpBytes|DownBytes|Traffic|Ledger| CodexOwnTurn' ./internal/gateway: ok - go test -run Budget ./internal/gui: ok (after the rebase) - go vet -tags nogui for darwin, linux, windows on usage, gateway, usageapi, gui: ok; gofmt -l clean - GUI: usage-upload.test.cjs 32/32 (chromium + webkit, 1180 and 420, en zh zh-TW ja de); with i18n-keys, i18n-en-no-cjk, usage-ledger-bytes, usage-traffic, usage-ledger-detail: 144 pass, 0 fail - GUI subset i18n*, usage*, ledger* atf1f34d624: the only reds are usage-agents-hide, usage-cards-hide, usage-fold, usage-hidden-way-back, usage-ledger, usage-range-times and usage-speed-all-models. They are red the same way on origin/mainf1f34d624without this change and are already filed (#3414, #3415, #6003, #6294, #6295, #6499, #5834). - Screenshots of the card: chromium en 1180 light, webkit zh 1180 dark, chromium zh 420 light. - Benchmark: promptOf on a 1.17 MB body, 2.8-3.9 ms/op with counting vs 3.2-3.7 without, same allocations (noise). - Broken by hand: without the b.again guard, TestPromptKnowsWhatItsBytesWere goes red. Not run: the full go test ./... and the full GUI suite. mote and mica were loaded, with a suite already queued under suite.lock.
This commit is contained in:
@@ -772,6 +772,28 @@ a large body shows as a burst. `TestTrafficCountsWhatRowsCount`,
|
||||
`TestUsageTrafficSaysWhatTheGatewayCounted` and `usage-traffic.test.cjs`
|
||||
cover it.
|
||||
|
||||
What the bytes up were made of (theforeveriris on X: 8.6 GB up over 8169
|
||||
requests). Every request resends the whole conversation, so ~1 MB a request
|
||||
is a long context, not a leak. The prompt reader (`promptOf`, already run off
|
||||
the request path by `inspectPrompt`) adds each piece's length as it reads it
|
||||
into `Prompt.sent`: the system prompt (with skills and memory), the tools'
|
||||
definitions, images, and everything read (`all`). A tool result shared by the
|
||||
files it read counts once (`again`). `upParts` scales those to the bytes
|
||||
that went on the wire into the row's `UpParts`. A row gets none when its
|
||||
bytes up aren't its body's: a Responses WebSocket delta, a body whose images
|
||||
went as files, or a body not read. The request page keeps the parts in
|
||||
255ths of `UpBytes` in the packed row (`upMix`, flag `rowUpParts`, still 152
|
||||
bytes). `Totals` sum `UpCalls` (requests that sent any bytes), `UpMeasured`
|
||||
(the bytes of those with parts) and the three parts, per period and per
|
||||
agent, model or provider. The Requests card's ↑ opens `#ledUp`. It shows the
|
||||
bytes a request, a bar of the conversation, tools, system prompt, images and
|
||||
what wasn't measured, and the bytes of each agent and model. A request's
|
||||
details say "Made of". `TestPromptKnowsWhatItsBytesWere` (fails if a shared
|
||||
tool result is counted per file), `TestUpPartsScaleToTheWire`,
|
||||
`TestLedgerKeepsUpParts`, `TestRowUpPartsKept`, `TestTotalsSumUpParts` and
|
||||
`usage-upload.test.cjs` cover it. `BenchmarkPromptOfLargeBody` times the
|
||||
reader on a 1.2 MB body.
|
||||
|
||||
### Calls read from the agents' own files
|
||||
|
||||
A call an agent made without magpie reaches Usage only when its own files
|
||||
|
||||
@@ -1089,8 +1089,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
captureTitle := false
|
||||
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)
|
||||
var sentPrompt *Prompt // what the body was made of, read at end (upParts)
|
||||
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))
|
||||
@@ -1142,6 +1143,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
replyDigest = titleReplyDigest(titleReply.buf.Bytes(), nil)
|
||||
}
|
||||
prompt := promptRead() // outside the trace's lock, which reading it takes
|
||||
sentPrompt = prompt
|
||||
s.trace.update(tr, func(t *Route) {
|
||||
// what masking took: magpie's own time isn't split here
|
||||
t.Masking = maskingMs(r.Context(), 0)
|
||||
@@ -1676,6 +1678,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
if up := upBytesOf(r.Context()); up != nil {
|
||||
rec.UpBytes, rec.PlainBytes, rec.Socket = up.wire, up.plain, up.socket
|
||||
rec.DownBytes = up.downOf()
|
||||
rec.UpParts = upParts(sentPrompt, up)
|
||||
}
|
||||
appendUsage(r, rec)
|
||||
}
|
||||
|
||||
@@ -5626,6 +5626,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
if up := upBytesOf(r.Context()); up != nil {
|
||||
rec.UpBytes, rec.PlainBytes, rec.Socket = up.wire, up.plain, up.socket
|
||||
rec.DownBytes, rec.ImageFilesSaved, rec.ImageFiles = up.downOf(), up.saved, up.images
|
||||
rec.UpParts = upParts(prompt, up)
|
||||
}
|
||||
failedWith(&rec, call.Status, call.Error, call.Usage.ErrType)
|
||||
withBodies(&rec, &call)
|
||||
|
||||
@@ -52,8 +52,23 @@ type Prompt struct {
|
||||
Held bool `json:"held,omitempty"`
|
||||
Turns int `json:"turns,omitempty"` // the user's turns in it
|
||||
Parts []PromptPart `json:"parts"`
|
||||
// sent is what the body's bytes were made of (sentSizes), for the
|
||||
// ledger row's Record.UpParts; never written to the routing history
|
||||
sent sentSizes
|
||||
}
|
||||
|
||||
// sentSizes is a body's bytes by what they were, as the builder read the
|
||||
// pieces it already had in hand: the agent's own prompt and its
|
||||
// instructions (system, skills, memory), the tools' definitions, the
|
||||
// images and documents sent inline, and all it read (the rest is the
|
||||
// conversation, and the JSON around it). Counting them is a length added
|
||||
// per piece, no second read of the body (#upload).
|
||||
type sentSizes struct{ system, tools, images, all int }
|
||||
|
||||
// size is how many bytes a piece took in the body: its raw JSON, its
|
||||
// text, an image's source, a sealed piece's size.
|
||||
func (pc *PromptPiece) size() int { return len(pc.raw) + len(pc.img) + len(pc.Text) + pc.Size }
|
||||
|
||||
// PromptPart is one kind of what a prompt holds.
|
||||
type PromptPart struct {
|
||||
Kind string `json:"kind"`
|
||||
@@ -111,6 +126,11 @@ type promptBuilder struct {
|
||||
// (itemKey), for PromptText; off when only the sizes are read
|
||||
keep bool
|
||||
pieces map[string][]PromptPiece
|
||||
// sent: the pieces' bytes by what they were (sentSizes); again off
|
||||
// while one tool result is shared among the files it read (result),
|
||||
// so its bytes count once
|
||||
sent sentSizes
|
||||
again bool
|
||||
}
|
||||
|
||||
// PromptPiece is a stretch of an item's text as the request sent it: a
|
||||
@@ -172,6 +192,18 @@ func (b *promptBuilder) add(kind, name, tag string, tokens int, pc PromptPiece)
|
||||
}
|
||||
it.N++
|
||||
it.Tokens += tokens
|
||||
if !b.again {
|
||||
n := pc.size()
|
||||
b.sent.all += n
|
||||
switch {
|
||||
case tag == "image":
|
||||
b.sent.images += n
|
||||
case kind == PartSystem || kind == PartSkills || kind == PartMemory:
|
||||
b.sent.system += n
|
||||
case kind == PartTools:
|
||||
b.sent.tools += n
|
||||
}
|
||||
}
|
||||
if b.keep {
|
||||
b.pieces[kind+"\x00"+key] = append(b.pieces[kind+"\x00"+key], pc)
|
||||
}
|
||||
@@ -188,7 +220,7 @@ func (b *promptBuilder) chat(tokens int, pc PromptPiece) {
|
||||
func (b *promptBuilder) newTurn() { b.turn++ }
|
||||
|
||||
func (b *promptBuilder) prompt() *Prompt {
|
||||
p := &Prompt{Held: b.held, Turns: b.turn, Parts: []PromptPart{}}
|
||||
p := &Prompt{Held: b.held, Turns: b.turn, Parts: []PromptPart{}, sent: b.sent}
|
||||
for _, kind := range partOrder {
|
||||
m := b.parts[kind]
|
||||
if len(m) == 0 {
|
||||
@@ -611,8 +643,10 @@ func (b *promptBuilder) result(callID string, tokens int, pc PromptPiece) {
|
||||
if !readTools[c.name] {
|
||||
tag = "shell"
|
||||
}
|
||||
b.again = i > 0
|
||||
b.add(PartFiles, f, tag, n, pc)
|
||||
}
|
||||
b.again = false
|
||||
return
|
||||
}
|
||||
b.add(PartResults, c.name, "result", tokens, pc)
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// upBytes is what a request's tries sent up to the vendor, kept in the
|
||||
@@ -172,3 +174,17 @@ func (d *downCount) Read(b []byte) (int, error) {
|
||||
|
||||
// downOf is the reply bytes counted so far (upBytes.down).
|
||||
func (u *upBytes) downOf() int { return int(u.down.Load()) }
|
||||
|
||||
// upParts is what a request's bytes up were made of (usage.UpParts): the
|
||||
// parts of the body the prompt was read from, each scaled to what went on
|
||||
// the wire, so a compressed or retried request's parts sum to its bytes
|
||||
// as its whole does. None when the body wasn't read (p nil), nothing
|
||||
// went, the last try went over a kept socket (its bytes a delta, not the
|
||||
// body) or images went by file (the bytes no longer the body's).
|
||||
func upParts(p *Prompt, u *upBytes) *usage.UpParts {
|
||||
if p == nil || u == nil || u.wire <= 0 || u.socket || u.images > 0 || p.sent.all <= 0 {
|
||||
return nil
|
||||
}
|
||||
of := func(n int) int { return int(int64(n) * int64(u.wire) / int64(p.sent.all)) }
|
||||
return &usage.UpParts{System: of(p.sent.system), Tools: of(p.sent.tools), Images: of(p.sent.images)}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// upPartsBody is a Chat Completions request with every part: a system
|
||||
// prompt, a tool's definition, an inline image, and a conversation whose
|
||||
// one tool call read two files, its result shared between them.
|
||||
func upPartsBody(model string) (body string, system, tool, image, result int) {
|
||||
sys := strings.Repeat("You are a careful agent. ", 200)
|
||||
def := `{"type":"function","function":{"name":"exec_command","description":"` + strings.Repeat("Runs a command. ", 100) + `","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}}`
|
||||
img := "data:image/png;base64," + strings.Repeat("iVBORw0KGgo", 300)
|
||||
out := strings.Repeat("package main // the files' text\n", 300)
|
||||
q, _ := json.Marshal(out)
|
||||
body = `{"model":"` + model + `","messages":[` +
|
||||
`{"role":"system","content":"` + sys + `"},` +
|
||||
`{"role":"user","content":[{"type":"text","text":"read these"},{"type":"image_url","image_url":{"url":"` + img + `"}}]},` +
|
||||
`{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"exec_command","arguments":"{\"cmd\":\"cat a.go b.go\"}"}}]},` +
|
||||
`{"role":"tool","tool_call_id":"c1","content":` + string(q) + `}],` +
|
||||
`"tools":[` + def + `]}`
|
||||
return body, len(sys), len(def), len(img), len(out)
|
||||
}
|
||||
|
||||
// A request's body is told apart by what its bytes were, as the prompt
|
||||
// is read: the system prompt, the tools' definitions and the images each
|
||||
// at least their own bytes, and nothing counted twice — a tool result
|
||||
// shared among the files it read counts once, so the parts never sum past
|
||||
// the body (theforeveriris on X: what are 8.6 GB up made of?).
|
||||
func TestPromptKnowsWhatItsBytesWere(t *testing.T) {
|
||||
body, system, tool, image, result := upPartsBody("m")
|
||||
p := promptOf(provider.Chat, []byte(body))
|
||||
if p == nil {
|
||||
t.Fatal("the body wasn't read")
|
||||
}
|
||||
read := 0
|
||||
for _, it := range partOf(p, PartFiles).Items {
|
||||
if it.Name == "a.go" || it.Name == "b.go" {
|
||||
read++
|
||||
}
|
||||
}
|
||||
if read != 2 {
|
||||
t.Fatalf("the cat's two files weren't read as files: %+v", p.Parts)
|
||||
}
|
||||
s := p.sent
|
||||
if s.system < system || s.tools < tool || s.images < image {
|
||||
t.Fatalf("parts %+v; the body holds system %d, tools %d, an image %d", s, system, tool, image)
|
||||
}
|
||||
if s.all > len(body) {
|
||||
t.Fatalf("the parts read %d bytes of a %d-byte body: something counted twice", s.all, len(body))
|
||||
}
|
||||
if rest := s.all - s.system - s.tools - s.images; rest < result {
|
||||
t.Fatalf("the conversation is %d bytes; its tool result alone is %d", rest, result)
|
||||
}
|
||||
}
|
||||
|
||||
// What the parts are on a row is what went on the wire, each part scaled
|
||||
// by it; none where the bytes up aren't the body's.
|
||||
func TestUpPartsScaleToTheWire(t *testing.T) {
|
||||
p := &Prompt{sent: sentSizes{system: 100, tools: 200, images: 300, all: 1000}}
|
||||
got := upParts(p, &upBytes{wire: 500})
|
||||
if got == nil || *got != (usage.UpParts{System: 50, Tools: 100, Images: 150}) {
|
||||
t.Fatalf("got %+v", got)
|
||||
}
|
||||
for name, c := range map[string]struct {
|
||||
p *Prompt
|
||||
u *upBytes
|
||||
}{
|
||||
"not read": {nil, &upBytes{wire: 500}},
|
||||
"nothing went": {p, &upBytes{}},
|
||||
"a socket delta": {p, &upBytes{wire: 500, socket: true}},
|
||||
"images by file": {p, &upBytes{wire: 500, images: 2}},
|
||||
"empty body": {&Prompt{}, &upBytes{wire: 500}},
|
||||
} {
|
||||
if got := upParts(c.p, c.u); got != nil {
|
||||
t.Errorf("%s: %+v, want none", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A request's ledger row keeps what its bytes up were made of, the parts
|
||||
// within what went up and each where the body has it.
|
||||
func TestLedgerKeepsUpParts(t *testing.T) {
|
||||
fresh(t)
|
||||
got := 0
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
got = len(b)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, chatOK)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, system, tool, image, _ := upPartsBody("a/m")
|
||||
s := New()
|
||||
if code, reply := postAs(t, s, "", body); code != 200 {
|
||||
t.Fatalf("%d %s", code, reply)
|
||||
}
|
||||
route := lastRoute(s).ID
|
||||
var row *usage.Record
|
||||
for deadline := time.Now().Add(10 * time.Second); row == nil && time.Now().Before(deadline); {
|
||||
for _, u := range usage.Load(time.Time{}) {
|
||||
if u.RouteID == route {
|
||||
row = &u
|
||||
}
|
||||
}
|
||||
if row == nil {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
if row == nil {
|
||||
t.Fatal("no row for the request")
|
||||
}
|
||||
if row.UpBytes != got || row.UpParts == nil {
|
||||
t.Fatalf("UpBytes %d (the vendor got %d), parts %+v", row.UpBytes, got, row.UpParts)
|
||||
}
|
||||
u := row.UpParts
|
||||
if u.System+u.Tools+u.Images > row.UpBytes {
|
||||
t.Fatalf("parts %+v sum past %d bytes up", u, row.UpBytes)
|
||||
}
|
||||
// the body went on as it came, near enough: each part near its share
|
||||
near := func(part, want int) bool { return part >= want*9/10 && part <= want*13/10 }
|
||||
if !near(u.System, system) || !near(u.Tools, tool) || !near(u.Images, image) {
|
||||
t.Fatalf("parts %+v; the body holds system %d, tools %d, an image %d", u, system, tool, image)
|
||||
}
|
||||
}
|
||||
|
||||
// Reading a large body's parts is a length added per piece the prompt
|
||||
// already reads, nothing beside it: its cost is promptOf's.
|
||||
func BenchmarkPromptOfLargeBody(b *testing.B) {
|
||||
var msgs []string
|
||||
for i := range 400 {
|
||||
msgs = append(msgs, `{"role":"user","content":"`+strings.Repeat("a line of the conversation ", 40)+`"}`)
|
||||
msgs = append(msgs, `{"role":"assistant","content":null,"tool_calls":[{"id":"c`+string(rune('a'+i%26))+`","type":"function","function":{"name":"exec_command","arguments":"{\"cmd\":\"cat a.go b.go\"}"}}]}`)
|
||||
msgs = append(msgs, `{"role":"tool","tool_call_id":"c`+string(rune('a'+i%26))+`","content":"`+strings.Repeat("x", 1500)+`"}`)
|
||||
}
|
||||
body := []byte(`{"model":"m","messages":[{"role":"system","content":"` + strings.Repeat("s", 40000) + `"},` + strings.Join(msgs, ",") + `]}`)
|
||||
b.SetBytes(int64(len(body)))
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
if promptOf(provider.Chat, body) == nil {
|
||||
b.Fatal("not read")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1494,6 +1494,25 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske
|
||||
.led-strip .meter { height: 5px; margin-top: 8px; border-radius: 3px; background: var(--pill); overflow: hidden; }
|
||||
.led-strip .meter i { display: block; height: 100%; border-radius: 3px; background: var(--green); }
|
||||
.led-trend { padding: 10px 14px 10px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; }
|
||||
/* what the bytes sent upstream were made of, opened from the Requests card's ↑ */
|
||||
.led-up { margin-top: 10px; padding: 10px 14px 12px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; }
|
||||
.led-up[hidden] { display: none; }
|
||||
.led-up .led-bar { align-items: center; }
|
||||
.led-up-each { font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.led-up-x { margin-left: 6px; font-size: 16px; line-height: 1; padding: 0 4px; color: var(--muted); }
|
||||
.led-up-note { margin: 4px 0 10px; font-size: 12px; color: var(--muted); }
|
||||
.led-up-bar { display: flex; gap: 2px; height: 8px; border-radius: 4px; overflow: hidden; background: var(--pill); }
|
||||
.led-up-seg { display: block; min-width: 2px; flex-basis: 0; }
|
||||
.led-up-seg.rest { background: var(--pill); }
|
||||
.led-up-legend { display: flex; flex-wrap: wrap; gap: 4px 16px; margin-top: 8px; font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.led-up-key { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.led-up-key .dot { width: 8px; height: 8px; border-radius: 2px; background: var(--pill); }
|
||||
.led-up-key b { font-weight: 600; }
|
||||
.led-up-key .pc, .led-up-key.rest { color: var(--muted); }
|
||||
.led-up-lists { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 4px 24px; margin-top: 12px; }
|
||||
.led-up-by td.nm { position: relative; }
|
||||
.led-up-by td.nm > span { display: block; overflow: hidden; text-overflow: ellipsis; }
|
||||
.led-up-meter { display: block; height: 2px; margin-top: 3px; border-radius: 1px; background: var(--c1); opacity: .55; }
|
||||
.led-speed { margin-top: 10px; padding: 10px 14px 6px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; }
|
||||
.led-speed[hidden] { display: none; }
|
||||
.led-spd-t { font-size: 13px; font-weight: 600; }
|
||||
|
||||
@@ -78,6 +78,7 @@ magpie.plugin("usage", (ctx) => {
|
||||
<p class="usage-note" id="ledScope" data-t>Gateway and session-log calls; local rejections excluded from totals.</p>
|
||||
<div class="led-dash" id="ledDash" hidden>
|
||||
<div class="led-strip" id="ledKpi"></div>
|
||||
<section class="led-up" id="ledUp" hidden></section>
|
||||
<section class="led-trend">
|
||||
<div class="led-bar">
|
||||
<div class="segs" id="ledMetric"></div>
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
// kernel adds them to i18n.js's (magpie.strings).
|
||||
magpie.strings({
|
||||
zh: {
|
||||
"What the bytes sent upstream were made of": "发往上游的字节由什么组成",
|
||||
"≈ {size} a request": "每个请求约 {size}",
|
||||
"Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "每个请求都会把整段对话连同系统提示词和工具定义重新发送一遍,所以一个请求的字节数随上下文增长。",
|
||||
"Tool definitions": "工具定义",
|
||||
"Not measured": "未测量",
|
||||
"Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart": "magpie 没有读取请求体的请求:Responses WebSocket 的轮次,以及无法拆解的请求体",
|
||||
"Bytes sent": "已发送",
|
||||
"Per request": "每个请求",
|
||||
"Made of": "组成",
|
||||
"Order by": "排序方式",
|
||||
"Order this list": "给这个列表排序",
|
||||
"Model speed": "模型速度",
|
||||
@@ -282,6 +291,15 @@ magpie.strings({
|
||||
"Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同",
|
||||
},
|
||||
"zh-TW": {
|
||||
"What the bytes sent upstream were made of": "傳往上游的位元組由什麼組成",
|
||||
"≈ {size} a request": "每個請求約 {size}",
|
||||
"Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "每個請求都會把整段對話連同系統提示詞和工具定義重新傳送一遍,所以一個請求的位元組數隨上下文增長。",
|
||||
"Tool definitions": "工具定義",
|
||||
"Not measured": "未測量",
|
||||
"Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart": "magpie 沒有讀取請求內容的請求:Responses WebSocket 的輪次,以及無法拆解的請求內容",
|
||||
"Bytes sent": "已傳送",
|
||||
"Per request": "每個請求",
|
||||
"Made of": "組成",
|
||||
"Order by": "排序方式",
|
||||
"Order this list": "排序這個列表",
|
||||
"Model speed": "模型速度",
|
||||
@@ -562,6 +580,15 @@ magpie.strings({
|
||||
"Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同",
|
||||
},
|
||||
ja: {
|
||||
"What the bytes sent upstream were made of": "上流へ送ったバイトの内訳",
|
||||
"≈ {size} a request": "1 リクエストあたり約 {size}",
|
||||
"Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "各リクエストは会話全体をシステムプロンプトとツール定義ごと送り直すため、リクエストのバイト数はコンテキストとともに増えます。",
|
||||
"Tool definitions": "ツール定義",
|
||||
"Not measured": "未計測",
|
||||
"Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart": "magpie が本文を読まなかったリクエスト:Responses WebSocket のターンと、分解できなかった本文",
|
||||
"Bytes sent": "送信量",
|
||||
"Per request": "1 リクエストあたり",
|
||||
"Made of": "内訳",
|
||||
"Order by": "並べ替え",
|
||||
"Order this list": "この一覧を並べ替える",
|
||||
"Model speed": "モデルの速度",
|
||||
@@ -842,6 +869,15 @@ magpie.strings({
|
||||
"Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信",
|
||||
},
|
||||
de: {
|
||||
"What the bytes sent upstream were made of": "Woraus die an den Upstream gesendeten Bytes bestehen",
|
||||
"≈ {size} a request": "≈ {size} pro Anfrage",
|
||||
"Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "Jede Anfrage sendet die ganze Unterhaltung erneut, samt Systemprompt und Tool-Definitionen, daher wachsen die Bytes einer Anfrage mit ihrem Kontext.",
|
||||
"Tool definitions": "Tool-Definitionen",
|
||||
"Not measured": "Nicht gemessen",
|
||||
"Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart": "Anfragen, deren Inhalt magpie nicht gelesen hat: Züge über einen Responses-WebSocket und Inhalte, die es nicht zerlegen konnte",
|
||||
"Bytes sent": "Gesendet",
|
||||
"Per request": "Pro Anfrage",
|
||||
"Made of": "Zusammensetzung",
|
||||
"Order by": "Sortieren nach",
|
||||
"Order this list": "Diese Liste sortieren",
|
||||
"Model speed": "Modelltempo",
|
||||
|
||||
@@ -2067,6 +2067,11 @@ function ledDetail(r) {
|
||||
// DeepSeek's image files kept out of it (#5407); a row from before has
|
||||
// none of them, and says nothing
|
||||
if (r.up_bytes > 0) add("Sent upstream", fmtBytes(r.up_bytes));
|
||||
// and what it was made of, for a row whose body magpie read
|
||||
if (r.up_bytes > 0 && r.up_parts) {
|
||||
const p = ledUpParts({ up_bytes: r.up_bytes, up_measured: r.up_bytes, up_system: r.up_parts.system, up_tools: r.up_parts.tools, up_images: r.up_parts.images });
|
||||
add("Made of", LED_UP_PARTS.filter(([k]) => p[k] > 0).map(([k, label]) => t(label) + " " + fmtBytes(p[k])).join(" · "));
|
||||
}
|
||||
if (r.down_bytes > 0) add("Received", fmtBytes(r.down_bytes));
|
||||
// and how many images they were, for a row that kept it (matrix0487)
|
||||
if (r.image_files_saved > 0) add("Saved by image files", r.image_files > 0 ? t(r.image_files === 1 ? "{size} ({n} image)" : "{size} ({n} images)", { size: fmtBytes(r.image_files_saved), n: ledNum(r.image_files) }) : fmtBytes(r.image_files_saved));
|
||||
@@ -2329,11 +2334,114 @@ function drawLedSpeed(l) {
|
||||
box.append(head, scroll);
|
||||
}
|
||||
|
||||
// ---- what the bytes sent upstream were made of (theforeveriris on X:
|
||||
// "8.6 GB up from plain-text projects?"). Every request sends the whole
|
||||
// conversation again, so a request's bytes are about its context; the
|
||||
// card says so, splits the bytes of the requests whose body magpie read
|
||||
// into the system prompt, the tools' definitions, images and the
|
||||
// conversation, and lists them by agent and by model, each with its bytes
|
||||
// a request. Opened from the ↑ on the Requests card, kept open as left.
|
||||
let ledUpOpen = false;
|
||||
try { ledUpOpen = localStorage.getItem("magpie.ledUp") === "1"; } catch {}
|
||||
const LED_UP_PARTS = [
|
||||
["conv", "Conversation", "c1"],
|
||||
["tools", "Tool definitions", "c2"],
|
||||
["system", "System prompt", "c3"],
|
||||
["images", "Images", "c4"],
|
||||
["rest", "Not measured", ""],
|
||||
];
|
||||
function ledUpParts(x) {
|
||||
const sys = x.up_system || 0, tools = x.up_tools || 0, images = x.up_images || 0;
|
||||
const measured = Math.min(x.up_measured || 0, x.up_bytes || 0);
|
||||
return { conv: Math.max(0, measured - sys - tools - images), tools, system: sys, images, rest: Math.max(0, (x.up_bytes || 0) - measured) };
|
||||
}
|
||||
const ledUpEach = (x) => (x.up_calls > 0 ? (x.up_bytes || 0) / x.up_calls : 0);
|
||||
function drawLedUp(l, entering) {
|
||||
const box = $("#ledUp");
|
||||
box.hidden = !ledUpOpen || !(l.up_bytes > 0);
|
||||
box.replaceChildren();
|
||||
if (box.hidden) return;
|
||||
const head = el("div", "led-bar");
|
||||
head.append(el("b", "led-spd-t", t("Sent upstream")), el("span", "grow"));
|
||||
const each = ledUpEach(l);
|
||||
if (each) head.append(el("span", "led-up-each", t("≈ {size} a request", { size: fmtBytes(each) })));
|
||||
const close = el("button", "text led-up-x", "×");
|
||||
close.type = "button";
|
||||
close.setAttribute("aria-label", t("Close"));
|
||||
close.onclick = () => ledUpToggle(false);
|
||||
head.append(close);
|
||||
const note = el("p", "led-up-note", t("Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context."));
|
||||
const parts = ledUpParts(l);
|
||||
const bar = el("div", "led-up-bar");
|
||||
bar.setAttribute("role", "img");
|
||||
const legend = el("div", "led-up-legend");
|
||||
const said = [];
|
||||
for (const [key, label, c] of LED_UP_PARTS) {
|
||||
const n = parts[key];
|
||||
if (!(n > 0)) continue;
|
||||
const share = n / l.up_bytes;
|
||||
const seg = el("i", "led-up-seg " + key);
|
||||
if (c) seg.style.background = "var(--" + c + ")";
|
||||
seg.style.flexGrow = String(share);
|
||||
seg.title = t(label) + ": " + fmtBytes(n) + " (" + (100 * share).toFixed(1) + "%)";
|
||||
bar.append(seg);
|
||||
const item = el("span", "led-up-key " + key);
|
||||
const dot = el("i", "dot");
|
||||
if (c) dot.style.background = "var(--" + c + ")";
|
||||
item.append(dot, el("span", "", t(label)), el("b", "", fmtBytes(n)), el("span", "pc", (100 * share < 1 ? "<1" : Math.round(100 * share)) + "%"));
|
||||
if (key === "rest") item.title = t("Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart");
|
||||
legend.append(item);
|
||||
said.push(t(label) + " " + fmtBytes(n));
|
||||
}
|
||||
bar.setAttribute("aria-label", said.join(", "));
|
||||
const lists = el("div", "led-up-lists");
|
||||
for (const [dim, title] of [["agent", "Agent"], ["model", "Model"]]) {
|
||||
const rows = (l.by?.[dim] || []).filter((s) => s.up_bytes > 0).sort((a, b) => b.up_bytes - a.up_bytes);
|
||||
if (!rows.length) continue;
|
||||
const table = el("table", "led-spd led-up-by");
|
||||
const hr = el("tr");
|
||||
hr.append(el("th", "nm", t(title)), el("th", "n", t("Bytes sent")), el("th", "n", t("Per request")));
|
||||
const thead = el("thead");
|
||||
thead.append(hr);
|
||||
const body = el("tbody");
|
||||
const top = rows[0].up_bytes;
|
||||
for (const s of rows.slice(0, 8)) {
|
||||
const tr = el("tr");
|
||||
const nm = el("td", "nm");
|
||||
const name = s.name || s.id || "—";
|
||||
nm.append(el("span", "", dim === "agent" ? t(name) : name));
|
||||
nm.title = name;
|
||||
const meter = el("i", "led-up-meter");
|
||||
meter.style.width = (100 * s.up_bytes / top).toFixed(1) + "%";
|
||||
nm.append(meter);
|
||||
tr.append(nm, el("td", "", fmtBytes(s.up_bytes)), el("td", ledUpEach(s) ? "" : "faint", ledUpEach(s) ? fmtBytes(ledUpEach(s)) : "—"));
|
||||
body.append(tr);
|
||||
}
|
||||
table.append(thead, body);
|
||||
lists.append(table);
|
||||
}
|
||||
box.append(head, note, bar, legend, lists);
|
||||
if (entering && box.animate) {
|
||||
const still = calm();
|
||||
box.animate([{ opacity: 0, transform: still ? "none" : "translateY(-4px)" }, { opacity: 1, transform: "none" }], { duration: 200, easing: "cubic-bezier(.23, 1, .32, 1)" });
|
||||
}
|
||||
}
|
||||
let ledUpLast = null;
|
||||
function ledUpToggle(open) {
|
||||
ledUpOpen = open;
|
||||
try { localStorage.setItem("magpie.ledUp", open ? "1" : "0"); } catch {}
|
||||
for (const b of document.querySelectorAll("#ledKpi .led-up-open")) b.setAttribute("aria-expanded", String(open));
|
||||
if (ledUpLast) drawLedUp(ledUpLast, open);
|
||||
if (!open) $("#ledKpi .led-up-open")?.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
function renderLedgerDash(l) {
|
||||
const dash = $("#ledDash");
|
||||
dash.hidden = !l.total && !l.day;
|
||||
if (dash.hidden) return;
|
||||
drawLedSpeed(l);
|
||||
ledUpLast = l;
|
||||
drawLedUp(l);
|
||||
const total = allTokens(l);
|
||||
// of the calls whose vendor counted the cache: none when no call's was (#3464)
|
||||
const rate = cacheHitOf(l);
|
||||
@@ -2391,6 +2499,17 @@ function renderLedgerDash(l) {
|
||||
const io = line(...usageParts(["↑ " + fmtBytes(l.up_bytes || 0), "↓ " + fmtBytes(l.down_bytes || 0), ...(l.image_files_saved > 0 ? [t("{n} saved by image files", { n: fmtBytes(l.image_files_saved) })] : [])]));
|
||||
io.classList.add("parts", "led-io");
|
||||
io.title = t("Sent upstream") + ": " + ledNum(l.up_bytes || 0) + " B\n" + t("Received") + ": " + ledNum(l.down_bytes || 0) + " B";
|
||||
// the ↑ opens what those bytes were made of (drawLedUp)
|
||||
if (l.up_bytes > 0) {
|
||||
const up = io.firstElementChild;
|
||||
const b = el("button", "led-jump led-up-open", up.textContent);
|
||||
b.type = "button";
|
||||
b.title = t("What the bytes sent upstream were made of");
|
||||
b.setAttribute("aria-controls", "ledUp");
|
||||
b.setAttribute("aria-expanded", String(ledUpOpen));
|
||||
b.onclick = () => ledUpToggle(!ledUpOpen);
|
||||
up.replaceChildren(b);
|
||||
}
|
||||
strip.lastChild.append(io);
|
||||
}
|
||||
// and how fast it flows now, while requests are in flight (ledFlow)
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// What the bytes sent upstream were made of (theforeveriris on X: 8169
|
||||
// requests, "↑ 8.6 GB" from plain-text projects). The Requests card's ↑ is
|
||||
// a button that opens a card under the strip: the bytes a request, a line
|
||||
// saying each request sends the whole conversation again, a bar and its
|
||||
// legend of the conversation, the tools' definitions, the system prompt,
|
||||
// images and what wasn't measured, and the bytes of each agent and each model,
|
||||
// largest first. It stays open as left across a reload and closes from its
|
||||
// ×. A request's details say what its bytes were made of; one that kept no
|
||||
// parts says nothing. A period with nothing sent has no button. At 1180 and
|
||||
// 420 wide nothing 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 now = Date.now();
|
||||
|
||||
const row = (rid, more) => ({ t: new Date(now - 60e3).toISOString(), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "openai", providerName: "OpenAI", req: "gpt-5", model: "gpt-5", served: "gpt-5", in: 300, out: 40, ms: 2380, status: 200, rid, ep: "/v1/chat/completions", cost: 0.01, priced: true, ...more });
|
||||
const ROWS = [
|
||||
row("req_parts", { up_bytes: 1_000_000, down_bytes: 3_000, up_parts: { system: 200_000, tools: 50_000 } }),
|
||||
row("req_plain", { up_bytes: 40_000, down_bytes: 900 }),
|
||||
];
|
||||
const UP = { up_bytes: 8_600_000_000, up_calls: 8169, up_measured: 8_000_000_000, up_system: 1_000_000_000, up_tools: 500_000_000, up_images: 100_000_000, down_bytes: 1_000_000_000 };
|
||||
const share = (id, name, up, calls) => ({ id, name, calls, input: 1, output: 1, up_bytes: up, up_calls: calls });
|
||||
const BY = {
|
||||
agent: [share("claude", "Claude Code", 2_100_000_000, 4000), share("codex", "Codex", 6_500_000_000, 4169), share("gemini", "Gemini CLI", 0, 0)],
|
||||
model: [share("gpt-5", "gpt-5", 6_500_000_000, 4169), share("claude-sonnet", "claude-sonnet", 2_100_000_000, 4000)],
|
||||
};
|
||||
|
||||
function page(q, sent) {
|
||||
return {
|
||||
period: q.get("period"), rows: ROWS, offset: 0, total: ROWS.length, calls: 8169, errors: 0,
|
||||
input: 700, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0.03, unpriced: 0,
|
||||
...(sent ? UP : {}), by: sent ? BY : {},
|
||||
agents: [{ id: "codex", name: "Codex", icon: "codex-color" }],
|
||||
};
|
||||
}
|
||||
|
||||
function server(lang, sent) {
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.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/requests") return json(page(url.searchParams, sent));
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/usage") return json({ calls: 3, errors: 0, input: 700, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 0.03, bucket: "day", series: [], agents: [], models: [], path: "~/.config/magpie/usage.jsonl" });
|
||||
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.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: { each: "≈ 1.1 MB a request", conv: "Conversation", tools: "Tool definitions", system: "System prompt", images: "Images", rest: "Not measured", agent: "Agent", model: "Model", made: "Made of", note: /whole conversation again/ },
|
||||
zh: { each: "每个请求约 1.1 MB", conv: "会话内容", tools: "工具定义", system: "系统提示词", images: "图像", rest: "未测量", agent: "Agent", model: "模型", made: "组成", note: /整段对话/ },
|
||||
"zh-TW": { each: "每個請求約 1.1 MB", conv: "會話內容", tools: "工具定義", system: "系統提示詞", images: "影像", rest: "未測量", agent: "Agent", model: "模型", made: "組成", note: /整段對話/ },
|
||||
ja: { each: "1 リクエストあたり約 1.1 MB", conv: "会話", tools: "ツール定義", system: "システムプロンプト", images: "画像", rest: "未計測", agent: "エージェント", model: "モデル", made: "内訳", note: /会話全体/ },
|
||||
de: { each: "≈ 1.1 MB pro Anfrage", conv: "Unterhaltung", tools: "Tool-Definitionen", system: "Systemprompt", images: "Bilder", rest: "Nicht gemessen", agent: "Agent", model: "Modell", made: "Zusammensetzung", note: /ganze Unterhaltung/ },
|
||||
};
|
||||
|
||||
async function open(browser, lang, width, sent, storage) {
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce", ...(storage ? { storageState: storage } : {}) });
|
||||
const p = await ctx.newPage();
|
||||
p.setDefaultTimeout(5000);
|
||||
p.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
p.on("pageerror", (e) => errors.push(e.message));
|
||||
await p.route("**/*", server(lang, sent));
|
||||
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("#ledWrap .led tbody tr.led-row").first().waitFor();
|
||||
await p.locator("#ledKpi .blk").first().waitFor();
|
||||
return { ctx, p, errors };
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": what the bytes sent upstream were made of", 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());
|
||||
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 { ctx, p, errors } = await open(browser, lang, width, true);
|
||||
const btn = p.locator("#ledKpi .led-io .led-up-open");
|
||||
assert.equal(await btn.count(), 1);
|
||||
assert.equal((await btn.textContent()).trim(), "↑ 8.6 GB");
|
||||
assert.equal(await btn.getAttribute("aria-expanded"), "false");
|
||||
assert.equal(await p.locator("#ledUp").isVisible(), false);
|
||||
await btn.click();
|
||||
const box = p.locator("#ledUp");
|
||||
await box.waitFor();
|
||||
assert.equal(await btn.getAttribute("aria-expanded"), "true");
|
||||
assert.equal((await box.locator(".led-up-each").textContent()).trim(), w.each);
|
||||
assert.match(await box.locator(".led-up-note").textContent(), w.note);
|
||||
// the legend: each part, its bytes, its share, in this order
|
||||
const keys = await box.locator(".led-up-key").evaluateAll((ks) => ks.map((k) => [...k.querySelectorAll("span, b")].map((s) => s.textContent)));
|
||||
assert.deepEqual(keys, [
|
||||
[w.conv, "6.4 GB", "74%"], [w.tools, "500 MB", "6%"], [w.system, "1.0 GB", "12%"], [w.images, "100 MB", "1%"], [w.rest, "600 MB", "7%"],
|
||||
]);
|
||||
// the bar's segments are as wide as their shares
|
||||
const segs = await box.locator(".led-up-bar").evaluate((b) => [b.getBoundingClientRect().width, ...[...b.children].map((s) => s.getBoundingClientRect().width)]);
|
||||
assert.equal(segs.length, 6);
|
||||
assert(segs[1] > segs[3] && segs[3] > segs[2] && segs[2] > segs[4], `segments ${segs}`);
|
||||
// by agent and by model, largest first, with the bytes a request; none for an agent that sent nothing
|
||||
const tables = await box.locator(".led-up-by").evaluateAll((ts) => ts.map((tb) => [...tb.querySelectorAll("tr")].map((tr) => [...tr.children].map((c) => c.textContent.trim()))));
|
||||
assert.deepEqual(tables, [
|
||||
[[w.agent, tables[0][0][1], tables[0][0][2]], ["Codex", "6.5 GB", "1.6 MB"], ["Claude Code", "2.1 GB", "525 KB"]],
|
||||
[[w.model, tables[1][0][1], tables[1][0][2]], ["gpt-5", "6.5 GB", "1.6 MB"], ["claude-sonnet", "2.1 GB", "525 KB"]],
|
||||
]);
|
||||
const sideways = await p.evaluate(() => [document.documentElement.scrollWidth - innerWidth, ...[...document.querySelectorAll("#ledKpi .blk, #ledUp")].map((b) => b.scrollWidth - b.clientWidth)]);
|
||||
assert(sideways.every((n) => n <= 1), `scrolls sideways: ${sideways}`);
|
||||
|
||||
// a request's details: what its bytes were made of; one without parts, nothing
|
||||
const rows = p.locator(".led tbody tr.led-row");
|
||||
const pairs = () => p.locator("#ledReqPane .led-detail").evaluate((d) => Object.fromEntries([...d.querySelectorAll("dt")].map((dt) => [dt.textContent, dt.nextElementSibling.textContent])));
|
||||
await reader.click(p, rows.nth(0));
|
||||
await p.locator("#ledReqPane .led-detail").waitFor();
|
||||
assert.equal((await pairs())[w.made], `${w.conv} 750 KB · ${w.tools} 50 KB · ${w.system} 200 KB`);
|
||||
await reader.closeRequest(p);
|
||||
await reader.click(p, rows.nth(1));
|
||||
await p.locator("#ledReqPane .led-detail").waitFor();
|
||||
assert(!(w.made in (await pairs())), "a row with no parts says what it was made of");
|
||||
await reader.closeRequest(p);
|
||||
|
||||
// kept open across a reload, closed from its ×
|
||||
const state = await ctx.storageState();
|
||||
const again = await open(browser, lang, width, true, state);
|
||||
await again.p.locator("#ledUp").waitFor();
|
||||
assert.equal(await again.p.locator("#ledKpi .led-up-open").getAttribute("aria-expanded"), "true");
|
||||
await again.p.locator("#ledUp .led-up-x").click();
|
||||
assert.equal(await again.p.locator("#ledUp").isVisible(), false);
|
||||
assert.equal(await again.p.locator("#ledKpi .led-up-open").getAttribute("aria-expanded"), "false");
|
||||
assert.deepEqual([...errors, ...again.errors], []);
|
||||
await again.ctx.close();
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
await t.test(lang + " nothing sent", async () => {
|
||||
const { ctx, p, errors } = await open(browser, lang, 1180, false);
|
||||
assert.equal(await p.locator("#ledKpi .led-up-open").count(), 0);
|
||||
assert.equal(await p.locator("#ledUp").isVisible(), false);
|
||||
assert.deepEqual(errors, []);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -34,7 +34,7 @@ import (
|
||||
// history again on its first start, the cold start's peak (#2278). Raise
|
||||
// it with any change to what a row counts as; TestSettledCountedAsVersioned
|
||||
// fails until it is raised.
|
||||
const settledCountVersion = "4"
|
||||
const settledCountVersion = "5"
|
||||
|
||||
func heatDiskPath() string {
|
||||
return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-v1.json")
|
||||
@@ -249,10 +249,14 @@ func hashRows(h hash.Hash, c *rowChunk) {
|
||||
b = binary.AppendVarint(b, p.RouteID)
|
||||
b = binary.AppendUvarint(b, math.Float64bits(p.Cost))
|
||||
b = binary.AppendUvarint(b, math.Float64bits(p.Credits))
|
||||
for _, v := range [...]int32{p.Millis, p.TTFT, p.FirstText, p.Sent, p.Flow, p.FirstReasoning, p.Own, p.Retried, p.Queued, p.Masking, p.Status, int32(p.Tries), p.UpBytes, p.DownBytes, p.FilesSaved} {
|
||||
for _, v := range [...]int32{p.Millis, p.TTFT, p.FirstText, p.Sent, p.Flow, p.FirstReasoning, p.Own, p.Retried, p.Queued, p.Masking, int32(p.Status), int32(p.Tries), p.UpBytes, p.DownBytes, p.FilesSaved} {
|
||||
b = binary.AppendVarint(b, int64(v))
|
||||
}
|
||||
b = binary.AppendUvarint(b, uint64(p.Flags))
|
||||
if p.Flags&rowUpParts != 0 {
|
||||
// only where kept, so a row from before hashes as it did
|
||||
b = append(b, p.upMix[:]...)
|
||||
}
|
||||
if len(b) > 30<<10 {
|
||||
h.Write(b)
|
||||
b = b[:0]
|
||||
|
||||
@@ -956,9 +956,7 @@ func (t *Totals) plus(d *Totals) {
|
||||
t.FloorOut += d.FloorOut
|
||||
t.FloorMs += d.FloorMs
|
||||
t.FloorN += d.FloorN
|
||||
t.UpBytes += d.UpBytes
|
||||
t.DownBytes += d.DownBytes
|
||||
t.ImageFilesSaved += d.ImageFilesSaved
|
||||
t.plusBytes(d)
|
||||
}
|
||||
|
||||
// FloorAgents are the agents whose session files time a call from what
|
||||
|
||||
@@ -93,16 +93,20 @@ type packedRow struct {
|
||||
Sent, Flow, FirstReasoning int32
|
||||
Own, Retried, Queued int32
|
||||
Masking int32 // ms (Record.Masking)
|
||||
Status int32
|
||||
// Tries and ImageFiles in 16 bits, so the row is no larger than its
|
||||
// 152 bytes before the count was kept: neither comes near 32767
|
||||
// (smallOf)
|
||||
Tries, ImageFiles int16
|
||||
// the bytes up and down (Record.UpBytes, DownBytes, ImageFilesSaved),
|
||||
// in 32 bits as Masking: 2GiB is past any request a vendor takes
|
||||
UpBytes, DownBytes, FilesSaved int32
|
||||
Flags uint16
|
||||
zone uint16
|
||||
// Status and ImageFiles in 16 bits, and Tries in 8, so the row is no
|
||||
// larger than its 152 bytes before the counts and upMix were kept:
|
||||
// no status passes 32767, no request 32767 images or 255 tries
|
||||
// (smallOf, tinyOf)
|
||||
Status, ImageFiles int16
|
||||
Flags uint16
|
||||
zone uint16
|
||||
Tries uint8
|
||||
// upMix is Record.UpParts, each part's share of UpBytes in 255ths
|
||||
// (upMixOf), where Flags has rowUpParts
|
||||
upMix [3]uint8
|
||||
}
|
||||
|
||||
// rowZones are the zones rows' times are in, by a row's zone; 0 is the
|
||||
@@ -227,6 +231,26 @@ const rowCacheUnknown = 8192
|
||||
// rowSocket is the Flags bit of Record.Socket.
|
||||
const rowSocket = 16384
|
||||
|
||||
// rowUpParts marks a row that kept what its bytes up were made of
|
||||
// (Record.UpParts, packedRow.upMix).
|
||||
const rowUpParts = 32768
|
||||
|
||||
// upMixOf is u's parts as shares of up in 255ths, for a packed row: a
|
||||
// part rounds to the nearest 255th of the request, so the sums of many
|
||||
// rows stay within a fraction of a percent.
|
||||
func upMixOf(u *UpParts, up int) (m [3]uint8) {
|
||||
for i, n := range [3]int{u.System, u.Tools, u.Images} {
|
||||
m[i] = uint8(min(max((n*255+up/2)/up, 0), 255))
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// upPartsOf is what upMixOf kept, as bytes of up.
|
||||
func upPartsOf(m [3]uint8, up int) *UpParts {
|
||||
part := func(i int) int { return up * int(m[i]) / 255 }
|
||||
return &UpParts{System: part(0), Tools: part(1), Images: part(2)}
|
||||
}
|
||||
|
||||
type rowChunk struct {
|
||||
Archive []byte
|
||||
Locations []*time.Location
|
||||
@@ -356,7 +380,7 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
|
||||
c.Bytes += int64(len(s) + 48)
|
||||
return id
|
||||
}
|
||||
p := packedRow{Tokens: [6]int32{tokensOf(int64(r.Input)), tokensOf(int64(r.Output)), tokensOf(int64(r.CacheRead)), tokensOf(int64(r.CacheWrite)), tokensOf(int64(r.Reasoning)), tokensOf(int64(r.CacheWrite1h))}, Millis: msOf(r.Millis), TTFT: msOf(r.TTFT), FirstText: msOf(r.FirstText), FirstReasoning: msOf(r.FirstReasoning), Sent: msOf(r.Sent), Flow: msOf(r.Flow), Own: msOf(r.Own), Masking: int32(min(r.Masking, math.MaxInt32)), Retried: msOf(r.Retried), Queued: msOf(r.Queued), Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: int32(r.Status), Tries: smallOf(r.Tries), ImageFiles: smallOf(r.ImageFiles), UpBytes: bytesOf(r.UpBytes), DownBytes: bytesOf(r.DownBytes), FilesSaved: bytesOf(r.ImageFilesSaved)}
|
||||
p := packedRow{Tokens: [6]int32{tokensOf(int64(r.Input)), tokensOf(int64(r.Output)), tokensOf(int64(r.CacheRead)), tokensOf(int64(r.CacheWrite)), tokensOf(int64(r.Reasoning)), tokensOf(int64(r.CacheWrite1h))}, Millis: msOf(r.Millis), TTFT: msOf(r.TTFT), FirstText: msOf(r.FirstText), FirstReasoning: msOf(r.FirstReasoning), Sent: msOf(r.Sent), Flow: msOf(r.Flow), Own: msOf(r.Own), Masking: int32(min(r.Masking, math.MaxInt32)), Retried: msOf(r.Retried), Queued: msOf(r.Queued), Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: smallOf(r.Status), Tries: tinyOf(r.Tries), ImageFiles: smallOf(r.ImageFiles), UpBytes: bytesOf(r.UpBytes), DownBytes: bytesOf(r.DownBytes), FilesSaved: bytesOf(r.ImageFilesSaved)}
|
||||
p.setTime(r.Time)
|
||||
var t [rowTexts]uint32
|
||||
for i, s := range rowText(&r) {
|
||||
@@ -388,6 +412,10 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
|
||||
if r.Socket {
|
||||
p.Flags |= rowSocket
|
||||
}
|
||||
if r.UpParts != nil && p.UpBytes > 0 {
|
||||
p.Flags |= rowUpParts
|
||||
p.upMix = upMixOf(r.UpParts, int(p.UpBytes))
|
||||
}
|
||||
if failed {
|
||||
p.Flags |= 16
|
||||
}
|
||||
@@ -435,6 +463,11 @@ func smallOf(n int) int16 {
|
||||
return int16(max(min(n, math.MaxInt16), 0))
|
||||
}
|
||||
|
||||
// tinyOf is a count of tries in a packed row's 8 bits, as smallOf.
|
||||
func tinyOf(n int) uint8 {
|
||||
return uint8(max(min(n, math.MaxUint8), 0))
|
||||
}
|
||||
|
||||
func (c *rowChunk) row(i int) Row {
|
||||
p := &c.Rows[i]
|
||||
r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time(), Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: int64(p.Millis), TTFT: int64(p.TTFT), FirstText: int64(p.FirstText), FirstReasoning: int64(p.FirstReasoning), ReasoningHidden: p.Flags&rowReasoningHidden != 0, CacheUnknown: p.Flags&rowCacheUnknown != 0, Socket: p.Flags&rowSocket != 0, Sent: int64(p.Sent), Flow: int64(p.Flow), Own: int64(p.Own), Masking: int64(p.Masking), Retried: int64(p.Retried), Queued: int64(p.Queued), Status: int(p.Status), Tries: int(p.Tries), UpBytes: int(p.UpBytes), DownBytes: int(p.DownBytes), ImageFilesSaved: int(p.FilesSaved), ImageFiles: int(p.ImageFiles), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
|
||||
@@ -442,6 +475,9 @@ func (c *rowChunk) row(i int) Row {
|
||||
credits := p.Credits
|
||||
r.Credits = &credits
|
||||
}
|
||||
if p.Flags&rowUpParts != 0 && p.UpBytes > 0 {
|
||||
r.UpParts = upPartsOf(p.upMix, int(p.UpBytes))
|
||||
}
|
||||
if p.Flags&rowCompactionKnown != 0 {
|
||||
compacted := p.Flags&rowCompaction != 0
|
||||
r.Compaction = &compacted
|
||||
|
||||
@@ -101,6 +101,9 @@ func (c *rowChunk) encode(keep func([]byte) bool) ([]byte, []*time.Location) {
|
||||
put(uint64(p.DownBytes))
|
||||
put(uint64(int64(p.FilesSaved)))
|
||||
put(uint64(p.ImageFiles))
|
||||
if p.Flags&rowUpParts != 0 {
|
||||
put(uint64(p.upMix[0]) | uint64(p.upMix[1])<<8 | uint64(p.upMix[2])<<16)
|
||||
}
|
||||
if p.Flags&rowCredits != 0 {
|
||||
put(math.Float64bits(p.Credits))
|
||||
}
|
||||
@@ -301,11 +304,16 @@ func (c *rowChunk) unpackReusing(dst *rowChunk, into []packedRow, strs []string,
|
||||
p.Sent, p.Flow = msOf(int64(take())), msOf(int64(take()))
|
||||
p.Own, p.Retried, p.Queued = msOf(int64(take())), msOf(int64(take())), msOf(int64(take()))
|
||||
p.FirstReasoning = msOf(int64(take()))
|
||||
p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int32(take()), uint16(take())
|
||||
p.Tries = int16(take())
|
||||
p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int16(take()), uint16(take())
|
||||
p.Tries = uint8(take())
|
||||
p.Masking = int32(take())
|
||||
p.UpBytes, p.DownBytes, p.FilesSaved = int32(take()), int32(take()), int32(take())
|
||||
p.ImageFiles = int16(take())
|
||||
p.upMix = [3]uint8{}
|
||||
if p.Flags&rowUpParts != 0 {
|
||||
m := take()
|
||||
p.upMix = [3]uint8{uint8(m), uint8(m >> 8), uint8(m >> 16)}
|
||||
}
|
||||
p.Credits = 0
|
||||
if p.Flags&rowCredits != 0 {
|
||||
p.Credits = math.Float64frombits(take())
|
||||
|
||||
@@ -151,7 +151,7 @@ func TestRowImageFilesKept(t *testing.T) {
|
||||
if a.ImageFiles != 3 || a.ImageFilesSaved != 10_000_000 || a.Tries != 2 {
|
||||
t.Fatalf("%d: read back %d images, saved %d, %d tries", i, a.ImageFiles, a.ImageFilesSaved, a.Tries)
|
||||
}
|
||||
if b.ImageFiles != math.MaxInt16 || b.Tries != math.MaxInt16 {
|
||||
if b.ImageFiles != math.MaxInt16 || b.Tries != math.MaxUint8 {
|
||||
t.Fatalf("%d: past the most read back %d images, %d tries", i, b.ImageFiles, b.Tries)
|
||||
}
|
||||
if old.ImageFiles != 0 {
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
// settled days, under settledCountVersion. A change that counts them
|
||||
// otherwise changes it: raise settledCountVersion and set this to the new
|
||||
// hash in the same commit.
|
||||
const settledCounted = "8715ad3d4bdd7a48a9d882be5a089b17231152b10abc3d278e17070e879f107c"
|
||||
const settledCounted = "e27e12fd0fb0b8589936f2a562ae602f0cc2f1368d2e7a8f4668cdff6afe5952"
|
||||
|
||||
// The settled days, a page's cells and Codex's effort are kept on disk
|
||||
// under settledCountVersion, not under this package's source: an upgrade
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// A row keeps what its bytes up were made of (Record.UpParts) in 255ths
|
||||
// of them, packed and read back, so each part is within a 255th of the
|
||||
// request; a row that kept none reads back none, and keeping it made no
|
||||
// row larger. usage.jsonl has the parts as they were.
|
||||
func TestRowUpPartsKept(t *testing.T) {
|
||||
at := time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC)
|
||||
parts := UpParts{System: 120_000, Tools: 40_000, Images: 1_000}
|
||||
c := &rowChunk{}
|
||||
c.add(Row{Record: Record{Time: at, UpBytes: 1_000_000, UpParts: &parts, Tries: 3, Status: 529}}, "", 0, false)
|
||||
c.add(Row{Record: Record{Time: at, UpBytes: 1_000_000}}, "", 1, false)
|
||||
c.add(Row{Record: Record{Time: at, UpParts: &parts}}, "", 2, false) // nothing went up: no parts to be shares of
|
||||
for i, c := range []*rowChunk{c, c.pack().unpack()} {
|
||||
a, old, none := c.row(0), c.row(1), c.row(2)
|
||||
u := a.UpParts
|
||||
if u == nil {
|
||||
t.Fatalf("%d: the parts weren't kept", i)
|
||||
}
|
||||
for _, p := range [][2]int{{u.System, parts.System}, {u.Tools, parts.Tools}, {u.Images, parts.Images}} {
|
||||
if d := p[0] - p[1]; d < -1_000_000/255 || d > 1_000_000/255 {
|
||||
t.Fatalf("%d: read back %+v, was %+v", i, *u, parts)
|
||||
}
|
||||
}
|
||||
if a.Tries != 3 || a.Status != 529 {
|
||||
t.Fatalf("%d: beside them, %d tries and status %d", i, a.Tries, a.Status)
|
||||
}
|
||||
if old.UpParts != nil || none.UpParts != nil {
|
||||
t.Fatalf("%d: a row without parts reads back %+v, %+v", i, old.UpParts, none.UpParts)
|
||||
}
|
||||
}
|
||||
if n := unsafe.Sizeof(packedRow{}); n != 152 {
|
||||
t.Fatalf("a packed row is %d bytes, was 152", n)
|
||||
}
|
||||
line, _ := json.Marshal(Record{Time: at, UpBytes: 9, UpParts: &UpParts{System: 4}})
|
||||
var back Record
|
||||
if err := json.Unmarshal(line, &back); err != nil || back.UpParts == nil || back.UpParts.System != 4 || !strings.Contains(string(line), `"up_parts":{"system":4}`) {
|
||||
t.Fatalf("usage.jsonl's line %s read back %+v (%v)", line, back.UpParts, err)
|
||||
}
|
||||
if line, _ := json.Marshal(Record{Time: at, UpBytes: 9}); strings.Contains(string(line), "up_parts") {
|
||||
t.Fatalf("a row with no parts says some: %s", line)
|
||||
}
|
||||
}
|
||||
|
||||
// A period's totals, and each agent's, say what their bytes up were made
|
||||
// of: how many requests sent any (for the bytes a request), the bytes of
|
||||
// those whose parts were read, and the parts summed. From the rows and
|
||||
// from the request page's cells alike, and from records.
|
||||
func TestTotalsSumUpParts(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: 2550, UpParts: &UpParts{System: 510, Tools: 1020}, Status: 200},
|
||||
{Time: now, Provider: "a", Agent: "codex", Model: "m", Input: 10, UpBytes: 5100, UpParts: &UpParts{Images: 2600}, Status: 200},
|
||||
{Time: now, Provider: "b", Agent: "claude", Model: "n", Input: 10, UpBytes: 700, Status: 200}, // not read
|
||||
{Time: now, Provider: "b", Agent: "claude", Model: "n", Input: 10, Status: 200}, // nothing went
|
||||
}
|
||||
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)
|
||||
}
|
||||
page := buildRequestPage(Today, Filter{}, 0, 100, gateway, nil)
|
||||
var recs, rows, sum Totals
|
||||
for _, r := range records {
|
||||
recs.add(r, nil)
|
||||
}
|
||||
for _, r := range all.Rows {
|
||||
rows.addRow(r)
|
||||
}
|
||||
sum.plus(&rows)
|
||||
for name, s := range map[string]Totals{"page": page.Sum, "records": recs, "rows": rows, "plus": sum} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if s.UpBytes != 8350 || s.UpCalls != 3 || s.UpMeasured != 7650 || s.UpSystem != 510 || s.UpTools != 1020 || s.UpImages != 2600 {
|
||||
t.Fatalf("the period: %+v", s)
|
||||
}
|
||||
})
|
||||
}
|
||||
agents := map[string]Totals{}
|
||||
for _, sh := range page.By["agent"] {
|
||||
agents[sh.ID] = sh.Totals
|
||||
}
|
||||
if c := agents["codex"]; c.UpCalls != 2 || c.UpMeasured != 7650 || c.UpImages != 2600 {
|
||||
t.Fatalf("codex: %+v", c)
|
||||
}
|
||||
if c := agents["claude"]; c.UpCalls != 1 || c.UpMeasured != 0 || c.UpBytes != 700 {
|
||||
t.Fatalf("claude: %+v", c)
|
||||
}
|
||||
}
|
||||
@@ -229,6 +229,11 @@ type Record struct {
|
||||
// what ImageFilesSaved was saved on (matrix0487 on Discord). None in a
|
||||
// row from before it was kept.
|
||||
ImageFiles int `json:"image_files,omitempty"`
|
||||
// UpParts is what UpBytes was made of, where the body was read to
|
||||
// know (UpParts); nil where it wasn't: a socket's delta, a request
|
||||
// whose images went by file, a row from before it was kept
|
||||
// (theforeveriris on X: 8.6 GB up from plain-text projects).
|
||||
UpParts *UpParts `json:"up_parts,omitempty"`
|
||||
// Socket says the request went over the Responses WebSocket, its
|
||||
// last try (provider.Socket, matrix0487 on Discord): UpBytes is then
|
||||
// what the socket was sent, a delta on a kept socket.
|
||||
@@ -612,6 +617,27 @@ type Totals struct {
|
||||
UpBytes int64 `json:"up_bytes,omitempty"`
|
||||
DownBytes int64 `json:"down_bytes,omitempty"`
|
||||
ImageFilesSaved int64 `json:"image_files_saved,omitempty"`
|
||||
// UpCalls is how many rows sent any bytes up, what UpBytes is spread
|
||||
// over; UpMeasured the bytes of those whose parts were read
|
||||
// (Record.UpParts), and UpSystem, UpTools and UpImages those parts
|
||||
// summed: the conversation is UpMeasured less the three
|
||||
UpCalls int `json:"up_calls,omitempty"`
|
||||
UpMeasured int64 `json:"up_measured,omitempty"`
|
||||
UpSystem int64 `json:"up_system,omitempty"`
|
||||
UpTools int64 `json:"up_tools,omitempty"`
|
||||
UpImages int64 `json:"up_images,omitempty"`
|
||||
}
|
||||
|
||||
// UpParts is a request's bytes up by what they were: the agent's own
|
||||
// prompt and instructions (system prompt, skills, memory), the tools'
|
||||
// definitions, and the images and documents it sent inline, each scaled
|
||||
// to the bytes that went up (Record.UpBytes). The rest is the
|
||||
// conversation: the messages, the tool calls and their results, which an
|
||||
// agent sends again whole on every request.
|
||||
type UpParts struct {
|
||||
System int `json:"system,omitempty"`
|
||||
Tools int `json:"tools,omitempty"`
|
||||
Images int `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
// addBytes adds r's bytes on the wire (Totals.UpBytes …).
|
||||
@@ -619,6 +645,27 @@ func (t *Totals) addBytes(r *Record) {
|
||||
t.UpBytes += int64(r.UpBytes)
|
||||
t.DownBytes += int64(r.DownBytes)
|
||||
t.ImageFilesSaved += int64(r.ImageFilesSaved)
|
||||
if r.UpBytes > 0 {
|
||||
t.UpCalls++
|
||||
if u := r.UpParts; u != nil {
|
||||
t.UpMeasured += int64(r.UpBytes)
|
||||
t.UpSystem += int64(u.System)
|
||||
t.UpTools += int64(u.Tools)
|
||||
t.UpImages += int64(u.Images)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// plusBytes adds what addBytes counted of another sum.
|
||||
func (t *Totals) plusBytes(d *Totals) {
|
||||
t.UpBytes += d.UpBytes
|
||||
t.DownBytes += d.DownBytes
|
||||
t.ImageFilesSaved += d.ImageFilesSaved
|
||||
t.UpCalls += d.UpCalls
|
||||
t.UpMeasured += d.UpMeasured
|
||||
t.UpSystem += d.UpSystem
|
||||
t.UpTools += d.UpTools
|
||||
t.UpImages += d.UpImages
|
||||
}
|
||||
|
||||
// Tokens is what went in and out, excluding cache traffic.
|
||||
|
||||
Reference in New Issue
Block a user