diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index e89403703..b6daba692 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1628,7 +1628,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st RequestID: requestID(res.Header), ResponseID: uu.ResponseID, Endpoint: r.URL.Path} failedWith(&rec, call.Status, call.Error, errType) if up := upBytesOf(r.Context()); up != nil { - rec.UpBytes, rec.PlainBytes = up.wire, up.plain + rec.UpBytes, rec.PlainBytes, rec.Socket = up.wire, up.plain, up.socket rec.DownBytes = up.downOf() } appendUsage(r, rec) diff --git a/internal/gateway/codex_socket.go b/internal/gateway/codex_socket.go index e42b863be..777438410 100644 --- a/internal/gateway/codex_socket.go +++ b/internal/gateway/codex_socket.go @@ -159,9 +159,15 @@ func (t codexSocket) RoundTrip(req *http.Request) (*http.Response, error) { // overSocket is RoundTrip for a turn that may go over the socket; shun // says a refused handshake leaves the host to HTTP for a while. func (t codexSocket) overSocket(req *http.Request, shun bool) (*http.Response, error) { + overHTTP := false + defer func() { sentOnSocket(req.Context(), !overHTTP) }() + viaHTTP := func() (*http.Response, error) { + overHTTP = true + return t.next.RoundTrip(req) + } body, ok := codexSocketMessage(req) if !ok { - return t.next.RoundTrip(req) + return viaHTTP() } msg := codexCreate(body) var shape *codexTurnShape @@ -188,11 +194,11 @@ func (t codexSocket) overSocket(req *http.Request, shun bool) (*http.Response, e } } if codexMessageTooBig(req.URL.Host, len(msg)) { - return t.next.RoundTrip(req) + return viaHTTP() } res, err := t.socket(req, msg, key, shape, shun) if errors.Is(err, errCodexSocketFallBack) { - return t.next.RoundTrip(req) + return viaHTTP() } return res, err } @@ -394,6 +400,7 @@ func (t codexSocket) turn(req *http.Request, k *codexKept, msg []byte, shape *co k.close() return nil, ended(err) } + wroteSocket(req.Context(), len(msg)) header := k.header.Clone() body := &codexSocketBody{c: k.c, ctx: req.Context(), k: k, shape: shape} for range codexSocketPrelude { diff --git a/internal/gateway/codex_socket_keep_test.go b/internal/gateway/codex_socket_keep_test.go index e14bcd608..c96a45626 100644 --- a/internal/gateway/codex_socket_keep_test.go +++ b/internal/gateway/codex_socket_keep_test.go @@ -3,12 +3,15 @@ package gateway import ( "fmt" "net/http/httptest" + "sort" "strings" "sync" "testing" "time" "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/usage" ) // keptReply answers a turn as the backend does: one assistant message, @@ -278,3 +281,47 @@ func TestCodexKeptSocketOtherReplyGoesWhole(t *testing.T) { t.Errorf("a turn after another reply went as a delta: %s", f.turn(1).msg) } } + +// matrix0487 on Discord: a request's row said 13 MB went up while its +// kept socket was sent the new input alone. A turn that went over the +// socket counts what the socket was sent, the delta on a kept one, and +// says it went over the socket; one over HTTP says neither. +func TestCodexSocketRowCountsWhatTheSocketSent(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{keep: true} + f.frames = keptReply(f) + chatgpt(t, f.ServeHTTP) + + start := time.Now() + long := strings.Repeat("x", 50_000) + big := strings.Replace(userPing, "ping", long, 1) + keptPost(t, "acct-1", keptTurn("conv-1", "gpt-5.5-ws", big)) + keptPost(t, "acct-1", keptTurn("conv-1", "gpt-5.5-ws", big, asstPong, userAgain)) + if posts, sockets := f.counts(); posts != 0 || sockets != 2 || f.opened() != 1 { + t.Fatalf("%d posts, %d turns on %d sockets; want both turns on one socket", posts, sockets, f.opened()) + } + var rows []usage.Record + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) { + rows = rows[:0] + for _, r := range usage.Load(start) { + if r.Time.After(start) && r.Model == "gpt-5.5-ws" { + rows = append(rows, r) + } + } + if len(rows) >= 2 || time.Now().After(deadline) { + break + } + } + if len(rows) != 2 { + t.Fatalf("%d rows, want 2", len(rows)) + } + sort.Slice(rows, func(i, j int) bool { return rows[i].Time.Before(rows[j].Time) }) + for i, r := range rows { + if want := len(f.turn(i).msg); !r.Socket || r.UpBytes != want { + t.Errorf("turn %d: socket %v, %d bytes up; want the socket's %d", i, r.Socket, r.UpBytes, want) + } + } + if rows[1].UpBytes > 1000 { + t.Errorf("the delta turn counted %d bytes up, the whole conversation", rows[1].UpBytes) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 9c0a722d8..3cd57e0be 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5346,7 +5346,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro rec.Tries = tries } if up := upBytesOf(r.Context()); up != nil { - rec.UpBytes, rec.PlainBytes = up.wire, up.plain + rec.UpBytes, rec.PlainBytes, rec.Socket = up.wire, up.plain, up.socket rec.DownBytes, rec.ImageFilesSaved, rec.ImageFiles = up.downOf(), up.saved, up.images } failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) diff --git a/internal/gateway/upbytes.go b/internal/gateway/upbytes.go index d985876e5..60d9db005 100644 --- a/internal/gateway/upbytes.go +++ b/internal/gateway/upbytes.go @@ -25,6 +25,13 @@ type upBytes struct { // 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 + // last is what sentUp last counted, the try's body as HTTP sends it; + // socket says that try went over the Responses WebSocket instead + // (overSocket), which counted what it was sent in its place + last int + socket bool + // ws is what the socket was written for that try so far (wroteSocket) + ws int } type upBytesKey struct{} @@ -42,9 +49,39 @@ func sentUp(ctx context.Context, wire, plain int) { if u := upBytesOf(ctx); u != nil { u.wire += wire u.plain = plain + u.last, u.socket, u.ws = wire, false, 0 } } +// wroteSocket counts a message the Responses WebSocket was sent for the +// try sentUp last counted: a kept socket's delta, or the whole turn on a +// new one. +func wroteSocket(ctx context.Context, n int) { + if u := upBytesOf(ctx); u != nil { + u.ws += n + } +} + +// sentOnSocket settles that try once the socket is done with it. A turn +// the socket answered (only) sent what the socket was written, not the +// body sentUp counted: #5781's matrix0487 saw 13 MB a row while a kept +// socket was sent the new input alone. One that went over HTTP after +// all sent both. +func sentOnSocket(ctx context.Context, only bool) { + u := upBytesOf(ctx) + if u == nil { + return + } + if only { + u.wire += u.ws - u.last + u.last = u.ws + } else { + u.wire += u.ws + u.last += u.ws + } + u.socket, u.ws = only, 0 +} + // 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 diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 5baf67126..da23e2633 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -1426,7 +1426,8 @@ function ledProtos(r) { function ledProtoBadge(r) { const p = ledProtos(r); if (!p) return null; - const k = el("span", "src proto proto-" + p.to.toLowerCase(), p.from !== p.to ? p.from + " → " + p.to : p.to); + // "· WS" for one that went over the Responses WebSocket (matrix0487) + const k = el("span", "src proto proto-" + p.to.toLowerCase(), (p.from !== p.to ? p.from + " → " + p.to : p.to) + (r.ws ? " · WS" : "")); k.title = p.from !== p.to ? t("The agent spoke {from}; sent upstream as {to}", p) : t("Sent upstream as {to}, as the agent spoke it", p); return k; } @@ -1502,7 +1503,10 @@ function ledDetail(r, cols) { add("Request ID", r.rid); add("Endpoint", r.ep); const protos = ledProtos(r); - if (protos) add("Protocol", protos.from !== protos.to ? protos.from + " → " + protos.to : protos.to); + // and the Responses WebSocket it went over, whose Sent upstream is then + // what the socket was sent: a kept one's new input (matrix0487) + const proto = protos ? (protos.from !== protos.to ? protos.from + " → " + protos.to : protos.to) : ""; + if (proto || r.ws) add("Protocol", proto && r.ws ? proto + " · WebSocket" : proto || "WebSocket"); // why the upstream said its reply ended, in its own words: a reply that // ended too soon is told apart by it (蓝猫 on Discord) add("Upstream stop reason", r.stop); diff --git a/internal/gui/tests/usage-ledger-bytes.test.cjs b/internal/gui/tests/usage-ledger-bytes.test.cjs index adac1dec3..44d46d30c 100644 --- a/internal/gui/tests/usage-ledger-bytes.test.cjs +++ b/internal/gui/tests/usage-ledger-bytes.test.cjs @@ -22,7 +22,7 @@ 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 }, + { 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/responses", ws: true, 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 @@ -64,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", 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"] }, + en: { proto: "Protocol", 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: { proto: "协议", 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": { proto: "協議", 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: { proto: "プロトコル", 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: { proto: "Protokoll", 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"])) { @@ -105,10 +105,16 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(got[w.up], "1.2 MB"); assert.equal(got[w.down], "34 KB"); assert.equal(got[w.saved], "72 KB"); + // one that went over the Responses WebSocket says so, in its + // details and its row's badge (matrix0487); one over HTTP doesn't + assert.equal(got[w.proto], "Responses · WebSocket"); + assert.equal((await rows.nth(0).locator(".proto").textContent()).trim(), "Responses · WS"); + assert.equal((await rows.nth(1).locator(".proto").textContent()).trim(), "Chat"); // 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]}`); + assert.equal(old[w.proto], "Chat"); // an upload that cost more than it saved says nothing saved await reader.click(p, rows.nth(2)); const upload = await pairs(2); diff --git a/internal/usage/reasoning_stream_speed_test.go b/internal/usage/reasoning_stream_speed_test.go index 6ebd20360..b029148a3 100644 --- a/internal/usage/reasoning_stream_speed_test.go +++ b/internal/usage/reasoning_stream_speed_test.go @@ -150,7 +150,7 @@ func TestRowFlagsApart(t *testing.T) { } }) } - bits := []uint16{1, 2, 4, 8, 16, 32, swapKnown, rowHandedOn, rowReasoningHidden, rowOwnCost, rowCompactionKnown, rowCompaction, rowCredits, rowCacheUnknown} + bits := []uint16{1, 2, 4, 8, 16, 32, swapKnown, rowHandedOn, rowReasoningHidden, rowOwnCost, rowCompactionKnown, rowCompaction, rowCredits, rowCacheUnknown, rowSocket} var all uint16 for _, b := range bits { if all&b != 0 { @@ -159,3 +159,26 @@ func TestRowFlagsApart(t *testing.T) { all |= b } } + +// A row that went over the Responses WebSocket says so as it was kept, +// packed and read back (matrix0487), and one that didn't doesn't. +func TestRowKeepsSocket(t *testing.T) { + for _, ws := range []bool{true, false} { + r := Record{Time: time.Now(), Provider: "codex", Model: "gpt-5.5", Output: 10, Status: 200, UpBytes: 300, Socket: ws} + made := func() *rowChunk { + var chunk rowChunk + for i := 0; i < 80; i++ { + chunk.add(Row{Record: r}, "", int64(i), false) + } + return &chunk + } + b := newBlockPricer(provider.Renames{}, nil, func(Record) *catalog.Price { return nil }) + raw := made() + for _, row := range []Row{raw.row(0), b.block(raw).row(0), b.block(made().pack()).row(0)} { + if row.Socket != ws || row.UpBytes != 300 { + t.Errorf("socket %v, %d up; want %v, 300", row.Socket, row.UpBytes, ws) + } + } + b.release() + } +} diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index b92468ce9..74fff1563 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -218,6 +218,9 @@ const rowCredits = 4096 // counted no cache (#3464). const rowCacheUnknown = 8192 +// rowSocket is the Flags bit of Record.Socket. +const rowSocket = 16384 + type rowChunk struct { Archive []byte Locations []*time.Location @@ -376,6 +379,9 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) { if r.CacheUnknown { p.Flags |= rowCacheUnknown } + if r.Socket { + p.Flags |= rowSocket + } if failed { p.Flags |= 16 } @@ -425,7 +431,7 @@ func smallOf(n int) int16 { 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), 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} + 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} if p.Flags&rowCredits != 0 { credits := p.Credits r.Credits = &credits diff --git a/internal/usage/usage.go b/internal/usage/usage.go index aaf065d86..980be1ccc 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -224,6 +224,10 @@ 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"` + // 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. + Socket bool `json:"ws,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"`