usage: the plan credits a reply says it cost are summed by model, agent and session (#2512)
wwcraft_ on Discord asked for the WorkBuddy credits spent on the Usage page, by model, agent and session. WorkBuddy's chat stream ends with usage.credit, the per-request figure its own app shows as "Credits Consumed". The built-in and the moved plugin both hand that chunk to the gateway's chat decoder (the plugin's renamed()/kept() pass usage on as it came), so cUsage reads `credit` into Usage.Credits and the three record sites keep it on the row. A reply that says nothing has no credits, not 0. - usage: Record.Credits; Totals/Via sum Credits and count Credited; the packed row keeps it under its own flag bit (4096, in TestRowFlagsApart); the ledger CSV gains a trailing "credits" column. - GUI: the Usage ranking's line says "0.7 credits" (积分, 積分, クレジット, Credits) beside the cost, its title how many requests said it; the Sessions page's Routed line says it per route. TUI usage page and `magpie usage` tables say it muted on the same line. No new layout. Real replies on workbuddy-ai, 10-16: gemini-3.5-flash "credit":0.01; deepseek-v4.1-flash, minimax-m3, kimi-k2.6 "credit":0; glm-5.3-flash refused (14003). The tests use those bytes. Run (at b07b518e7 on origin/main63be47717, with #2511's commit): - gofmt -l clean; go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean; go build: ok. - go test -timeout 45m ./... with pipefail, sandbox HOME: 63 packages ok, usage (200s), cli, tui, gui among them; agent, gateway and library timed out at load ~270 (see the #2511 commit); library ok alone, agent and gateway ok with -timeout 150m: agent ok (5529s); gateway red only in TestIntentClassifierGroup (#1813), TestMaxRPMWaitsForRoomInTheMinute (#1791) and TestMaxRPMGroupPrefersMemberWithRoom (#2520), known timing reds under load, each passing alone here -count=3 (19s). - New: TestPlanCreditsReachTheLedger (chat stream, whole reply, translated /v1/messages, free 0, none), TestPlanCreditsSummed, TestPlanCreditsPacked, TestFormatCredits, TestUsageSaysCredits, and plan-credits.test.cjs (en, zh, zh-TW, ja, de; Chromium and WebKit; 420px fit) 12/12. - Broken by hand: dropping Credits at the record site turns the gateway test red; skipping it in unpack turns the usage tests red; dropping the ranking's ledCredits turns plan-credits red in every language. - GUI reds elsewhere: see the #2511 commit (#2536, #2552, a provider-detect-draft load timeout that passes 3/3 alone). - Rebased onto origin/mainba132d68b(13 commits; chat.go, gateway.go, app.js, i18n.js among theirs): gofmt and go vet ./internal/... clean; Credits/DeepSeek/Balance/Ledger/RowFlags tests in usage, gateway, provider, cli, tui ok; plan-credits 12/12, balance-parts 4/4, i18n-keys 3/3 in both engines.
This commit is contained in:
@@ -193,7 +193,7 @@ func boolToInt(b bool) int {
|
||||
// printUsage is a summary's totals and its tables: agents, models,
|
||||
// upstream keys, accounts, gateway keys and the top sessions.
|
||||
func printUsage(out io.Writer, s stats.Summary, title string, names map[string]string) {
|
||||
fmt.Fprintln(out, bold.Render(fmtTokens(s.Tokens())+" tokens"), muted.Render(title+" ·"), plural(s.Calls, "call"), muted.Render("·"), cost(s.Totals)+unpricedNote(s.Unpriced))
|
||||
fmt.Fprintln(out, bold.Render(fmtTokens(s.Tokens())+" tokens"), muted.Render(title+" ·"), plural(s.Calls, "call"), muted.Render("·"), cost(s.Totals)+unpricedNote(s.Unpriced)+credits(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
|
||||
@@ -219,7 +219,7 @@ func printUsage(out io.Writer, s stats.Summary, title string, names map[string]s
|
||||
if s.Tokens() > 0 {
|
||||
share = fmt.Sprintf("%3.0f%%", 100*float64(g.Tokens())/float64(s.Tokens()))
|
||||
}
|
||||
fmt.Fprintln(out, " "+pad(name(g), w), muted.Render(share), pad(fmtTokens(g.Tokens()), 7), faint.Render(pad(plural(g.Calls, "call"), 10)), cost(g.Totals), faint.Render(speed(g.Totals)))
|
||||
fmt.Fprintln(out, " "+pad(name(g), w), muted.Render(share), pad(fmtTokens(g.Tokens()), 7), faint.Render(pad(plural(g.Calls, "call"), 10)), cost(g.Totals), faint.Render(speed(g.Totals)), muted.Render(stats.FormatCredits(g.Totals)))
|
||||
}
|
||||
}
|
||||
provider := func(id string) string {
|
||||
@@ -338,6 +338,15 @@ func fmtTokens(n int) string {
|
||||
return fmt.Sprint(n)
|
||||
}
|
||||
|
||||
// credits is " · " and what the credited calls cost in their plans'
|
||||
// credits, as the replies said (#2512); "" when none said.
|
||||
func credits(t stats.Totals) string {
|
||||
if c := stats.FormatCredits(t); c != "" {
|
||||
return muted.Render(" · " + c)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// cost renders list-price cost, saying when some calls could not be
|
||||
// priced, in costCurrency at costRate (set once per command by
|
||||
// loadCostCurrency).
|
||||
|
||||
@@ -178,3 +178,29 @@ func TestUsageSaysCallsUnpriced(t *testing.T) {
|
||||
t.Fatalf("headline %q", head)
|
||||
}
|
||||
}
|
||||
|
||||
// magpie usage says what the requests cost in their plans' credits where
|
||||
// the replies said (WorkBuddy's usage.credit, #2512): in the summary, and
|
||||
// on each agent's, model's and session's row of them; nothing where none did.
|
||||
func TestUsageSaysCredits(t *testing.T) {
|
||||
groupsHome(t)
|
||||
day := stats.Today.Since(holdUsageClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)))
|
||||
c := 0.35
|
||||
for i := 0; i < 2; i++ {
|
||||
stats.Append(stats.Record{Time: day.Add(time.Duration(i+1) * time.Second), Agent: "codex", Session: "s1", Provider: "workbuddy-ai", Model: "gemini-3.5-flash", Input: 10, Output: 2, Status: 200, Credits: &c})
|
||||
}
|
||||
stats.Append(stats.Record{Time: day.Add(5 * time.Second), Agent: "pi", Session: "s2", Provider: "a", Model: "m", Input: 1, Output: 1, Status: 200})
|
||||
var b strings.Builder
|
||||
if err := usageTo(&b, []string{"usage", "today"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := b.String()
|
||||
if n := strings.Count(out, "0.7 credits"); n < 4 { // the summary, the agent, the model and the session
|
||||
t.Fatalf("0.7 credits said %d times:\n%s", n, out)
|
||||
}
|
||||
for _, l := range strings.Split(out, "\n") {
|
||||
if strings.Contains(l, "pi") && strings.Contains(l, "credits") {
|
||||
t.Fatalf("a row with no credits said says some: %q", l)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -796,6 +796,8 @@ type cUsage struct {
|
||||
CachedTokens int `json:"cached_tokens"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
||||
// Credit is what WorkBuddy says the request cost in its plan's credits
|
||||
Credit *float64 `json:"credit"`
|
||||
// what a plugin's step collected of its conversation's earlier steps,
|
||||
// which their own replies couldn't count (the Cursor plugin's usage
|
||||
// events that showed late, yetone/magpie#1053): billed with the step,
|
||||
@@ -832,6 +834,9 @@ func (u cUsage) usage() Usage {
|
||||
if u.CompletionTokensDetails != nil {
|
||||
out.Reasoning = u.CompletionTokensDetails.ReasoningTokens
|
||||
}
|
||||
if c := u.Credit; c != nil && *c >= 0 {
|
||||
out.Credits = c
|
||||
}
|
||||
if d := u.MagpieDeferred; d != nil && d.PromptTokens+d.CompletionTokens > 0 {
|
||||
out.Deferred = &Usage{Input: max(d.PromptTokens-d.CachedTokens-d.CacheWriteTokens, 0), Output: d.CompletionTokens,
|
||||
CacheRead: d.CachedTokens, CacheWrite: d.CacheWriteTokens}
|
||||
@@ -1083,7 +1088,7 @@ func (d *chatDecoder) decode(data string, emit func(Event)) error {
|
||||
emit(Event{Kind: KStop, Stop: stopFromChat(c.FinishReason)})
|
||||
}
|
||||
}
|
||||
if ch.Usage != nil && (ch.Usage.PromptTokens > 0 || ch.Usage.CompletionTokens > 0 || ch.Usage.MagpieDeferred != nil) {
|
||||
if ch.Usage != nil && (ch.Usage.PromptTokens > 0 || ch.Usage.CompletionTokens > 0 || ch.Usage.MagpieDeferred != nil || ch.Usage.Credit != nil) {
|
||||
emit(Event{Kind: KUsage, Usage: ch.Usage.usage()})
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -2847,7 +2847,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
|
||||
Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream,
|
||||
Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead,
|
||||
CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().Reasoning, Effort: wentAt, Millis: try.Millis, Status: call.Status,
|
||||
CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status,
|
||||
TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier,
|
||||
TTFT: try.TTFT, FirstText: try.FirstText, FirstReasoning: try.FirstReasoning, ReasoningHidden: try.ReasoningHidden, 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(), HandedOn: true}
|
||||
@@ -2891,7 +2891,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
|
||||
Requested: call.Model, Served: call.Usage.Served,
|
||||
Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead,
|
||||
CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().Reasoning, Effort: wentAt, Millis: try.Millis, Status: call.Status,
|
||||
CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status,
|
||||
TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier,
|
||||
TTFT: try.TTFT, FirstText: try.FirstText, FirstReasoning: try.FirstReasoning, ReasoningHidden: try.ReasoningHidden, 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(), HandedOn: true}
|
||||
@@ -3356,7 +3356,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
|
||||
Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream,
|
||||
Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead,
|
||||
CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().Reasoning, Effort: wentAt, Millis: call.Millis, Status: call.Status,
|
||||
CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: call.Millis, Status: call.Status,
|
||||
TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier,
|
||||
TTFT: call.TTFT, FirstText: call.FirstText, FirstReasoning: call.FirstReasoning, ReasoningHidden: call.ReasoningHidden, Flow: call.Flow, Sent: sentMs, Own: ownMs, Retried: retriedMs, Queued: queuedMs, 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()}
|
||||
|
||||
@@ -364,6 +364,10 @@ type Usage struct {
|
||||
// conversation, which their own replies couldn't (cUsage's
|
||||
// MagpieDeferred): billed with this one, never told as its prompt
|
||||
Deferred *Usage `json:"deferred,omitempty"`
|
||||
// Credits is what the reply said the request cost in its plan's own
|
||||
// credits, nil when it said none: WorkBuddy's usage.credit, the
|
||||
// figure its app shows on each reply as "Credits Consumed" (#2512)
|
||||
Credits *float64 `json:"credits,omitempty"`
|
||||
}
|
||||
|
||||
// billed is what the request is billed for: its own count, and what it
|
||||
@@ -432,6 +436,9 @@ func (u *Usage) add(v Usage) {
|
||||
if v.Deferred != nil {
|
||||
u.Deferred = v.Deferred
|
||||
}
|
||||
if v.Credits != nil {
|
||||
u.Credits = v.Credits
|
||||
}
|
||||
}
|
||||
|
||||
// Result is a whole reply, for non-streaming clients.
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// WorkBuddy AI's last chunk for gemini-3.5-flash, as it came on 10-16:
|
||||
// usage.credit is what the request cost in the plan's credits, the figure
|
||||
// WorkBuddy's app shows on a reply as "Credits Consumed" (#2512)
|
||||
const wbCreditUsage = `"usage":{"prompt_tokens":9,"completion_tokens":12,"total_tokens":21,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":12,"rejected_prediction_tokens":0,"cached_tokens":0},"prompt_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0,"cached_tokens":0},"prompt_cache_hit_tokens":0,"prompt_cache_miss_tokens":9,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"prompt_cache_write_tokens":0,"completion_thinking_tokens":12,"credit":0.01,"cached_tokens":0}`
|
||||
|
||||
// and a free model's: credit 0 is said, so it is known to have cost none
|
||||
const wbFreeUsage = `"usage":{"prompt_tokens":166,"completion_tokens":10,"total_tokens":176,"prompt_tokens_details":{"cached_tokens":128},"completion_thinking_tokens":0,"credit":0,"cached_tokens":0}`
|
||||
|
||||
// The ledger keeps what each request said it cost in credits, however the
|
||||
// agent asked: a chat stream passed through, a whole reply, or translated
|
||||
// for Claude Code. A reply that says no credit leaves it unknown, not 0.
|
||||
func TestPlanCreditsReachTheLedger(t *testing.T) {
|
||||
stream := func(usage string) string {
|
||||
return sse(`data: {"id":"c","model":"m1","choices":[{"index":0,"delta":{"content":"hi"}}]}`,
|
||||
`data: {"id":"c","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],`+usage+`}`, "data: [DONE]")
|
||||
}
|
||||
whole := func(usage string) string {
|
||||
return `{"id":"c","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],` + usage + `}`
|
||||
}
|
||||
const chat = `{"model":"m1","messages":[{"role":"user","content":"hi"}]}`
|
||||
const chatStream = `{"model":"m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`
|
||||
const messages = `{"model":"m1","max_tokens":10,"stream":true,"messages":[{"role":"user","content":"hi"}]}`
|
||||
none := `"usage":{"prompt_tokens":9,"completion_tokens":12}`
|
||||
for _, c := range []struct {
|
||||
name, ctype, reply, path, request string
|
||||
want *float64
|
||||
}{
|
||||
{"chat stream", "", stream(wbCreditUsage), "/v1/chat/completions", chatStream, ptr(0.01)},
|
||||
{"whole reply", "application/json", whole(wbCreditUsage), "/v1/chat/completions", chat, ptr(0.01)},
|
||||
{"translated for Claude Code", "", stream(wbCreditUsage), "/v1/messages", messages, ptr(0.01)},
|
||||
{"a free model", "", stream(wbFreeUsage), "/v1/chat/completions", chatStream, ptr(0.0)},
|
||||
{"translated, free", "", stream(wbFreeUsage), "/v1/messages", messages, ptr(0.0)},
|
||||
{"no credit said", "", stream(none), "/v1/chat/completions", chatStream, nil},
|
||||
{"translated, no credit said", "", stream(none), "/v1/messages", messages, nil},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
setup(t, provider.Chat, &fake{ctype: c.ctype, reply: c.reply})
|
||||
if code, body := post(t, c.path, c.request); code != 200 {
|
||||
t.Fatalf("gateway: %d %s", code, body)
|
||||
}
|
||||
r := lastUsage(t)
|
||||
switch {
|
||||
case c.want == nil && r.Credits != nil:
|
||||
t.Fatalf("credits %v from a reply that said none", *r.Credits)
|
||||
case c.want != nil && (r.Credits == nil || *r.Credits != *c.want):
|
||||
t.Fatalf("credits %v, want %v", r.Credits, *c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func ptr[T any](v T) *T { return &v }
|
||||
@@ -17794,6 +17794,15 @@ function computerOpts(cs) {
|
||||
...others.map((c) => ({ v: c.id, name: c.name || c.id, note: "" }))];
|
||||
}
|
||||
const ledNum = (n) => (n || 0).toLocaleString(intlLang());
|
||||
// what x's credited requests cost in their plan's credits, as the replies
|
||||
// said (WorkBuddy's usage.credit, #2512): nothing when none said
|
||||
function ledCredits(x) {
|
||||
if (!x?.credited) return null;
|
||||
const n = x.credits || 0;
|
||||
const s = el("span", "rk-credits", t("{n} credits", { n: n > 0 && n < 0.01 ? "<0.01" : (+n.toFixed(2)).toLocaleString(intlLang()) }));
|
||||
s.title = t("What {n} of these requests cost in their plan's credits, as the replies said", { n: ledNum(x.credited) });
|
||||
return s;
|
||||
}
|
||||
// an average first token is a fraction of a millisecond: whole ones under a
|
||||
// second, rounded first so 999.6 reads 1.0 s rather than 1000 ms
|
||||
const ledTook = (ms = 0) => (ms = Math.round(ms) || 0) < 1000 ? t("{n} ms", { n: ms }) : t("{n} s", { n: (ms / 1000).toFixed(ms < 10e3 ? 1 : 0) });
|
||||
@@ -18142,6 +18151,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
|
||||
if (metric !== "calls") more.push(t(x.calls === 1 ? "{n} request" : "{n} requests", { n: ledNum(x.calls) }));
|
||||
if (metric !== "tokens") more.push(t("{n} tokens", { n: fmtN(allTokens(x)) }));
|
||||
if (metric !== "cost" && x.cost) more.push("≈" + fmtCost(x));
|
||||
if (x.credited) more.push(ledCredits(x));
|
||||
// how fast its replies came, beside what they cost (#860)
|
||||
if (metric !== "speed" && gs) more.push(Object.assign(el("span", "rk-speed", gs.text), { title: gs.title }));
|
||||
if (ledTTFT(x)) more.push(t("TTFT {ms}", { ms: ledTook(ledTTFT(x)) }));
|
||||
@@ -18163,7 +18173,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
|
||||
for (const x of top) box.append(one(x, x.color));
|
||||
if (rest.length) {
|
||||
const tot = rest.reduce((acc, x) => {
|
||||
for (const k of ["calls", "errors", "loops", "input", "output", "cache_read", "cache_write", "cost", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n"]) acc[k] = (acc[k] || 0) + (x[k] || 0);
|
||||
for (const k of ["calls", "errors", "loops", "input", "output", "cache_read", "cache_write", "cost", "credits", "credited", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n"]) acc[k] = (acc[k] || 0) + (x[k] || 0);
|
||||
return acc;
|
||||
}, { id: "\0other", name: t("Other ({n})", { n: rest.length }) });
|
||||
box.append(one(tot, "var(--faint)", true));
|
||||
@@ -18343,7 +18353,7 @@ function sessUsageDetail(d, s, line) {
|
||||
}
|
||||
d.append(m);
|
||||
}
|
||||
(s.via || []).forEach((v, i) => line(i ? "" : t("Routed"), viaText(v) + " · " + t("{n} tokens", { n: fmtN(v.tokens) })));
|
||||
(s.via || []).forEach((v, i) => line(i ? "" : t("Routed"), viaText(v) + " · " + t("{n} tokens", { n: fmtN(v.tokens) }) + (v.credited ? " · " + ledCredits(v).textContent : "")));
|
||||
}
|
||||
|
||||
// one place a session's calls went through magpie, in words
|
||||
|
||||
@@ -2812,6 +2812,8 @@ const I18N = {
|
||||
"{when} · nothing": "{when} · 无",
|
||||
"{n} call": "{n} 次调用",
|
||||
"{n} calls": "{n} 次调用",
|
||||
"{n} credits": "{n} 积分",
|
||||
"What {n} of these requests cost in their plan's credits, as the replies said": "其中 {n} 次请求按回复所说消耗的套餐积分",
|
||||
"{n} cached": "缓存 {n}",
|
||||
|
||||
// sync
|
||||
@@ -6463,6 +6465,8 @@ const I18N = {
|
||||
"{when} · nothing": "{when} · 無",
|
||||
"{n} call": "{n} 次呼叫",
|
||||
"{n} calls": "{n} 次呼叫",
|
||||
"{n} credits": "{n} 積分",
|
||||
"What {n} of these requests cost in their plan's credits, as the replies said": "其中 {n} 次請求依回覆所述消耗的方案積分",
|
||||
"{n} cached": "快取 {n}",
|
||||
"Model lists refreshed": "模型列表已重新整理",
|
||||
"Sync failed: {e}": "同步失敗:{e}",
|
||||
@@ -10121,6 +10125,8 @@ const I18N = {
|
||||
"{when} · nothing": "{when} · なし",
|
||||
"{n} call": "{n} 回の呼び出し",
|
||||
"{n} calls": "{n} 回の呼び出し",
|
||||
"{n} credits": "{n} クレジット",
|
||||
"What {n} of these requests cost in their plan's credits, as the replies said": "うち {n} 件のリクエストが消費したプランのクレジット(応答の申告どおり)",
|
||||
"{n} cached": "キャッシュ {n}",
|
||||
"Model lists refreshed": "モデル一覧を更新しました",
|
||||
"Sync failed: {e}": "同期に失敗しました:{e}",
|
||||
@@ -13789,6 +13795,8 @@ const I18N = {
|
||||
"{when} · nothing": "{when} · nichts",
|
||||
"{n} call": "{n} Aufruf",
|
||||
"{n} calls": "{n} Aufrufe",
|
||||
"{n} credits": "{n} Credits",
|
||||
"What {n} of these requests cost in their plan's credits, as the replies said": "Was {n} dieser Anfragen laut Antwort an Credits des Plans gekostet haben",
|
||||
"{n} cached": "{n} im Cache",
|
||||
"Model lists refreshed": "Modelllisten aktualisiert",
|
||||
"Sync failed: {e}": "Synchronisierung fehlgeschlagen: {e}",
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// What WorkBuddy requests cost in the plan's credits (#2512, wwcraft_ on
|
||||
// Discord: the Usage page should say the credits spent by model, agent and
|
||||
// session). Each reply says it as usage.credit, the figure WorkBuddy's own
|
||||
// app shows on a reply as "Credits Consumed"; magpie keeps it on the row and
|
||||
// the Usage page's ranking says the sum on its line of numbers, the
|
||||
// Sessions page on the line of where magpie routed the session. A group no
|
||||
// reply said credits for says none, not 0. Every language, Chromium and
|
||||
// WebKit; no backend, the API is faked.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const now = Date.now();
|
||||
const H = 3600e3;
|
||||
const hour = (i) => new Date(Math.floor(now / H) * H - i * H).toISOString();
|
||||
const row = (i, model, provider) => ({
|
||||
route_id: 900 + i, t: new Date(now - (i + 1) * 60e3).toISOString(), agent: "codex", agentName: "Codex", icon: "codex-color",
|
||||
provider, providerName: provider, req: model, model, served: model, in: 9, out: 12, cache_read: 0, cache_write: 0,
|
||||
ms: 900, status: 200, rid: "req_" + i, ep: "/v1/chat/completions", cost: 0, priced: false,
|
||||
});
|
||||
// 70 gemini-3.5-flash replies at 0.01 credits, one free deepseek reply that
|
||||
// said 0, and a model of another provider that said nothing
|
||||
const GEM = { id: "gemini-3.5-flash", calls: 70, input: 630, output: 840, cache_read: 0, cache_write: 0, cost: 0, credits: 0.7000000000000005, credited: 70 };
|
||||
const FREE = { id: "deepseek-v4.1-flash", calls: 1, input: 9, output: 1, cache_read: 0, cache_write: 0, cost: 0, credits: 0, credited: 1 };
|
||||
const OTHER = { id: "glm-5.2", calls: 3, input: 9, output: 1, cache_read: 0, cache_write: 0, cost: 0 };
|
||||
|
||||
function ledger(period) {
|
||||
const all = [GEM, FREE, OTHER];
|
||||
const s = (k) => all.reduce((a, x) => a + (x[k] || 0), 0);
|
||||
return {
|
||||
period, rows: [row(0, "gemini-3.5-flash", "workbuddy-ai"), row(1, "glm-5.2", "zai")], offset: 0, total: 2,
|
||||
calls: s("calls"), errors: 0, input: s("input"), output: s("output"), cache_read: 0, cache_write: 0, cost: 0, unpriced: 74, credits: 0.7, credited: 71,
|
||||
by: { model: all }, bucket: "hour",
|
||||
series: [{ label: "", time: hour(0), calls: s("calls"), input: s("input"), output: s("output"), by: { model: Object.fromEntries(all.map((x) => [x.id, { calls: x.calls, tokens: x.input + x.output, cost: 0 }])) } }],
|
||||
agents: [{ id: "codex", name: "Codex", icon: "codex-color" }],
|
||||
};
|
||||
}
|
||||
|
||||
const at = (min) => new Date(now - min * 60e3).toISOString();
|
||||
const SESSION = {
|
||||
agent: "codex", id: "c-1", cwd: "/work/tool", title: "port the parser", start: at(30), last: at(5), name: "Codex", icon: "openai",
|
||||
models: [{ model: "gemini-3.5-flash", input: 630, output: 840, cache_read: 0, cache_write: 0, cost: 0, priced: false }],
|
||||
input: 630, output: 840, cache_read: 0, cache_write: 0, cost: 0, unpriced: 70,
|
||||
resume: "cd /work/tool && codex resume c-1", path: "~/.codex/x/c-1.jsonl",
|
||||
via: [{ provider: "workbuddy-ai", model: "gemini-3.5-flash", calls: 70, tokens: 1470, credits: 0.7000000000000005, credited: 70 }, { provider: "zai", model: "glm-5.2", calls: 3, tokens: 10 }],
|
||||
};
|
||||
|
||||
function server(lang) {
|
||||
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({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/usage/requests") return json(ledger(url.searchParams.get("period")));
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/usage") return json({ calls: 0, errors: 0, input: 0, output: 0, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "" });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: false } });
|
||||
if (url.pathname === "/api/sessions") return json({ sessions: [SESSION], terminal: true, dirs: ["~/.codex/sessions"] });
|
||||
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
|
||||
if (url.pathname === "/api/sessions/manage") {
|
||||
return json({ agents: [{ agent: "codex", count: 1, deletable: true, name: "Codex", icon: "openai" }], agent: "codex", sessions: [{ ...SESSION, size: 4096, messages: 6, files: 1, deletable: true }], terminal: true, trash: [], trashDir: "~/magpie/trash/sessions" });
|
||||
}
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
const body = await fs.readFile(file).catch(() => null);
|
||||
await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }));
|
||||
};
|
||||
}
|
||||
|
||||
// each language's "0.7 credits" and "0 credits"
|
||||
const L = {
|
||||
en: ["0.7 credits", "0 credits", /credits/],
|
||||
zh: ["0.7 积分", "0 积分", /积分/],
|
||||
"zh-TW": ["0.7 積分", "0 積分", /積分/],
|
||||
ja: ["0.7 クレジット", "0 クレジット", /クレジット/],
|
||||
de: ["0,7 Credits", "0 Credits", /Credits/],
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": the credits WorkBuddy's replies said, by model and by session", async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const [lang, [gem, free, word]] of Object.entries(L)) {
|
||||
await t.test(lang, async () => {
|
||||
const errors = [];
|
||||
const ctx = await browser.newContext({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" });
|
||||
const p = await ctx.newPage();
|
||||
p.setDefaultTimeout(5000);
|
||||
p.on("pageerror", (e) => errors.push(e.message));
|
||||
await p.route("**/*", server(lang));
|
||||
await p.goto("http://magpie.test/");
|
||||
await p.locator('[data-view="usage"]').first().click();
|
||||
await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
|
||||
await p.locator("#ledWrap .led tbody tr").first().waitFor();
|
||||
await p.waitForTimeout(300);
|
||||
|
||||
// the ranking: each model's sum on its line, none where none was said
|
||||
const line = async (id) => (await p.locator("#ledRank .rk").filter({ hasText: id }).locator(".rk-b").textContent()).trim();
|
||||
const g = await line("gemini-3.5-flash");
|
||||
assert(g.includes(gem), `gemini-3.5-flash's line: ${g}`);
|
||||
assert(!/0{5}/.test(g), `no float noise: ${g}`);
|
||||
const f = await line("deepseek-v4.1-flash");
|
||||
assert(f.includes(free), `the free model's line: ${f}`);
|
||||
const o = await line("glm-5.2");
|
||||
assert(!word.test(o), `a model no reply said credits for: ${o}`);
|
||||
const tip = await p.locator("#ledRank .rk").filter({ hasText: "gemini-3.5-flash" }).locator(".rk-credits").getAttribute("title");
|
||||
assert(tip && tip.includes("70"), "its title says how many requests: " + tip);
|
||||
|
||||
// a narrow window keeps the line inside the ranking
|
||||
await p.setViewportSize({ width: 420, height: 800 });
|
||||
await p.waitForTimeout(150);
|
||||
const fits = await p.locator("#ledRank .rk").filter({ hasText: "gemini-3.5-flash" }).evaluate((b) => b.scrollWidth <= b.clientWidth + 1);
|
||||
assert(fits, "the ranking's line fits a 420px window");
|
||||
await p.setViewportSize({ width: 1100, height: 800 });
|
||||
|
||||
// the Sessions page: the routed line of the session says them
|
||||
await p.goto("http://magpie.test/?view=sessions");
|
||||
const view = p.locator("#view-sessions");
|
||||
const r = view.locator('.row.sm-sess[data-id="c-1"]');
|
||||
await r.waitFor();
|
||||
await r.click();
|
||||
const det = view.locator(".sm-item.open .sess-detail");
|
||||
await det.waitFor();
|
||||
const text = await det.innerText();
|
||||
assert(text.includes("workbuddy-ai/gemini-3.5-flash") && text.includes(gem), "the session's details: " + text);
|
||||
const glm = text.split("\n").find((l) => l.includes("zai/glm-5.2")) || "";
|
||||
assert(glm && !word.test(glm), "the route no reply said credits for: " + glm);
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-plan-credits.png`) });
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
+11
-1
@@ -1121,6 +1121,15 @@ func fmtCost(t usage.Totals) string {
|
||||
return "≈" + s
|
||||
}
|
||||
|
||||
// credits is " · " and what the credited calls cost in their plans'
|
||||
// credits, as the replies said (#2512); "" when none said.
|
||||
func credits(t usage.Totals) string {
|
||||
if c := usage.FormatCredits(t); c != "" {
|
||||
return " · " + c
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var bars = []rune(" ▁▂▃▄▅▆▇█")
|
||||
|
||||
func (m model) viewUsage() string {
|
||||
@@ -1178,6 +1187,7 @@ func (m model) usageBlock(b *strings.Builder, s usage.Summary, room int, names m
|
||||
if s.Unpriced > 0 { // calls with no known price, not in the cost (#1856)
|
||||
line += sMuted.Render(fmt.Sprintf(" (%d call%s unpriced)", s.Unpriced, plural(s.Unpriced)))
|
||||
}
|
||||
line += sMuted.Render(credits(s.Totals))
|
||||
if s.Errors > 0 {
|
||||
line += sMuted.Render(" · ") + sBad.Render(fmt.Sprintf("%d error%s", s.Errors, plural(s.Errors)))
|
||||
}
|
||||
@@ -1217,7 +1227,7 @@ func (m model) usageBlock(b *strings.Builder, s usage.Summary, room int, names m
|
||||
break
|
||||
}
|
||||
share := fmt.Sprintf("%3.0f%%", 100*float64(g.Tokens())/float64(max(1, s.Tokens())))
|
||||
b.WriteString(pad + " " + sText.Render(padRight(name(g), w)) + " " + sMuted.Render(share) + " " + sText.Render(padRight(fmtTokens(g.Tokens()), 7)) + " " + sFaint.Render(padRight(fmt.Sprintf("%d call%s", g.Calls, plural(g.Calls)), 10)) + " " + sOK.Render(fmtCost(g.Totals)) + "\n")
|
||||
b.WriteString(pad + " " + sText.Render(padRight(name(g), w)) + " " + sMuted.Render(share) + " " + sText.Render(padRight(fmtTokens(g.Tokens()), 7)) + " " + sFaint.Render(padRight(fmt.Sprintf("%d call%s", g.Calls, plural(g.Calls)), 10)) + " " + sOK.Render(fmtCost(g.Totals)) + sMuted.Render(credits(g.Totals)) + "\n")
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
|
||||
@@ -570,7 +570,7 @@ 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", "tries", "handed_on", "tier_asked", "tier_sent", "tier_served", "upstream_stop"}
|
||||
"cache_write_5m_tokens", "cache_write_1h_tokens", "tries", "handed_on", "tier_asked", "tier_sent", "tier_served", "upstream_stop", "credits"}
|
||||
|
||||
// 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
|
||||
@@ -583,7 +583,9 @@ var CSVHeader = []string{"time", "agent", "requested_model", "provider", "host",
|
||||
// on: the request's outcome is the row with the same route_id after it.
|
||||
// tier_asked, tier_sent and tier_served are the service tier the client
|
||||
// asked for, the one sent on the row's try and the one the reply said it
|
||||
// ran at, each empty when there was none (Record.TierAsked).
|
||||
// ran at, each empty when there was none (Record.TierAsked). credits is
|
||||
// what the reply said the call cost in its plan's credits, empty when it
|
||||
// said none (Record.Credits).
|
||||
func WriteCSV(w io.Writer, rows []Row) error {
|
||||
cw := csv.NewWriter(w)
|
||||
cw.Write(CSVHeader)
|
||||
@@ -601,6 +603,10 @@ func WriteCSV(w io.Writer, rows []Row) error {
|
||||
if r.Tries > 0 {
|
||||
tries = n(r.Tries)
|
||||
}
|
||||
credits := ""
|
||||
if r.Credits != nil {
|
||||
credits = strconv.FormatFloat(*r.Credits, 'f', -1, 64)
|
||||
}
|
||||
routeID := ""
|
||||
if r.RouteID != 0 {
|
||||
routeID = strconv.FormatInt(r.RouteID, 10)
|
||||
@@ -610,7 +616,7 @@ func WriteCSV(w io.Writer, rows []Row) error {
|
||||
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)), tries, strconv.FormatBool(r.HandedOn),
|
||||
r.TierAsked, r.TierSent, r.TierServed, r.Stop})
|
||||
r.TierAsked, r.TierSent, r.TierServed, r.Stop, credits})
|
||||
}
|
||||
cw.Flush()
|
||||
return cw.Error()
|
||||
|
||||
@@ -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,,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"
|
||||
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,,false,,,,\n", ",true,s2,,,,,,req_lim,,You've hit your limit,rate_limit,log,false,,,false,,,,,0,0,,false,,,,\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())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
)
|
||||
|
||||
// What a request said it cost in its plan's credits (#2512) is summed by
|
||||
// model, agent and session, through the packed blocks a long history is
|
||||
// kept in; a call that said nothing is not counted as credited.
|
||||
func TestPlanCreditsSummed(t *testing.T) {
|
||||
resetUsageTest(t)
|
||||
at := Clock().Add(-time.Hour)
|
||||
credit := func(v float64) *float64 { return &v }
|
||||
// past a block's 64 rows, so the rows are read back from a packed one
|
||||
for i := 0; i < 70; i++ {
|
||||
Append(Record{Time: at.Add(time.Duration(i) * time.Second), Agent: "claude-code", Session: "s1", Provider: "workbuddy-ai", Model: "gemini-3.5-flash", Input: 9, Output: 12, Status: 200, Credits: credit(0.01)})
|
||||
}
|
||||
Append(Record{Time: at.Add(2 * time.Minute), Agent: "codex", Session: "s2", Provider: "workbuddy-ai", Model: "deepseek-v4.1-flash", Input: 9, Output: 1, Status: 200, Credits: credit(0)})
|
||||
Append(Record{Time: at.Add(3 * time.Minute), Agent: "codex", Session: "s2", Provider: "p", Model: "m", Input: 9, Output: 1, Status: 200})
|
||||
|
||||
near := func(a, b float64) bool { return math.Abs(a-b) < 1e-9 }
|
||||
page := QueryPage(All, Filter{}, 0, 50)
|
||||
if s := page.Sum; !near(s.Credits, 0.7) || s.Credited != 71 {
|
||||
t.Fatalf("sum: %v credits of %d calls", s.Credits, s.Credited)
|
||||
}
|
||||
byModel := map[string]Share{}
|
||||
for _, s := range page.By["model"] {
|
||||
byModel[s.ID] = s
|
||||
}
|
||||
if s := byModel["gemini-3.5-flash"]; !near(s.Credits, 0.7) || s.Credited != 70 {
|
||||
t.Fatalf("gemini-3.5-flash: %v credits of %d calls", s.Credits, s.Credited)
|
||||
}
|
||||
if s := byModel["deepseek-v4.1-flash"]; s.Credits != 0 || s.Credited != 1 {
|
||||
t.Fatalf("a free model: %v credits of %d calls", s.Credits, s.Credited)
|
||||
}
|
||||
if s := byModel["m"]; s.Credited != 0 {
|
||||
t.Fatalf("a call that said none is credited: %+v", s)
|
||||
}
|
||||
for _, s := range page.By["agent"] {
|
||||
if want := map[string]int{"claude-code": 70, "codex": 1}[s.ID]; s.Credited != want {
|
||||
t.Fatalf("agent %s: %d credited, want %d", s.ID, s.Credited, want)
|
||||
}
|
||||
}
|
||||
vias := Vias(time.Time{})
|
||||
if v := vias["claude-code|s1"]; len(v) != 1 || !near(v[0].Credits, 0.7) || v[0].Credited != 70 {
|
||||
t.Fatalf("session s1: %+v", v)
|
||||
}
|
||||
if v := vias["codex|s2"]; len(v) != 2 || v[0].Credited+v[1].Credited != 1 {
|
||||
t.Fatalf("session s2: %+v", v)
|
||||
}
|
||||
if got := FormatCredits(page.Sum); got != "0.7 credits" {
|
||||
t.Fatalf("FormatCredits %q", got)
|
||||
}
|
||||
// the CSV's credits column: the reply's figure, empty where it said none
|
||||
rows, _, _ := Ledger(All, Filter{})
|
||||
var b strings.Builder
|
||||
if err := WriteCSV(&b, rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cells, err := csv.NewReader(strings.NewReader(b.String())).ReadAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
col := slices.Index(CSVHeader, "credits")
|
||||
said := map[string]int{}
|
||||
for _, c := range cells[1:] {
|
||||
said[c[col]]++
|
||||
}
|
||||
if said["0.01"] != 70 || said["0"] != 1 || said[""] != 1 {
|
||||
t.Fatalf("credits column: %v", said)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatCredits(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
t Totals
|
||||
want string
|
||||
}{
|
||||
{Totals{}, ""},
|
||||
{Totals{Credited: 3}, "0 credits"},
|
||||
{Totals{Credits: 0.004, Credited: 1}, "<0.01 credits"},
|
||||
{Totals{Credits: 5.71, Credited: 1}, "5.71 credits"},
|
||||
{Totals{Credits: 0.1 + 0.2, Credited: 2}, "0.3 credits"},
|
||||
{Totals{Credits: 1234.567, Credited: 9}, "1234.57 credits"},
|
||||
} {
|
||||
if got := FormatCredits(c.t); got != c.want {
|
||||
t.Errorf("FormatCredits(%v of %d) = %q, want %q", c.t.Credits, c.t.Credited, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A packed block, and one the block pricer rewrote, give each row's
|
||||
// credits back, and only to the rows that had them.
|
||||
func TestPlanCreditsPacked(t *testing.T) {
|
||||
credit := 0.25
|
||||
var chunk rowChunk
|
||||
for i := 0; i < 80; i++ {
|
||||
r := Record{Time: time.Now(), Provider: "workbuddy-ai", Model: "m", Input: 1, Output: 1, Status: 200}
|
||||
if i%2 == 0 {
|
||||
r.Credits = &credit
|
||||
}
|
||||
chunk.add(Row{Record: r}, "", int64(i), false)
|
||||
}
|
||||
b := newBlockPricer(nil, nil, func(Record) *catalog.Price { return nil })
|
||||
defer b.release()
|
||||
packed := chunk.pack()
|
||||
if len(packed.Archive) == 0 {
|
||||
t.Fatal("the block wasn't packed")
|
||||
}
|
||||
for name, c := range map[string]*rowChunk{"raw": &chunk, "unpacked": packed.unpack(), "priced": b.block(packed)} {
|
||||
for i := 0; i < 80; i++ {
|
||||
got := c.row(i).Credits
|
||||
if i%2 == 0 && (got == nil || *got != credit) || i%2 == 1 && got != nil {
|
||||
t.Fatalf("%s row %d: credits %v", name, i, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,7 +149,7 @@ func TestRowFlagsApart(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
bits := []uint16{1, 2, 4, 8, 16, 32, swapKnown, rowHandedOn, rowReasoningHidden, rowOwnCost, rowCompactionKnown, rowCompaction}
|
||||
bits := []uint16{1, 2, 4, 8, 16, 32, swapKnown, rowHandedOn, rowReasoningHidden, rowOwnCost, rowCompactionKnown, rowCompaction, rowCredits}
|
||||
var all uint16
|
||||
for _, b := range bits {
|
||||
if all&b != 0 {
|
||||
|
||||
@@ -68,7 +68,7 @@ type packedRow struct {
|
||||
Sent, Flow, FirstReasoning int64
|
||||
Own, Retried, Queued int64
|
||||
RouteID int64
|
||||
Cost float64
|
||||
Cost, Credits float64
|
||||
Status, Tries int32
|
||||
Flags uint16
|
||||
}
|
||||
@@ -88,6 +88,11 @@ const (
|
||||
// Record.OwnCost again.
|
||||
const rowOwnCost = 256
|
||||
|
||||
// rowCredits marks a call whose reply said what it cost in its plan's
|
||||
// credits (#2512): Credits is that, and reading the row back gives
|
||||
// Record.Credits again.
|
||||
const rowCredits = 4096
|
||||
|
||||
type rowChunk struct {
|
||||
Archive []byte
|
||||
Locations []*time.Location
|
||||
@@ -171,6 +176,10 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
|
||||
p.Flags |= rowOwnCost
|
||||
p.Cost = *r.OwnCost
|
||||
}
|
||||
if r.Credits != nil {
|
||||
p.Flags |= rowCredits
|
||||
p.Credits = *r.Credits
|
||||
}
|
||||
if r.Compaction != nil {
|
||||
p.Flags |= rowCompactionKnown
|
||||
if *r.Compaction {
|
||||
@@ -197,6 +206,10 @@ 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, FirstReasoning: p.FirstReasoning, ReasoningHidden: p.Flags&rowReasoningHidden != 0, Sent: p.Sent, Flow: p.Flow, Own: p.Own, Retried: p.Retried, Queued: p.Queued, Status: int(p.Status), Tries: int(p.Tries), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
|
||||
if p.Flags&rowCredits != 0 {
|
||||
credits := p.Credits
|
||||
r.Credits = &credits
|
||||
}
|
||||
if p.Flags&rowCompactionKnown != 0 {
|
||||
compacted := p.Flags&rowCompaction != 0
|
||||
r.Compaction = &compacted
|
||||
|
||||
@@ -62,6 +62,9 @@ func (c *rowChunk) pack() *rowChunk {
|
||||
put(uint64(p.Status))
|
||||
put(uint64(p.Flags))
|
||||
put(uint64(p.Tries))
|
||||
if p.Flags&rowCredits != 0 {
|
||||
put(math.Float64bits(p.Credits))
|
||||
}
|
||||
}
|
||||
archive := s2.Encode(nil, data)
|
||||
if int64(len(archive)) >= c.Bytes {
|
||||
@@ -157,6 +160,10 @@ func (c *rowChunk) unpackInto(into []packedRow) *rowChunk {
|
||||
p.FirstReasoning = int64(take())
|
||||
p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int32(take()), uint16(take())
|
||||
p.Tries = int32(take())
|
||||
p.Credits = 0
|
||||
if p.Flags&rowCredits != 0 {
|
||||
p.Credits = math.Float64frombits(take())
|
||||
}
|
||||
}
|
||||
if !valid || len(data) != 0 {
|
||||
return nil
|
||||
|
||||
@@ -8,10 +8,12 @@ import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -194,6 +196,9 @@ type Record struct {
|
||||
// said nothing: the call is then priced at magpie's own prices, as the
|
||||
// gateway's calls are, and priced again when those change.
|
||||
OwnCost *float64 `json:"cost,omitempty"`
|
||||
// Credits is what the vendor said the call cost in its plan's own
|
||||
// credits (WorkBuddy's usage.credit, #2512), nil when it said none
|
||||
Credits *float64 `json:"credits,omitempty"`
|
||||
// Watched is a row of a request an Observer watched (observe.go): it
|
||||
// has the request's attempts already, so it can pass the row over.
|
||||
// Never persisted.
|
||||
@@ -393,6 +398,10 @@ type Totals struct {
|
||||
Reasoning int `json:"reasoning"`
|
||||
Cost float64 `json:"cost"` // USD at the effective price, for the priced calls
|
||||
Unpriced int `json:"unpriced"` // calls with tokens but no known price
|
||||
// Credits are what the vendors said Credited of the calls cost in
|
||||
// their plans' own credits (Record.Credits): the rest said nothing
|
||||
Credits float64 `json:"credits,omitempty"`
|
||||
Credited int `json:"credited,omitempty"`
|
||||
// Timed: the answered calls whose first token was timed (streamed),
|
||||
// TTFT the sum of their ttft_ms; DecodeMs the time from it to the end
|
||||
// of those that wrote any, over which DecodeOut tokens came (a
|
||||
@@ -551,6 +560,18 @@ func (r Record) Decode() (tokens int, w int64) {
|
||||
return DecodeOf(r.Output, r.Reasoning, r.Millis, r.TTFT, r.FirstText, r.Flow, r.FirstReasoning)
|
||||
}
|
||||
|
||||
// FormatCredits is what t's credited calls cost in their plans' credits,
|
||||
// as their replies said (#2512): "" when none said.
|
||||
func FormatCredits(t Totals) string {
|
||||
switch {
|
||||
case t.Credited == 0:
|
||||
return ""
|
||||
case t.Credits > 0 && t.Credits < 0.01:
|
||||
return "<0.01 credits"
|
||||
}
|
||||
return strconv.FormatFloat(math.Round(t.Credits*100)/100, 'f', -1, 64) + " credits"
|
||||
}
|
||||
|
||||
// FormatCost renders an effective-price cost, kept in USD everywhere it's
|
||||
// stored, as the CLI and TUI show it: at amountUSD's own price when
|
||||
// currency isn't "cny", else converted at rate (CNY per one USD, from
|
||||
@@ -613,6 +634,11 @@ const LoopErrType = "reply_loop"
|
||||
// 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) {
|
||||
// a try handed on is billed its credits too, though it is no request
|
||||
if r.Credits != nil {
|
||||
t.Credits += *r.Credits
|
||||
t.Credited++
|
||||
}
|
||||
if r.HandedOn {
|
||||
return
|
||||
}
|
||||
@@ -965,6 +991,10 @@ type Via struct {
|
||||
Calls int `json:"calls"`
|
||||
Tokens int `json:"tokens"` // in and out, as Totals counts them
|
||||
Last time.Time `json:"last"`
|
||||
// Credits are what Credited of the calls cost in the plan's own
|
||||
// credits, as their replies said (Record.Credits)
|
||||
Credits float64 `json:"credits,omitempty"`
|
||||
Credited int `json:"credited,omitempty"`
|
||||
}
|
||||
|
||||
// Vias is what the gateway sent each session's calls to since a time, by
|
||||
@@ -987,6 +1017,10 @@ func buildVias(snapshot *logSnapshot, since time.Time) map[string][]Via {
|
||||
}
|
||||
vs[i].Calls++
|
||||
vs[i].Tokens += r.Input + r.Output
|
||||
if r.Credits != nil {
|
||||
vs[i].Credits += *r.Credits
|
||||
vs[i].Credited++
|
||||
}
|
||||
if r.Time.After(vs[i].Last) {
|
||||
vs[i].Last = r.Time
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user