diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 21270cd68..017b757bc 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -278,6 +278,7 @@ var notYet = map[string]string{ "POST /api/profile/{action}": A, // api.go "POST /api/proxy/check": S2, // api.go "POST /api/pipelines/check": S2, // pipecheck.go: Settings › Models' Quick check, one real call a pipeline + "POST /api/relay-check": S2, // pipecheck.go: the Usage speed card by provider, its check button: a few small real calls to one model on one provider "POST /api/proxies/save": S2, // proxies.go: Settings › Network's saved proxies "POST /api/proxies/delete": S2, // proxies.go "POST /api/proxies/test": S2, // proxies.go diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index a6a29ea71..dd5ef49d9 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -881,6 +881,8 @@ func appendUsage(r *http.Request, rec usage.Record) { // a request an MCP tool call made: its row names the model (mcpUse) mcpUseOf(r.Context()).used(rec.Provider, rec.Model) } + // a relay check reads its calls' rows (relay_check.go) + tapUsage(r, rec) budget.Append(rec) } diff --git a/internal/gateway/relay_check.go b/internal/gateway/relay_check.go new file mode 100644 index 000000000..990e320e9 --- /dev/null +++ b/internal/gateway/relay_check.go @@ -0,0 +1,304 @@ +package gateway + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// A relay check (skingstyle48487 on X, with more than ten relays: which +// one waters a model down, which one answers with another) makes a few +// small real calls to one model on one provider, through this gateway as +// an agent would, and says what each found: what the reply named itself, +// how many input tokens a short prompt was counted as, whether a fixed +// answer came back right, whether a tool was called, and how fast. Each +// is a finding, a number or a match, never a verdict on the provider: a +// model that misses a sum on one call is no proof of a swap. It costs +// what the calls cost, so it is made only when the user presses Check. + +// The kinds of call a check makes. A check makes one count call, a few +// math calls and a few tool calls, each with an answer known in advance, +// so what came back is right or not, and a count of right answers can be +// set beside another provider's (skingstyle48487's second ask: accuracy +// and tool-call success, relay beside relay). +const ( + RelayPartCount = "count" // write 1 to 40: the reply, its speed, its tokens + RelayPartMath = "math" // a multiplication with a known product + RelayPartTool = "tool" // a question one of two tools answers +) + +// RelayCheckResult is what a check of one model on one provider found. +type RelayCheckResult struct { + Provider string `json:"provider"` + Model string `json:"model"` + Parts []RelayPart `json:"parts"` +} + +// RelayPart is what one call found. Ask is what the call asked, shown +// beside its kind: the multiplication, or the tool it should call. OK is that the call was answered; +// Match that the answer was the one asked for. Served is the model the +// reply named when that reads as another model than the one asked for +// (usage.Swapped), and By the provider that answered when the gateway +// handed the call on. Input is what the provider counted the prompt as, +// PromptChars how long that prompt was. +type RelayPart struct { + Kind string `json:"kind"` + Ask string `json:"ask,omitempty"` + OK bool `json:"ok"` + Match bool `json:"match"` + Status int `json:"status,omitempty"` + Error string `json:"error,omitempty"` + Want string `json:"want,omitempty"` + Got string `json:"got,omitempty"` + Served string `json:"served,omitempty"` + By string `json:"by,omitempty"` + Millis int64 `json:"ms"` + TTFT int64 `json:"ttft_ms,omitempty"` + TPS float64 `json:"tps,omitempty"` + Input int `json:"input,omitempty"` + Output int `json:"output,omitempty"` + PromptChars int `json:"prompt_chars,omitempty"` + Tries int `json:"tries,omitempty"` +} + +// relayTap collects the usage records of one check call: what the +// provider counted, the model its reply named and how long it took are +// what the gateway records, read here rather than parsed from a reply +// each protocol words its own way. +type relayTap struct { + mu sync.Mutex + recs []usage.Record +} + +type relayTapKey struct{} + +func tapUsage(r *http.Request, rec usage.Record) { + if t, _ := r.Context().Value(relayTapKey{}).(*relayTap); t != nil { + t.mu.Lock() + t.recs = append(t.recs, rec) + t.mu.Unlock() + } +} + +// relayCountTo is how far the count call counts: long enough for a speed +// to be measured, short enough to cost a few hundred tokens. +const relayCountTo = 40 + +// relayMaths are the multiplications the math calls ask, and their +// products: four-digit numbers, past what a model answers from memory. +var relayMaths = [][2]string{{"1234 * 5678", "7006652"}, {"987 * 654", "645498"}, {"2468 * 1357", "3349076"}} + +// relayTools are the tool calls' questions, the tool each should call and +// the word its arguments should hold. Both calls offer both tools, so the +// right one has to be picked. +var relayTools = []struct{ q, tool, arg string }{ + {"What is the weather in Paris now? Use a tool.", "get_weather", "paris"}, + {"What time is it in Tokyo now? Use a tool.", "get_time", "tokyo"}, +} + +// CheckRelay checks model on providerID with its calls, three at a time. A provider or model the gateway can't resolve is each call's +// error, as an agent would meet it. +func (s *Server) CheckRelay(ctx context.Context, providerID, model string) RelayCheckResult { + out := RelayCheckResult{Provider: providerID, Model: model} + ref := providerID + "/" + model + var nums []string + for i := 1; i <= relayCountTo; i++ { + nums = append(nums, strconv.Itoa(i)) + } + count := "Write the whole numbers from 1 to " + strconv.Itoa(relayCountTo) + " in order, separated by single spaces, and nothing else." + type call struct { + kind, ask, prompt, want, arg string + tools bool + } + calls := []call{{kind: RelayPartCount, prompt: count, want: strings.Join(nums, " ")}} + for _, m := range relayMaths { + calls = append(calls, call{kind: RelayPartMath, ask: strings.ReplaceAll(m[0], "*", "×"), prompt: "What is " + m[0] + "? Answer with the number only, without separators.", want: m[1]}) + } + for _, x := range relayTools { + calls = append(calls, call{kind: RelayPartTool, ask: x.tool, prompt: x.q, want: x.tool, arg: x.arg, tools: true}) + } + out.Parts = make([]RelayPart, len(calls)) + var wg sync.WaitGroup + // three at a time: a relay that limits a key's concurrent calls should + // answer a check as it answers an agent + slots := make(chan struct{}, 3) + for i, c := range calls { + wg.Add(1) + go func() { + defer wg.Done() + slots <- struct{}{} + defer func() { <-slots }() + p := s.relayCall(ctx, ref, c.prompt, c.tools) + p.Kind, p.Ask, p.Want = c.kind, c.ask, c.want + switch c.kind { + case RelayPartCount: + p.Match = p.OK && strings.Join(strings.Fields(p.Got), " ") == c.want + case RelayPartMath: + p.Match = p.OK && strings.Trim(strings.NewReplacer(",", "", " ", "", " ", "").Replace(p.Got), ".`*\n") == c.want + case RelayPartTool: + p.Match = p.OK && strings.HasPrefix(p.Got, c.want+"(") && strings.Contains(strings.ToLower(p.Got), c.arg) + } + if c.kind == RelayPartCount { + p.PromptChars = len(c.prompt) + } + if p.Served != "" && !relayAnother(providerID, model, p.Served) { + p.Served = "" + } + if p.By == providerID { + p.By = "" + } + out.Parts[i] = p + }() + } + wg.Wait() + return out +} + +// relayAnother is whether a reply that named served was another model than +// model on providerID, as the ledger marks a swap: not the same model +// spelled another way, nor a name the provider lists it under. +func relayAnother(providerID, model, served string) bool { + return usage.Swapped(model, served) && !usage.SameSpelled(model, served) && !usage.ListedAs(providerID, model, served) +} + +// relayCheckTools are the tools a tool call offers. +var relayCheckTools = json.RawMessage(`[{"type":"function","function":{"name":"get_weather","description":"Get the current weather in a city.","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}},{"type":"function","function":{"name":"get_time","description":"Get the current local time in a city.","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]`) + +// relayCall makes one streamed Chat Completions call for ref through the +// gateway and reads its reply: the text, or the tool calls as +// name(arguments), and the last answered try's usage record. +func (s *Server) relayCall(ctx context.Context, ref, prompt string, tools bool) RelayPart { + var p RelayPart + body := map[string]any{ + "model": ref, + "stream": true, + "max_tokens": 400, + "messages": []map[string]string{{"role": "user", "content": prompt}}, + } + if tools { + body["tools"] = relayCheckTools + } + b, _ := json.Marshal(body) + tap := &relayTap{} + ctx = context.WithValue(ctx, relayTapKey{}, tap) + req := httptest.NewRequestWithContext(ctx, http.MethodPost, URL()+"/v1/chat/completions", bytes.NewReader(b)) + req.RemoteAddr = "127.0.0.1:0" + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+TokenFor(CheckAgent)) + start := time.Now() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + p.Millis = time.Since(start).Milliseconds() + p.Status = rec.Code + if rec.Code != http.StatusOK { + p.Error = provider.APIError(rec.Body.Bytes(), http.StatusText(rec.Code)) + } else { + text, calls, msg := readChatStream(rec.Body.Bytes()) + p.Got = text + if len(calls) > 0 { + p.Got = strings.Join(calls, " ") + } + switch { + case msg != "": + p.Error = msg + case p.Got == "": + p.Error = "the answer was empty" + default: + p.OK = true + } + } + tap.mu.Lock() + recs := tap.recs + tap.mu.Unlock() + p.Tries = len(recs) + for _, r := range recs { + if r.Failed() || r.Status >= 400 { + continue + } + p.By = r.Provider + if r.Served != "" { + p.Served = r.Served + } + p.Input, p.Output = r.Input+r.CacheRead+r.CacheWrite, r.Output + p.TTFT = r.TTFT + if r.TTFT > 0 && r.Millis > r.TTFT && r.Output > 0 { + p.TPS = float64(r.Output) / (float64(r.Millis-r.TTFT) / 1000) + } + } + if len(p.Got) > 400 { + p.Got = p.Got[:400] + "…" + } + return p +} + +// readChatStream reads a Chat Completions stream: its text, its tool calls +// as name(arguments), and an error event's message. The model the reply +// named is the usage record's, which the gateway reads off the vendor's +// own reply. +func readChatStream(b []byte) (text string, calls []string, errMsg string) { + var sb strings.Builder + type call struct{ name, args strings.Builder } + var cs []*call + sc := bufio.NewScanner(bytes.NewReader(b)) + sc.Buffer(make([]byte, 64<<10), 8<<20) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + data, ok := strings.CutPrefix(line, "data:") + if !ok { + continue + } + data = strings.TrimSpace(data) + if data == "[DONE]" { + break + } + var ev struct { + Choices []struct { + Delta struct { + Content string `json:"content"` + ToolCalls []struct { + Index int `json:"index"` + Function struct { + Name string `json:"name"` + Arguments string `json:"arguments"` + } `json:"function"` + } `json:"tool_calls"` + } `json:"delta"` + } `json:"choices"` + Error *struct { + Message string `json:"message"` + } `json:"error"` + } + if json.Unmarshal([]byte(data), &ev) != nil { + continue + } + if ev.Error != nil && ev.Error.Message != "" { + errMsg = ev.Error.Message + } + for _, c := range ev.Choices { + sb.WriteString(c.Delta.Content) + for _, tc := range c.Delta.ToolCalls { + for len(cs) <= tc.Index { + cs = append(cs, &call{}) + } + cs[tc.Index].name.WriteString(tc.Function.Name) + cs[tc.Index].args.WriteString(tc.Function.Arguments) + } + } + } + for _, c := range cs { + if c.name.Len() > 0 { + calls = append(calls, c.name.String()+"("+c.args.String()+")") + } + } + return strings.TrimSpace(sb.String()), calls, errMsg +} diff --git a/internal/gateway/relay_check_test.go b/internal/gateway/relay_check_test.go new file mode 100644 index 000000000..519bae549 --- /dev/null +++ b/internal/gateway/relay_check_test.go @@ -0,0 +1,216 @@ +package gateway + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// checkedRelayUp is an OpenAI-compatible relay that streams answer(prompt) for +// each call, naming named as the model and counting the prompt as in. A +// tool answer is name{arguments}. +func checkedRelayUp(t *testing.T, named string, in int, answer func(prompt string, tools bool) (text, tool string)) *atomic.Int32 { + t.Helper() + var calls atomic.Int32 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + var req struct { + Messages []struct { + Content any `json:"content"` + } `json:"messages"` + Tools []any `json:"tools"` + } + b, _ := io.ReadAll(r.Body) + json.Unmarshal(b, &req) + prompt := "" + for _, m := range req.Messages { + prompt += fmt.Sprint(m.Content) + } + text, tool := answer(prompt, len(req.Tools) > 0) + w.Header().Set("Content-Type", "text/event-stream") + ev := func(v any) { + j, _ := json.Marshal(v) + fmt.Fprintf(w, "data: %s\n\n", j) + } + if tool != "" { + i := strings.Index(tool, "{") + ev(map[string]any{"id": "c", "model": named, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"tool_calls": []any{map[string]any{"index": 0, "id": "t1", "type": "function", "function": map[string]any{"name": tool[:i], "arguments": tool[i:]}}}}}}}) + } + for _, w := range strings.SplitAfter(text, " ") { + if w != "" { + ev(map[string]any{"id": "c", "model": named, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"content": w}}}}) + } + } + finish := "stop" + if tool != "" { + finish = "tool_calls" + } + ev(map[string]any{"id": "c", "model": named, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": finish}}}) + ev(map[string]any{"id": "c", "model": named, "choices": []any{}, "usage": map[string]any{"prompt_tokens": in, "completion_tokens": 50, "total_tokens": in + 50}}) + io.WriteString(w, "data: [DONE]\n\n") + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-5.5"}}); err != nil { + t.Fatal(err) + } + return &calls +} + +// relayParts keys a check's parts by kind and what each asked. +func relayParts(c RelayCheckResult) map[string]RelayPart { + m := map[string]RelayPart{} + for _, p := range c.Parts { + m[p.Kind+" "+p.Ask] = p + } + return m +} + +// relayRight answers each part as asked: the count, every product, and +// the tool each question needs. +func relayRight(prompt string, tools bool) (string, string) { + switch { + case strings.Contains(prompt, "Paris"): + return "", `get_weather{"city":"Paris"}` + case strings.Contains(prompt, "Tokyo"): + return "", `get_time{"city":"Tokyo"}` + } + for _, m := range relayMaths { + if strings.Contains(prompt, m[0]) { + return m[1], "" + } + } + var n []string + for i := 1; i <= relayCountTo; i++ { + n = append(n, fmt.Sprint(i)) + } + return strings.Join(n, " "), "" +} + +// A relay that answers as asked: every part matches, nothing names another +// model, and what it counted the prompt as comes back. +func TestCheckRelayAnsweredAsAsked(t *testing.T) { + fresh(t) + calls := checkedRelayUp(t, "gpt-5.5", 31, func(prompt string, tools bool) (string, string) { + if strings.Contains(prompt, "1234") { + return "7,006,652", "" // separators are read past + } + return relayRight(prompt, tools) + }) + c := New().CheckRelay(context.Background(), "relay", "gpt-5.5") + n := 1 + len(relayMaths) + len(relayTools) + if c.Provider != "relay" || c.Model != "gpt-5.5" || len(c.Parts) != n || int(calls.Load()) != n { + t.Fatalf("%+v, %d calls", c, calls.Load()) + } + ps := relayParts(c) + if len(ps) != n { + t.Fatalf("parts not apart: %v", ps) + } + for k, p := range ps { + if !p.OK || !p.Match || p.Served != "" || p.By != "" || p.Error != "" || p.Tries != 1 { + t.Fatalf("%s: %+v", k, p) + } + } + if p := ps["count "]; p.Input != 31 || p.Output != 50 || p.PromptChars == 0 { + t.Fatalf("count: %+v", p) + } + if p := ps["math 987 × 654"]; p.Got != "645498" { + t.Fatalf("math: %+v", p) + } + if p := ps["tool get_time"]; p.Got != `get_time({"city":"Tokyo"})` { + t.Fatalf("tool: %+v", p) + } +} + +// A model that calls the wrong one of the two tools, or answers one +// product wrong, has those parts not as asked and the others as asked. +func TestCheckRelayCountsEachAnswer(t *testing.T) { + fresh(t) + checkedRelayUp(t, "gpt-5.5", 31, func(prompt string, tools bool) (string, string) { + switch { + case strings.Contains(prompt, "Tokyo"): + return "", `get_weather{"city":"Tokyo"}` + case strings.Contains(prompt, "2468"): + return "3349176", "" + } + return relayRight(prompt, tools) + }) + ps := relayParts(New().CheckRelay(context.Background(), "relay", "gpt-5.5")) + var off []string + for k, p := range ps { + if !p.OK { + t.Fatalf("%s: %+v", k, p) + } + if !p.Match { + off = append(off, k) + } + } + slices.Sort(off) + if strings.Join(off, ",") != "math 2468 × 1357,tool get_time" { + t.Fatalf("not as asked: %v", off) + } +} + +// A relay that answers with another model, a wrong product, no tool call +// and a prompt counted many times over: each is said as found. +func TestCheckRelaySaysWhatDiffers(t *testing.T) { + fresh(t) + checkedRelayUp(t, "qwen3-8b", 4200, func(prompt string, tools bool) (string, string) { + if tools { + return "It is sunny.", "" + } + if strings.Contains(prompt, "*") { + return "7006552", "" + } + return "1 2 3 4 5", "" + }) + ps := relayParts(New().CheckRelay(context.Background(), "relay", "gpt-5.5")) + for k, p := range ps { + if !p.OK || p.Match || p.Served != "qwen3-8b" { + t.Fatalf("%s: %+v", k, p) + } + } + if p := ps["math 1234 × 5678"]; p.Got != "7006552" || p.Want != "7006652" { + t.Fatalf("math: %+v", p) + } + if p := ps["count "]; p.Input != 4200 { + t.Fatalf("count: %+v", p) + } +} + +// A refusal is the call's error in the vendor's words, and nothing matches. +func TestCheckRelaySaysTheRefusal(t *testing.T) { + fresh(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(403) + io.WriteString(w, `{"error":{"message":"this key has no access to gpt-5.5"}}`) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-5.5"}}); err != nil { + t.Fatal(err) + } + for _, p := range New().CheckRelay(context.Background(), "relay", "gpt-5.5").Parts { + if p.OK || p.Match || p.Status != 403 || !strings.Contains(p.Error, "no access to gpt-5.5") { + t.Fatalf("%+v", p) + } + } +} + +func TestReadChatStreamToolCallsInPieces(t *testing.T) { + b := []byte("data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"ci\"}}]}}]}\n\n" + + "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"ty\\\":\\\"Paris\\\"}\"}}]}}]}\n\n" + + "data: [DONE]\n\n") + text, calls, msg := readChatStream(b) + if text != "" || msg != "" || len(calls) != 1 || calls[0] != `get_weather({"city":"Paris"})` { + t.Fatalf("%q %q %q", text, calls, msg) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 7031415ad..a55261536 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2271,6 +2271,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { mux.HandleFunc("POST /api/proxy/check", handleProxyCheck) proxyRoutes(mux) mux.HandleFunc("POST /api/pipelines/check", handlePipelineCheck) + mux.HandleFunc("POST /api/relay-check", handleRelayCheck) mux.HandleFunc("POST /api/settings/codex-titles", func(rw http.ResponseWriter, r *http.Request) { var in struct{ Model string } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 158e899ef..234a0f4c6 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1621,6 +1621,16 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske .led-spd-h:hover, .led-spd-h.on { color: var(--fg); } .led-spd th[aria-sort="descending"] .led-spd-h::after { content: " ↓"; } .led-spd th[aria-sort="ascending"] .led-spd-h::after { content: " ↑"; } +.led-spd-by .opt { height: 20px; padding: 0 9px; font-size: 11px; } +.led-spd .led-spd-prov { overflow: hidden; text-overflow: ellipsis; font-size: 11px; font-weight: 400; color: var(--muted); } +.led-spd.by-prov tbody td { vertical-align: top; } +.led-spd.by-prov td.nm { min-width: 112px; } +.led-spd th.act, .led-spd td.act { width: 1px; padding-left: 8px; } +.led-spd td.off { color: var(--amber); } +.led-spd-check { height: 20px; padding: 0 2px; font-size: 11px; transition: opacity 150ms ease; } +@media (hover: hover) and (pointer: fine) { + .led-spd tr:not(:hover) .led-spd-check:not(:focus-visible) { opacity: 0; } +} .led-bar { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; margin-bottom: 8px; } .led-bar .grow { flex: 1; } .led-by { font-size: 11.5px; color: var(--muted); } @@ -5659,3 +5669,19 @@ body.linux .action-confirm::backdrop { -webkit-backdrop-filter: none; backdrop-f .field.ag-speed .v .bolts { display: inline-flex; } .field.ag-speed .v .bolts svg + svg { margin-left: -5px; } .field.ag-speed .ag-speed-by { color: var(--faint); font-weight: 400; white-space: pre; } + +/* the Usage speed card's check dialog (relaycheck.js) */ +.relay-check > p, .relay-parts { grid-column: 1 / -1; } +.relay-parts { display: flex; flex-direction: column; gap: 10px; min-width: 0; margin: 4px 0 12px; } +.relay-part { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.relay-top { display: flex; align-items: center; gap: 8px; font-weight: 600; } +.relay-sum { display: flex; flex-wrap: wrap; gap: 4px 16px; font-weight: 500; } +.relay-mark { flex: none; width: 7px; height: 7px; border-radius: 50%; background: var(--muted); } +.relay-mark.ok { background: var(--green); } +.relay-mark.off { background: var(--amber); } +.relay-mark.err { background: var(--red); } +.relay-said { font-weight: 400; font-size: 12px; } +.relay-line { padding-left: 15px; font-size: 12px; overflow-wrap: anywhere; } +.relay-line.mono { font-family: var(--code); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.relay-line.err, .relay-part.err { color: var(--red); } +.relay-wait { font-size: 12px; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 75256fef4..ff4c0bb62 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4,6 +4,27 @@ // works. {name} slots are filled by t(str, vars). const I18N = { zh: { + "Check {model} on {provider}": "在 {provider} 上检查 {model}", + "A few small real calls with known answers, billed as any other: write the numbers 1 to 40, multiply, call the right tool. Each says what came back.": "几次小的真实调用,答案事先已知,照常计费:写出 1 到 40、算乘法、调用正确的工具。每一项都列出实际返回的内容。", + "Count to 40": "数到 40", + "Multiply {q}": "计算 {q}", + "Call {tool}": "调用 {tool}", + "Expected answer": "符合预期", + "Unexpected answer": "不符合预期", + "Answered in text, without calling a tool": "用文字回答,没有调用工具", + "Answers right: {n} of {m}": "答对 {n} / {m}", + "Right tool calls: {n} of {m}": "工具调用正确 {n} / {m}", + "Answers": "答对", + "Right answers in the last check of the model on this provider": "该供应商上次检查此模型时答对的题数", + "Right tool calls in the last check of the model on this provider": "该供应商上次检查此模型时正确的工具调用", + "{n} of {m} right, checked {when}": "{m} 题答对 {n},{when}检查", + "Got: {text}": "返回:{text}", + "The reply named {model}": "回复标明的模型是 {model}", + "Answered by {provider}, after this one failed": "此供应商失败后,由 {provider} 回答", + "A {n}-character prompt was counted as {m} input tokens": "{n} 个字符的提示词被计为 {m} 个输入 token", + "More than a prompt this short holds: the provider may add instructions of its own, or count another way": "比这么短的提示词应有的多:供应商可能加入了自己的指令,或者用另一种方式计数", + "First token {took}": "首 token {took}", + "{took} in all": "共 {took}", "Keep on top": "窗口置顶", "Stop keeping on top": "取消置顶", "Calls": "调用次数", @@ -5401,6 +5422,27 @@ const I18N = { "runs everything without asking": "所有操作都直接运行,不询问", }, "zh-TW": { + "Check {model} on {provider}": "在 {provider} 上檢查 {model}", + "A few small real calls with known answers, billed as any other: write the numbers 1 to 40, multiply, call the right tool. Each says what came back.": "幾次小的真實呼叫,答案事先已知,照常計費:寫出 1 到 40、算乘法、呼叫正確的工具。每一項都列出實際回傳的內容。", + "Count to 40": "數到 40", + "Multiply {q}": "計算 {q}", + "Call {tool}": "呼叫 {tool}", + "Expected answer": "符合預期", + "Unexpected answer": "不符合預期", + "Answered in text, without calling a tool": "用文字回答,沒有呼叫工具", + "Answers right: {n} of {m}": "答對 {n} / {m}", + "Right tool calls: {n} of {m}": "工具呼叫正確 {n} / {m}", + "Answers": "答對", + "Right answers in the last check of the model on this provider": "該供應商上次檢查此模型時答對的題數", + "Right tool calls in the last check of the model on this provider": "該供應商上次檢查此模型時正確的工具呼叫", + "{n} of {m} right, checked {when}": "{m} 題答對 {n},{when}檢查", + "Got: {text}": "回傳:{text}", + "The reply named {model}": "回覆標明的模型是 {model}", + "Answered by {provider}, after this one failed": "此供應商失敗後,由 {provider} 回答", + "A {n}-character prompt was counted as {m} input tokens": "{n} 個字元的提示詞被計為 {m} 個輸入 token", + "More than a prompt this short holds: the provider may add instructions of its own, or count another way": "比這麼短的提示詞應有的多:供應商可能加入了自己的指示,或者用另一種方式計數", + "First token {took}": "首 token {took}", + "{took} in all": "共 {took}", "Keep on top": "視窗置頂", "Stop keeping on top": "取消置頂", "Calls": "呼叫次數", @@ -10782,6 +10824,27 @@ const I18N = { "runs everything without asking": "所有操作都直接執行,不詢問", }, ja: { + "Check {model} on {provider}": "{provider} で {model} をチェック", + "A few small real calls with known answers, billed as any other: write the numbers 1 to 40, multiply, call the right tool. Each says what came back.": "答えの決まった小さな実際の呼び出しを数回行います(通常どおり課金):1 から 40 までを書く、掛け算、正しいツールを呼ぶ。それぞれ返ってきた内容を示します。", + "Count to 40": "40 まで数える", + "Multiply {q}": "{q} を計算", + "Call {tool}": "{tool} を呼ぶ", + "Expected answer": "想定どおり", + "Unexpected answer": "想定と異なる", + "Answered in text, without calling a tool": "ツールを呼ばずにテキストで答えた", + "Answers right: {n} of {m}": "正解 {n} / {m}", + "Right tool calls: {n} of {m}": "正しいツール呼び出し {n} / {m}", + "Answers": "正解", + "Right answers in the last check of the model on this provider": "このプロバイダでの前回のチェックの正解数", + "Right tool calls in the last check of the model on this provider": "このプロバイダでの前回のチェックの正しいツール呼び出し数", + "{n} of {m} right, checked {when}": "{m} 問中 {n} 問正解、{when}にチェック", + "Got: {text}": "返答:{text}", + "The reply named {model}": "返答のモデル名は {model}", + "Answered by {provider}, after this one failed": "このプロバイダが失敗した後、{provider} が答えた", + "A {n}-character prompt was counted as {m} input tokens": "{n} 文字のプロンプトが入力 {m} トークンと数えられた", + "More than a prompt this short holds: the provider may add instructions of its own, or count another way": "この短さのプロンプトにしては多い:プロバイダが独自の指示を加えているか、別の方法で数えている可能性があります", + "First token {took}": "最初のトークン {took}", + "{took} in all": "合計 {took}", "Keep on top": "最前面に固定", "Stop keeping on top": "最前面の固定を解除", "Calls": "呼び出し数", @@ -16165,6 +16228,27 @@ const I18N = { "runs everything without asking": "すべて確認せずに実行する", }, de: { + "Check {model} on {provider}": "{model} bei {provider} prüfen", + "A few small real calls with known answers, billed as any other: write the numbers 1 to 40, multiply, call the right tool. Each says what came back.": "Ein paar kleine echte Aufrufe mit bekannten Antworten, wie jeder andere berechnet: die Zahlen 1 bis 40 schreiben, multiplizieren, das richtige Werkzeug aufrufen. Jeder zeigt, was zurückkam.", + "Count to 40": "Bis 40 zählen", + "Multiply {q}": "{q} rechnen", + "Call {tool}": "{tool} aufrufen", + "Expected answer": "Wie erwartet", + "Unexpected answer": "Nicht wie erwartet", + "Answered in text, without calling a tool": "Als Text beantwortet, ohne ein Werkzeug aufzurufen", + "Answers right: {n} of {m}": "Richtige Antworten: {n} von {m}", + "Right tool calls: {n} of {m}": "Richtige Werkzeugaufrufe: {n} von {m}", + "Answers": "Richtig", + "Right answers in the last check of the model on this provider": "Richtige Antworten bei der letzten Prüfung des Modells bei diesem Anbieter", + "Right tool calls in the last check of the model on this provider": "Richtige Werkzeugaufrufe bei der letzten Prüfung des Modells bei diesem Anbieter", + "{n} of {m} right, checked {when}": "{n} von {m} richtig, geprüft {when}", + "Got: {text}": "Erhalten: {text}", + "The reply named {model}": "Die Antwort nannte {model}", + "Answered by {provider}, after this one failed": "Von {provider} beantwortet, nachdem dieser fehlschlug", + "A {n}-character prompt was counted as {m} input tokens": "Ein Prompt mit {n} Zeichen wurde als {m} Eingabe-Token gezählt", + "More than a prompt this short holds: the provider may add instructions of its own, or count another way": "Mehr, als ein so kurzer Prompt enthält: Der Anbieter fügt vielleicht eigene Anweisungen hinzu oder zählt anders", + "First token {took}": "Erstes Token {took}", + "{took} in all": "{took} insgesamt", "Keep on top": "Im Vordergrund halten", "Stop keeping on top": "Nicht mehr im Vordergrund halten", "Calls": "Aufrufe", diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index 05ffe00fb..1db787ba5 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -2,6 +2,13 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "Other model": "其他模型", + "Check…": "检查…", + "Tries that failed, those handed on to another provider too": "失败的尝试,包括转交给其他供应商的", + "Replies that named another model than the one asked for": "回复标明的模型与请求的不同", + "{n} of {m} failed": "{m} 次中失败 {n} 次", + "{n} of {m} replies named another model": "{m} 次中有 {n} 次回复标明了其他模型", + "Check {model} on {provider} with a few small real calls": "用几次小的真实调用检查 {provider} 上的 {model}", "{n} client": "{n} 个客户端", "{n} clients": "{n} 个客户端", "Clients under 1% of the tokens, idle for 3 days or past the top 20. Their calls still count in every total.": "token 不到总量 1%、3 天未使用或排在前 20 名之后的客户端。它们的调用仍计入每一项总计。", @@ -293,6 +300,13 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同", }, "zh-TW": { + "Other model": "其他模型", + "Check…": "檢查…", + "Tries that failed, those handed on to another provider too": "失敗的嘗試,包括轉交給其他供應商的", + "Replies that named another model than the one asked for": "回覆標明的模型與請求的不同", + "{n} of {m} failed": "{m} 次中失敗 {n} 次", + "{n} of {m} replies named another model": "{m} 次中有 {n} 次回覆標明了其他模型", + "Check {model} on {provider} with a few small real calls": "用幾次小的真實呼叫檢查 {provider} 上的 {model}", "{n} client": "{n} 個用戶端", "{n} clients": "{n} 個用戶端", "Clients under 1% of the tokens, idle for 3 days or past the top 20. Their calls still count in every total.": "token 不到總量 1%、3 天未使用或排在前 20 名之後的用戶端。它們的呼叫仍計入每一項總計。", @@ -584,6 +598,13 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同", }, ja: { + "Other model": "別のモデル", + "Check…": "チェック…", + "Tries that failed, those handed on to another provider too": "失敗した試行(別のプロバイダに回したものも含む)", + "Replies that named another model than the one asked for": "要求したものと別のモデル名を返した返答", + "{n} of {m} failed": "{m} 回中 {n} 回失敗", + "{n} of {m} replies named another model": "{m} 回中 {n} 回の返答が別のモデル名だった", + "Check {model} on {provider} with a few small real calls": "{provider} の {model} を小さな実際の呼び出し数回でチェック", "{n} client": "{n} 個のクライアント", "{n} clients": "{n} 個のクライアント", "Clients under 1% of the tokens, idle for 3 days or past the top 20. Their calls still count in every total.": "トークンが 1% 未満で、3 日間使われていないか上位 20 位より下のクライアント。その呼び出しはすべての合計に含まれます。", @@ -875,6 +896,13 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信", }, de: { + "Other model": "Anderes Modell", + "Check…": "Prüfen…", + "Tries that failed, those handed on to another provider too": "Fehlgeschlagene Versuche, auch an einen anderen Anbieter weitergegebene", + "Replies that named another model than the one asked for": "Antworten, die ein anderes als das verlangte Modell nannten", + "{n} of {m} failed": "{n} von {m} fehlgeschlagen", + "{n} of {m} replies named another model": "{n} von {m} Antworten nannten ein anderes Modell", + "Check {model} on {provider} with a few small real calls": "{model} bei {provider} mit ein paar kleinen echten Aufrufen prüfen", "{n} client": "{n} Client", "{n} clients": "{n} Clients", "Clients under 1% of the tokens, idle for 3 days or past the top 20. Their calls still count in every total.": "Clients unter 1 % der Tokens, seit 3 Tagen ungenutzt oder nach den ersten 20. Ihre Aufrufe zählen weiter in jeder Summe mit.", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index b8c75d609..ed53e4970 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -2397,14 +2397,44 @@ function ledShowStatus(to) { // ledger with the page (usage.ModelSpeed): failed, canceled and short // replies are left out. Sortable by any column; the fastest first. let ledSpeedSort = { key: "tps", dir: -1 }; +// by model, or each model on each provider it went to (skingstyle48487 on +// X, with a dozen relays: which one is slow, which one fails, which one +// answers with another model), kept as left +let ledSpeedBy = "model"; +try { ledSpeedBy = localStorage.getItem("magpie.ledSpeedBy") === "provider" ? "provider" : "model"; } catch {} const LED_SPEED_COLS = [ { key: "name", label: "Model", dir: 1 }, { key: "tps", label: "Speed", dir: -1 }, { key: "ttft_ms", label: "First token", dir: 1 }, { key: "requests", label: "Requests", dir: -1 }, ]; +// a provider's row counts its tries, and how many failed or were answered +// by another model, beside the speed of those answered +const LED_PROV_COLS = [ + { key: "name", label: "Model", dir: 1 }, + { key: "tps", label: "Speed", dir: -1 }, + { key: "ttft_ms", label: "First token", dir: 1 }, + { key: "tries", label: "Requests", dir: -1 }, + { key: "fail", label: "Failed", dir: -1 }, + { key: "swapped", label: "Other model", dir: -1 }, + { key: "right", label: "Answers", dir: -1 }, + { key: "tools", label: "Tool calls", dir: -1 }, +]; +const ledFail = (x) => x.tries ? (x.failed || 0) / x.tries : 0; +// the last check of each model on each provider (relaycheck.js relayKeep): +// its right answers and right tool calls, set beside the other providers' +function ledChecks() { + try { return JSON.parse(localStorage.getItem("magpie.relayChecks") || "{}") || {}; } catch { return {}; } +} +const ledCheckShare = (x, key) => { + const c = x.check, of = c && (key === "tools" ? c.tools_of : c.of); + return of ? (key === "tools" ? c.tools : c.right) / of : -1; +}; +let ledSpeedLast; +window.addEventListener("magpie-relay-checked", () => { if (ledSpeedLast && $("#ledSpeed")) drawLedSpeed(ledSpeedLast); }); function ledSpeedOrder(list) { const { key, dir } = ledSpeedSort; + const nm = (x) => (x.name || x.model) + (x.provider_name ? "\u0000" + x.provider_name : ""); return [...list].sort((a, b) => { // a model with nothing measured goes last, whichever way it is sorted if (key === "tps" || key === "ttft_ms") { @@ -2412,30 +2442,59 @@ function ledSpeedOrder(list) { if (!x !== !y) return x ? -1 : 1; if (x !== y) return dir * (x - y); } else if (key === "name") { - const c = (a.name || a.model).localeCompare(b.name || b.model); + const c = nm(a).localeCompare(nm(b)); if (c) return dir * c; - } else if (a[key] !== b[key]) return dir * (a[key] - b[key]); - return b.requests - a.requests || (a.name || a.model).localeCompare(b.name || b.model); + } else if (key === "fail") { + const c = ledFail(a) - ledFail(b); + if (c) return dir * c; + } else if (key === "right" || key === "tools") { + // a provider not checked goes last, whichever way it is sorted + const x = ledCheckShare(a, key), y = ledCheckShare(b, key); + if ((x < 0) !== (y < 0)) return x < 0 ? 1 : -1; + if (x !== y) return dir * (x - y); + } else if ((a[key] || 0) !== (b[key] || 0)) return dir * ((a[key] || 0) - (b[key] || 0)); + return (b.requests ?? b.tries) - (a.requests ?? a.tries) || nm(a).localeCompare(nm(b)); }); } function drawLedSpeed(l) { const box = $("#ledSpeed"); - const list = l.speeds || []; - box.hidden = !list.length; + ledSpeedLast = l; + const byProv = ledSpeedBy === "provider"; + const checks = byProv ? ledChecks() : {}; + const list = ((byProv ? l.provider_speeds : l.speeds) || []).map((x) => byProv ? { ...x, check: checks[x.provider + "\u0000" + x.model] } : x); + box.hidden = !(l.speeds?.length || l.provider_speeds?.length); box.replaceChildren(); if (box.hidden) return; const head = el("div", "led-bar"); const title = el("b", "led-spd-t", t("Model speed")); title.title = t("Medians of the answered requests that wrote {n} tokens or more", { n: l.speed_min || 100 }); - head.append(title); - const table = el("table", "led-spd"); + const by = sessSegs([["model", "Models"], ["provider", "Providers"]], ledSpeedBy, (to) => { + ledSpeedBy = to; + try { localStorage.setItem("magpie.ledSpeedBy", to); } catch {} + if (!LED_SPEED_COLS.concat(to === "provider" ? LED_PROV_COLS : []).some((c) => c.key === ledSpeedSort.key)) ledSpeedSort = { key: "tps", dir: -1 }; + drawLedSpeed(l); + $("#ledSpeed .segs .opt.on")?.focus({ preventScroll: true }); + }); + by.classList.add("led-spd-by"); + head.append(title, el("span", "grow"), by); + // Other model shows once a reply named another model than the one asked + // for, and Answers and Tool calls once a provider was checked; nothing + // to say before + const checked = list.some((x) => x.check); + const cols = byProv ? LED_PROV_COLS.filter((c) => (c.key !== "swapped" || list.some((x) => x.swapped)) && (!["right", "tools"].includes(c.key) || checked)) : LED_SPEED_COLS; + if (!cols.some((c) => c.key === ledSpeedSort.key)) ledSpeedSort = { key: "tps", dir: -1 }; + const table = el("table", "led-spd" + (byProv ? " by-prov" : "")); const hr = el("tr"); - for (const c of LED_SPEED_COLS) { + for (const c of cols) { const th = el("th", c.key === "name" ? "nm" : "n"); const on = ledSpeedSort.key === c.key; th.setAttribute("aria-sort", on ? (ledSpeedSort.dir > 0 ? "ascending" : "descending") : "none"); const b = el("button", "led-spd-h" + (on ? " on" : ""), t(c.label)); b.type = "button"; + if (c.key === "fail") b.title = t("Tries that failed, those handed on to another provider too"); + if (c.key === "swapped") b.title = t("Replies that named another model than the one asked for"); + if (c.key === "right") b.title = t("Right answers in the last check of the model on this provider"); + if (c.key === "tools") b.title = t("Right tool calls in the last check of the model on this provider"); b.onclick = () => { ledSpeedSort = on ? { key: c.key, dir: -ledSpeedSort.dir } : { key: c.key, dir: c.dir }; drawLedSpeed(l); @@ -2444,6 +2503,7 @@ function drawLedSpeed(l) { th.append(b); hr.append(th); } + if (byProv) hr.append(el("th", "act")); const thead = el("thead"); thead.append(hr); const body = el("tbody"); @@ -2451,10 +2511,46 @@ function drawLedSpeed(l) { const tr = el("tr"); const name = el("td", "nm", x.name || x.model); name.title = x.name || x.model; + if (byProv) { + const sub = el("div", "led-spd-prov", x.provider_name || x.provider); + name.title += " · " + sub.textContent; + name.append(sub); + } tr.append(name, el("td", "n" + (x.tps ? "" : " faint"), x.tps ? t("{n} tok/s", { n: ledNum(Math.round(x.tps)) }) : "—"), - el("td", "n" + (x.ttft_ms ? "" : " faint"), x.ttft_ms ? ledTook(x.ttft_ms) : "—"), - el("td", "n", ledNum(x.requests))); + el("td", "n" + (x.ttft_ms ? "" : " faint"), x.ttft_ms ? ledTook(x.ttft_ms) : "—")); + if (!byProv) { + tr.append(el("td", "n", ledNum(x.requests))); + body.append(tr); + continue; + } + const f = ledFail(x); + const fail = el("td", "n" + (x.failed ? "" : " faint"), x.failed ? (f < 0.001 ? "<0.1%" : (f * 100).toFixed(f < 0.1 ? 1 : 0) + "%") : "0"); + fail.title = t("{n} of {m} failed", { n: ledNum(x.failed || 0), m: ledNum(x.tries) }); + tr.append(el("td", "n", ledNum(x.tries)), fail); + if (cols.some((c) => c.key === "swapped")) { + const sw = el("td", "n" + (x.swapped ? "" : " faint"), ledNum(x.swapped || 0)); + sw.title = t("{n} of {m} replies named another model", { n: ledNum(x.swapped || 0), m: ledNum(x.tries) }); + tr.append(sw); + } + for (const key of checked ? ["right", "tools"] : []) { + const c = x.check, of = c && (key === "tools" ? c.tools_of : c.of), n = c && (key === "tools" ? c.tools : c.right); + const td = el("td", "n" + (!of ? " faint" : n < of ? " off" : ""), of ? n + "/" + of : "—"); + if (of) td.title = t("{n} of {m} right, checked {when}", { n, m: of, when: ago(c.at) }); + tr.append(td); + } + // a check of this model on this provider: a few small real calls, made + // only on the press (relaycheck.js) + const act = el("td", "act"); + const go = el("button", "text led-spd-check", t("Check…")); + go.type = "button"; + go.title = t("Check {model} on {provider} with a few small real calls", { model: x.name || x.model, provider: x.provider_name || x.provider }); + go.onclick = async () => { + try { window.relayCheck || await import(new URL("relaycheck.js", document.baseURI).href); } catch (err) { return status(err.message, "err"); } + relayCheck(x.provider, x.model, x.provider_name || x.provider, x.name || x.model); + }; + act.append(go); + tr.append(act); body.append(tr); } table.append(thead, body); diff --git a/internal/gui/assets/relaycheck.js b/internal/gui/assets/relaycheck.js new file mode 100644 index 000000000..ca90976f5 --- /dev/null +++ b/internal/gui/assets/relaycheck.js @@ -0,0 +1,124 @@ +// The Usage speed card's check on a provider's row (skingstyle48487 on X, +// with more than ten relays): one model on one provider checked with a +// few small real calls through the gateway (/api/relay-check), each with +// an answer known in advance: count to 40, three multiplications, two +// questions a tool answers. What each found is said as found, a number or +// what came back, never a verdict on the provider: a model can miss a sum +// on one call, and a provider can count tokens its own way. The right +// answers are counted and kept (relayKeep), so the card sets each +// provider's last check beside the others'. The calls cost what they +// cost, so only the dialog's Check sends them. plugins/usage/page.js +// imports this on the first press. +// a prompt this short is a few dozen tokens with any tokenizer and any +// chat template; well past that, something was added or counted another way +const RELAY_PADDED = 300; + +window.relayCheck = function (provider, model, providerName, modelName) { + const ed = el("div", "editor relay-check"); + const head = el("div", "ehead"); + head.append(el("b", "", t("Check {model} on {provider}", { model: modelName, provider: providerName }))); + const say = el("p", "lib-confirm", t("A few small real calls with known answers, billed as any other: write the numbers 1 to 40, multiply, call the right tool. Each says what came back.")); + const list = el("div", "relay-parts"); + list.setAttribute("role", "status"); + list.hidden = true; + const bar = el("div", "bar"); + const close = el("button", "text", t("Close")); + close.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; + const go = el("button", "text primary", t("Check")); + go.onclick = async (e) => { + e.stopPropagation(); + go.disabled = true; + go.textContent = t("Checking…"); + list.hidden = false; + list.replaceChildren(el("div", "relay-wait faint", t("Checking…"))); + let r; + try { r = await api("relay-check", { provider, model }); } catch (err) { r = { error: t(err.message) }; } + if (!r.error) relayKeep(provider, model, r); + if (confirmAsk !== ed) return; // closed while it ran + go.disabled = false; + go.textContent = t("Check again"); + relayFill(list, r); + }; + bar.append(el("span", "grow"), close, go); + ed.append(head, say, list, bar); + confirmAsk = ed; + openModal(ed); + $("#modal").classList.add("lib"); + go.focus({ preventScroll: true }); +}; + +// relayTally counts a check's right answers apart from its right tool +// calls; a call that failed counts as asked and not right +function relayTally(r) { + const n = { right: 0, of: 0, tools: 0, tools_of: 0 }; + for (const p of r.parts || []) { + if (p.kind === "tool") { n.tools_of++; if (p.match) n.tools++; } + else { n.of++; if (p.match) n.right++; } + } + return n; +} + +// relayKeep keeps the tally of each provider's last check of a model, in +// this window's storage, for the speed card's Answers and Tool calls +// columns, and has the card drawn again +function relayKeep(provider, model, r) { + try { + const all = JSON.parse(localStorage.getItem("magpie.relayChecks") || "{}"); + all[provider + "\u0000" + model] = { ...relayTally(r), at: Date.now() }; + const keys = Object.keys(all).sort((a, b) => all[b].at - all[a].at); + for (const k of keys.slice(200)) delete all[k]; + localStorage.setItem("magpie.relayChecks", JSON.stringify(all)); + } catch {} + window.dispatchEvent(new CustomEvent("magpie-relay-checked")); +} + +function relayName(p) { + if (p.kind === "count") return t("Count to 40"); + if (p.kind === "math") return t("Multiply {q}", { q: p.ask }); + return t("Call {tool}", { tool: p.ask }); +} + +// relayFill says how many answers were right, then each part: its name, +// whether the answer was the one asked for, and what it measured +function relayFill(list, r) { + if (r.error) return list.replaceChildren(el("div", "relay-part err", r.error)); + const n = relayTally(r); + const sum = el("div", "relay-sum"); + sum.append(el("span", "", t("Answers right: {n} of {m}", { n: n.right, m: n.of })), el("span", "", t("Right tool calls: {n} of {m}", { n: n.tools, m: n.tools_of }))); + list.replaceChildren(sum, ...(r.parts || []).map((p) => { + const row = el("div", "relay-part"); + const top = el("div", "relay-top"); + const mark = el("span", "relay-mark " + (p.match ? "ok" : p.ok ? "off" : "err")); + mark.setAttribute("aria-hidden", "true"); + const said = p.match ? t("Expected answer") : p.ok ? t("Unexpected answer") : t("Failed"); + top.append(mark, el("span", "relay-name", relayName(p)), el("span", "grow"), el("span", "relay-said" + (p.match ? " faint" : ""), said)); + row.append(top); + const lines = []; + if (!p.ok) lines.push([(p.status ? p.status + " · " : "") + (p.error || ""), "err"]); + else if (!p.match) { + if (p.kind === "tool" && !/^get_\w+\(/.test(p.got)) lines.push([t("Answered in text, without calling a tool"), ""]); + lines.push([t("Got: {text}", { text: p.got }), "mono"]); + } + if (p.served) lines.push([t("The reply named {model}", { model: p.served }), "note"]); + if (p.by) lines.push([t("Answered by {provider}, after this one failed", { provider: p.by }), "note"]); + if (p.kind === "count" && p.input) { + lines.push([t("A {n}-character prompt was counted as {m} input tokens", { n: p.prompt_chars, m: ledNum(p.input) }), p.input > RELAY_PADDED ? "note" : "faint"]); + if (p.input > RELAY_PADDED) lines.push([t("More than a prompt this short holds: the provider may add instructions of its own, or count another way"), "faint"]); + } + // the count writes the most, so its speed is the one worth reading; + // a call not answered as asked says how long it took too + const speed = []; + if (p.kind === "count" || !p.match) { + if (p.ttft_ms) speed.push(t("First token {took}", { took: ledTook(p.ttft_ms) })); + if (p.tps) speed.push(t("{n} tok/s", { n: ledNum(Math.round(p.tps)) })); + if (p.ms) speed.push(t("{took} in all", { took: ledTook(p.ms) })); + } + if (speed.length) lines.push([speed.join(" · "), "faint"]); + for (const [text, cls] of lines) { + const line = el("div", "relay-line" + (cls ? " " + cls : ""), text); + line.title = text; + row.append(line); + } + return row; + })); +} diff --git a/internal/gui/pipecheck.go b/internal/gui/pipecheck.go index a22428162..0ad569127 100644 --- a/internal/gui/pipecheck.go +++ b/internal/gui/pipecheck.go @@ -30,3 +30,23 @@ func handlePipelineCheck(rw http.ResponseWriter, r *http.Request) { } writeJSON(rw, gw.CheckPipeline(r.Context(), in.Kind)) } + +// handleRelayCheck checks one model on one provider with a few small real +// calls (gateway.CheckRelay), made only when the user presses Check. +func handleRelayCheck(rw http.ResponseWriter, r *http.Request) { + var in struct{ Provider, Model string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if in.Provider == "" || in.Model == "" { + fail(rw, errors.New("a check needs a provider and a model")) + return + } + gw := served.Load() + if gw == nil { + fail(rw, errors.New("Another magpie serves the gateway: check there")) + return + } + writeJSON(rw, gw.CheckRelay(r.Context(), in.Provider, in.Model)) +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index edc421922..371ea834a 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -175,7 +175,8 @@ test("compat.js is the first of the page's own scripts", async () => { // navicons.js (the sidebar lists' marks) with the first list drawn; // autoswitchtip.js when a provider's accounts draw their switch; // codexprojects.js when the open Codex app shows fewer projects; - // pipecheck.js when Settings draws Models; + // pipecheck.js when Settings draws Models; relaycheck.js on Usage › Model + // speed's first Check… press; // addfloat.js when the Providers page's add sheet first opens; // plugingrid.js and plugininstalled.js when Plugins first draws; // rotfig.js when a routing's In turn is first shown; @@ -189,7 +190,7 @@ test("compat.js is the first of the page's own scripts", async () => { // navorder.js once a page order is kept, or Settings › Sidebar pages draws; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "plugininstalled.js", "rotfig.js", "ompadvisor.js", "kimisub.js", "agentspeed.js", "claudemagpie.js", "keyrates.js", "maximages.js", "qianwenplan.js", "qianfanplan.js", "agymove.js", "updatetrust.js", "currencyprefs.js", "appearance.js", "mirroredit.js", "navorder.js", "instancename.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "relaycheck.js", "addfloat.js", "plugingrid.js", "plugininstalled.js", "rotfig.js", "ompadvisor.js", "kimisub.js", "agentspeed.js", "claudemagpie.js", "keyrates.js", "maximages.js", "qianwenplan.js", "qianfanplan.js", "agymove.js", "updatetrust.js", "currencyprefs.js", "appearance.js", "mirroredit.js", "navorder.js", "instancename.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/usage-model-speed.test.cjs b/internal/gui/tests/usage-model-speed.test.cjs index f43f4e8fa..378c330ee 100644 --- a/internal/gui/tests/usage-model-speed.test.cjs +++ b/internal/gui/tests/usage-model-speed.test.cjs @@ -4,6 +4,11 @@ // first-token wait and its request count, the fastest first, sortable by each // column, a model with nothing measured always last, in every language, at a // phone's width without scrolling sideways, and gone when no request counted. +// By provider (skingstyle48487 on X, with a dozen relays): each model on each +// provider with its tries, the share that failed and the replies that named +// another model, and a Check… that sends its calls only on the dialog's +// Check, saying what each found and how many answers and tool calls were +// right, kept as the provider's Answers and Tool calls beside the others'. // No backend, the API is faked. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); @@ -27,6 +32,23 @@ const SPEEDS = [ { model: "kimi-slow", name: "kimi-slow", requests: 3, tps: 10.2, tps_n: 3, ttft_ms: 2100 }, { model: "burst-model", name: "burst-model", requests: 5, ttft_ms: 400 }, ]; +// the same models by provider: glm-fast on two, one of which failed 1 of 4 +// tries and once answered with another model +const PROV = [ + { model: "glm-fast", name: "GLM Fast", provider: "zai", provider_name: "Z.ai Coding Plan", requests: 20, tries: 20, tps: 80, tps_n: 20, ttft_ms: 550 }, + { model: "glm-fast", name: "GLM Fast", provider: "relay9", provider_name: "Relay Nine", requests: 3, tries: 4, failed: 1, swapped: 1, tps: 40, tps_n: 3, ttft_ms: 900 }, + { model: "kimi-slow", name: "kimi-slow", provider: "relay9", provider_name: "Relay Nine", requests: 3, tries: 3, tps: 10.2, tps_n: 3, ttft_ms: 2100 }, +]; +const CHECK = { + provider: "relay9", model: "glm-fast", parts: [ + { kind: "count", ok: true, match: true, want: "1 2 3", got: "1 2 3", ms: 2400, ttft_ms: 600, tps: 42, input: 4200, output: 120, prompt_chars: 118, tries: 1 }, + { kind: "math", ask: "1234 × 5678", ok: true, match: false, want: "7006652", got: "7006552", served: "qwen3-8b", ms: 900, ttft_ms: 500, input: 30, output: 5, tries: 1 }, + { kind: "math", ask: "987 × 654", ok: true, match: true, want: "645498", got: "645498", ms: 700, ttft_ms: 400, input: 30, output: 5, tries: 1 }, + { kind: "tool", ask: "get_weather", ok: false, match: false, want: "get_weather", status: 403, error: "this key has no access to tools", ms: 80, tries: 1 }, + { kind: "tool", ask: "get_time", ok: true, match: true, want: "get_time", got: 'get_time({"city":"Tokyo"})', ms: 800, ttft_ms: 600, input: 90, output: 12, tries: 1 }, + ], +}; +let checks = 0; const FAST = { id: "glm-fast", calls: 28, input: 1, output: 3780, cache_read: 0, cache_write: 0, cost: 0.3, timed: 27, ttft_ms: 27 * 600, decode_ms: 27 * 1800, decode_out: 27 * 135 }; let speeds = SPEEDS; @@ -37,7 +59,7 @@ function ledger(period) { timed: 27, ttft_ms: 27 * 600, decode_ms: 27 * 1800, decode_out: 27 * 135, by: { model: [FAST] }, bucket: "hour", series: [], agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], - speeds, speed_min: 100, + speeds, provider_speeds: speeds.length ? PROV : [], speed_min: 100, }; } @@ -58,6 +80,11 @@ function server(lang) { if (url.pathname === "/api/state") return json(STATE(lang)); 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/relay-check") { + checks++; + assert.deepEqual(route.request().postDataJSON(), { provider: "relay9", model: "glm-fast" }); + return json(CHECK); + } 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: [], dirs: [] }); @@ -72,11 +99,11 @@ function server(lang) { const L = { - en: { title: "Model speed", heads: ["Model", "Speed", "First token", "Requests"], fast: "75 tok/s", slow: "10 tok/s", wait: "600 ms" }, - zh: { title: "模型速度", heads: ["模型", "速度", "首字耗时", "请求"], fast: "75 token/秒", slow: "10 token/秒", wait: "600 毫秒" }, - "zh-TW": { title: "模型速度", heads: ["模型", "速度", "首字耗時", "請求"], fast: "75 token/秒", slow: "10 token/秒", wait: "600 毫秒" }, - ja: { title: "モデルの速度", heads: ["モデル", "速度", "最初のトークン", "リクエスト"], fast: "75", slow: "10", wait: "600" }, - de: { title: "Modelltempo", heads: ["Modell", "Tempo", "Erstes Token", "Anfragen"], fast: "75", slow: "10", wait: "600" }, + en: { title: "Model speed", heads: ["Model", "Speed", "First token", "Requests"], fast: "75 tok/s", slow: "10 tok/s", wait: "600 ms", by: ["Models", "Providers"], more: ["Failed", "Other model"], check: "Check…", run: "Check", asked: "Expected answer", tokens: "4,200", sum: ["Answers right: 2 of 3", "Right tool calls: 1 of 2"], checked: ["Answers", "Tool calls"] }, + zh: { title: "模型速度", heads: ["模型", "速度", "首字耗时", "请求"], fast: "75 token/秒", slow: "10 token/秒", wait: "600 毫秒", by: ["模型", "供应商"], more: ["失败", "其他模型"], check: "检查…", run: "检查", asked: "符合预期", tokens: "4,200", sum: ["答对 2 / 3", "工具调用正确 1 / 2"], checked: ["答对", "工具调用"] }, + "zh-TW": { title: "模型速度", heads: ["模型", "速度", "首字耗時", "請求"], fast: "75 token/秒", slow: "10 token/秒", wait: "600 毫秒", by: ["模型", "供應商"], more: ["失敗", "其他模型"], check: "檢查…", run: "檢查", asked: "符合預期", tokens: "4,200", sum: ["答對 2 / 3", "工具呼叫正確 1 / 2"], checked: ["答對", "工具呼叫"] }, + ja: { title: "モデルの速度", heads: ["モデル", "速度", "最初のトークン", "リクエスト"], fast: "75", slow: "10", wait: "600", by: ["モデル", "プロバイダ"], more: ["失敗", "別のモデル"], check: "チェック…", run: "チェック", asked: "想定どおり", tokens: "4,200", sum: ["正解 2 / 3", "正しいツール呼び出し 1 / 2"], checked: ["正解", "ツール呼び出し"] }, + de: { title: "Modelltempo", heads: ["Modell", "Tempo", "Erstes Token", "Anfragen"], fast: "75", slow: "10", wait: "600", by: ["Modelle", "Anbieter"], more: ["Fehlgeschlagen", "Anderes Modell"], check: "Prüfen…", run: "Prüfen", asked: "Wie erwartet", tokens: "4.200", sum: ["Richtige Antworten: 2 von 3", "Richtige Werkzeugaufrufe: 1 von 2"], checked: ["Richtig", "Tool-Aufrufe"] }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -142,6 +169,95 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const cut = await card.locator("tbody td.nm").first().evaluate((e) => getComputedStyle(e).textOverflow); assert.equal(cut, "ellipsis"); + // by provider: each model on each provider, with its tries, the + // share that failed and the replies that named another model + const by = card.locator(".led-spd-by .opt"); + assert.deepEqual((await by.allTextContents()).map((x) => x.trim()), w.by); + await by.nth(1).click(); + await card.locator(".led-spd.by-prov").waitFor(); + // the sort is kept across the switch: by name, then the fastest first + assert.deepEqual(await card.locator("tbody .led-spd-prov").allTextContents(), ["Relay Nine", "Z.ai Coding Plan", "Relay Nine"]); + await head(1).click(); + const pheads = (await card.locator("thead th").allTextContents()).map((x) => x.replace(/[↑↓]/g, "").trim()); + assert.deepEqual(pheads, [...w.heads, ...w.more, ""]); + assert.deepEqual(await card.locator("tbody .led-spd-prov").allTextContents(), ["Z.ai Coding Plan", "Relay Nine", "Relay Nine"]); + const relay = await card.locator("tbody tr").nth(1).locator("td").allTextContents(); + assert.equal(relay[3].trim(), "4", "tries"); + assert.equal(relay[4].trim(), "25%", "1 of 4 failed"); + assert.equal(relay[5].trim(), "1", "one reply named another model"); + // the failed share sorts, most first + await head(4).click(); + assert.equal((await card.locator("tbody tr").first().locator(".led-spd-prov").textContent()), "Relay Nine"); + await card.locator("thead th").nth(1).locator("button").click(); + const fitsProv = await card.evaluate((e) => ({ card: e.scrollWidth <= e.clientWidth + 1, doc: document.documentElement.scrollWidth <= window.innerWidth + 1 })); + assert.deepEqual(fitsProv, { card: true, doc: true }); + if (lang === "en" && process.env.SHOTS) { + // the page scrolls inside the window: a tall one shows the card + await p.setViewportSize({ width: 400, height: 3000 }); + await p.waitForTimeout(300); + await card.screenshot({ path: path.join(process.env.SHOTS, engine + "-providers-400.png") }); + await p.setViewportSize({ width: 1000, height: 3000 }); + await p.waitForTimeout(300); + await card.screenshot({ path: path.join(process.env.SHOTS, engine + "-providers-1000.png") }); + await p.setViewportSize({ width: 400, height: 800 }); + } + + // Check… opens a dialog and sends nothing; only its Check does + checks = 0; + const go = card.locator("tbody tr").nth(1).locator(".led-spd-check"); + assert.equal((await go.textContent()).trim(), w.check); + await go.click(); + const dlg = p.locator("#modal .relay-check"); + await dlg.waitFor(); + await p.waitForTimeout(150); + assert.equal(checks, 0, "opening the dialog sends no call"); + await dlg.locator(".bar button.primary").click(); + await dlg.locator(".relay-part").nth(4).waitFor(); + assert.equal(checks, 1); + const parts = dlg.locator(".relay-part"); + // the right answers counted apart from the right tool calls + assert.deepEqual((await dlg.locator(".relay-sum span").allTextContents()).map((x) => x.trim()), w.sum); + assert.equal((await parts.nth(0).locator(".relay-said").textContent()).trim(), w.asked); + assert.deepEqual(await dlg.locator(".relay-mark").evaluateAll((ms) => ms.map((m) => m.className.replace("relay-mark ", ""))), ["ok", "off", "ok", "err", "ok"]); + assert((await parts.nth(1).locator(".relay-name").textContent()).includes("1234 × 5678")); + assert((await parts.nth(4).locator(".relay-name").textContent()).includes("get_time")); + assert.equal(await parts.nth(2).locator(".relay-line").count(), 0, "an answer as asked says nothing more"); + const count = await parts.nth(0).locator(".relay-line").allTextContents(); + assert(count.some((x) => x.includes("118") && x.includes(w.tokens)), "the prompt's count: " + count); + const math = (await parts.nth(1).locator(".relay-line").allTextContents()).join("\n"); + assert(math.includes("7006552") && math.includes("qwen3-8b"), math); + assert((await parts.nth(3).locator(".relay-line.err").textContent()).includes("403 · this key has no access to tools")); + const fitsDlg = await dlg.evaluate((e) => ({ doc: document.documentElement.scrollWidth <= window.innerWidth + 1, dlg: e.parentElement.scrollWidth <= e.parentElement.clientWidth + 1 })); + assert.deepEqual(fitsDlg, { doc: true, dlg: true }, "the dialog fits a phone's width"); + if (lang === "en" && process.env.SHOTS) await p.locator("#modal > *").first().screenshot({ path: path.join(process.env.SHOTS, engine + "-check-400.png") }); + await p.keyboard.press("Escape"); + await dlg.waitFor({ state: "hidden" }); + // the check is kept beside the other providers: Answers and Tool + // calls, for the one checked, and nothing for the others + const checkedHeads = async () => (await card.locator("thead th").allTextContents()).map((x) => x.replace(/[↑↓]/g, "").trim()); + assert.deepEqual(await checkedHeads(), [...w.heads, ...w.more, ...w.checked, ""]); + const cells = (i) => card.locator("tbody tr").nth(i).locator("td").allTextContents(); + assert.deepEqual((await cells(1)).slice(6, 8).map((x) => x.trim()), ["2/3", "1/2"]); + assert.deepEqual((await cells(0)).slice(6, 8).map((x) => x.trim()), ["—", "—"]); + // the checked one first by Answers, the ones not checked last + await head(6).click(); + assert.equal(await card.locator("tbody tr").first().locator(".led-spd-prov").textContent(), "Relay Nine"); + assert.equal(await card.locator("tbody tr").first().locator("td").nth(6).getAttribute("class"), "n off"); + if (lang === "en" && process.env.SHOTS) { + await p.setViewportSize({ width: 1000, height: 3000 }); + await p.waitForTimeout(300); + await card.screenshot({ path: path.join(process.env.SHOTS, engine + "-providers-checked-1000.png") }); + await p.setViewportSize({ width: 400, height: 800 }); + } + // the choice is kept: Providers again after a reload + await p.reload(); + await p.locator('[data-view="usage"]').first().click(); + await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + await card.locator(".led-spd.by-prov").waitFor(); + assert.deepEqual(await checkedHeads(), [...w.heads, ...w.more, ...w.checked, ""], "the check is kept after a reload"); + await card.locator(".led-spd-by .opt").first().click(); + await card.locator(".led-spd:not(.by-prov)").waitFor(); + // nothing counted: the card is gone speeds = []; await p.reload();