diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index b5b5d5196..ed3ebb0a5 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1237,7 +1237,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st sent = provider.CodexCompressed(req, body) // counted for the request's ledger row, as forwardOnce's are (#4456) sentUp(r.Context(), sent, len(body)) - if res, err = s.client.Do(req); err != nil { + res, err = s.client.Do(req) + res = gotDown(r.Context(), res) + if err != nil { msg := "OpenAI: " + err.Error() if overload && busyAgain < lastRetries && droppedUnanswered(r.Context(), err) { // the connection closed with nothing of a reply (a @@ -1588,6 +1590,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st failedWith(&rec, call.Status, call.Error, errType) if up := upBytesOf(r.Context()); up != nil { rec.UpBytes, rec.PlainBytes = up.wire, up.plain + rec.DownBytes = up.downOf() } appendUsage(r, rec) } diff --git a/internal/gateway/deepseek_files.go b/internal/gateway/deepseek_files.go index 768bb27c8..77397855f 100644 --- a/internal/gateway/deepseek_files.go +++ b/internal/gateway/deepseek_files.go @@ -329,6 +329,10 @@ func (s *Server) withDeepSeekFiles(ctx context.Context, p provider.Provider, to sent.keys = append(sent.keys, k) } } + if u := upBytesOf(ctx); u != nil { + // the inline images this try left out, for the request's row + u.saved += len(body) - len(out) + } return out, true } @@ -445,6 +449,7 @@ func (s *Server) dsResolve(ctx context.Context, p provider.Provider, to provider } if u := upBytesOf(ctx); u != nil { u.wire += up + u.saved -= up // and are what the files cost it } } return ids diff --git a/internal/gateway/deepseek_files_test.go b/internal/gateway/deepseek_files_test.go index 47ea8ecf9..ef30ab990 100644 --- a/internal/gateway/deepseek_files_test.go +++ b/internal/gateway/deepseek_files_test.go @@ -16,6 +16,7 @@ import ( "time" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" ) const responsesWholeOK = `{"id":"resp_1","object":"response","status":"completed","model":"m1","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok","annotations":[]}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}` @@ -450,3 +451,53 @@ func dsWaitingFlights() map[string]*dsFlight { defer st.mu.Unlock() return maps.Clone(st.flights) } + +// A row says what DeepSeek's image files saved the request: the inline +// image its body left out, less the upload that put it up. The turn that +// uploads keeps the image's base64 out and pays for the upload; the next +// turn only keeps it out. Each row's bytes up and saved add up to what +// the turn would have sent inline (faithleysath, matrix0487 on Discord). +func TestDeepSeekImageFilesSavedInRow(t *testing.T) { + s, u := dsSetup(t) + img := base64.StdEncoding.EncodeToString([]byte("\x89PNG\r\n\x1a\n" + strings.Repeat("an image's pixels ", 3000))) + path, upPath, body := dsBody("chat", "deepseek/deepseek-flash", img) + var rows []usage.Record + for turn := range 2 { + if code, reply := postTo(t, s, path, body); code != 200 { + t.Fatalf("turn %d: %d %s", turn, code, reply) + } + if strings.Contains(u.last(upPath), img) { + t.Fatalf("turn %d went inline", turn) + } + deadline := time.Now().Add(10 * time.Second) + for { + rows = rows[:0] + for _, r := range usage.Load(time.Time{}) { + if r.Provider == "deepseek" && !r.HandedOn { + rows = append(rows, r) + } + } + if len(rows) == turn+1 || time.Now().After(deadline) { + break + } + time.Sleep(20 * time.Millisecond) + } + if len(rows) != turn+1 { + t.Fatalf("turn %d: rows %+v", turn, rows) + } + } + if len(u.uploaded()) != 1 { + t.Fatalf("uploads %v", u.uploaded()) + } + upload := len(img) / 4 * 3 + first, second := rows[0], rows[1] + if second.ImageFilesSaved < len(img)*9/10 || second.ImageFilesSaved > len(img)+200 { // the base64, its data: URL and block, less the file block + t.Fatalf("the second turn saved %d of an image of %d base64 bytes", second.ImageFilesSaved, len(img)) + } + if first.ImageFilesSaved != second.ImageFilesSaved-upload { + t.Fatalf("the first turn saved %d; the second %d, less the upload's %d", first.ImageFilesSaved, second.ImageFilesSaved, upload) + } + if a, b := first.UpBytes+first.ImageFilesSaved, second.UpBytes+second.ImageFilesSaved; a != b || a <= len(img) { + t.Fatalf("up and saved come to %d and %d, the inline turn's bytes (image %d)", a, b, len(img)) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2168257a2..31bdabbef 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5052,6 +5052,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 = up.wire, up.plain + rec.DownBytes, rec.ImageFilesSaved = up.downOf(), up.saved } failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) withBodies(&rec, &call) @@ -5728,9 +5729,12 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid n = int(r.ContentLength) } sentUp(ctx, n, len(body)) - return p.Do(s.client, r) + res, err := p.Do(s.client, r) + return gotDown(ctx, res), err } res, err := p.Do(s.client, req) + // what comes back is counted as it is read, as what went is (#4456) + res = gotDown(ctx, res) if err == nil && res.StatusCode >= 400 && provider.OpenCodeURL(req.URL.String()) { logOpenCodeRefusal(p, req, res.StatusCode) } diff --git a/internal/gateway/upbytes.go b/internal/gateway/upbytes.go index 8d1e3592c..a173221b0 100644 --- a/internal/gateway/upbytes.go +++ b/internal/gateway/upbytes.go @@ -1,6 +1,11 @@ package gateway -import "context" +import ( + "context" + "io" + "net/http" + "sync/atomic" +) // upBytes is what a request's tries sent up to the vendor, kept in the // request's context as a tool call's mcpUse is: forwardOnce adds a try's @@ -10,6 +15,13 @@ import "context" type upBytes struct { wire int // the bytes that went on the wire, tries summed plain int // the last try's body before compression + // down is the bytes of the vendor's replies read, tries summed: added + // as a body is read, which can be on another goroutine than the + // request's (a stream's pump), so atomic + down atomic.Int64 + // saved is what DeepSeek's image files kept out of the tries' bodies, + // less what uploading them cost this request (withDeepSeekFiles) + saved int } type upBytesKey struct{} @@ -29,3 +41,31 @@ func sentUp(ctx context.Context, wire, plain int) { u.plain = plain } } + +// gotDown counts res's body for the request's ledger row as it is read +// (upBytes.down), and gives res back. A body is counted as Go's client +// hands it over: after the transport undid a gzip it asked for, so a +// gzipped reply counts more than its wire bytes. A 101's body is the +// connection itself and is left as it is. +func gotDown(ctx context.Context, res *http.Response) *http.Response { + u := upBytesOf(ctx) + if u == nil || res == nil || res.Body == nil || res.Body == http.NoBody || res.StatusCode == http.StatusSwitchingProtocols { + return res + } + res.Body = &downCount{ReadCloser: res.Body, u: u} + return res +} + +type downCount struct { + io.ReadCloser + u *upBytes +} + +func (d *downCount) Read(b []byte) (int, error) { + n, err := d.ReadCloser.Read(b) + d.u.down.Add(int64(n)) + return n, err +} + +// downOf is the reply bytes counted so far (upBytes.down). +func (u *upBytes) downOf() int { return int(u.down.Load()) } diff --git a/internal/gateway/upbytes_test.go b/internal/gateway/upbytes_test.go index ec6ace960..d528056e7 100644 --- a/internal/gateway/upbytes_test.go +++ b/internal/gateway/upbytes_test.go @@ -1,10 +1,12 @@ package gateway import ( + "fmt" "io" "net/http" "net/http/httptest" "strings" + "sync" "testing" "time" @@ -93,7 +95,7 @@ func TestLedgerKeepsUpBytes(t *testing.T) { func TestCodexOwnTurnKeepsUpBytes(t *testing.T) { setup(t, provider.Chat, &fake{t: t}) zstdTurns(t) - var wire, plain int + var wire, plain, down int chatgpt(t, func(w http.ResponseWriter, r *http.Request) { b, _ := io.ReadAll(r.Body) wire = len(b) @@ -108,7 +110,8 @@ func TestCodexOwnTurnKeepsUpBytes(t *testing.T) { } plain = len(p) w.Header().Set("Content-Type", "text/event-stream") - io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9,"output_tokens":2}}}`)) + n, _ := io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9,"output_tokens":2}}}`)) + down = n }) codexChatGPTAuth(t, "me@example.com") rec := httptest.NewRecorder() @@ -129,6 +132,9 @@ func TestCodexOwnTurnKeepsUpBytes(t *testing.T) { if u[0].UpBytes != wire || u[0].PlainBytes != plain { t.Fatalf("row says up %d plain %d; the backend got %d of %d", u[0].UpBytes, u[0].PlainBytes, wire, plain) } + if u[0].DownBytes != down { + t.Fatalf("row says down %d; the backend answered %d bytes", u[0].DownBytes, down) + } } // A request asked again inside one try — Aloha's relay refusing both key @@ -180,3 +186,87 @@ func TestLedgerCountsATrysSecondAsk(t *testing.T) { t.Fatalf("row says up %d plain %d; the relay got %v", rows[0].UpBytes, rows[0].PlainBytes, sizes) } } + +// rowOf is the row a request ended with (not a try that handed it on), +// once it is in the ledger. +func rowOf(t *testing.T, of func(usage.Record) bool) usage.Record { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + var rows []usage.Record + for _, u := range usage.Load(time.Time{}) { + if of(u) && !u.HandedOn { + rows = append(rows, u) + } + } + if len(rows) == 1 { + return rows[0] + } + if len(rows) > 1 || time.Now().After(deadline) { + t.Fatalf("the request's rows: %+v", rows) + } + time.Sleep(20 * time.Millisecond) + } +} + +// A request's row says what came back down as well as what went up: +// DownBytes the bytes of the vendors' replies magpie read, its tries +// summed, the overloaded member's refusal too, whole or streamed +// (faithleysath, matrix0487 on Discord). Before, a row had none. +func TestLedgerKeepsDownBytes(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) + var mu sync.Mutex + served := 0 + serve := func(w http.ResponseWriter, s string) { + n, _ := io.WriteString(w, s) + mu.Lock() + served += n + mu.Unlock() + } + 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) + serve(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") + serve(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") + serve(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() + 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 }) + mu.Lock() + want := served + mu.Unlock() + if row.Tries != 2 || row.DownBytes != want { + t.Fatalf("row: tries %d, down %d; the vendors answered %d bytes", row.Tries, row.DownBytes, want) + } + }) + } +} diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index 2299faa90..c4a0563e2 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -2,6 +2,8 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "Saved by image files": "图片文件省下", + "{n} saved by image files": "图片文件省下 {n}", "Show in Overview": "在概览中显示", "Show {n} Hidden": "显示已隐藏的 {n} 个", "Hide from Overview": "从概览中隐藏", @@ -243,6 +245,8 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同", }, "zh-TW": { + "Saved by image files": "圖片檔案省下", + "{n} saved by image files": "圖片檔案省下 {n}", "Show in Overview": "在概覽中顯示", "Show {n} Hidden": "顯示已隱藏的 {n} 個", "Hide from Overview": "從概覽中隱藏", @@ -484,6 +488,8 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同", }, ja: { + "Saved by image files": "画像ファイルで節約", + "{n} saved by image files": "画像ファイルで {n} 節約", "Show in Overview": "概要に表示", "Show {n} Hidden": "非表示の {n} 件を表示", "Hide from Overview": "概要から隠す", @@ -725,6 +731,8 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信", }, de: { + "Saved by image files": "Durch Bilddateien gespart", + "{n} saved by image files": "{n} durch Bilddateien gespart", "Show in Overview": "In der Übersicht einblenden", "Show {n} Hidden": "{n} ausgeblendete anzeigen", "Hide from Overview": "In der Übersicht ausblenden", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 335081450..d9674c75f 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -1403,6 +1403,12 @@ function ledDetail(r, cols) { if (r.credits != null) add("Credits", ledCredits({ credits: r.credits, credited: 1 }).textContent); if (ledRowSpeed(r)) add("Speed", t("{n} tok/s", { n: ledNum(Math.round(ledRowSpeed(r))) })); else if (ledFloorSpeed(r)) add("Speed", "≥" + t("{n} tok/s", { n: ledNum(Math.round(ledFloorSpeed(r))) })); + // what went up to the vendor and came back, its tries summed, and what + // 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)); + if (r.down_bytes > 0) add("Received", fmtBytes(r.down_bytes)); + if (r.image_files_saved > 0) add("Saved by image files", fmtBytes(r.image_files_saved)); add("Request ID", r.rid); add("Endpoint", r.ep); const protos = ledProtos(r); @@ -1632,6 +1638,14 @@ function renderLedgerDash(l) { ? jumps(jump(t("{n} failed", { n: fmtN(l.errors) }), "failed", t("Show only the failed requests")), " · " + t("{p} succeeded", { p: (100 * (1 - l.errors / l.calls)).toFixed(1) + "%" })) : line(t("none failed")), "", exactN(l.calls)); if (l.retried) strip.lastChild.append(jumps(jump(t("{n} answered on a retry", { n: fmtN(l.retried) }), "retried", t("Show only the requests answered on a retry")))); + // the period's traffic, of the requests that kept it: up and down, and + // what DeepSeek's image files saved on the way up + if (l.up_bytes > 0 || l.down_bytes > 0) { + const io = line("↑ " + 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("led-io"); + io.title = t("Sent upstream") + ": " + ledNum(l.up_bytes || 0) + " B\n" + t("Received") + ": " + ledNum(l.down_bytes || 0) + " B"; + strip.lastChild.append(io); + } const c = fmtCost(l); block("Cost", c ? "≈" + c : "—", line(l.unpriced ? t(l.unpriced === 1 ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: l.unpriced }) : t("effective prices")), c ? "cost" : ""); const hit = block("Cache hit rate", rate === null ? "—" : (100 * rate).toFixed(1) + "%", cacheLeftOut(l) ? line(cacheLeftOut(l)) : null, "", t("The share of the prompt read from the cache")); diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 7c86b232c..7c2d2a047 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -1251,6 +1251,15 @@ status; its models are the one asked for, the one sent as asked and the one that do the same, text selected in the details is not a click, and the rows stay open when the list is asked for again; in English and Chinese. +`usage-ledger-bytes.test.cjs` checks that Requests says what a request sent +up and got back (faithleysath): a row's details name "Sent upstream", +"Received" and what DeepSeek's image files saved (#5407), a row from before +they were kept shows none of them, and a saving below 0 shows none. Under +the Requests card the period reads "↑ up · ↓ down" with the saving beside +it, and nothing for a period with no bytes. At 1180 and 420 wide nothing +scrolls sideways; Chromium and WebKit, every language. The old page.js +shows it failing. + `ledger-cache-tokens.test.cjs` (#1839) opens a request's details and finds its tokens there at every width: in, out, cache read and cache creation, 0 said as 0 for a prompt that missed the cache, with what was written for an hour; a diff --git a/internal/gui/tests/usage-ledger-bytes.test.cjs b/internal/gui/tests/usage-ledger-bytes.test.cjs new file mode 100644 index 000000000..6be63f902 --- /dev/null +++ b/internal/gui/tests/usage-ledger-bytes.test.cjs @@ -0,0 +1,134 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Usage page's Requests says what a request sent up to the vendor and got +// back (faithleysath, matrix0487 on Discord): a row's details name both, and +// what DeepSeek's image files kept out of it (#5407); a row from before they +// were kept says nothing of them, not 0. Under the Requests card the period's +// traffic reads "↑ up · ↓ down", with what the image files saved beside it, +// and a period with none says nothing. 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 now = Date.now(); + +const ROWS = [ + // the gateway's, with its bytes: 1.2 MB up, 34 KB down, 72 KB saved + { t: new Date(now - 60e3).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", provider: "deepseek", providerName: "DeepSeek", req: "deepseek-flash", model: "deepseek-flash", served: "deepseek-flash", in: 300, out: 40, ms: 2380, status: 200, rid: "req_new", ep: "/v1/chat/completions", cost: 0.01, priced: true, up_bytes: 1_234_567, plain_bytes: 1_234_567, down_bytes: 34_100, image_files_saved: 72_039 }, + // one from before the bytes were kept + { t: new Date(now - 120e3).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", provider: "deepseek", providerName: "DeepSeek", req: "deepseek-flash", model: "deepseek-flash", served: "deepseek-flash", in: 200, out: 20, ms: 1200, status: 200, rid: "req_old", ep: "/v1/chat/completions", cost: 0.01, priced: true }, + // an upload that cost more than it saved this once + { t: new Date(now - 180e3).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", provider: "deepseek", providerName: "DeepSeek", req: "deepseek-flash", model: "deepseek-flash", served: "deepseek-flash", in: 200, out: 20, ms: 1200, status: 200, rid: "req_upload", ep: "/v1/chat/completions", cost: 0.01, priced: true, up_bytes: 54_000, down_bytes: 900, image_files_saved: -40 }, +]; + +function page(q, bytes) { + return { + period: q.get("period"), rows: bytes ? ROWS : ROWS.slice(1, 2), offset: 0, total: bytes ? 3 : 1, calls: bytes ? 3 : 1, errors: 0, + input: 700, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0.03, unpriced: 0, + ...(bytes ? { up_bytes: 1_288_567, down_bytes: 35_000, image_files_saved: 71_999 } : {}), + agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], + }; +} + +function server(lang, bytes) { + 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, bytes)); + 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: { up: "Sent upstream", down: "Received", saved: "Saved by image files", line: "↑ 1.3 MB · ↓ 35 KB · 72 KB saved by image files" }, + zh: { up: "发往上游", down: "收到", saved: "图片文件省下", line: "↑ 1.3 MB · ↓ 35 KB · 图片文件省下 72 KB" }, + "zh-TW": { up: "送往上游", down: "收到", saved: "圖片檔案省下", line: "↑ 1.3 MB · ↓ 35 KB · 圖片檔案省下 72 KB" }, + ja: { up: "上流へ送信", down: "受信", saved: "画像ファイルで節約", line: "↑ 1.3 MB · ↓ 35 KB · 画像ファイルで 72 KB 節約" }, + de: { up: "An den Anbieter gesendet", down: "Empfangen", saved: "Durch Bilddateien gespart", line: "↑ 1.3 MB · ↓ 35 KB · 72 KB durch Bilddateien gespart" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a request's bytes up and down", 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 errors = []; + const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + const p = await ctx.newPage(); + p.setDefaultTimeout(5000); + p.setDefaultNavigationTimeout(60000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang, true)); + 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(); + + // the period's traffic under the Requests card + const io = p.locator("#ledKpi .led-io"); + assert.equal(await io.count(), 1); + assert.equal((await io.textContent()).trim(), w.line); + assert.equal(await io.getAttribute("title"), `${w.up}: 1,288,567 B\n${w.down}: 35,000 B`.replace(/,/g, lang === "de" ? "." : ",")); + + const rows = p.locator(".led tbody tr.led-row"); + const pairs = (n) => p.locator(".led-detail").nth(n).evaluate((d) => Object.fromEntries([...d.querySelectorAll("dt")].map((dt) => [dt.textContent, dt.nextElementSibling.textContent]))); + await reader.click(p, rows.nth(0)); + const got = await pairs(0); + assert.equal(got[w.up], "1.2 MB"); + assert.equal(got[w.down], "34 KB"); + assert.equal(got[w.saved], "72 KB"); + // a row from before: none of them, not 0 + await reader.click(p, rows.nth(1)); + const old = await pairs(1); + for (const k of [w.up, w.down, w.saved]) assert(!(k in old), `an old row shows ${k}: ${old[k]}`); + // an upload that cost more than it saved says nothing saved + await reader.click(p, rows.nth(2)); + const upload = await pairs(2); + assert.equal(upload[w.up], "54 KB"); + assert.equal(upload[w.down], "900 B"); + assert(!(w.saved in upload), "nothing saved is shown for a loss"); + + const sideways = await p.evaluate(() => [document.documentElement.scrollWidth - innerWidth, ...[...document.querySelectorAll("#ledKpi .blk")].map((b) => b.scrollWidth - b.clientWidth)]); + assert(sideways.every((n) => n <= 1), `scrolls sideways: ${sideways}`); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + // a period of rows from before: the card says nothing of traffic + await t.test(lang + " old", async () => { + const ctx = await browser.newContext({ viewport: { width: 1180, height: 760 }, reducedMotion: "reduce" }); + const p = await ctx.newPage(); + p.setDefaultTimeout(5000); + p.setDefaultNavigationTimeout(60000); + await p.route("**/*", server(lang, false)); + 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(); + assert.equal(await p.locator("#ledKpi .led-io").count(), 0); + await ctx.close(); + }); + } + }); +} diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go index b5afa800f..d63eb654f 100644 --- a/internal/usage/heat_disk.go +++ b/internal/usage/heat_disk.go @@ -30,7 +30,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 = "1" +const settledCountVersion = "2" func heatDiskPath() string { return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-v1.json") @@ -179,7 +179,7 @@ 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, p.Tries} { + 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, p.Tries, p.UpBytes, p.DownBytes, p.FilesSaved} { b = binary.AppendVarint(b, int64(v)) } b = binary.AppendUvarint(b, uint64(p.Flags)) diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index 1efdc06c8..e4a9bf1a6 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -796,6 +796,7 @@ func (t *Totals) addRow(r Row) { t.CacheWrite1h += r.CacheWrite1h t.countCache(r.Record) t.Reasoning += r.Reasoning + t.addBytes(&r.Record) switch { case r.Priced: t.Cost += r.Cost @@ -832,6 +833,9 @@ 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 } // FloorAgents are the agents whose session files time a call from what diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index cade68793..9f6a6baf5 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -88,8 +88,11 @@ type packedRow struct { Own, Retried, Queued int32 Masking int32 // ms (Record.Masking) Status, Tries int32 - Flags uint16 - zone uint16 + // 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 } // rowZones are the zones rows' times are in, by a row's zone; 0 is the @@ -340,7 +343,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: int32(r.Tries)} + 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: int32(r.Tries), 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) { @@ -404,9 +407,15 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) { } c.Bytes += int64(unsafe.Sizeof(packedRow{})) } + +// bytesOf is n in a packed row's 32 bits, held at an int32's ends. +func bytesOf(n int) int32 { + return int32(max(min(n, math.MaxInt32), math.MinInt32)) +} + 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, 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), 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} + 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, 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), 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} if p.Flags&rowCredits != 0 { credits := p.Credits r.Credits = &credits diff --git a/internal/usage/request_snapshot.go b/internal/usage/request_snapshot.go index 11193f1e4..dfab043bc 100644 --- a/internal/usage/request_snapshot.go +++ b/internal/usage/request_snapshot.go @@ -97,6 +97,9 @@ func (c *rowChunk) encode(keep func([]byte) bool) ([]byte, []*time.Location) { put(uint64(p.Flags)) put(uint64(p.Tries)) put(uint64(p.Masking)) + put(uint64(p.UpBytes)) + put(uint64(p.DownBytes)) + put(uint64(int64(p.FilesSaved))) if p.Flags&rowCredits != 0 { put(math.Float64bits(p.Credits)) } @@ -300,6 +303,7 @@ func (c *rowChunk) unpackReusing(dst *rowChunk, into []packedRow, strs []string, p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int32(take()), uint16(take()) p.Tries = int32(take()) p.Masking = int32(take()) + p.UpBytes, p.DownBytes, p.FilesSaved = int32(take()), int32(take()), int32(take()) p.Credits = 0 if p.Flags&rowCredits != 0 { p.Credits = math.Float64frombits(take()) diff --git a/internal/usage/row_shape_test.go b/internal/usage/row_shape_test.go index 4f9f9d75d..984d745ac 100644 --- a/internal/usage/row_shape_test.go +++ b/internal/usage/row_shape_test.go @@ -90,3 +90,43 @@ func TestRowTokensAndZoneKept(t *testing.T) { } } } + +// A row keeps what its request sent up and got back, and what DeepSeek's +// image files saved it (below 0 when an upload cost more), as the row +// was and packed and read back; a row from before has none. The totals +// of a period sum them, from records and from rows. +func TestRowBytesKept(t *testing.T) { + at := time.Date(2026, 11, 5, 12, 0, 0, 0, time.UTC) + c := &rowChunk{} + c.add(Row{Record: Record{Time: at, UpBytes: 120_000, PlainBytes: 400_000, DownBytes: 3_000, ImageFilesSaved: -40}}, "", 0, false) + c.add(Row{Record: Record{Time: at, UpBytes: 5_000_000_000, DownBytes: 900, ImageFilesSaved: 72_000}}, "", 1, false) + c.add(Row{Record: Record{Time: at, Input: 1}}, "", 2, false) + for _, c := range []*rowChunk{c, c.pack().unpack()} { + a, b, old := c.row(0), c.row(1), c.row(2) + if a.UpBytes != 120_000 || a.DownBytes != 3_000 || a.ImageFilesSaved != -40 { + t.Fatalf("read back up %d, down %d, saved %d", a.UpBytes, a.DownBytes, a.ImageFilesSaved) + } + if b.UpBytes != math.MaxInt32 || b.DownBytes != 900 || b.ImageFilesSaved != 72_000 { + t.Fatalf("read back up %d, down %d, saved %d", b.UpBytes, b.DownBytes, b.ImageFilesSaved) + } + if old.UpBytes != 0 || old.DownBytes != 0 || old.ImageFilesSaved != 0 { + t.Fatalf("a row from before reads back %+v", old.Record) + } + var rows, sum Totals + rows.addRow(a) + rows.addRow(b) + rows.addRow(old) + sum.plus(&rows) + var recs Totals + recs.add(a.Record, nil) + recs.add(old.Record, nil) + for _, got := range []Totals{rows, sum} { + if got.UpBytes != 120_000+math.MaxInt32 || got.DownBytes != 3_900 || got.ImageFilesSaved != 71_960 { + t.Fatalf("totals up %d, down %d, saved %d", got.UpBytes, got.DownBytes, got.ImageFilesSaved) + } + } + if recs.UpBytes != 120_000 || recs.DownBytes != 3_000 || recs.ImageFilesSaved != -40 { + t.Fatalf("records' totals up %d, down %d, saved %d", recs.UpBytes, recs.DownBytes, recs.ImageFilesSaved) + } + } +} diff --git a/internal/usage/settled_version_test.go b/internal/usage/settled_version_test.go index 0fadf39ad..e179f5e67 100644 --- a/internal/usage/settled_version_test.go +++ b/internal/usage/settled_version_test.go @@ -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 = "d7ac763fc3c86fa5e0061f7025974d9c18d5c0fca1305bbf1488139a1fbad51e" +const settledCounted = "8715ad3d4bdd7a48a9d882be5a089b17231152b10abc3d278e17070e879f107c" // 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 @@ -40,7 +40,7 @@ func TestSettledCountedAsVersioned(t *testing.T) { writeCodexCall(t, path, id, "s"+id, `"vscode"`, "resp-"+id, "m", effort, at, 100+i, 10+i) Append(Record{Time: at.Add(time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 100 + i, Output: 10 + i, CacheRead: 7 * i, Status: 200, ResponseID: "resp-" + id, Session: "s" + id}) } - Append(Record{Time: now.AddDate(0, 0, -30), Agent: "claude", Provider: "openai", Model: "m", Input: 40, Output: 20, CacheRead: 300, CacheWrite: 50, Status: 200}) + Append(Record{Time: now.AddDate(0, 0, -30), Agent: "claude", Provider: "openai", Model: "m", Input: 40, Output: 20, CacheRead: 300, CacheWrite: 50, Status: 200, UpBytes: 2400, DownBytes: 800, ImageFilesSaved: 300}) Append(Record{Time: now.AddDate(0, 0, -25), Agent: "claude", Provider: "openai", Model: "m", Input: 9, Status: 500}) codexEffort.Lock() codexEffort.periods = map[Period]*effortEntry{} diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 71daf4f73..f36644017 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -207,6 +207,18 @@ type Record struct { // it, a compressed turn's discount and a retried request's re-sends // both read off the row. None when no try went out. PlainBytes int `json:"plain_bytes,omitempty"` + // DownBytes is how many bytes of the vendor's replies to this call's + // tries magpie read, tries summed as UpBytes is: a reply's body as it + // came, after the HTTP client undid a gzip the vendor sent it in, so + // more than the wire's for a gzipped reply. A record from before it was + // kept has none. + DownBytes int `json:"down_bytes,omitempty"` + // ImageFilesSaved is how many fewer bytes went up because DeepSeek's + // image files named the request's inline images by file id (#5407): + // the inline base64 its tries left out, less the images this request + // uploaded for it. Below 0 when an upload cost more than it saved this + // time. None where no image went by file. + ImageFilesSaved int `json:"image_files_saved,omitempty"` // Kind is what the agent made the call for when it isn't a turn of // the conversation: a Codex subagent's (review, compact, guardian…) Kind string `json:"kind,omitempty"` @@ -570,6 +582,19 @@ type Totals struct { FloorOut int `json:"floor_out,omitempty"` FloorMs int64 `json:"floor_ms,omitempty"` FloorN int `json:"floor_n,omitempty"` + // UpBytes, DownBytes and ImageFilesSaved are the rows' own summed + // (Record.UpBytes …): what went up to the vendors and came back, of + // the rows that kept it; none when no row did + UpBytes int64 `json:"up_bytes,omitempty"` + DownBytes int64 `json:"down_bytes,omitempty"` + ImageFilesSaved int64 `json:"image_files_saved,omitempty"` +} + +// addBytes adds r's bytes on the wire (Totals.UpBytes …). +func (t *Totals) addBytes(r *Record) { + t.UpBytes += int64(r.UpBytes) + t.DownBytes += int64(r.DownBytes) + t.ImageFilesSaved += int64(r.ImageFilesSaved) } // Tokens is what went in and out, excluding cache traffic. @@ -814,6 +839,7 @@ func (t *Totals) addFrom(row Row, price *catalog.Price) { t.CacheWrite1h += r.CacheWrite1h t.countCache(r) t.Reasoning += r.Reasoning + t.addBytes(&r) if r.TTFT > 0 && !r.Failed() { t.Timed++ t.TTFT += r.TTFT