Files
magpie/internal/gateway/usage_api_test.go
T
yetone b6a263b9fd gateway, usage: the Usage page's numbers are read over the gateway, and a Claude Code subagent's call says which subagent and which started it (HoGee_xxl on X)
HoGee_xxl wants their own usage app to read magpie over the gateway,
which had no /api/usage counterpart, and asked for subagents' parent ids.

- GET /v1/magpie/usage (the /api/usage summary, ?period=) and
  GET /v1/magpie/usage/requests (the /api/usage/requests ledger page, same
  filters, offset/limit) on the gateway. The builders moved out of gui into
  internal/usageapi so both serve the same JSON; gui keeps aliases and sets
  usageapi.Clients for agent names (gateway can't import agent). Guard as
  /v1/magpie/quotas: this machine, or another with an enabled gateway key,
  behind the same Host check. A key held to a budget, models or accounts is
  refused the summary (403) and gets the ledger filtered to its own
  CallerKey, with callerKeys/agents/providers/accounts cut to its own rows
  (usageapi.OwnPage): those facets are drawn from every call in the period.
  `path` is left out for another machine.
- usage.Record gains subagent and parent_agent; session stays the parent
  conversation. Gateway rows take them from x-claude-code-agent-id and
  x-claude-code-parent-agent-id; session-file rows from the file name
  (<session>/subagents[/workflows/<run>]/agent-<id>.jsonl, no cache version
  bump) and the parentAgentId of the agent-<id>.meta.json beside it. Both
  packed into the request page's text columns (now 29, msg at 29).
  Codex sub-threads: only kind, as before; no spawned thread on disk to
  take a parent shape from.

Run: real Claude Code 2.1.296 under a sandbox CLAUDE_CONFIG_DIR against a
local fake Anthropic endpoint that made it spawn a subagent from a
subagent: the nested request carried X-Claude-Code-Agent-Id=a143287ac46b82a96
and X-Claude-Code-Parent-Agent-Id=a99ca20c03d1813d8, the first-level one
the agent id only, Session-Id the parent's throughout; the nested meta.json
had parentAgentId. Tests use those bytes. TestUsageOverGateway goes red
with OwnPage, the CallerKey pin, or the header read removed (each tried).
gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
GOOS=windows go vet ./...; set -o pipefail; go test ./... green.
2026-10-10 20:47:00 +08:00

109 lines
4.6 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usageapi"
)
// The Usage page's numbers are read over the gateway too (HoGee_xxl on
// X): /v1/magpie/usage and /v1/magpie/usage/requests answer this machine,
// another one only with a gateway key, and a key held to a budget only
// with its own calls. A Claude Code subagent's call says which subagent
// made it and which one started that.
func TestUsageOverGateway(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":30,"completion_tokens":5}}`)
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Laptop", "Held")
if _, err := access.Update("limit-key", access.Change{Key: keys[1].ID, Limit: &access.Limit{Period: "day", Tokens: 1_000_000}}); err != nil {
t.Fatal(err)
}
h := lanGuard(New().Handler())
do := func(method, path, from string, body io.Reader, hdr ...string) (int, string) {
r := httptest.NewRequest(method, path, body)
r.RemoteAddr = from
for i := 0; i+1 < len(hdr); i += 2 {
r.Header.Set(hdr[i], hdr[i+1])
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code, w.Body.String()
}
// the main conversation, then a subagent of it that another started, as
// Claude Code 2.1.296 sends a nested one (captured headers)
if c, b := do("POST", "/v1/chat/completions", "127.0.0.1:5000", strings.NewReader(chatReq), "Authorization", "Bearer "+secrets[0], "X-Claude-Code-Session-Id", "conv-1"); c != 200 {
t.Fatal(c, b)
}
if c, b := do("POST", "/v1/chat/completions", "127.0.0.1:5000", strings.NewReader(chatReq), "Authorization", "Bearer "+secrets[0], "X-Claude-Code-Session-Id", "conv-1",
"X-Claude-Code-Agent-Id", "a143287ac46b82a96", "X-Claude-Code-Parent-Agent-Id", "a99ca20c03d1813d8"); c != 200 {
t.Fatal(c, b)
}
if c, b := do("POST", "/v1/chat/completions", "127.0.0.1:5000", strings.NewReader(chatReq), "Authorization", "Bearer "+secrets[1]); c != 200 {
t.Fatal(c, b)
}
var sum usageapi.Usage
c, b := do("GET", "/v1/magpie/usage?period=all", "127.0.0.1:5000", nil)
if c != 200 || json.Unmarshal([]byte(b), &sum) != nil || sum.Calls != 3 || len(sum.CallerKeys) != 2 || sum.Path == "" {
t.Fatal("loopback summary:", c, b)
}
var page usageapi.Ledger
c, b = do("GET", "/v1/magpie/usage/requests?period=all", "127.0.0.1:5000", nil)
if c != 200 || json.Unmarshal([]byte(b), &page) != nil || page.Total != 3 {
t.Fatal("loopback requests:", c, b)
}
subs := 0
for _, r := range page.Rows {
if r.Subagent != "" {
subs++
if r.Subagent != "a143287ac46b82a96" || r.ParentAgent != "a99ca20c03d1813d8" || r.Session != "conv-1" {
t.Fatalf("the subagent's row: %+v", r.Row)
}
} else if r.ParentAgent != "" {
t.Fatalf("a parent with no subagent: %+v", r.Row)
}
}
if subs != 1 {
t.Fatal("subagent rows:", subs, b)
}
if c, _ := do("GET", "/v1/magpie/usage", "192.168.1.9:5000", nil); c != http.StatusUnauthorized {
t.Fatal("another machine with no key got", c)
}
sum = usageapi.Usage{}
c, b = do("GET", "/v1/magpie/usage?period=all", "192.168.1.9:5000", nil, "Authorization", "Bearer "+secrets[0])
if c != 200 || json.Unmarshal([]byte(b), &sum) != nil || sum.Calls != 3 || sum.Path != "" {
t.Fatal("another machine with a key:", c, b)
}
// the held key: no summary of everyone, and its own calls alone
for _, from := range []string{"127.0.0.1:5000", "192.168.1.9:5000"} {
if c, b := do("GET", "/v1/magpie/usage?period=all", from, nil, "x-api-key", secrets[1]); c != http.StatusForbidden || !strings.Contains(b, "/v1/magpie/usage/requests") {
t.Fatal("held key's summary from", from, c, b)
}
page = usageapi.Ledger{}
c, b := do("GET", "/v1/magpie/usage/requests?period=all&callerKey="+keys[0].ID, from, nil, "x-api-key", secrets[1])
if c != 200 || json.Unmarshal([]byte(b), &page) != nil || page.Total != 1 || len(page.Rows) != 1 || page.Rows[0].CallerKeyID != keys[1].ID {
t.Fatal("held key's requests from", from, c, b)
}
if len(page.CallerKeys) != 1 || strings.Contains(b, "Laptop") || strings.Contains(b, keys[0].ID) || strings.Contains(b, "conv-1") {
t.Fatal("held key told of another key's calls:", b)
}
}
}