usage, gateway, gui: the Requests card counts requests once, a try handed on to the next isn't a failure, and says how many were answered on a retry (小一 on Discord)
小一's Codex-on-credits ledger read "5,482 · 1,094 failed" while many rows said "2 tries/3 tries" and had been answered. "Failed" counted usage rows, not requests: besides each request's final row, the gateway writes a row for every try a vendor refused or turned away (hw.refused/hw.turnedAway), and each of those was counted as a call and a failure even when a later member answered. (Ordinary failovers write no row; 499 cancels and the agent's own client-side retries are separate requests.) In the owner's own usage.jsonl, 24 of the 71 "failed" rows were such refusals a later member answered. Now a request counts once, by how it ended: - usage.Record gains `tries` (final row, when the route took more than one) and `handed_on` (the row of a try that failed and handed the request on). Totals.count skips handed-on rows; a failure is a request whose agent got an error (LostRequest); one answered after a failed try is Totals.Retried (RetriedRequest), with a `retried=1` filter. - Logs written before this are read the same way: the log index marks a failed, non-rejected row followed by another of the same route id as handed on and raises the later row's tries (routeRows); the packed row and its snapshot carry both. - Panel card, Usage overview tile, ledger card, rankings and group rows, `magpie usage` and the TUI say "N answered on a retry"; the CSV adds `tries` and `handed_on` at the end. A row says "· handed on" (with why in its title) or "· N tries". - On the ledger's Requests card "N failed" and "N answered on a retry" are buttons that switch the list to the Failed / new Retried filter, and back when pressed again. The lines wrap rather than cut a button off (German). zh, zh-TW, ja, de strings added. - Docs: reference.md (counting, filter, CSV columns), gateway-routing.md. Run: - go test -tags nogui ./internal/usage ./internal/usageapi ./internal/tui ./internal/gateway . : ok. New TestRequestsCountedOnceWithTheirRetries (JSONL fixture: legacy refused row + 200, handed_on + 200 tries 3, 502 tries 2, plain 200, routeless 429 → 5 calls, 2 failed, 2 retried, across Ledger, QueryPage, Summarize, heatmap, filters, CSV) and TestRetriedRequestCountsOnce (group a refuses, b 500s, c answers → 1 call, 0 errors, 1 retried; a lone 400 → 1 error). - Broke each by hand (count without the HandedOn skip, gateway without HandedOn, log index without routeRows): each test went red; restored. - go test -tags nogui -timeout 40m ./... under the gotest lock, rebased on origin/mainde1ba9f12: all ok - gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on ., the usage, usageapi, tui, gateway and gui packages: clean. - Playwright ledger-retried.test.cjs, Chromium and WebKit, en zh zh-TW ja de, 420 and 1100 wide: 20/20 (German first failed on the cut-off line, fixed by letting the button lines wrap). usage-*, api-key-usage, purpose-filter (Failed is now the 2nd of 3 options), panel-usage, click-scroll, request-archive-usage, both engines: all green except purpose-filter's Routing case (1px focus scroll), which fails the same on909d76747andde1ba9f12, in Chromium too; it is #1291 (commented)
This commit is contained in:
+14
-2
@@ -271,11 +271,23 @@ deleted keys keep their historical identity. Older records appear as
|
||||
**key not recorded**, never inferred from today's configured key.
|
||||
These are upstream credentials, not keys clients use to call Magpie.
|
||||
|
||||
The CSV's `cache_write_tokens` is still every cache write; the last two
|
||||
The CSV's `cache_write_tokens` is still every cache write; the two
|
||||
columns, `cache_write_5m_tokens` and `cache_write_1h_tokens`, split it by how
|
||||
long Anthropic keeps it (a record from before the split is all 5-minute).
|
||||
The app shows the split on a request's Cache and the usage tiles' tooltips.
|
||||
|
||||
**Requests and failures** count requests, each once by how it ended: a
|
||||
request failed when the agent got an error. One that a later try answered
|
||||
(the next member of a group, another account) is not a failure; the Usage
|
||||
page, the Requests card, its rankings and group rows, and `magpie usage`
|
||||
count it as answered on a retry (`retried` in the JSON). On the Requests
|
||||
card each count is a button for its requests in the list below (the
|
||||
Failed and Retried filters, `failed=1` and `retried=1`). A try a vendor
|
||||
refused or turned away keeps its own row, for what it billed and why, marked
|
||||
handed on, and isn't counted as a request. The CSV's last columns are
|
||||
`tries` (on the final row, when the request took more than one) and
|
||||
`handed_on`.
|
||||
|
||||
**Output speed** (tok/s on the Usage and Routing pages, `magpie usage`) is
|
||||
output tokens over the time after the first token, summed per request: the
|
||||
tokens of every timed request over the sum of their windows, so concurrent
|
||||
@@ -1478,7 +1490,7 @@ machine), with every session in `sessions` where the window's lists the
|
||||
top 100 by tokens; `sessionCount` is how many there are. `GET /v1/magpie/usage/requests` is its requests a page at a time
|
||||
(`offset`, `limit` up to 500), with the same filters as the Requests log:
|
||||
`period`, `day`, `agent`, `provider`, `model`, `account`, `callerKey`,
|
||||
`purpose`, `failed`, `q`, `via`, `computer`. What was said in a call is not
|
||||
`purpose`, `failed`, `retried`, `q`, `via`, `computer`. What was said in a call is not
|
||||
in either. Like `/v1/magpie/quotas`, they answer this machine, and another
|
||||
only with a gateway key. A key held to a budget, to some models or to some
|
||||
accounts is told its own calls alone: `/v1/magpie/usage` refuses it with a
|
||||
|
||||
@@ -48,6 +48,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
## Constraints and failure behavior
|
||||
|
||||
- A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another.
|
||||
- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try.
|
||||
- A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying "<provider> refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes.
|
||||
- A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came.
|
||||
- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a stream under a type that says neither JSON nor a stream goes through as it comes (`sseStart` reads its first bytes); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun: `eventLead`) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE").
|
||||
@@ -193,6 +194,7 @@ Covered by `TestSearchMCPServesWebSearch`, `TestSearchMCPWithNoSearcher`,
|
||||
```sh
|
||||
go test -tags nogui ./internal/gateway -run 'TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls'
|
||||
go test -tags nogui ./internal/gateway -run 'TestVertex'
|
||||
go test -tags nogui ./internal/gateway ./internal/usage -run 'TestRetriedRequestCountsOnce|TestRequestsCountedOnceWithTheirRetries'
|
||||
go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie|TestRedactedKinds|TestKeyLimitTellsOnlyTheCaller'
|
||||
go test -tags nogui ./internal/gateway -run 'TestSearchMCP'
|
||||
go test -tags nogui ./internal/redact ./internal/gui -run 'TestMoreKinds|TestCategoryDefaults|TestRedactKindsAreRedacts|TestRedactRuleEdit'
|
||||
|
||||
@@ -2289,7 +2289,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead,
|
||||
CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: sent, Millis: time.Since(began).Milliseconds(), Status: call.Status,
|
||||
TTFT: try.TTFT, FirstText: try.FirstText, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
|
||||
RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName()}
|
||||
RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true}
|
||||
failedWith(&rec, call.Status, call.Error, call.Usage.ErrType)
|
||||
// what this account answered is its refusal, the reply
|
||||
// captured so far being no one's yet
|
||||
@@ -2332,7 +2332,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead,
|
||||
CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: sent, Millis: time.Since(began).Milliseconds(), Status: call.Status,
|
||||
TTFT: try.TTFT, FirstText: try.FirstText, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
|
||||
RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName()}
|
||||
RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true}
|
||||
failedWith(&rec, call.Status, call.Error, call.Usage.ErrType)
|
||||
// what this account answered is its refusal, the reply
|
||||
// captured so far being no one's yet
|
||||
@@ -2685,8 +2685,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
if prompt != nil && lastTried.ID != "" {
|
||||
window = windowOf(lastTried, model)
|
||||
}
|
||||
tries := 0 // the request's tries, as its route lists them
|
||||
s.trace.update(tr, func(t *Route) {
|
||||
t.Done, t.Status, t.Error, t.Millis = true, call.Status, call.Error, call.Millis
|
||||
tries = len(t.Tries)
|
||||
if t.TitleLink != nil && isTitleKind(t.Kind) && call.Status < 400 && call.Error == "" && !call.ResponseTruncated {
|
||||
link := *t.TitleLink
|
||||
link.Reply = replyDigest
|
||||
@@ -2714,6 +2716,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: sent, Millis: call.Millis, Status: call.Status,
|
||||
TTFT: call.TTFT, FirstText: call.FirstText, Flow: call.Flow, Sent: sentMs, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
|
||||
RequestID: call.Usage.RequestID, ResponseID: call.Usage.ResponseID, Endpoint: endpointOf(r, from, call.To, lastTried, model), Stop: call.Usage.Stop, Archive: call.archiveName()}
|
||||
if tries > 1 {
|
||||
// answered, or not, after a try that failed first: the ledger
|
||||
// counts it once, as the request it is (小一 on Discord)
|
||||
rec.Tries = tries
|
||||
}
|
||||
failedWith(&rec, call.Status, call.Error, call.Usage.ErrType)
|
||||
withBodies(&rec, &call)
|
||||
appendUsage(r, rec)
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// A request a group answered on its third member, after the first refused
|
||||
// (its row kept for what it billed) and the second failed, is one request
|
||||
// answered on a retry, not a failure (小一 on Discord): the refused try's
|
||||
// row is marked handed on, and the answer's row says how many tries it
|
||||
// took. A request that fails outright is the one failure.
|
||||
func TestRetriedRequestCountsOnce(t *testing.T) {
|
||||
fresh(t)
|
||||
a := &scripted{replies: []reply{{200, "text/event-stream", anthropicRefusal}}}
|
||||
b := &scripted{replies: []reply{{500, "application/json", `{"error":{"message":"overloaded"}}`}}}
|
||||
c := &scripted{replies: []reply{{200, "text/event-stream", anthropicAnswer}}}
|
||||
scriptedOn(t, "a", provider.Anthropic, a)
|
||||
scriptedOn(t, "b", provider.Anthropic, b)
|
||||
scriptedOn(t, "c", provider.Anthropic, c)
|
||||
refusalGroup(t, "a/m", "b/m", "c/m")
|
||||
s := New()
|
||||
code, body := sendTo(s, "/v1/responses", codexAsk)
|
||||
if code != 200 || a.n != 1 || b.n == 0 || c.n != 1 {
|
||||
t.Fatalf("%d %s (a %d, b %d, c %d)", code, body, a.n, b.n, c.n)
|
||||
}
|
||||
route := s.trace.routes[len(s.trace.routes)-1]
|
||||
if len(route.Tries) < 3 {
|
||||
t.Fatalf("tries: %+v", route.Tries)
|
||||
}
|
||||
recs := usage.Load(time.Time{})
|
||||
if len(recs) != 2 || recs[0].Provider != "a" || !recs[0].HandedOn || recs[0].Status != 400 ||
|
||||
recs[1].Provider != "c" || recs[1].HandedOn || recs[1].Status != 200 || recs[1].Tries != len(route.Tries) {
|
||||
t.Fatalf("usage: %+v", recs)
|
||||
}
|
||||
_, sum, _ := usage.Ledger(usage.All, usage.Filter{})
|
||||
if sum.Calls != 1 || sum.Errors != 0 || sum.Retried != 1 {
|
||||
t.Fatalf("ledger counts %d calls, %d failed, %d retried", sum.Calls, sum.Errors, sum.Retried)
|
||||
}
|
||||
if rows, _, _ := usage.Ledger(usage.All, usage.Filter{Failed: true}); len(rows) != 0 {
|
||||
t.Fatalf("failed filter keeps a request that was answered: %+v", rows)
|
||||
}
|
||||
if rows, _, _ := usage.Ledger(usage.All, usage.Filter{Retried: true}); len(rows) != 1 || rows[0].Provider != "c" {
|
||||
t.Fatalf("retried filter: %+v", rows)
|
||||
}
|
||||
|
||||
// one provider, failing outright: one request, one failure
|
||||
fresh(t)
|
||||
x := &scripted{replies: []reply{{400, "application/json", `{"type":"error","error":{"type":"invalid_request_error","message":"bad"}}`}}}
|
||||
scriptedOn(t, "x", provider.Anthropic, x)
|
||||
code, body = sendTo(New(), "/v1/messages", `{"model":"x/m","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code < 400 {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
_, sum, _ = usage.Ledger(usage.All, usage.Filter{})
|
||||
if sum.Calls != 1 || sum.Errors != 1 || sum.Retried != 0 {
|
||||
t.Fatalf("outright failure counts %d calls, %d failed, %d retried", sum.Calls, sum.Errors, sum.Retried)
|
||||
}
|
||||
if rows, _, _ := usage.Ledger(usage.All, usage.Filter{Failed: true}); len(rows) != 1 || rows[0].HandedOn || rows[0].Tries > 1 {
|
||||
t.Fatalf("failed filter: %+v", rows)
|
||||
}
|
||||
}
|
||||
@@ -827,6 +827,11 @@ body.window .field.solo { grid-column: auto; }
|
||||
.led-strip .v.cost { color: var(--green); }
|
||||
.led-strip .sub { display: block; margin-top: 3px; font-size: 11px; color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.led-strip .sub b { font-weight: 600; color: var(--fg-2); }
|
||||
/* a count on the Requests card that lists its requests */
|
||||
.led-strip .sub.jumps { white-space: normal; overflow: visible; }
|
||||
.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; }
|
||||
.led-strip .led-jump.bad { color: var(--red); }
|
||||
.led-strip .led-jump:hover, .led-strip .led-jump.on { text-decoration-style: solid; }
|
||||
.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; }
|
||||
|
||||
+50
-14
@@ -14861,7 +14861,7 @@ function renderPanelUse() {
|
||||
// the total counts the cache's tokens too, so they're named beside in and out
|
||||
const cached = l.cache_read + l.cache_write;
|
||||
blk("Tokens", fmtN(allTokens(l)), t("{a} in · {b} out", { a: fmtN(l.input), b: fmtN(l.output) }) + (cached ? " · " + t("{n} cached", { n: fmtN(cached) }) : ""));
|
||||
blk("Requests", ledNum(l.calls), l.errors ? t("{n} failed", { n: ledNum(l.errors) }) : t("none failed"), "", l.errors ? "bad" : "");
|
||||
blk("Requests", ledNum(l.calls), [l.errors ? t("{n} failed", { n: ledNum(l.errors) }) : t("none failed"), l.retried ? t("{n} answered on a retry", { n: ledNum(l.retried) }) : ""].filter(Boolean).join(" · "), "", l.errors ? "bad" : "");
|
||||
const c = fmtCost(l);
|
||||
blk("Cost", c ? "≈" + c : "—", l.unpriced ? t("{n} unpriced", { n: l.unpriced }) : t("effective prices"), c ? "cost" : "");
|
||||
blk("Cache hit rate", prompt ? Math.round((100 * l.cache_read) / prompt) + "%" : "—", t("of the prompt"));
|
||||
@@ -15975,7 +15975,7 @@ function renderUsage() {
|
||||
const hit = u.cache_read && promptTokens ? t("hit rate {p}", { p: Math.round(100 * u.cache_read / promptTokens) + "%" }) : "";
|
||||
tile(fmtN(u.cache_read), t("cache read"), hit, u.cache_write ? t("{n} written", { n: fmtN(u.cache_write) }) + cacheTTLs(u, fmtN) : "");
|
||||
tile(fmtN(u.reasoning), t("reasoning"), t("inside output"));
|
||||
tile(String(u.calls), t(u.calls === 1 ? "call" : "calls"), u.errors ? t("{n} failed", { n: u.errors }) : "");
|
||||
tile(String(u.calls), t(u.calls === 1 ? "call" : "calls"), [u.errors ? t("{n} failed", { n: u.errors }) : "", u.retried ? t("{n} answered on a retry", { n: u.retried }) : ""].filter(Boolean).join(" · "));
|
||||
|
||||
// the timeline: one bar per hour, day or week; output sits on top of input
|
||||
const chart = $("#chart");
|
||||
@@ -16015,6 +16015,7 @@ function renderUsage() {
|
||||
if (g.sub) sub.push(g.sub);
|
||||
sub.push(t(g.calls === 1 ? "{n} call" : "{n} calls", { n: g.calls }));
|
||||
if (g.errors) sub.push(t("{n} failed", { n: g.errors }));
|
||||
if (g.retried) sub.push(t("{n} answered on a retry", { n: g.retried }));
|
||||
// how long the streamed replies took to begin, and how fast they
|
||||
// wrote after (#196)
|
||||
if (g.timed) {
|
||||
@@ -16057,7 +16058,7 @@ function renderUsage() {
|
||||
// server pages it (/api/usage/requests) and saves it whole as CSV.
|
||||
|
||||
let ledger = null; // the page shown: { rows, offset, total, agents, …totals }
|
||||
let ledOffset = 0, ledPurpose = "", ledAgent = "", ledProvider = "", ledAccount = "", ledCallerKey = "", ledFailed = false, ledQuery = "", ledModel = "", ledRoute = 0, ledComputer = "", ledDay = "", ledVia = "";
|
||||
let ledOffset = 0, ledPurpose = "", ledAgent = "", ledProvider = "", ledAccount = "", ledCallerKey = "", ledFailed = false, ledRetried = false, ledQuery = "", ledModel = "", ledRoute = 0, ledComputer = "", ledDay = "", ledVia = "";
|
||||
|
||||
// computerOpts are the Computer filter's choices: this computer, the others
|
||||
// together, and each other one, as sync shares their usage (#542); none
|
||||
@@ -16079,10 +16080,10 @@ try {
|
||||
|
||||
let ledRouteInfo = null, ledBeforeRoute = null;
|
||||
window.openUsageRoute = (route) => {
|
||||
if (!ledBeforeRoute) ledBeforeRoute = { period, ledOffset, ledPurpose, ledAgent, ledProvider, ledAccount, ledCallerKey, ledFailed, ledQuery, ledModel, ledComputer, ledDay, ledVia };
|
||||
if (!ledBeforeRoute) ledBeforeRoute = { period, ledOffset, ledPurpose, ledAgent, ledProvider, ledAccount, ledCallerKey, ledFailed, ledRetried, ledQuery, ledModel, ledComputer, ledDay, ledVia };
|
||||
ledRoute = route.id;
|
||||
ledRouteInfo = route;
|
||||
ledOffset = 0; ledPurpose = ""; ledAgent = ""; ledProvider = ""; ledAccount = ""; ledCallerKey = ""; ledFailed = false; ledQuery = ""; ledModel = ""; ledComputer = ""; ledVia = "";
|
||||
ledOffset = 0; ledPurpose = ""; ledAgent = ""; ledProvider = ""; ledAccount = ""; ledCallerKey = ""; ledFailed = false; ledRetried = false; ledQuery = ""; ledModel = ""; ledComputer = ""; ledVia = "";
|
||||
ledDay = "";
|
||||
$("#ledQ").value = "";
|
||||
period = "all";
|
||||
@@ -16103,6 +16104,7 @@ function ledParams(extra) {
|
||||
if (ledVia) q.set("via", ledVia);
|
||||
if (ledRoute) q.set("route", ledRoute);
|
||||
if (ledFailed) q.set("failed", "1");
|
||||
if (ledRetried) q.set("retried", "1");
|
||||
if (ledModel) q.set("model", ledModel);
|
||||
else if (ledQuery.trim()) q.set("q", ledQuery.trim());
|
||||
if (extra) for (const k in extra) q.set(k, extra[k]);
|
||||
@@ -16781,6 +16783,16 @@ function ledRail(rail, box) {
|
||||
};
|
||||
}
|
||||
|
||||
// the request list's status filter: "" for all, "failed" or "retried"
|
||||
const ledStatusOf = () => ledFailed ? "failed" : ledRetried ? "retried" : "";
|
||||
function ledShowStatus(to) {
|
||||
if (to === ledStatusOf()) return;
|
||||
ledFailed = to === "failed";
|
||||
ledRetried = to === "retried";
|
||||
ledOffset = 0;
|
||||
loadLedger().catch((e) => status(e.message, "err"));
|
||||
}
|
||||
|
||||
function renderLedgerDash(l) {
|
||||
const dash = $("#ledDash");
|
||||
dash.hidden = !l.total && !l.day;
|
||||
@@ -16799,8 +16811,25 @@ function renderLedgerDash(l) {
|
||||
return b;
|
||||
};
|
||||
const line = (...parts) => { const s = el("span", "sub"); s.append(...parts); return s; };
|
||||
// a line holding a count's button wraps rather than cut the button off
|
||||
// (German's "nach erneutem Versuch beantwortet" runs past a narrow card)
|
||||
const jumps = (...parts) => { const s = line(...parts); s.classList.add("jumps"); return s; };
|
||||
block("Tokens", fmtN(total), line(t("{a} in · {b} out", { a: fmtN(l.input), b: fmtN(l.output) }), " · ", t("{a} cache", { a: fmtN(l.cache_read + l.cache_write) })), "", ledNum(total));
|
||||
block("Requests", ledNum(l.calls), line(l.errors ? t("{n} failed", { n: ledNum(l.errors) }) + " · " + t("{p} succeeded", { p: (100 * (1 - l.errors / l.calls)).toFixed(l.errors ? 1 : 0) + "%" }) : t("none failed")));
|
||||
// a request is counted once, by how it ended: one a later try answered
|
||||
// is not a failure, and is counted beside them as answered on a retry
|
||||
// (小一 on Discord). Each count is a button for its requests in the list.
|
||||
const jump = (text, to, title) => {
|
||||
const b = el("button", "led-jump" + (to === "failed" ? " bad" : "") + (ledStatusOf() === to ? " on" : ""), text);
|
||||
b.type = "button";
|
||||
b.title = title;
|
||||
b.setAttribute("aria-pressed", ledStatusOf() === to ? "true" : "false");
|
||||
b.onclick = () => ledShowStatus(ledStatusOf() === to ? "" : to);
|
||||
return b;
|
||||
};
|
||||
block("Requests", ledNum(l.calls), l.errors
|
||||
? jumps(jump(t("{n} failed", { n: ledNum(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")));
|
||||
if (l.retried) strip.lastChild.append(jumps(jump(t("{n} answered on a retry", { n: ledNum(l.retried) }), "retried", t("Show only the requests answered on a retry"))));
|
||||
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", (100 * rate).toFixed(1) + "%", null, "", t("The share of the prompt read from the cache"));
|
||||
@@ -17199,14 +17228,17 @@ function renderLedger() {
|
||||
})), "Gateway keys", (v) => { ledCallerKey = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
|
||||
const seg = $("#ledStatus");
|
||||
seg.replaceChildren();
|
||||
for (const [on, name] of [[false, "All"], [true, "Failed"]]) {
|
||||
const b = el("button", "opt" + (on === ledFailed ? " on" : ""), t(name));
|
||||
// every request, those the agent got an error for, and those answered
|
||||
// after a try that failed first
|
||||
const shown = ledStatusOf();
|
||||
for (const [on, name] of [["", "All"], ["failed", "Failed"], ["retried", "Retried"]]) {
|
||||
const b = el("button", "opt" + (on === shown ? " on" : ""), t(name));
|
||||
if (on === "retried") b.title = t("Show only the requests answered on a retry");
|
||||
b.onclick = () => {
|
||||
if (on === ledFailed) return;
|
||||
if (on === ledStatusOf()) return;
|
||||
for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b);
|
||||
slide(seg, "ledStatus");
|
||||
ledFailed = on; ledOffset = 0;
|
||||
loadLedger().catch((e) => status(e.message, "err"));
|
||||
ledShowStatus(on);
|
||||
};
|
||||
seg.append(b);
|
||||
}
|
||||
@@ -17217,6 +17249,7 @@ function renderLedger() {
|
||||
if (l.total) {
|
||||
sum.push(t("{n} in", { n: fmtN(l.input) }), t("{n} out", { n: fmtN(l.output) }), t("{n} cache write", { n: fmtN(l.cache_write) }), t("{n} cache read", { n: fmtN(l.cache_read) }));
|
||||
if (l.errors) sum.push(t("{n} failed", { n: l.errors }));
|
||||
if (l.retried) sum.push(t("{n} answered on a retry", { n: l.retried }));
|
||||
}
|
||||
$("#ledSum").textContent = sum.join(" · ");
|
||||
// the two sources and their total, in the same block of cells as the totals
|
||||
@@ -17277,7 +17310,7 @@ function renderLedger() {
|
||||
$("#ledRouteClear").setAttribute("aria-label", t("Clear filter"));
|
||||
$("#ledRouteClear").onclick = () => {
|
||||
ledRoute = 0; ledRouteInfo = null;
|
||||
if (ledBeforeRoute) ({ period, ledOffset, ledPurpose = "", ledAgent, ledProvider, ledAccount = "", ledCallerKey, ledFailed, ledQuery, ledModel, ledComputer = "", ledDay = "", ledVia = "" } = ledBeforeRoute);
|
||||
if (ledBeforeRoute) ({ period, ledOffset, ledPurpose = "", ledAgent, ledProvider, ledAccount = "", ledCallerKey, ledFailed, ledRetried = false, ledQuery, ledModel, ledComputer = "", ledDay = "", ledVia = "" } = ledBeforeRoute);
|
||||
ledBeforeRoute = null;
|
||||
$("#ledQ").value = ledQuery;
|
||||
loadLedger().catch((e) => status(e.message, "err"));
|
||||
@@ -17289,7 +17322,7 @@ function renderLedger() {
|
||||
const pager = $("#ledPager");
|
||||
if (!l.total) {
|
||||
wrap.classList.add("none");
|
||||
const filtered = ledPurpose || ledDay || ledRoute || ledAgent || ledProvider || ledAccount || ledComputer || ledCallerKey || ledModel || ledVia || ledFailed || ledQuery.trim();
|
||||
const filtered = ledPurpose || ledDay || ledRoute || ledAgent || ledProvider || ledAccount || ledComputer || ledCallerKey || ledModel || ledVia || ledFailed || ledRetried || ledQuery.trim();
|
||||
const none = noCallsIn(period);
|
||||
wrap.replaceChildren(el("div", "led-none", filtered ? t("No requests match these filters.") : t(none)));
|
||||
ledFit();
|
||||
@@ -17403,8 +17436,11 @@ function renderLedger() {
|
||||
// and says only whether it went well
|
||||
let word = r.status ? String(r.status) : r.source === "log" ? (bad ? r.err_type || t("Failed") : t("Succeeded")) : "—";
|
||||
if (r.status && bad && r.err_type) word += " · " + r.err_type;
|
||||
if (r.handed_on) word += " · " + t("handed on");
|
||||
else if (r.tries > 1) word += " · " + t("{n} tries", { n: r.tries });
|
||||
st.append(el("i", "dot"), document.createTextNode(word));
|
||||
td(st, "", bad ? (r.err || t("Failed: the agent was answered {status}", { status: r.status })) : "");
|
||||
td(st, "", [r.handed_on && t("This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try"),
|
||||
bad ? (r.err || t("Failed: the agent was answered {status}", { status: r.status })) : ""].filter(Boolean).join("\n"));
|
||||
const detail = ledOpen.has(key) ? ledDetail(r, LED_COLS.length) : null;
|
||||
const toggle = () => {
|
||||
if (ledOpen.delete(key)) { tr.classList.remove("open"); tr.setAttribute("aria-expanded", "false"); tr.nextElementSibling?.classList.contains("led-detail") && tr.nextElementSibling.remove(); return; }
|
||||
|
||||
@@ -2404,6 +2404,12 @@ const I18N = {
|
||||
"Nothing in this period": "这段时间没有数据",
|
||||
"No known price for these requests": "这些请求没有已知价格",
|
||||
"none failed": "没有失败",
|
||||
"{n} answered on a retry": "{n} 次重试后成功",
|
||||
"Retried": "重试后成功",
|
||||
"Show only the requests answered on a retry": "只看重试后成功的请求",
|
||||
"Show only the failed requests": "只看失败的请求",
|
||||
"handed on": "已转交",
|
||||
"This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "这次尝试失败,请求已转交给下一个:请求按最终结果计数,不算这次尝试",
|
||||
"{p} succeeded": "成功 {p}",
|
||||
"{a} cache": "缓存 {a}",
|
||||
"The share of the prompt read from the cache": "提示词中从缓存读取的比例",
|
||||
@@ -6661,6 +6667,12 @@ const I18N = {
|
||||
"Nothing in this period": "這段時間沒有資料",
|
||||
"No known price for these requests": "這些請求沒有已知價格",
|
||||
"none failed": "沒有失敗",
|
||||
"{n} answered on a retry": "{n} 次重試後成功",
|
||||
"Retried": "重試後成功",
|
||||
"Show only the requests answered on a retry": "只看重試後成功的請求",
|
||||
"Show only the failed requests": "只看失敗的請求",
|
||||
"handed on": "已轉交",
|
||||
"This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "這次嘗試失敗,請求已轉交給下一個:請求依最終結果計數,不算這次嘗試",
|
||||
"{p} succeeded": "成功 {p}",
|
||||
"{a} cache": "快取 {a}",
|
||||
"The share of the prompt read from the cache": "提示詞中從快取讀取的比例",
|
||||
@@ -10919,6 +10931,12 @@ const I18N = {
|
||||
"Nothing in this period": "この期間のデータはありません",
|
||||
"No known price for these requests": "これらのリクエストの価格は不明です",
|
||||
"none failed": "失敗なし",
|
||||
"{n} answered on a retry": "{n} 件が再試行で成功",
|
||||
"Retried": "再試行で成功",
|
||||
"Show only the requests answered on a retry": "再試行で成功したリクエストだけを表示",
|
||||
"Show only the failed requests": "失敗したリクエストだけを表示",
|
||||
"handed on": "引き継ぎ",
|
||||
"This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "この試行は失敗し、リクエストは次へ引き継がれました。リクエストはこの試行ではなく最終結果で数えます",
|
||||
"{p} succeeded": "成功 {p}",
|
||||
"{a} cache": "キャッシュ {a}",
|
||||
"The share of the prompt read from the cache": "プロンプトのうちキャッシュから読み取られた割合",
|
||||
@@ -15176,6 +15194,12 @@ const I18N = {
|
||||
"Nothing in this period": "Nichts in diesem Zeitraum",
|
||||
"No known price for these requests": "Kein bekannter Preis für diese Anfragen",
|
||||
"none failed": "keine fehlgeschlagen",
|
||||
"{n} answered on a retry": "{n} nach erneutem Versuch beantwortet",
|
||||
"Retried": "Wiederholt",
|
||||
"Show only the requests answered on a retry": "Nur die nach erneutem Versuch beantworteten Anfragen zeigen",
|
||||
"Show only the failed requests": "Nur die fehlgeschlagenen Anfragen zeigen",
|
||||
"handed on": "weitergereicht",
|
||||
"This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "Dieser Versuch schlug fehl, und die Anfrage ging an den nächsten weiter: Gezählt wird die Anfrage nach ihrem Ausgang, nicht nach diesem Versuch",
|
||||
"{p} succeeded": "{p} erfolgreich",
|
||||
"{a} cache": "{a} Cache",
|
||||
"The share of the prompt read from the cache": "Anteil des Prompts, der aus dem Cache gelesen wurde",
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// The Requests card counts requests, each once by how it ended (小一 on
|
||||
// Discord: 「5,482 · 1,094 次失败」 while the list's 「2 次尝试 / 3 次尝试」
|
||||
// rows had been answered): a request answered after a try that failed is
|
||||
// counted beside the failures as answered on a retry. Each count is a
|
||||
// button for its requests: "N failed" turns on the list's Failed filter,
|
||||
// "N answered on a retry" its Retried one, and the button again turns it
|
||||
// off. A try handed on to the next says so in its row, and a request that
|
||||
// took more than one says how many. No click moves the page, nothing runs
|
||||
// past the window at 420 or 1100 wide, in every language; 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 = new Date();
|
||||
const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString();
|
||||
const row = (i, extra) => ({
|
||||
t: at(i), agent: "codex", agentName: "Codex", icon: "codex", provider: "relay", providerName: "Relay",
|
||||
req: "group/g", model: "gpt-5", served: "gpt-5", in: 300, out: 40, ms: 2000, status: 200, rid: "r-" + i, route_id: 1000 + i, ...extra,
|
||||
});
|
||||
// answered on its third try, after a refusal kept for what it billed; one
|
||||
// that failed outright; one answered at once
|
||||
const RETRIED = row(0, { tries: 3, route_id: 900 });
|
||||
const HANDED = row(1, { status: 400, err: "refused", handed_on: true, route_id: 900, out: 2 });
|
||||
const FAILED = row(2, { status: 502, err: "bad gateway", tries: 2, out: 0 });
|
||||
const OK = row(3);
|
||||
const sum = (rows, calls, errors, retried) => ({ rows, offset: 0, total: rows.length, calls, errors, retried, input: 300 * rows.length, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0, unpriced: rows.length });
|
||||
|
||||
function serve(lang, asked) {
|
||||
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3));
|
||||
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
|
||||
}
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/requests") {
|
||||
const q = url.searchParams;
|
||||
asked.push(q);
|
||||
const base = { period: q.get("period"), agents: [{ id: "codex", name: "Codex", icon: "codex" }] };
|
||||
if (q.get("failed") === "1") return json({ ...base, ...sum([FAILED], 1, 1, 0) });
|
||||
if (q.get("retried") === "1") return json({ ...base, ...sum([RETRIED], 1, 0, 1) });
|
||||
return json({ ...base, ...sum([RETRIED, HANDED, FAILED, OK], 3, 1, 1) });
|
||||
}
|
||||
if (url.pathname === "/api/usage/requests/content") return json({ found: false, why: "read" });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/usage") return json({ calls: 3, errors: 1, retried: 1, input: 1200, output: 160, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 4, cost: 0, 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.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)];
|
||||
const body = await fs.readFile(file).catch(() => null);
|
||||
await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }));
|
||||
};
|
||||
}
|
||||
|
||||
const STRINGS = ["{n} failed", "{n} answered on a retry", "Retried", "Failed", "Show only the failed requests", "Show only the requests answered on a retry",
|
||||
"handed on", "{n} tries", "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try"];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
for (const width of [420, 1100]) {
|
||||
test(`${engine} ${lang} ${width}: the Requests card's counts list their requests`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], asked = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, asked));
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-retried.png`), fullPage: true });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
const tr = (k, vars) => page.evaluate(([k, vars]) => t(k, vars), [k, vars || {}]);
|
||||
await page.locator("#usageTab .opt").nth(1).click();
|
||||
const rows = page.locator(".led tbody tr.led-row");
|
||||
await rows.nth(3).waitFor({ timeout: 15000 });
|
||||
|
||||
// every string, in every language
|
||||
for (const l of ["zh", "zh-TW", "ja", "de"]) {
|
||||
const missing = await page.evaluate(([l, ks]) => ks.filter((k) => !I18N[l][k]), [l, STRINGS]);
|
||||
assert.deepEqual(missing, [], `every string has its ${l}`);
|
||||
}
|
||||
|
||||
// the card: 3 requests, 1 failed, 1 answered on a retry, each a button
|
||||
const card = page.locator("#ledKpi .blk").nth(1);
|
||||
assert.equal((await card.locator(".v").textContent()).trim(), "3");
|
||||
const failed = card.locator("button.led-jump.bad"), retried = card.locator("button.led-jump:not(.bad)");
|
||||
assert.equal(await failed.textContent(), await tr("{n} failed", { n: "1" }));
|
||||
assert.equal(await retried.textContent(), await tr("{n} answered on a retry", { n: "1" }));
|
||||
assert.equal(await failed.getAttribute("title"), await tr("Show only the failed requests"));
|
||||
// whole, inside the card, and nothing past the window
|
||||
const fits = await card.evaluate((b) => {
|
||||
const r = b.getBoundingClientRect();
|
||||
return [...b.querySelectorAll("button.led-jump")].map((x) => {
|
||||
const s = x.getBoundingClientRect(), line = x.parentElement;
|
||||
return s.width > 0 && s.left >= r.left - 0.5 && s.right <= r.right + 0.5 && line.scrollWidth <= line.clientWidth + 1;
|
||||
});
|
||||
});
|
||||
assert.deepEqual(fits, [true, true], "both counts shown whole in the card");
|
||||
const noHScroll = () => page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1);
|
||||
assert(await noHScroll(), "the page runs past the window");
|
||||
const seg = await page.locator("#ledStatus").evaluate((s) => {
|
||||
const r = s.getBoundingClientRect();
|
||||
return { opts: [...s.querySelectorAll(".opt")].map((o) => o.textContent), inside: r.right <= innerWidth + 0.5 && r.left >= -0.5 };
|
||||
});
|
||||
assert.deepEqual(seg.opts, [await tr("All"), await tr("Failed"), await tr("Retried")]);
|
||||
assert(seg.inside, "the status filter is cut off");
|
||||
|
||||
// the rows: the try handed on, and the request that took three
|
||||
const status = (i) => rows.nth(i).locator("td .st").textContent();
|
||||
assert.equal(await status(0), "200 · " + (await tr("{n} tries", { n: 3 })));
|
||||
assert.equal(await status(1), "400 · " + (await tr("handed on")));
|
||||
const why = await rows.nth(1).locator("td:has(.st)").getAttribute("title");
|
||||
assert(why.includes(await tr("This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try")) && why.includes("refused"), why);
|
||||
assert.equal(await status(3), "200");
|
||||
|
||||
// a click on a count: the list's filter, the page where it was
|
||||
const top = () => page.locator("#view-usage").evaluate((v) => v.scrollTop);
|
||||
const press = async (b) => {
|
||||
await reader.inView(page, b);
|
||||
const was = await top(), xy = await page.evaluate(() => [scrollX, scrollY]);
|
||||
const n = asked.length;
|
||||
await b.click();
|
||||
await page.waitForTimeout(300);
|
||||
assert(asked.length > n, "the click asked for the list again");
|
||||
assert.equal(await top(), was, "a click moved the page");
|
||||
assert.deepEqual(await page.evaluate(() => [scrollX, scrollY]), xy);
|
||||
return asked[asked.length - 1];
|
||||
};
|
||||
let q = await press(failed);
|
||||
assert.equal(q.get("failed"), "1");
|
||||
assert.equal(q.get("retried"), null);
|
||||
await page.waitForFunction(() => document.querySelectorAll(".led tbody tr.led-row").length === 1);
|
||||
assert.equal(await page.locator("#ledStatus .opt.on").textContent(), await tr("Failed"));
|
||||
assert.equal(await card.locator("button.led-jump.bad").getAttribute("aria-pressed"), "true");
|
||||
// pressed again: every request
|
||||
q = await press(card.locator("button.led-jump.bad"));
|
||||
assert.equal(q.get("failed"), null);
|
||||
await rows.nth(3).waitFor();
|
||||
assert.equal(await page.locator("#ledStatus .opt.on").textContent(), await tr("All"));
|
||||
|
||||
q = await press(card.locator("button.led-jump:not(.bad)"));
|
||||
assert.equal(q.get("retried"), "1");
|
||||
assert.equal(q.get("failed"), null);
|
||||
await page.waitForFunction(() => document.querySelectorAll(".led tbody tr.led-row").length === 1);
|
||||
assert.equal(await page.locator("#ledStatus .opt.on").textContent(), await tr("Retried"));
|
||||
// and from the filter itself, straight to Failed
|
||||
q = await press(page.locator("#ledStatus .opt").nth(1));
|
||||
assert.equal(q.get("failed"), "1");
|
||||
assert.equal(q.get("retried"), null);
|
||||
await page.locator("#ledStatus .opt.on", { hasText: await tr("Failed") }).waitFor();
|
||||
q = await press(page.locator("#ledStatus .opt").nth(0));
|
||||
assert.equal(q.get("failed"), null);
|
||||
await rows.nth(3).waitFor();
|
||||
assert(await noHScroll(), "the page runs past the window");
|
||||
|
||||
// the Usage page's overview counts the same way
|
||||
await page.locator("#usageTab .opt").nth(0).click();
|
||||
const both = (await tr("{n} failed", { n: 1 })) + " · " + (await tr("{n} answered on a retry", { n: 1 }));
|
||||
await page.waitForFunction((s) => document.querySelector("#view-usage").textContent.includes(s), both);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -135,7 +135,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.equal(await page.locator("#ledPurpose span").textContent(), lang === "zh" ? "未标记" : "Unmarked");
|
||||
await choose("#ledPurpose", "kind:thread_title");
|
||||
await waitRows(100);
|
||||
await click(page, page.locator("#ledStatus .opt").last());
|
||||
await click(page, page.locator("#ledStatus .opt").nth(1)); // Failed
|
||||
await waitRows(1);
|
||||
await click(page, page.locator("#ledExport"));
|
||||
await page.waitForFunction(() => document.querySelector("#status")?.textContent.includes("purpose.csv"));
|
||||
|
||||
@@ -1032,6 +1032,9 @@ func (m model) usageBlock(b *strings.Builder, s usage.Summary, room int, names m
|
||||
if s.Errors > 0 {
|
||||
line += sMuted.Render(" · ") + sBad.Render(fmt.Sprintf("%d error%s", s.Errors, plural(s.Errors)))
|
||||
}
|
||||
if s.Retried > 0 { // answered after a try that failed first, not an error
|
||||
line += sMuted.Render(fmt.Sprintf(" · %d answered on a retry", s.Retried))
|
||||
}
|
||||
b.WriteString(pad + " " + line + "\n")
|
||||
b.WriteString(pad + " " + sMuted.Render("in "+fmtTokens(s.Input)+" out "+fmtTokens(s.Output)+" cache read "+fmtTokens(s.CacheRead)+" cache write "+fmtTokens(s.CacheWrite)+" reasoning "+fmtTokens(s.Reasoning)) + "\n\n")
|
||||
|
||||
|
||||
@@ -83,7 +83,9 @@ func heatmapOf(since, now time.Time, visit func(add func(Row))) *Heatmap {
|
||||
x = &Day{Date: d}
|
||||
at[d] = x
|
||||
}
|
||||
x.Calls++
|
||||
if !r.HandedOn {
|
||||
x.Calls++ // a request, not each try at it
|
||||
}
|
||||
x.Tokens += r.Input + r.Output + r.CacheRead + r.CacheWrite
|
||||
switch {
|
||||
case r.Priced:
|
||||
|
||||
@@ -54,7 +54,12 @@ type Filter struct {
|
||||
// Account narrows to the calls a subscription account answered, by its
|
||||
// name as Record.Account gives it (#557)
|
||||
Account string
|
||||
// Failed keeps the rows of the requests the agent got an error for
|
||||
// (Record.LostRequest), Retried those of the requests answered after a
|
||||
// try that failed first (Record.RetriedRequest): what the Requests
|
||||
// card's two counts are of
|
||||
Failed bool
|
||||
Retried bool
|
||||
Query string
|
||||
// Computer narrows to the calls of one computer (#542): ThisComputer,
|
||||
// OtherComputers, or another's id; "" is every computer's
|
||||
@@ -149,7 +154,10 @@ func (f Filter) keeps(r Record) bool {
|
||||
if !f.computer(r) {
|
||||
return false
|
||||
}
|
||||
if f.Failed && !r.Failed() {
|
||||
if f.Failed && !r.LostRequest() {
|
||||
return false
|
||||
}
|
||||
if f.Retried && !r.RetriedRequest() {
|
||||
return false
|
||||
}
|
||||
if q := strings.ToLower(strings.TrimSpace(f.Query)); q != "" {
|
||||
@@ -483,14 +491,17 @@ var CSVHeader = []string{"time", "agent", "requested_model", "provider", "host",
|
||||
"effort", "input_tokens", "output_tokens", "cache_write_tokens", "cache_read_tokens", "reasoning_tokens",
|
||||
"cost_usd", "duration_ms", "ttft_ms", "status", "error", "session", "kind", "provider_key_id", "provider_key_name", "provider_account", "route_id",
|
||||
"request_id", "endpoint", "error_message", "error_type", "source", "rejected", "session_provider", "session_account", "session_official_login", "caller_key_id", "caller_key_name", "response_id", "upstream",
|
||||
"cache_write_5m_tokens", "cache_write_1h_tokens"}
|
||||
"cache_write_5m_tokens", "cache_write_1h_tokens", "tries", "handed_on"}
|
||||
|
||||
// WriteCSV writes rows as CSV, a header first (cache_write_tokens is every
|
||||
// cache write, as it always was, and the last two columns split it into
|
||||
// 5-minute and 1-hour writes): times in RFC 3339 with
|
||||
// their offset, the cost in USD at the effective price (empty when unknown), error
|
||||
// "true" for a call that failed: answered with a status of 400 or more, or
|
||||
// ended by an error a session file tells.
|
||||
// ended by an error a session file tells. tries is how many tries the
|
||||
// gateway made at the request the row ends, when more than one, and
|
||||
// handed_on "true" for the row of a try that failed and handed the request
|
||||
// on: the request's outcome is the row with the same route_id after it.
|
||||
func WriteCSV(w io.Writer, rows []Row) error {
|
||||
cw := csv.NewWriter(w)
|
||||
cw.Write(CSVHeader)
|
||||
@@ -504,6 +515,10 @@ func WriteCSV(w io.Writer, rows []Row) error {
|
||||
if r.TTFT > 0 {
|
||||
ttft = strconv.FormatInt(r.TTFT, 10)
|
||||
}
|
||||
tries := ""
|
||||
if r.Tries > 0 {
|
||||
tries = n(r.Tries)
|
||||
}
|
||||
routeID := ""
|
||||
if r.RouteID != 0 {
|
||||
routeID = strconv.FormatInt(r.RouteID, 10)
|
||||
@@ -512,7 +527,7 @@ func WriteCSV(w io.Writer, rows []Row) error {
|
||||
strconv.FormatBool(r.Swapped), r.Effort, n(r.Input), n(r.Output), n(r.CacheWrite), n(r.CacheRead), n(r.Reasoning),
|
||||
cost, strconv.FormatInt(r.Millis, 10), ttft, n(r.Status), strconv.FormatBool(r.Failed()), r.Session, r.Kind, r.ProviderKeyID, r.ProviderKeyName, r.Account(), routeID,
|
||||
r.RequestID, r.Endpoint, r.Error, r.ErrType, r.Source, strconv.FormatBool(r.IsRejected()), r.SessionProvider, r.SessionAccount, strconv.FormatBool(r.SessionOfficialLogin), r.CallerKeyID, r.CallerKeyName, r.ResponseID, r.Upstream,
|
||||
n(r.CacheWrite - min(r.CacheWrite1h, r.CacheWrite)), n(min(r.CacheWrite1h, r.CacheWrite))})
|
||||
n(r.CacheWrite - min(r.CacheWrite1h, r.CacheWrite)), n(min(r.CacheWrite1h, r.CacheWrite)), tries, strconv.FormatBool(r.HandedOn)})
|
||||
}
|
||||
cw.Flush()
|
||||
return cw.Error()
|
||||
@@ -614,10 +629,7 @@ func (t *Totals) addRow(r Row) {
|
||||
t.FloorMs += ms
|
||||
t.FloorN++
|
||||
}
|
||||
t.Calls++
|
||||
if r.Failed() {
|
||||
t.Errors++
|
||||
}
|
||||
t.count(r.Record)
|
||||
t.Input += r.Input
|
||||
t.Output += r.Output
|
||||
t.CacheRead += r.CacheRead
|
||||
@@ -789,7 +801,9 @@ type Part struct {
|
||||
|
||||
// add counts a row in the part.
|
||||
func (p *Part) add(r Row) {
|
||||
p.Calls++
|
||||
if !r.HandedOn {
|
||||
p.Calls++
|
||||
}
|
||||
p.Tokens += r.Input + r.Output + r.CacheRead + r.CacheWrite
|
||||
if r.Priced {
|
||||
p.Cost += r.Cost
|
||||
|
||||
@@ -90,8 +90,8 @@ func TestLedger(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := strings.Join(CSVHeader, ",") + "\n" +
|
||||
rows[1].Time.Format(time.RFC3339) + ",codex,relay/sol,relay,relay.example,sol,sol-2026-01-01,false,,10,1,0,0,0,0.000028,100,,200,false,,,,,,,,,,,,false,,,false,,,,,0,0\n" +
|
||||
rows[2].Time.Format(time.RFC3339) + ",codex,fast,relay,relay.example,sol,luna,true,high,2000,500,1000,4000,0,0.012500,3200,400,200,false,s1,,,,,123,,,,,,false,,,false,,,,,1000,0\n"
|
||||
rows[1].Time.Format(time.RFC3339) + ",codex,relay/sol,relay,relay.example,sol,sol-2026-01-01,false,,10,1,0,0,0,0.000028,100,,200,false,,,,,,,,,,,,false,,,false,,,,,0,0,,false\n" +
|
||||
rows[2].Time.Format(time.RFC3339) + ",codex,fast,relay,relay.example,sol,luna,true,high,2000,500,1000,4000,0,0.012500,3200,400,200,false,s1,,,,,123,,,,,,false,,,false,,,,,1000,0,,false\n"
|
||||
if b.String() != want {
|
||||
t.Fatalf("csv:\n%s\nwant:\n%s", b.String(), want)
|
||||
}
|
||||
@@ -261,7 +261,7 @@ func TestLedgerWithSessionLogCalls(t *testing.T) {
|
||||
if err := WriteCSV(&b, rows[2:4]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{",req_log,,,,log,false,,,false,,,,,500,0\n", ",true,s2,,,,,,req_lim,,You've hit your limit,rate_limit,log,false,,,false,,,,,0,0\n"} {
|
||||
for _, want := range []string{",req_log,,,,log,false,,,false,,,,,500,0,,false\n", ",true,s2,,,,,,req_lim,,You've hit your limit,rate_limit,log,false,,,false,,,,,0,0,,false\n"} {
|
||||
if !strings.Contains(b.String(), want) {
|
||||
t.Fatalf("csv lacks %q:\n%s", want, b.String())
|
||||
}
|
||||
|
||||
@@ -116,9 +116,13 @@ func readLogSnapshot() *logSnapshot {
|
||||
return next
|
||||
}
|
||||
var tail *rowChunk
|
||||
routes := routeRows{}
|
||||
if n := len(next.blocks); n > 0 && next.blocks[n-1].Count < logBlockRows {
|
||||
tail = next.blocks[n-1].writable()
|
||||
next.blocks = next.blocks[:n-1]
|
||||
for i := range tail.Rows {
|
||||
routes.seen(tail, i)
|
||||
}
|
||||
}
|
||||
rd := bufio.NewReaderSize(io.LimitReader(f, info.Size()-next.off), 64<<10)
|
||||
for next.off < info.Size() {
|
||||
@@ -135,7 +139,9 @@ func readLogSnapshot() *logSnapshot {
|
||||
if tail == nil {
|
||||
tail = &rowChunk{}
|
||||
}
|
||||
routes.handedOn(tail, &r)
|
||||
tail.add(Row{Record: r}, "", next.off, false)
|
||||
routes.seen(tail, len(tail.Rows)-1)
|
||||
if !r.IsRejected() && (next.first.IsZero() || r.Time.Before(next.first)) {
|
||||
next.first = r.Time
|
||||
}
|
||||
@@ -145,6 +151,7 @@ func readLogSnapshot() *logSnapshot {
|
||||
if len(tail.Rows) == logBlockRows {
|
||||
next.blocks = append(next.blocks, tail.freeze())
|
||||
tail = nil
|
||||
clear(routes)
|
||||
}
|
||||
}
|
||||
if tail != nil {
|
||||
@@ -171,6 +178,37 @@ func readLogSnapshot() *logSnapshot {
|
||||
return next
|
||||
}
|
||||
|
||||
// routeRows are the rows of the block being written, by their route: where
|
||||
// each route's last row is.
|
||||
type routeRows map[int64]int
|
||||
|
||||
func (o routeRows) seen(c *rowChunk, i int) {
|
||||
if id := c.Rows[i].RouteID; id != 0 {
|
||||
o[id] = i
|
||||
}
|
||||
}
|
||||
|
||||
// handedOn tells, of a log written before Record.HandedOn was, the row of
|
||||
// a try that failed and handed its request on: a failed row of r's route
|
||||
// before r, whose outcome r is. r then ends a request with a try before
|
||||
// it. Only rows in the same block are told, which is where the gateway's
|
||||
// rows of one request land but for one in 512 at a block's edge.
|
||||
func (o routeRows) handedOn(c *rowChunk, r *Record) {
|
||||
if r.RouteID == 0 {
|
||||
return
|
||||
}
|
||||
j, ok := o[r.RouteID]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
p := &c.Rows[j]
|
||||
if p.Flags&rowHandedOn != 0 || p.Flags&4 != 0 || !(p.Status >= 400 || p.Text[rowError] != 0) {
|
||||
return
|
||||
}
|
||||
p.Flags |= rowHandedOn
|
||||
r.Tries = max(r.Tries, 2)
|
||||
}
|
||||
|
||||
func (s *logSnapshot) visit(since time.Time, fn func(Record)) {
|
||||
for _, packed := range s.blocks {
|
||||
if !since.IsZero() && packed.Latest.Before(since) {
|
||||
|
||||
@@ -65,9 +65,13 @@ type packedRow struct {
|
||||
Sent, Flow int64
|
||||
RouteID int64
|
||||
Cost float64
|
||||
Status int32
|
||||
Status, Tries int32
|
||||
Flags uint8
|
||||
}
|
||||
|
||||
// rowHandedOn is the Flags bit of Record.HandedOn
|
||||
const rowHandedOn = 128
|
||||
|
||||
type rowChunk struct {
|
||||
Archive []byte
|
||||
Locations []*time.Location
|
||||
@@ -83,8 +87,12 @@ type rowChunk struct {
|
||||
Computer string
|
||||
}
|
||||
|
||||
// rowMsg is the Text of a row's Claude message id, after rowText's
|
||||
const rowMsg = 29
|
||||
// rowMsg is the Text of a row's Claude message id, after rowText's, and
|
||||
// rowError its error's
|
||||
const (
|
||||
rowMsg = 29
|
||||
rowError = 9
|
||||
)
|
||||
|
||||
func rowText(r *Row) [29]*string {
|
||||
return [29]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream, &r.Subagent, &r.ParentAgent}
|
||||
@@ -104,7 +112,7 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
|
||||
c.Bytes += int64(len(s) + 48)
|
||||
return id
|
||||
}
|
||||
p := packedRow{Time: r.Time, Tokens: [6]int64{int64(r.Input), int64(r.Output), int64(r.CacheRead), int64(r.CacheWrite), int64(r.Reasoning), int64(r.CacheWrite1h)}, Millis: r.Millis, TTFT: r.TTFT, FirstText: r.FirstText, Sent: r.Sent, Flow: r.Flow, Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: int32(r.Status)}
|
||||
p := packedRow{Time: r.Time, Tokens: [6]int64{int64(r.Input), int64(r.Output), int64(r.CacheRead), int64(r.CacheWrite), int64(r.Reasoning), int64(r.CacheWrite1h)}, Millis: r.Millis, TTFT: r.TTFT, FirstText: r.FirstText, Sent: r.Sent, Flow: r.Flow, Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: int32(r.Status), Tries: int32(r.Tries)}
|
||||
for i, s := range rowText(&r) {
|
||||
p.Text[i] = intern(*s)
|
||||
}
|
||||
@@ -127,6 +135,9 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
|
||||
if failed {
|
||||
p.Flags |= 16
|
||||
}
|
||||
if r.HandedOn {
|
||||
p.Flags |= rowHandedOn
|
||||
}
|
||||
c.Rows = append(c.Rows, p)
|
||||
c.Count = len(c.Rows)
|
||||
if r.Time.After(c.Latest) {
|
||||
@@ -136,7 +147,7 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
|
||||
}
|
||||
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: p.Millis, TTFT: p.TTFT, FirstText: p.FirstText, Sent: p.Sent, Flow: p.Flow, Status: int(p.Status), 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: p.Millis, TTFT: p.TTFT, FirstText: p.FirstText, Sent: p.Sent, Flow: p.Flow, 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}
|
||||
for i, s := range rowText(&r) {
|
||||
*s = c.Strings[p.Text[i]]
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ func (c *rowChunk) pack() *rowChunk {
|
||||
put(math.Float64bits(p.Cost))
|
||||
put(uint64(p.Status))
|
||||
put(uint64(p.Flags))
|
||||
put(uint64(p.Tries))
|
||||
}
|
||||
archive := s2.Encode(nil, data)
|
||||
if int64(len(archive)) >= c.Bytes {
|
||||
@@ -153,6 +154,7 @@ func (c *rowChunk) unpackInto(into []packedRow) *rowChunk {
|
||||
p.RouteID = int64(take())
|
||||
p.Sent, p.Flow = int64(take()), int64(take())
|
||||
p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int32(take()), uint8(take())
|
||||
p.Tries = int32(take())
|
||||
}
|
||||
if !valid || len(data) != 0 {
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The Requests card counts requests, not tries (小一 on Discord): a try
|
||||
// that failed and handed its request on to another account is neither a
|
||||
// request nor a failure of its own, and a request answered after such a
|
||||
// try is counted as answered on a retry. Failed is what the agent got an
|
||||
// error for. A log written before the gateway marked those tries is told
|
||||
// by its route: a failed row whose route a later row ends.
|
||||
func TestRequestsCountedOnceWithTheirRetries(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
now := time.Now()
|
||||
at := func(m int) string { return now.Add(time.Duration(m-10) * time.Second).Format(time.RFC3339Nano) }
|
||||
lines := []string{
|
||||
// written before handed_on: a safety refusal that a group's next
|
||||
// member answered, the two sharing the route
|
||||
`{"t":"` + at(1) + `","agent":"claude","provider":"yylx","model":"m","in":10,"ms":5,"status":400,"error":"content blocked by the safety filter","route_id":101}`,
|
||||
`{"t":"` + at(2) + `","agent":"claude","provider":"b","model":"m","in":10,"out":5,"ms":9,"status":200,"route_id":101}`,
|
||||
// today's: a refused try handed on, a 429 that wrote no row, then
|
||||
// the answer on the third try
|
||||
`{"t":"` + at(3) + `","agent":"codex","provider":"a","model":"m","in":20,"ms":5,"status":400,"error":"refused","route_id":102,"handed_on":true}`,
|
||||
`{"t":"` + at(4) + `","agent":"codex","provider":"c","model":"m","in":20,"out":7,"ms":9,"status":200,"route_id":102,"tries":3}`,
|
||||
// a request that failed outright, after two tries
|
||||
`{"t":"` + at(5) + `","agent":"codex","provider":"a","model":"m","ms":5,"status":502,"error":"bad gateway","route_id":103,"tries":2}`,
|
||||
// one answered at once, and one that failed with no route at all
|
||||
`{"t":"` + at(6) + `","agent":"codex","provider":"a","model":"m","in":1,"out":1,"ms":5,"status":200,"route_id":104}`,
|
||||
`{"t":"` + at(7) + `","agent":"codex","provider":"a","model":"m","ms":5,"status":429}`,
|
||||
}
|
||||
var b bytes.Buffer
|
||||
for _, l := range lines {
|
||||
b.WriteString(l + "\n")
|
||||
}
|
||||
os.MkdirAll(filepath.Dir(Path()), 0o755)
|
||||
if err := os.WriteFile(Path(), b.Bytes(), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rows, sum, _ := Ledger(Today, Filter{})
|
||||
// five requests: 101 and 102 answered on a retry, 103 and the routeless
|
||||
// 429 failed, 104 answered; all seven rows are still listed, and the
|
||||
// handed-on tries' tokens are still in the sums
|
||||
if len(rows) != 7 || sum.Calls != 5 || sum.Errors != 2 || sum.Retried != 2 || sum.Input != 61 {
|
||||
t.Fatalf("rows %d, calls %d, errors %d, retried %d, in %d", len(rows), sum.Calls, sum.Errors, sum.Retried, sum.Input)
|
||||
}
|
||||
handed := 0
|
||||
for _, r := range rows {
|
||||
if r.HandedOn {
|
||||
handed++
|
||||
if r.RouteID != 101 && r.RouteID != 102 {
|
||||
t.Fatalf("handed on: %+v", r)
|
||||
}
|
||||
}
|
||||
if r.RouteID == 101 && r.Status == 200 && r.Tries != 2 {
|
||||
t.Fatalf("legacy answer's tries %d", r.Tries)
|
||||
}
|
||||
}
|
||||
if handed != 2 {
|
||||
t.Fatalf("%d rows handed on, want 2", handed)
|
||||
}
|
||||
|
||||
failed, fsum, _ := Ledger(Today, Filter{Failed: true})
|
||||
if len(failed) != 2 || fsum.Errors != 2 || fsum.Calls != 2 {
|
||||
t.Fatalf("failed filter: %d rows, %+v", len(failed), fsum)
|
||||
}
|
||||
for _, r := range failed {
|
||||
if r.HandedOn || !r.Failed() {
|
||||
t.Fatalf("failed filter kept %+v", r)
|
||||
}
|
||||
}
|
||||
retried, rsum, _ := Ledger(Today, Filter{Retried: true})
|
||||
if len(retried) != 2 || rsum.Retried != 2 || rsum.Errors != 0 {
|
||||
t.Fatalf("retried filter: %d rows, %+v", len(retried), rsum)
|
||||
}
|
||||
for _, r := range retried {
|
||||
if r.Status != 200 || r.Tries < 2 {
|
||||
t.Fatalf("retried filter kept %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
page := QueryPage(Today, Filter{}, 0, 100)
|
||||
if page.Sum.Calls != 5 || page.Sum.Errors != 2 || page.Sum.Retried != 2 {
|
||||
t.Fatalf("page sum %+v", page.Sum)
|
||||
}
|
||||
if p := QueryPage(Today, Filter{Failed: true}, 0, 100); p.Total != 2 {
|
||||
t.Fatalf("failed page has %d rows", p.Total)
|
||||
}
|
||||
if p := QueryPage(Today, Filter{Retried: true}, 0, 100); p.Total != 2 {
|
||||
t.Fatalf("retried page has %d rows", p.Total)
|
||||
}
|
||||
if s := Summarize(Today); s.Calls != 5 || s.Errors != 2 || s.Retried != 2 {
|
||||
t.Fatalf("summary %d calls, %d errors, %d retried", s.Calls, s.Errors, s.Retried)
|
||||
}
|
||||
calls := 0
|
||||
for _, d := range HeatmapOf(Filter{}).Days {
|
||||
calls += d.Calls
|
||||
}
|
||||
if calls != 5 {
|
||||
t.Fatalf("heatmap counts %d calls", calls)
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := WriteCSV(&out, rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recs, err := csv.NewReader(&out).ReadAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head := recs[0]
|
||||
ti, hi := -1, -1
|
||||
for i, h := range head {
|
||||
switch h {
|
||||
case "tries":
|
||||
ti = i
|
||||
case "handed_on":
|
||||
hi = i
|
||||
}
|
||||
}
|
||||
if ti < 0 || hi < 0 {
|
||||
t.Fatalf("CSV header %v", head)
|
||||
}
|
||||
seen := map[string]int{}
|
||||
for _, r := range recs[1:] {
|
||||
seen[r[ti]+"/"+r[hi]]++
|
||||
}
|
||||
if seen["/true"] != 2 || seen["3/false"] != 1 || seen["2/false"] != 2 {
|
||||
t.Fatalf("CSV tries/handed_on %v", seen)
|
||||
}
|
||||
}
|
||||
+39
-4
@@ -123,6 +123,17 @@ type Record struct {
|
||||
ParentAgent string `json:"parent_agent,omitempty"`
|
||||
// Rejected is a request refused locally before an upstream was contacted.
|
||||
Rejected bool `json:"rejected,omitempty"`
|
||||
// Tries is how many tries the gateway made at the request this row
|
||||
// ends, as its route lists them, when there was more than one: a
|
||||
// request answered on a later try was answered, not failed (小一 on
|
||||
// Discord). HandedOn marks the row of one try that failed and handed
|
||||
// the request on to the next (a vendor's refusal kept for what it
|
||||
// billed): it is not the request's outcome, which a later row with
|
||||
// the same RouteID is, so it is neither a request nor a failure of
|
||||
// its own. Neither is in a record written before they were; the log
|
||||
// index tells HandedOn from such a record's route (handedOn).
|
||||
Tries int `json:"tries,omitempty"`
|
||||
HandedOn bool `json:"handed_on,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"`
|
||||
@@ -301,8 +312,12 @@ func (r Record) CostAt(p catalog.Price) float64 {
|
||||
|
||||
// Totals is a sum of calls.
|
||||
type Totals struct {
|
||||
// Calls are the requests, Errors those the agent got an error for, and
|
||||
// Retried those answered after a try that failed first (Record.Tries):
|
||||
// a try handed on is in neither count, but its tokens are in the sums
|
||||
Calls int `json:"calls"`
|
||||
Errors int `json:"errors"`
|
||||
Retried int `json:"retried,omitempty"`
|
||||
Input int `json:"input"`
|
||||
Output int `json:"output"`
|
||||
CacheRead int `json:"cache_read"`
|
||||
@@ -482,10 +497,7 @@ func FormatCost(amountUSD float64, currency string, rate float64) string {
|
||||
}
|
||||
|
||||
func (t *Totals) add(r Record, price *catalog.Price) {
|
||||
t.Calls++
|
||||
if r.Failed() {
|
||||
t.Errors++
|
||||
}
|
||||
t.count(r)
|
||||
t.Input += r.Input
|
||||
t.Output += r.Output
|
||||
t.CacheRead += r.CacheRead
|
||||
@@ -511,6 +523,29 @@ func (t *Totals) add(r Record, price *catalog.Price) {
|
||||
t.Cost += r.CostAt(*price)
|
||||
}
|
||||
|
||||
// count counts r as the request it ends: failed, answered on a retry, or
|
||||
// answered; a try handed on to another is no request of its own.
|
||||
func (t *Totals) count(r Record) {
|
||||
if r.HandedOn {
|
||||
return
|
||||
}
|
||||
t.Calls++
|
||||
switch {
|
||||
case r.Failed():
|
||||
t.Errors++
|
||||
case r.Tries > 1:
|
||||
t.Retried++
|
||||
}
|
||||
}
|
||||
|
||||
// LostRequest is whether r ends a request the agent got an error for: a
|
||||
// failed row that no later try took over from.
|
||||
func (r Record) LostRequest() bool { return r.Failed() && !r.HandedOn }
|
||||
|
||||
// RetriedRequest is whether r ends a request that was answered after a try
|
||||
// that failed first.
|
||||
func (r Record) RetriedRequest() bool { return !r.HandedOn && !r.Failed() && r.Tries > 1 }
|
||||
|
||||
// Group is the share of one agent or model.
|
||||
type Group struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -149,7 +149,7 @@ func PeriodOf(s string) usage.Period {
|
||||
|
||||
func FilterOf(q url.Values) usage.Filter {
|
||||
id, _ := strconv.ParseInt(q.Get("route"), 10, 64)
|
||||
return usage.Filter{Day: q.Get("day"), RouteID: id, Model: q.Get("model"), Agent: q.Get("agent"), Provider: q.Get("provider"), Purpose: q.Get("purpose"), Account: q.Get("account"), CallerKey: q.Get("callerKey"), Failed: q.Get("failed") == "1", Query: q.Get("q"), Computer: q.Get("computer"), Through: viaOf(q.Get("via"))}
|
||||
return usage.Filter{Day: q.Get("day"), RouteID: id, Model: q.Get("model"), Agent: q.Get("agent"), Provider: q.Get("provider"), Purpose: q.Get("purpose"), Account: q.Get("account"), CallerKey: q.Get("callerKey"), Failed: q.Get("failed") == "1", Retried: q.Get("retried") == "1", Query: q.Get("q"), Computer: q.Get("computer"), Through: viaOf(q.Get("via"))}
|
||||
}
|
||||
|
||||
// viaOf is the source a request's ?via= names, "" for both.
|
||||
|
||||
+8
-2
@@ -115,10 +115,16 @@ func printUsage(out io.Writer, s stats.Summary, title string, names map[string]s
|
||||
fmt.Fprintln(out, bold.Render(fmtTokens(s.Tokens())+" tokens"), muted.Render(title+" ·"), plural(s.Calls, "call"), muted.Render("·"), cost(s.Totals))
|
||||
fmt.Fprintln(out, muted.Render(" in "+fmtTokens(s.Input)+" out "+fmtTokens(s.Output)+" cache read "+fmtTokens(s.CacheRead)+" cache write "+fmtTokens(s.CacheWrite)+" reasoning "+fmtTokens(s.Reasoning)),
|
||||
func() string {
|
||||
// requests, each counted once by how it ended: one a later try
|
||||
// answered is not an error (小一 on Discord)
|
||||
more := ""
|
||||
if s.Errors > 0 {
|
||||
return muted.Render(" · ") + plural(s.Errors, "error")
|
||||
more += muted.Render(" · ") + plural(s.Errors, "error")
|
||||
}
|
||||
return ""
|
||||
if s.Retried > 0 {
|
||||
more += muted.Render(" · ") + fmt.Sprintf("%d answered on a retry", s.Retried)
|
||||
}
|
||||
return more
|
||||
}())
|
||||
table := func(head string, gs []stats.Group, name func(stats.Group) string) {
|
||||
fmt.Fprintln(out)
|
||||
|
||||
Reference in New Issue
Block a user