MauriceCarlo asked for two things on Usage → Requests. 1. The gateway-key filter should show even when one key has calls. The picker hides itself under two options, and with one key it had one, so calls made with that key couldn't be told from calls made with no key. A "No gateway key" choice (callerKey=none) now sits beside the keys whenever the period has calls with no key, or it is the current pick. A single key's picker therefore shows and separates the two. The hidden condition itself is left to #2499, which another session has. 2. The trend chart and the ranking can split by gateway key. LED_SPLITS gains "Gateway key". It's offered only while the period has a key's calls, and it falls back to Model otherwise. A click on a rank row picks that key, or none, and a second click lets go, as the other splits do. Server: - usage.Dimensions gains "callerKey". A row's key is its CallerKeyID, or NoCallerKey ("none") when it has none, and the filter takes "none" as calls without a key. - Filter.Without(d) is the one place that clears a dimension's own pick, so the by-split lists every value. RequestPage's fast and slow paths both use it now; they each had their own switch. - usageapi names the split's shares from the key labels: "No gateway key" for none, the ID if a key was deleted. - OwnPage keeps a held key's view to its own share in by and in the chart's split, so one key never learns another's name or numbers. The series was already only its own rows. - docs/reference.md documents callerKey=none and by.callerKey. "No gateway key" goes into the core i18n.js. The gateway keys page says "No gateway keys yet", and i18n-keys' "a plugin's words are its own" matches on substrings. Tests: - TestCallerKeySplitAndNone runs the fast and the slow path over {}, one key, none, and none+an agent, and checks by.callerKey. Broken by hand, it goes red: once with the none clause in the filter removed, and once with Without's callerKey case removed. - TestUsageOverGateway: on loopback the split names both keys. A held key's by.callerKey is only its own. With the OwnPage scrub skipped, it goes red (another key's name leaked). - usage-ledger-key-split is new, in both engines, all five languages, and 1400 and 760 px. It checks: - the picker's options with the none choice; - filtering on none; - the split's rows, and a click picking and letting go; - no sideways scroll; - that a period with no key's calls shows neither the picker nor the pill. 32/32 pass. With the none option removed by hand, 11 go red. Run on origin/maind9b943555(head 663db0ecf), with the #2517, #2521 and #2522 changes, load ~240: - gofmt -l clean; go vet -tags nogui for darwin, linux and windows: ok. - go test -timeout 120m -count=1 ./... (pipefail): exit 0, every package ok (gateway 1416.8s, agent 1535.5s). Before the rebase, on63be47717: - The 45m run had agent and gateway past 45m (#2544, #2108). - TestMainWindowCorners was killed at its deadline (#1936). - TestSkillRelinkKeepsUnreadableCopy failed (#2555; it passes alone). - gateway alone with 120m was ok. - GUI, the 41 Requests/Usage files in serial, both engines, before the rebase: 493 pass, 3 fail. The 3 were usage-refresh "not yet 2 !== 1", the same on63be47717alone (1 of 3); seen again on #2184. - Rebased, these all pass, 102/102: i18n-keys, usage-ledger-ttft, usage-ledger-key-split, usage-ledger, usage-speed, usage-ledger-detail, gui-ja, gui-de and gui-zh-tw. - Rebased again onto9b04c4e20, which touches ledger.go, request_page.go and gateway.go: - vet ×3: ok. - internal/usage, internal/usageapi and internal/cli: ok. - internal/gateway -run 'NativeCompaction|UsageOverGateway|Capped|Cap': ok. - usage-ledger-ttft, usage-ledger-key-split, usage-ledger and usage-speed: 86 pass. i18n-keys was red from main's own words (#2586, fixed in the next commit).
121 lines
5.1 KiB
Go
121 lines
5.1 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)
|
|
}
|
|
// split by key, each named as the key filter names it (#2521)
|
|
split := map[string]string{}
|
|
for _, s := range page.By["callerKey"] {
|
|
split[s.ID] = s.Name
|
|
}
|
|
if len(split) != 2 || split[keys[0].ID] != "Laptop" || split[keys[1].ID] != "Held" {
|
|
t.Fatal("the split by key:", page.By["callerKey"])
|
|
}
|
|
|
|
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)
|
|
}
|
|
// the split by key is counted without the key's pick: cut to its own
|
|
if len(page.By["callerKey"]) != 1 || page.By["callerKey"][0].ID != keys[1].ID {
|
|
t.Fatal("held key's split by key:", page.By["callerKey"])
|
|
}
|
|
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)
|
|
}
|
|
}
|
|
}
|