routing: Accounts and keys count the whole day, not the last kept requests (#3351)

1234fsdc: the live Routing page's Accounts and keys said tried and
answered over the requests the page still keeps in memory, so on a busy
day the counts were a sliver of what Usage showed for the same accounts
and went down as old requests fell off. /api/trace/history (the read the
live page already makes every 15s) now carries `tallies`: per account or
key, today's tries, answers, fails by reason, models answered, the last
answer and the latest rest, read from routing/<today>.jsonl. The page
seeds the list with them and still takes the latest rest and readings
from the requests it keeps; a day looked at, or a purpose picked, counts
its own list as before. The note says "over today's requests" then.
Ported from ggbdpq's patch on the issue.

Changed from the patch:
- The patch parsed the whole day's file under history.mu on every look.
  A busy day's file is hundreds of MB (#3383) and saveRoute takes the
  same lock, so every 15s poll would stall the routes being written.
  DayTallies now folds in only the whole lines added since the last
  look (it keeps the offset, as History does); a line still being
  written waits for its end. It starts again when the day changes, the
  file shrank or was compressed, or the folder moved (another HOME).
- What it returns is a copy: the patch handed out the live tallies,
  and the JSON writer read a Fails map the next fold wrote.
- The latest name and rest go by the try's time, so no sort per look.
- docs/subsystems/gui-shell.md says how the counts are made and that a
  request done since the last look is counted at the next one.

Run on mote at this change on 394a92f0f. The pushed parent 5787d758a
adds usage, tray, redact and search changes and none of this change's
files:
- gofmt -l clean; go vet ./internal/gateway ./internal/gui for darwin,
  windows, and linux -tags nogui.
- go test ./internal/gateway -race -run 'History|DayTallies': ok.
- go test ./internal/gui -count=1 -timeout 45m: red in 11 tests, all
  red on main too. Ten are real-window AppKit tests killed at their
  deadline on mote (the same ten at 03f3e1528, #4125).
  TestSettingsSaveKeepsWhatItDoesNotSend is SearchAll on main (#4514).
  TestLiveHistoryTalliesTheWholeDay passes. At the pushed head, -run
  'Budget|Tallies': ok.
- GUI on WSL (wsl-run, Ubuntu 24.04, Playwright 1.62.0, Chromium and
  WebKit, every language each file runs):
  - The 229 test files that reach the Routing page, plus i18n-keys, at
    this change on 576b5dcbc (--test-concurrency=4): 3498 tests, 101 red
    in 31 files.
  - Those 31 files on main 03f3e1528: 94 red. With this change: 99 red.
    The same tests fail; which language or engine goes red changes from
    run to run (#4121, #4471).
  - Four of them run alone: 27 red on main, 21 with the change.
  - At 394a92f0f, routing-day-tallies, i18n-keys, account-weight,
    key-weight and routing-weight-chip passed. routing-columns' WebKit
    rows were red, as on main (#4520). Its fixture has no tallies.

Broken by hand:
- DayTallies re-reading the whole file each look (reset always true):
  TestDayTalliesFoldOnlyWhatWasAdded red, "a look after one route read
  101 lines, want 1".
- handing out the live tallies, no copy: red, "a tally handed out
  changed after: ... fails map[rate:3]".

Not tried: a real day's file of hundreds of MB. The first look after a
start still reads the whole day once under history.mu, as History's own
first read does. A real app beside a running gateway. Past days
are unchanged: still counted over their latest historyMax routes.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
yetone
2026-10-31 11:29:38 +08:00
co-authored by ggbdpq
parent 5787d758a7
commit bdc1617bed
9 changed files with 565 additions and 5 deletions
+22
View File
@@ -223,6 +223,28 @@ come only with Select, and Done lets the pick go. Relocate project and
Delete all sessions are in a folder's ⋯ menu, shown on hover (always on a
touch screen) and on a right-click. See `sessions-folder-list.test.cjs`.
### Routing day tallies
Live, an account's row under Accounts and keys counts its tried, answered
and failed over the day's whole history, not over the last few requests
the gateway keeps (#3351): the two said different things by orders of
magnitude, and the day tabs above the section count the day. The counts
come with the history read the page already polls (`/api/gateway/history`
with no day, its `tallies`), counted by `DayTallies` in
[`internal/gateway/history.go`](../../internal/gateway/history.go) from
the same files the Usage page reads, keyed as the page groups accounts
(provider and user, a key or provider by its id). Each look folds in only
the whole lines added to today's files since the last one: a busy day's
file is hundreds of MB (#3383), and the page asks every 15 seconds. A
request done since the last look is counted at the next one. The note
under the heading says the counts are today's. What the history cannot
say — the readings the latest request was weighed by, the rests, one
model resting alone, the accounts in the kept requests — the page still
takes from the trace over these tallies; a day picked, or a purpose
picked, counts its own list as before, and the note then points at that
list. An older answer without tallies counts the kept requests as it
did. See `routing-day-tallies.test.cjs`.
### Stored agent sessions in WSL
The Sessions page uses `sessions.ListAgent`; Usage → Sessions uses
+213
View File
@@ -13,8 +13,10 @@ import (
"compress/gzip"
"encoding/json"
"io"
"maps"
"os"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
@@ -58,6 +60,12 @@ var history struct {
mu sync.Mutex
pruned time.Time
counts map[string]counted // a day's file → its requests, as of its size
// the live page's tallies of today (DayTallies): each file's bytes
// folded in so far, up to the end of its last whole line, so a look
// reads only what was added since (#3383: a busy day is 350 MB)
talliedDay string
talliedOff map[string]int64
tallies map[string]*Tally
}
type counted struct {
@@ -469,6 +477,211 @@ func readDayFrom(path string, off int64, f func([]byte) bool) {
}
}
// Tally is one account or key's day, as the day's history tells it: how
// often it was tried, answered and failed, its latest answer, the models
// that answered, and how its latest try left it. The Routing page's
// accounts and keys say these of a whole day (#3351), read from the
// same files the Usage page reads, where counting the trace would say
// only of the last few requests the gateway keeps. What the history
// cannot say — the readings its latest request was weighed by, one model
// resting alone — the page keeps from the trace.
type Tally struct {
ID string `json:"id"` // what rests after a failure, as Weighed has it
Provider string `json:"provider"`
Name string `json:"name,omitempty"`
Icon string `json:"icon,omitempty"`
Preset string `json:"preset,omitempty"`
Who string `json:"who,omitempty"`
Kind string `json:"kind"`
Agent string `json:"agent,omitempty"`
Plan string `json:"plan,omitempty"`
Model string `json:"model,omitempty"`
Routing string `json:"routing,omitempty"`
Rank int `json:"rank,omitempty"`
Tried int `json:"tried"`
OK int `json:"ok"`
Fails map[string]int `json:"fails,omitempty"`
Last int64 `json:"last,omitempty"` // ms, of its latest answer
Models []string `json:"models,omitempty"`
Rest *Rest `json:"rest,omitempty"` // how its latest try left it
RestAt int64 `json:"restAt,omitempty"` // ms, of when it did
seen int64 // ms, of the latest request that weighed it
}
// tallied is the part of a kept route the tallies read: json.Unmarshal
// leaves the rest of the line alone.
type tallied struct {
Time time.Time `json:"time"`
Order []Weighed `json:"order"`
Tries []Try `json:"tries"`
}
// tallyKey is what the page groups an account by: its provider and its
// user, however it is weighed into a request (its sign-in may move); a
// key or a provider by its own id.
func tallyKey(w Weighed) string {
if w.Kind == "account" && w.Who != "" {
b, _ := json.Marshal([]string{w.Provider, strings.ToLower(strings.TrimSpace(w.Who))})
return string(b)
}
return w.ID
}
// DayTallies counts today's history per account or key, the Usage page's
// own source. The counts ride on the history read the live page already
// asks for, every 15s while it is open, so each look folds in only the
// lines added to today's files since the last: a busy day's file is
// hundreds of MB (#3383), read whole once at most. What it returns is a
// copy, written out after the lock is let go.
func DayTallies() map[string]Tally {
day := historyClock().Local().Format(dayForm)
history.mu.Lock()
defer history.mu.Unlock()
var files []dayFile
for _, d := range historyFiles(HistoryDir()) {
if d.day == day {
files = append(files, d)
}
}
reset := history.talliedDay != day || history.tallies == nil
have := map[string]bool{}
for _, d := range files {
have[d.path] = true
// a file that shrank, or a .gz of today (a late route's day over
// once), is counted again from the start: everything of the day
if off, ok := history.talliedOff[d.path]; ok && (d.size < off || strings.HasSuffix(d.path, ".gz") && d.size != off) {
reset = true
}
}
for path := range history.talliedOff {
if !have[path] { // a file gone, or the folder moved (a test's HOME)
reset = true
}
}
if reset {
history.talliedDay, history.talliedOff, history.tallies = day, map[string]int64{}, map[string]*Tally{}
}
for _, d := range files {
off := history.talliedOff[d.path]
if strings.HasSuffix(d.path, ".gz") {
if off == d.size {
continue
}
readDay(d.path, func(line []byte) bool { foldTally(history.tallies, line); return true })
history.talliedOff[d.path] = d.size
continue
}
if off < d.size {
history.talliedOff[d.path] = foldTallies(d.path, off, history.tallies)
}
}
out := make(map[string]Tally, len(history.tallies))
for k, a := range history.tallies {
c := *a
c.Fails, c.Models = maps.Clone(a.Fails), slices.Clone(a.Models)
out[k] = c
}
return out
}
// foldTallies folds path's whole lines from off into tallies, and says
// where the first line not folded starts: a line still being written
// (another magpie's, say) waits for the next look.
func foldTallies(path string, off int64, tallies map[string]*Tally) int64 {
f, err := os.Open(path)
if err != nil {
return off
}
defer f.Close()
if _, err := f.Seek(off, io.SeekStart); err != nil {
return off
}
br := bufio.NewReaderSize(f, 256<<10)
for {
line, err := br.ReadBytes('\n')
if err != nil { // no newline yet: not a whole line
return off
}
off += int64(len(line))
if line = bytes.TrimSpace(line); len(line) > 0 {
foldTally(tallies, line)
}
}
}
// tallyLines counts the lines foldTally has read, for the tests.
var tallyLines atomic.Int64
// foldTally counts one kept route into tallies. A route is written as it
// is done, so a day's lines are nearly, not quite, in time order: which
// rest and which name are the latest is told by their times.
func foldTally(tallies map[string]*Tally, line []byte) {
tallyLines.Add(1)
var r tallied
if json.Unmarshal(line, &r) != nil {
return
}
ms := r.Time.UnixMilli()
by := map[string]*Tally{} // a try's seat → its tally
for _, w := range r.Order {
k := tallyKey(w)
a := tallies[k]
if a == nil {
a = &Tally{}
tallies[k] = a
}
if a.seen == 0 || ms >= a.seen { // how the latest request weighed it
a.ID, a.Provider, a.Name, a.Icon, a.Preset = w.ID, w.Provider, w.Name, w.Icon, w.Preset
a.Who, a.Kind, a.Agent, a.Plan, a.Model, a.Routing, a.Rank = w.Who, w.Kind, w.Agent, w.Plan, w.Model, w.Routing, w.Rank
a.seen = ms
}
// a rest on one model alone says nothing of the account (#1960),
// which answers its others; the page keeps that one from the trace
if w.Rest != nil && w.Rest.Model == "" && ms >= a.RestAt {
rest := *w.Rest
a.Rest, a.RestAt = &rest, ms
}
by[w.ID] = a
}
for _, tr := range r.Tries {
a := by[tr.ID]
if a == nil || !tr.Done || tr.Fail == "canceled" { // the agent's doing, not its
continue
}
end := tr.Start.UnixMilli() + tr.Millis
a.Tried++
if tr.Status < 400 && tr.Fail == "" {
a.OK++
a.Last = max(a.Last, end)
m := tr.Model
if m == "" {
for _, w := range r.Order {
if w.ID == tr.ID {
m = w.Model
break
}
}
}
if m != "" && !slices.Contains(a.Models, m) {
a.Models = append(a.Models, m)
}
} else {
f := tr.Fail
if f == "" {
f = "other"
}
if a.Fails == nil {
a.Fails = map[string]int{}
}
a.Fails[f]++
}
if tr.Rest != nil && tr.Rest.Model == "" && end >= a.RestAt {
rest := *tr.Rest
a.Rest, a.RestAt = &rest, end
}
}
}
// HistoryRoute searches the request's day and its neighbours (the browser and
// gateway may use different time zones), without holding up history writes.
func HistoryRoute(id int64, day time.Time) (Route, bool) {
+93
View File
@@ -0,0 +1,93 @@
package gateway
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
)
// The live Routing page asks for today's tallies every 15s (#3351), and a
// busy day's file is hundreds of MB (#3383): each look folds in only the
// lines added since the last, a line still being written waits for its
// end, and a look at another day's folder starts again.
func TestDayTalliesFoldOnlyWhatWasAdded(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
now := historyNoon(t)
route := func(i int, who string, status int) Route {
w := Weighed{ID: "p/" + who, Provider: "p", Name: "P", Kind: "account", Who: who, Model: "m"}
tr := Try{ID: w.ID, Start: now.Add(time.Duration(i) * time.Second), Done: true, Millis: 100, Status: status}
if status >= 400 {
tr.Fail = "rate"
}
return Route{ID: int64(i + 1), Time: tr.Start, Done: true, Model: "m", Provider: "p", Order: []Weighed{w}, Tries: []Try{tr}}
}
for i := range 100 {
status := 200
if i == 0 || i == 45 {
status = 429
}
saveRoute(route(i, "A", status))
}
lines := tallyLines.Load()
got := DayTallies()
busy := got[`["p","a"]`]
if busy.Tried != 100 || busy.OK != 98 || busy.Fails["rate"] != 2 {
t.Fatalf("the day: tried %d, answered %d, fails %v", busy.Tried, busy.OK, busy.Fails)
}
if n := tallyLines.Load() - lines; n != 100 {
t.Fatalf("the first look read %d lines, want the day's 100", n)
}
// one route more: one line read, not the day again
saveRoute(route(100, "B", 200))
lines = tallyLines.Load()
got = DayTallies()
if n := tallyLines.Load() - lines; n != 1 {
t.Errorf("a look after one route read %d lines, want 1", n)
}
if got[`["p","a"]`].Tried != 100 || got[`["p","b"]`].Tried != 1 {
t.Errorf("after one route: A tried %d, B tried %d", got[`["p","a"]`].Tried, got[`["p","b"]`].Tried)
}
// nothing added: nothing read
lines = tallyLines.Load()
DayTallies()
if n := tallyLines.Load() - lines; n != 0 {
t.Errorf("a look with nothing added read %d lines", n)
}
// what a look hands out is a copy: counting on doesn't change it
held := DayTallies()[`["p","a"]`]
saveRoute(route(101, "A", 429))
DayTallies()
if held.Tried != 100 || held.Fails["rate"] != 2 {
t.Errorf("a tally handed out changed after: tried %d, fails %v", held.Tried, held.Fails)
}
// half a line, as another magpie writing it leaves it: not counted
// until its end is there, and then counted once
b, _ := json.Marshal(route(102, "B", 200))
path := filepath.Join(HistoryDir(), now.Format(dayForm)+".jsonl")
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
}
f.Write(b[:len(b)/2])
if got := DayTallies()[`["p","b"]`].Tried; got != 1 {
t.Errorf("with half a line: B tried %d, want 1", got)
}
f.Write(append(b[len(b)/2:], '\n'))
f.Close()
if got := DayTallies()[`["p","b"]`].Tried; got != 2 {
t.Errorf("the line finished: B tried %d, want 2", got)
}
// another folder (another HOME): its own day, nothing of the last
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
saveRoute(route(0, "C", 200))
got = DayTallies()
if _, ok := got[`["p","a"]`]; ok || got[`["p","c"]`].Tried != 1 {
t.Errorf("another folder's day: %v", got)
}
}
+21 -4
View File
@@ -1439,6 +1439,7 @@ function routingPage(part) {
const playing = new Map(); // the routes being played → the gen playing each
let rp = null; // a replay playing: see replay
let day = "", days = [], past = [], pastCut = false; // a kept day looked at ("" for live), the days kept, its routes
let tallies = null; // today's counts per account or key, from the history read (#3351); live only
const src = () => rp ? rp.routes : routes; // the routes the stage plays from
const LINGER = 12e3; // how long an agent's last request stays on the stage
let gen = 0, trips = [], waiters = [];
@@ -3266,6 +3267,7 @@ function routingPage(part) {
days = res.days || [];
noteAccounts(res.routes);
if (d && d === day) { past = (res.routes || []).map(whole); pastCut = !!res.cut; }
else if (!d) { tallies = res.tallies || null; actsFold = { rs: [], by: null }; } // the fold memo holds the pre-tallies list: drop it, the next fold seeds from the day (#3351)
} catch {}
renderHist(); // shown once there are days, though none are live
}
@@ -3898,6 +3900,17 @@ function routingPage(part) {
// Group accounts by their identity, resolving each try in its own route.
const keyOf = (w) => w.kind === "account" && w.who
? JSON.stringify([w.provider, w.who.trim().toLowerCase()]) : w.id;
// Live: the day's counts come with the history read the page already
// asks for (#3351) — the Usage page's own reading of the day, not the
// last few requests the gateway keeps. What that read cannot say (the
// readings its latest request was weighed by, one model resting alone)
// the kept requests below still do. A day looked at, or a purpose
// picked, counts its own list as before.
const seed = !day && !purpose.length && tallies && Object.keys(tallies).length ? tallies : null;
if (seed) for (const [k, x] of Object.entries(seed)) {
by.set(k, { w: x, tried: x.tried, ok: x.ok, fails: { ...x.fails }, last: x.last || 0,
rest: x.rest || null, restAt: x.restAt || 0, seen: 0, pos: 0, at: 0, models: new Set(x.models || []), mrests: new Map() });
}
for (const r of [...rs].reverse()) { // oldest first, so the latest wins
const candidates = new Map();
r.order.forEach((w, i) => {
@@ -3917,10 +3930,14 @@ function routingPage(part) {
for (const tr of r.tries) {
const a = candidates.get(tr.id);
if (!a || !tr.done || tr.fail === "canceled") continue; // the agent's doing, not its
a.tried++;
const end = at(tr.start) + (tr.ms || 0);
if (tryOk(tr)) { a.ok++; a.last = Math.max(a.last, end); const m = tr.model || r.order.find((x) => x.id === tr.id)?.model; if (m) a.models.add(m); }
else a.fails[tr.fail || "other"] = (a.fails[tr.fail || "other"] || 0) + 1;
if (seed) { // counted from the day already; when it last answered is news all the same
if (tryOk(tr)) a.last = Math.max(a.last, end);
} else {
a.tried++;
if (tryOk(tr)) { a.ok++; a.last = Math.max(a.last, end); const m = tr.model || r.order.find((x) => x.id === tr.id)?.model; if (m) a.models.add(m); }
else a.fails[tr.fail || "other"] = (a.fails[tr.fail || "other"] || 0) + 1;
}
const rm = tr.rest ? restModel(tr.rest, tr.model || r.order.find((x) => x.id === tr.id)?.model) : "";
if (rm) modelRest(a, rm, tr.rest, end);
else if (tr.rest && end >= a.restAt) { a.rest = tr.rest; a.restAt = end; }
@@ -3940,7 +3957,7 @@ function routingPage(part) {
return rest === a.rest && mrests === a.mrests ? a : { ...a, rest, mrests };
}).sort((x, y) => (x.w.name || "").localeCompare(y.w.name || "") || x.w.provider.localeCompare(y.w.provider) || rankOf(x.w) - rankOf(y.w) || x.pos - y.pos);
setText(actLabel, t("Accounts and keys"));
setText(actNote, t("over those requests"));
setText(actNote, t(!day && tallies && Object.keys(tallies).length ? "over today's requests" : "over those requests"));
// live, with a subscription account listed: a kept day's were weighed
// by readings long gone, and a key has no allowance to read
actRead.hidden = !!day || !list.some((a) => a.w.kind === "account");
@@ -517,6 +517,7 @@ magpie.strings({
"the last {n} the gateway keeps": "网关保留的最近 {n} 个",
"Accounts and keys": "账号与密钥",
"over those requests": "统计自这些请求",
"over today's requests": "统计自今天的请求",
"Nothing on {day}": "{day}没有请求",
"No requests since magpie started": "magpie 启动以来还没有请求",
"Each request an agent sends through magpie shows up here: who answered it, why, and each try.": "agent 经 magpie 发出的每个请求都列在这里:由谁应答、为何选它,以及每次尝试。",
@@ -1123,6 +1124,7 @@ magpie.strings({
"the last {n} the gateway keeps": "閘道保留的最近 {n} 個",
"Accounts and keys": "帳號與金鑰",
"over those requests": "統計自這些請求",
"over today's requests": "統計自今天的請求",
"Nothing on {day}": "{day}沒有請求",
"No requests since magpie started": "magpie 啟動以來還沒有請求",
"Each request an agent sends through magpie shows up here: who answered it, why, and each try.": "agent 經 magpie 發出的每個請求都列在這裡:由誰應答、為何選它,以及每次嘗試。",
@@ -1727,6 +1729,7 @@ magpie.strings({
"the last {n} the gateway keeps": "ゲートウェイが保持する直近 {n} 件",
"Accounts and keys": "アカウントとキー",
"over those requests": "これらのリクエストの集計",
"over today's requests": "今日のリクエストの集計",
"Nothing on {day}": "{day}はリクエストなし",
"No requests since magpie started": "magpie の起動以降リクエストはありません",
"Each request an agent sends through magpie shows up here: who answered it, why, and each try.": "エージェントが magpie 経由で送る各リクエストがここに表示されます:誰が応答したか、その理由、各試行。",
@@ -2333,6 +2336,7 @@ magpie.strings({
"the last {n} the gateway keeps": "die letzten {n}, die der Zugangspunkt aufbewahrt",
"Accounts and keys": "Konten und Schlüssel",
"over those requests": "über diese Anfragen",
"over today's requests": "über die heutigen Anfragen",
"Nothing on {day}": "Nichts am {day}",
"No requests since magpie started": "Keine Anfragen seit dem Start von magpie",
"Each request an agent sends through magpie shows up here: who answered it, why, and each try.": "Jede Anfrage, die ein Agent über magpie sendet, erscheint hier: wer sie beantwortet hat, warum und jeder Versuch.",
+8
View File
@@ -263,6 +263,14 @@ asked for and names the pill, with the bar held where it was; three days need
no such pill; a window narrowed then widened fits again. Chromium and WebKit,
in English, Chinese, Japanese and German.
`routing-day-tallies.test.cjs` checks #3351: live, an account's row under
Accounts and keys counts its day from the tallies the history read brings
(the Usage page's own files), not the kept requests — an account in no
request the gateway keeps still shows its day and its failures, the
kept account says its day's twelve over the kept ten, and the note says
the counts are today's. Chromium and WebKit, in English, Chinese,
Traditional Chinese, Japanese and German.
`dates-gui-lang.test.cjs` checks that dates and times read in the GUI's
language, not the system's (#1843): English on a zh-CN browser, English on
en-GB (the system's own English kept), and Chinese, Traditional Chinese,
@@ -0,0 +1,95 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// #3351: the Routing page's Accounts and keys counted each account's tried
// and answered over the last few requests the gateway keeps in memory,
// while the day tabs right above counted the day's whole history — the two
// could disagree by orders of magnitude. Live now, the day's counts come
// with the history read the page already polls (its `tallies`), counted
// from the same files the Usage page reads: an account tried all day but
// not in the kept window still shows its day, and the note says the counts
// are today's. What the tallies cannot say the kept requests still supply.
// In every language, in both engines.
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 iso = (ms) => new Date(ms).toISOString();
// the gateway keeps ten requests, all on the quiet account; the day's
// history says the busy one answered 88 of 90 tries, and the quiet one 12
const quiet = { id: "prov/quiet", provider: "prov", name: "Prov", who: "Quiet@Example.com", kind: "account", agent: "prov", model: "m" };
const routes = Array.from({ length: 10 }, (_, i) => ({
id: 100 + i, seq: 100 + i, time: iso(now - (60 - i) * 1000), agent: "prov", model: "m", provider: "prov", done: true, status: 200, ms: 300,
order: [quiet], tries: [{ id: "prov/quiet", model: "m", start: iso(now - (60 - i) * 1000), done: true, ms: 250, status: 200 }],
}));
const tallies = {
'["prov","busy@example.com"]': { id: "prov/busy", provider: "prov", name: "Prov", who: "busy@example.com", kind: "account", agent: "prov", model: "m", tried: 90, ok: 88, fails: { rate: 2 } },
'["prov","quiet@example.com"]': { id: "prov/quiet", provider: "prov", name: "Prov", who: "quiet@example.com", kind: "account", agent: "prov", model: "m", tried: 12, ok: 12 },
};
const words = {
en: ["tried 90", "answered 88", "2 rate limited", "over today's requests"],
zh: ["尝试 90", "应答 88", "2 限流", "统计自今天的请求"],
"zh-TW": ["嘗試 90", "應答 88", "2 限流", "統計自今天的請求"],
ja: ["試行 90", "応答 88", "2 レート制限", "今日のリクエストの集計"],
de: ["90 versucht", "88 beantwortet", "2 Rate-Limit", "über die heutigen Anfragen"],
};
function serve(lang) {
const state = { agents: [{ id: "prov", name: "Prov", path: "/test/prov", fields: [] }], profiles: [], settings: { lang, theme: "light", quotaLeft: false } };
return async (r) => {
const url = new URL(r.request().url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: new Date().toISOString(), seq: 110, totals: { requests: 102, rerouted: 0, errors: 2 }, routes });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [{ day: new Date(now).toISOString().slice(0, 10), requests: 102 }], routes: [], tallies });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage/quotas/history") return json([]);
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
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)];
await r.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: Accounts and keys says an account's day, not the kept window's`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of Object.keys(words)) {
await t.test(lang, async () => {
const ctx = await browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: "reduce" });
try {
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=routing");
// the busy account is in no request the gateway keeps, and is
// on the page all the same, with its day and its failures
const busy = page.locator(".rt-act", { hasText: "busy@example.com" }).first();
await busy.waitFor();
const tally = busy.locator(".tally span");
assert.deepEqual(await tally.allTextContents(), words[lang].slice(0, 3));
// the quiet account says its day's twelve, not the kept ten
const said = await page.locator(".rt-act", { hasText: "quiet@example.com" }).first().locator(".tally span").allTextContents();
assert.deepEqual(said.slice(0, 2), [words[lang][0].replace("90", "12"), words[lang][1].replace("88", "12")]);
// the note no longer points at the kept requests alone
assert.equal(await page.locator(".row-head:has(+ .rt-acts) .note").textContent(), words[lang][3]);
assert.deepEqual(errors, []);
} finally {
await ctx.close();
}
});
}
});
}
+8 -1
View File
@@ -399,7 +399,14 @@ func traceRoutes(mux *http.ServeMux) {
day := r.URL.Query().Get("day")
days, routes, cut := gateway.History(day)
rememberTitleHistory(day, routes)
writeJSON(rw, map[string]any{"days": days, "routes": pricedRoutes(routes), "cut": cut})
out := map[string]any{"days": days, "routes": pricedRoutes(routes), "cut": cut}
if day == "" {
// the live page's accounts and keys say tried and answered of
// the day the Usage page reads, not of the last few requests
// the trace still keeps (#3351)
out["tallies"] = gateway.DayTallies()
}
writeJSON(rw, out)
})
// the report saved of a request held too long before routing, for its
// row's Copy Report: the app's log goes only to stderr, which its user
+101
View File
@@ -0,0 +1,101 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
)
// The Routing page's accounts and keys counted each account's tried and
// answered over the last few requests the gateway keeps in memory, while
// the day tabs right above it counted the day's whole history — the two
// pages could disagree by orders of magnitude (#3351). The history read
// the live page already polls now carries the day's tallies, counted from
// the same files the Usage page reads, so its counts cover the day and
// not the last sixty requests.
func TestLiveHistoryTalliesTheWholeDay(t *testing.T) {
sandboxHome(t)
old := served.Swap(nil)
t.Cleanup(func() { served.Store(old) })
if err := os.MkdirAll(gateway.HistoryDir(), 0o700); err != nil {
t.Fatal(err)
}
write := func(rs []gateway.Route) {
t.Helper()
f, err := os.OpenFile(filepath.Join(gateway.HistoryDir(), time.Now().Local().Format("2006-01-02")+".jsonl"),
os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
}
enc := json.NewEncoder(f)
for _, r := range rs {
if enc.Encode(r) != nil {
t.Fatal("a route the gateway would have written")
}
}
f.Close()
}
// ninety requests weighed and tried on one account, then ten on
// another: the trace keeps the last sixty alone, so the live page's
// own counting could only ever name a fraction of the busy one's day
start := time.Now().Local().Add(-2 * time.Hour).Truncate(time.Second)
var rs []gateway.Route
for i := 0; i < 100; i++ {
w := gateway.Weighed{ID: "p/A", Provider: "p", Name: "P", Kind: "account", Who: "A", Model: "m"}
if i >= 90 {
w = gateway.Weighed{ID: "p/B", Provider: "p", Name: "P", Kind: "account", Who: "B", Model: "m"}
}
try := gateway.Try{ID: w.ID, Start: start.Add(time.Duration(i) * time.Minute), Done: true, Millis: 100, Status: 200}
if i == 0 || i == 45 { // two of the busy account's tries were turned away
try.Status, try.Fail = 429, "rate"
}
rs = append(rs, gateway.Route{ID: int64(i + 1), Time: try.Start, Done: true,
Model: "m", Provider: "p", Order: []gateway.Weighed{w}, Tries: []gateway.Try{try}})
}
write(rs)
ask := func() map[string]struct {
Tried int `json:"tried"`
OK int `json:"ok"`
Fails map[string]int `json:"fails"`
} {
mux := http.NewServeMux()
traceRoutes(mux)
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/gateway/history?day=", nil))
var out struct {
Tallies map[string]struct {
Tried int `json:"tried"`
OK int `json:"ok"`
Fails map[string]int `json:"fails"`
} `json:"tallies"`
}
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
t.Fatalf("the history read: %v %s", err, w.Body)
}
return out.Tallies
}
// the page groups an account by its provider and its user, however it
// is weighed into a request; the tallies speak the same keying
got := ask()
busy, quiet := got[`["p","a"]`], got[`["p","b"]`]
if busy.Tried != 90 || busy.OK != 88 || busy.Fails["rate"] != 2 {
t.Errorf("the busy account's day: tried %d, answered %d, fails %v", busy.Tried, busy.OK, busy.Fails)
}
if quiet.Tried != 10 || quiet.OK != 10 {
t.Errorf("the quiet account's day: tried %d, answered %d", quiet.Tried, quiet.OK)
}
// a day that has grown since is counted again, not served stale
try := gateway.Try{ID: "p/B", Start: start.Add(3 * time.Hour), Done: true, Millis: 50, Status: 200}
write([]gateway.Route{{ID: 101, Time: try.Start, Done: true, Model: "m", Provider: "p",
Order: []gateway.Weighed{{ID: "p/B", Provider: "p", Name: "P", Kind: "account", Who: "B", Model: "m"}},
Tries: []gateway.Try{try}}})
if got = ask(); got[`["p","b"]`].Tried != 11 {
t.Errorf("the day grown, the quiet account's day: tried %d", got[`["p","b"]`].Tried)
}
}