diff --git a/internal/gateway/deepseek_files.go b/internal/gateway/deepseek_files.go index 77397855f..6f2372dc2 100644 --- a/internal/gateway/deepseek_files.go +++ b/internal/gateway/deepseek_files.go @@ -309,6 +309,7 @@ func (s *Server) withDeepSeekFiles(ctx context.Context, p provider.Provider, to if len(ids) == 0 { return body, false } + byFile := 0 out, err := walkImages(to, body, func(im imageAt) (json.RawMessage, error) { _, b64, ok := dsInlineImage(to, im) if !ok { @@ -319,7 +320,11 @@ func (s *Server) withDeepSeekFiles(ctx context.Context, p provider.Provider, to if id == "" { return nil, nil } - return dsFileBlock(to, im.Block, id), nil + block := dsFileBlock(to, im.Block, id) + if block != nil { + byFile++ + } + return block, nil }) if err != nil || bytes.Equal(out, body) { return body, false @@ -332,6 +337,8 @@ func (s *Server) withDeepSeekFiles(ctx context.Context, p provider.Provider, to if u := upBytesOf(ctx); u != nil { // the inline images this try left out, for the request's row u.saved += len(body) - len(out) + // and how many they were (matrix0487 on Discord) + u.images = max(u.images, byFile) } return out, true } diff --git a/internal/gateway/deepseek_files_test.go b/internal/gateway/deepseek_files_test.go index ef30ab990..12a543009 100644 --- a/internal/gateway/deepseek_files_test.go +++ b/internal/gateway/deepseek_files_test.go @@ -501,3 +501,54 @@ func TestDeepSeekImageFilesSavedInRow(t *testing.T) { t.Fatalf("up and saved come to %d and %d, the inline turn's bytes (image %d)", a, b, len(img)) } } + +// A row says how many images went by file beside what they saved +// (matrix0487 on Discord: "10 MB(3 张)"): each inline image block the +// body named by file id, one sent twice counted twice as its bytes are, +// on the turn that uploads them and the turn after; a request with no +// image says none. +func TestDeepSeekImageFilesCountedInRow(t *testing.T) { + s, u := dsSetup(t) + block := func(img string) string { + return `{"type":"image_url","image_url":{"url":"data:image/png;base64,` + img + `"}}` + } + body := `{"model":"deepseek/deepseek-flash","stream":false,"messages":[{"role":"user","content":[{"type":"text","text":"what are they"},` + + block(dsPNG1) + `,` + block(dsPNG2) + `]},{"role":"assistant","content":"two images"},{"role":"user","content":[{"type":"text","text":"and again"},` + block(dsPNG1) + `]}]}` + plain := `{"model":"deepseek/deepseek-flash","stream":false,"messages":[{"role":"user","content":"no image"}]}` + rowsOf := func(n int) []usage.Record { + var rows []usage.Record + 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) >= n || time.Now().After(deadline) { + return rows + } + time.Sleep(20 * time.Millisecond) + } + } + for turn, b := range []string{body, body, plain} { + if code, reply := postTo(t, s, "/v1/chat/completions", b); code != 200 { + t.Fatalf("turn %d: %d %s", turn, code, reply) + } + if got := u.last("/v1/chat/completions"); turn < 2 && (strings.Contains(got, dsPNG1) || strings.Contains(got, dsPNG2)) { + t.Fatalf("turn %d went inline: %s", turn, got) + } + if rows := rowsOf(turn + 1); len(rows) != turn+1 { + t.Fatalf("turn %d: rows %+v", turn, rows) + } + } + rows := rowsOf(3) + for i, want := range []int{3, 3, 0} { + if rows[i].ImageFiles != want { + t.Fatalf("turn %d: %d images by file, want %d (saved %d)", i, rows[i].ImageFiles, want, rows[i].ImageFilesSaved) + } + } + if rows[1].ImageFilesSaved <= 0 { + t.Fatalf("the second turn saved %d", rows[1].ImageFilesSaved) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 620b8bc2a..56768faa4 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5063,7 +5063,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 + rec.DownBytes, rec.ImageFilesSaved, rec.ImageFiles = up.downOf(), up.saved, up.images } failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) withBodies(&rec, &call) diff --git a/internal/gateway/upbytes.go b/internal/gateway/upbytes.go index a173221b0..d985876e5 100644 --- a/internal/gateway/upbytes.go +++ b/internal/gateway/upbytes.go @@ -22,6 +22,9 @@ type upBytes struct { // saved is what DeepSeek's image files kept out of the tries' bodies, // less what uploading them cost this request (withDeepSeekFiles) saved int + // images is how many inline images went by file instead, the most of + // any one try: a retry sends the same ones again + images int } type upBytesKey struct{} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 16607df84..a7bed5da1 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1350,6 +1350,8 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske than its card on its own is cut (#2378: "缓存 879…") */ .led-strip .sub.parts, .kpi small.parts { white-space: normal; } .led-strip .sub.parts > span, .kpi small.parts > span { display: inline-block; max-width: 100%; vertical-align: bottom; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* the traffic line's parts read whole: one wider than the card wraps in itself, never cut (matrix0487) */ +.led-strip .sub.led-io > span { white-space: normal; } /* not the tile's label: .kpi span is its small capitals */ .kpi small.parts > span { margin-top: 0; font: inherit; letter-spacing: normal; text-transform: none; color: inherit; } .led-strip .led-jump { text-align: start; font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; text-decoration: underline dotted; text-underline-offset: 2px; } diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index c9ff3ea52..c6a232bfc 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -4,6 +4,8 @@ magpie.strings({ zh: { "Saved by image files": "图片文件省下", "{n} saved by image files": "图片文件省下 {n}", + "{size} ({n} image)": "{size}({n} 张)", + "{size} ({n} images)": "{size}({n} 张)", "Show in Overview": "在概览中显示", "Show {n} Hidden": "显示已隐藏的 {n} 个", "Hide from Overview": "从概览中隐藏", @@ -244,6 +246,8 @@ magpie.strings({ "zh-TW": { "Saved by image files": "圖片檔案省下", "{n} saved by image files": "圖片檔案省下 {n}", + "{size} ({n} image)": "{size}({n} 張)", + "{size} ({n} images)": "{size}({n} 張)", "Show in Overview": "在概覽中顯示", "Show {n} Hidden": "顯示已隱藏的 {n} 個", "Hide from Overview": "從概覽中隱藏", @@ -484,6 +488,8 @@ magpie.strings({ ja: { "Saved by image files": "画像ファイルで節約", "{n} saved by image files": "画像ファイルで {n} 節約", + "{size} ({n} image)": "{size}({n} 枚)", + "{size} ({n} images)": "{size}({n} 枚)", "Show in Overview": "概要に表示", "Show {n} Hidden": "非表示の {n} 件を表示", "Hide from Overview": "概要から隠す", @@ -724,6 +730,8 @@ magpie.strings({ de: { "Saved by image files": "Durch Bilddateien gespart", "{n} saved by image files": "{n} durch Bilddateien gespart", + "{size} ({n} image)": "{size} ({n} Bild)", + "{size} ({n} images)": "{size} ({n} Bilder)", "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 574f31d12..4bb7d8eb1 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -1408,7 +1408,8 @@ function ledDetail(r, cols) { // 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)); + // 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)); add("Request ID", r.rid); add("Endpoint", r.ep); const protos = ledProtos(r); @@ -1639,10 +1640,12 @@ function renderLedgerDash(l) { : 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 + // what DeepSeek's image files saved on the way up. Its parts kept whole, + // the saving going under in a card too narrow for all three rather than + // cut (matrix0487 on Discord: "图片文件省下 44…") 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"); + 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"; strip.lastChild.append(io); } diff --git a/internal/gui/tests/usage-ledger-bytes.test.cjs b/internal/gui/tests/usage-ledger-bytes.test.cjs index 6be63f902..adac1dec3 100644 --- a/internal/gui/tests/usage-ledger-bytes.test.cjs +++ b/internal/gui/tests/usage-ledger-bytes.test.cjs @@ -4,9 +4,12 @@ // 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. +// and a period with none says nothing. That line keeps each part whole, +// wrapping between them rather than cutting the saving (matrix0487: "图片文件 +// 省下 44…"), and a row that kept how many images went by file says so after +// the saving, "10 MB(3 张)", one from before with no count. 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"); @@ -24,13 +27,18 @@ const ROWS = [ { 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 }, + // the reporter's: 10 MB saved on 3 images, and one on a single image + { t: new Date(now - 240e3).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_three", ep: "/v1/chat/completions", cost: 0.01, priced: true, up_bytes: 54_000, down_bytes: 900, image_files_saved: 10_485_760, image_files: 3 }, + { t: new Date(now - 300e3).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_one", ep: "/v1/chat/completions", cost: 0.01, priced: true, up_bytes: 54_000, down_bytes: 900, image_files_saved: 72_039, image_files: 1 }, ]; +// the reporter's period: "↑ 13 GB · ↓ 13 MB · 图片文件省下 44…" +const BIG = { up_bytes: 13_000_000_000, down_bytes: 13_000_000, image_files_saved: 44_000_000 }; 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, + period: q.get("period"), rows: bytes ? ROWS : ROWS.slice(1, 2), offset: 0, total: bytes ? ROWS.length : 1, calls: bytes ? ROWS.length : 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 } : {}), + ...(bytes === "big" ? BIG : bytes ? { up_bytes: 1_288_567, down_bytes: 35_000, image_files_saved: 71_999 } : {}), agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], }; } @@ -56,11 +64,11 @@ function server(lang, bytes) { } 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" }, + en: { up: "Sent upstream", down: "Received", saved: "Saved by image files", line: "↑ 1.3 MB · ↓ 35 KB · 72 KB saved by image files", three: "10 MB (3 images)", one: "72 KB (1 image)", big: ["↑ 13 GB", "↓ 13 MB", "44 MB saved by image files"] }, + zh: { up: "发往上游", down: "收到", saved: "图片文件省下", line: "↑ 1.3 MB · ↓ 35 KB · 图片文件省下 72 KB", three: "10 MB(3 张)", one: "72 KB(1 张)", big: ["↑ 13 GB", "↓ 13 MB", "图片文件省下 44 MB"] }, + "zh-TW": { up: "送往上游", down: "收到", saved: "圖片檔案省下", line: "↑ 1.3 MB · ↓ 35 KB · 圖片檔案省下 72 KB", three: "10 MB(3 張)", one: "72 KB(1 張)", big: ["↑ 13 GB", "↓ 13 MB", "圖片檔案省下 44 MB"] }, + ja: { up: "上流へ送信", down: "受信", saved: "画像ファイルで節約", line: "↑ 1.3 MB · ↓ 35 KB · 画像ファイルで 72 KB 節約", three: "10 MB(3 枚)", one: "72 KB(1 枚)", big: ["↑ 13 GB", "↓ 13 MB", "画像ファイルで 44 MB 節約"] }, + de: { up: "An den Anbieter gesendet", down: "Empfangen", saved: "Durch Bilddateien gespart", line: "↑ 1.3 MB · ↓ 35 KB · 72 KB durch Bilddateien gespart", three: "10 MB (3 Bilder)", one: "72 KB (1 Bild)", big: ["↑ 13 GB", "↓ 13 MB", "44 MB durch Bilddateien gespart"] }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -107,6 +115,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", 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"); + // a row that kept its count: how many images, in the language's unit + await reader.click(p, rows.nth(3)); + assert.equal((await pairs(3))[w.saved], w.three); + await reader.click(p, rows.nth(4)); + assert.equal((await pairs(4))[w.saved], w.one, "one image, singular"); 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}`); @@ -114,6 +127,27 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await ctx.close(); }); } + // the reporter's period: every part of the line whole, none cut + for (const width of [1180, 760, 420]) { + await t.test(lang + " big " + width, async () => { + const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + const p = await ctx.newPage(); + p.setDefaultTimeout(5000); + p.setDefaultNavigationTimeout(60000); + await p.route("**/*", server(lang, "big")); + 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("#ledKpi .led-io").waitFor(); + const io = p.locator("#ledKpi .led-io"); + assert.deepEqual(await io.locator("span").allTextContents(), w.big); + const cut = await io.evaluate((e) => [e.scrollWidth - e.clientWidth, ...[...e.querySelectorAll("span")].map((s) => s.scrollWidth - s.clientWidth)]); + assert(cut.every((n) => n <= 1), `cut: ${cut}`); + const card = await io.evaluate((e) => { const b = e.closest(".blk").getBoundingClientRect(), r = e.getBoundingClientRect(); return [r.left >= b.left - 1, r.right <= b.right + 1]; }); + assert.deepEqual(card, [true, true], "inside its card"); + 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" }); diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go index d63eb654f..4582af158 100644 --- a/internal/usage/heat_disk.go +++ b/internal/usage/heat_disk.go @@ -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, 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, p.Status, int32(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/request_page.go b/internal/usage/request_page.go index 0ea67c343..8223e9ad6 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -87,7 +87,11 @@ type packedRow struct { Sent, Flow, FirstReasoning int32 Own, Retried, Queued int32 Masking int32 // ms (Record.Masking) - Status, Tries int32 + 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 @@ -343,7 +347,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), 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: int32(r.Status), Tries: smallOf(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) { @@ -413,9 +417,15 @@ func bytesOf(n int) int32 { return int32(max(min(n, math.MaxInt32), math.MinInt32)) } +// smallOf is a count of tries or images in a packed row's 16 bits, one +// past them kept as the most they hold +func smallOf(n int) int16 { + return int16(max(min(n, math.MaxInt16), 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, 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} + 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), 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} 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 dfab043bc..3235c3f03 100644 --- a/internal/usage/request_snapshot.go +++ b/internal/usage/request_snapshot.go @@ -100,6 +100,7 @@ func (c *rowChunk) encode(keep func([]byte) bool) ([]byte, []*time.Location) { put(uint64(p.UpBytes)) put(uint64(p.DownBytes)) put(uint64(int64(p.FilesSaved))) + put(uint64(p.ImageFiles)) if p.Flags&rowCredits != 0 { put(math.Float64bits(p.Credits)) } @@ -301,9 +302,10 @@ func (c *rowChunk) unpackReusing(dst *rowChunk, into []packedRow, strs []string, 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 = int32(take()) + p.Tries = int16(take()) p.Masking = int32(take()) p.UpBytes, p.DownBytes, p.FilesSaved = int32(take()), int32(take()), int32(take()) + p.ImageFiles = int16(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 984d745ac..c057e3217 100644 --- a/internal/usage/row_shape_test.go +++ b/internal/usage/row_shape_test.go @@ -1,9 +1,11 @@ package usage import ( + "encoding/json" "fmt" "math" "reflect" + "strings" "testing" "time" "unsafe" @@ -130,3 +132,41 @@ func TestRowBytesKept(t *testing.T) { } } } + +// A row keeps how many images went by file beside what they saved +// (matrix0487 on Discord: "10 MB(3 张)"), packed and read back, and in +// usage.jsonl; one from before has none, and a count past what the +// packed row holds is kept as its most. Keeping it made no row larger. +func TestRowImageFilesKept(t *testing.T) { + at := time.Date(2026, 11, 6, 12, 0, 0, 0, time.UTC) + c := &rowChunk{} + c.add(Row{Record: Record{Time: at, UpBytes: 50_000, ImageFilesSaved: 10_000_000, ImageFiles: 3, Tries: 2}}, "", 0, false) + c.add(Row{Record: Record{Time: at, ImageFilesSaved: 72_000, ImageFiles: 100_000, Tries: 100_000}}, "", 1, false) + c.add(Row{Record: Record{Time: at, Input: 1}}, "", 2, false) + for i, c := range []*rowChunk{c, c.pack().unpack()} { + a, b, old := c.row(0), c.row(1), c.row(2) + 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 { + t.Fatalf("%d: past the most read back %d images, %d tries", i, b.ImageFiles, b.Tries) + } + if old.ImageFiles != 0 { + t.Fatalf("%d: a row from before reads back %d images", i, old.ImageFiles) + } + } + line, err := json.Marshal(Record{Time: at, ImageFilesSaved: 10_000_000, ImageFiles: 3}) + if err != nil { + t.Fatal(err) + } + var back Record + if err := json.Unmarshal(line, &back); err != nil || back.ImageFiles != 3 || !strings.Contains(string(line), `"image_files":3`) { + t.Fatalf("usage.jsonl's line %s read back %d images (%v)", line, back.ImageFiles, err) + } + if line, _ := json.Marshal(Record{Time: at}); strings.Contains(string(line), "image_files") { + t.Fatalf("a row with no image says one: %s", line) + } + if n := unsafe.Sizeof(packedRow{}); n != 152 { + t.Fatalf("a packed row is %d bytes, was 152", n) + } +} diff --git a/internal/usage/usage.go b/internal/usage/usage.go index f36644017..cb6264316 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -219,6 +219,11 @@ type Record struct { // 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"` + // ImageFiles is how many of the request's inline images went by file + // instead, the most of any one try (a retry sends the same ones again): + // what ImageFilesSaved was saved on (matrix0487 on Discord). None in a + // row from before it was kept. + ImageFiles int `json:"image_files,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"`