gateway: auto affinity keeps a conversation on the cache its last reply wrote, not only one it read (vilicvane on Discord)
Affinity's auto mode kept a conversation on its last answerer across turns only while that reply had read at least cacheWorth (1024) tokens from the vendor's cache. A first turn reads nothing and writes the whole prompt (Anthropic's cache_creation_input_tokens), so the second turn was moved as "no-cache" and the cache just built was thrown away (vilicvane on Discord, 「会话保持 → 自动」: 「新的 cache 都建好了,再切走不可惜吗?」). answered() is now given the usage's CacheWrite beside CacheRead (both already parsed at that call site for every route: Anthropic, Chat's cache_write_tokens / cache_creation_input_tokens, Cursor, Command Code, plugins), and affine counts read + written against cacheWorth. The stick keeps cacheWrite in memory and in affinity.json (`cacheWrite`, omitempty); a file from before has no such field and reads as 0, so an old stick is judged by its read alone, as before. The trace's Affinity carries CacheWrite, and the Routing page's "cache" and "no-cache" explanations say what was read and what was written (en, zh, zh-TW, ja, de). Not covered: a vendor that caches without reporting a write (OpenAI's automatic prefix cache, Gemini) still reports CacheWrite 0 on a first turn, so its second turn may still move. Noted in gateway-routing.md. Docs: docs/subsystems/gateway-routing.md (affinity bullet), docs/reference.md (step 6 of how magpie picks an account). Run: - TestAffinityKeepsACacheJustWritten (new): an Anthropic Messages upstream streaming cache_creation_input_tokens 3000 / read 0; the second turn is kept as "cache", also across a restart (affinity.json reloaded); 600+600 is kept, 300+300 moves as "no-cache". Broken by hand twice and watched red: the old `st.cacheRead < cacheWorth` (written: why no-cache), and stickOf not reading CacheWrite from the file (restarted: no-cache). - routing-affinity-cache-write.test.cjs (new): chromium and webkit, 1100 and 420 wide, en/zh/zh-TW/ja/de, 20/20 pass; red on the old routing.js and i18n.js. i18n-keys.test.cjs and routing-account-identity.test.cjs pass. - gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows for internal/gateway. - go test ./internal/gateway/...: all pass except TestAgentGoneInTheRetryPause/group_replan, which failed in two full runs at load average 150-380 and passes alone (-count=3); its fixed 100ms sleep before cancelling assumes the pause has begun. Filed as #2175; it never reaches the affinity path this changes (a first request). - go test -timeout 40m ./... at load ~300-377: 50 packages ok; agent and gateway hit the 40m package timeout (no test failed before it); gui's TestSetAnswersWhileDevinAndProvidersHang (#1375) and TestMainWindowCorners (#1936) failed, both filed load reds. internal/agent rerun alone: ok (1008s at load ~200). - Not tried against a real Anthropic account.
This commit is contained in:
+4
-2
@@ -1346,8 +1346,10 @@ result for every request: who went first, and why.
|
||||
6. **The conversation's account first.** Once an account has answered a
|
||||
conversation, it is moved to the front for the conversation's next
|
||||
requests, as *Stays* says. In auto mode that is within a turn, and
|
||||
across turns while at least 1,024 tokens of the last request were read
|
||||
from the vendor's cache and it answered in the last 5 minutes. This
|
||||
across turns while the last request read from the vendor's cache and
|
||||
wrote to it at least 1,024 tokens between them, and it answered in the
|
||||
last 5 minutes. A first turn reads nothing and writes the whole prompt,
|
||||
so the second stays to read it. This
|
||||
never brings back an account that is resting, nor one that has used 98%
|
||||
of a window (100% In order). *Stays: Strict* does, and asks no other:
|
||||
the conversation stays on its account, resting, spent or past its cap,
|
||||
|
||||
@@ -97,7 +97,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.
|
||||
- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.
|
||||
- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. The last key left rests too when it is refused so, as the keys before it do. Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is back (`soonestBack`). A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.
|
||||
- Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while at least `cacheWorth` (1024) tokens were read from the cache and the cache isn't cold (`cacheCold`, 5 minutes).
|
||||
- Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while the last reply read from the cache and wrote to it at least `cacheWorth` (1024) tokens between them (the usage's `CacheRead` plus `CacheWrite`, passed to `answered`) and the cache isn't cold (`cacheCold`, 5 minutes). What was written counts: a first turn reads nothing and writes the whole prompt (Anthropic's `cache_creation_input_tokens`), and the second turn stays to read it rather than moving as `no-cache` and building it again elsewhere (vilicvane on Discord). The stick keeps both, on disk too (`affinity.json`'s `cacheWrite`, absent in a file from before and read as 0, so such a stick is judged by its read alone), and the trace's `Affinity.CacheWrite` lets the Routing page say what was read and what was written. A vendor that caches without reporting a write (OpenAI's automatic prefix cache, Gemini) still has a first turn's `CacheWrite` 0, so its second turn may move. `TestAffinityKeepsACacheJustWritten`, `routing-affinity-cache-write.test.cjs`.
|
||||
- Strict (`strict`, #1797, miniers) never moves a conversation to another key or account (`who`). Its stick is kept as session's is, and while it is fresh `affine` keeps only the candidates of that `who` (`strictOnly`): its other models stay, so a group's rules still pick among them, but no other account, key or provider is asked, and a resting or spent one is asked anyway. A failure there reaches the agent and rests the account as a non-lone candidate's would (`strictAlone`), so new conversations go elsewhere. Before planning, `strictKeep` takes the stuck account back from what holds new conversations off it: a usage cap (`pl.capped`, `capHeldOnly`), so the conversation goes on past it. An account held for credits it may not spend is answered 429 naming the account and Strict, and nothing reaches the vendor, rather than moved. An account removed, switched off, barred, or not allowed for the calling key is gone, and the conversation moves as under session. The trace says `strict` even with one candidate. `strict_affinity_test.go`, `stays-strict.test.cjs`.
|
||||
- In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models.
|
||||
- A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits <account> off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again.
|
||||
|
||||
@@ -11,8 +11,11 @@ package gateway
|
||||
// session; within a turn only — while the agent sends tool results back,
|
||||
// until the user speaks again; never; or, by default, worked out from the
|
||||
// conversation itself: within a turn always, and across turns while what
|
||||
// the vendor said it read from its cache the last time is worth keeping
|
||||
// and not yet gone cold.
|
||||
// the vendor said it read from its cache the last time, or wrote to it, is
|
||||
// worth keeping and not yet gone cold. Written counts as read: a first
|
||||
// turn reads nothing and writes the whole prompt, which the next turn
|
||||
// reads if it stays (vilicvane on Discord: the second turn moved, and the
|
||||
// cache just built was thrown away).
|
||||
//
|
||||
// Who answered is kept on disk as well (affinity.json, next to the
|
||||
// providers), so a restart — an update's included — doesn't hand a
|
||||
@@ -37,8 +40,9 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// cacheWorth is how many tokens read from the vendor's cache make a
|
||||
// conversation worth keeping where it is across turns.
|
||||
// cacheWorth is how many tokens read from the vendor's cache, or
|
||||
// written to it, make a conversation worth keeping where it is across
|
||||
// turns.
|
||||
cacheWorth = 1024
|
||||
// cacheCold is how long a vendor keeps a prompt cached without it being
|
||||
// read: five minutes at Anthropic and at OpenAI, the shortest there is.
|
||||
@@ -52,29 +56,31 @@ const (
|
||||
// Affinity is what the trace tells of a request's conversation and whether
|
||||
// it stayed with who answered it last.
|
||||
type Affinity struct {
|
||||
Mode string `json:"mode"` // the provider's or group's: "", session, turn, off
|
||||
Turn int `json:"turn"` // the user's turns in the conversation so far
|
||||
Within bool `json:"within,omitempty"` // the agent sending tool results back: mid-turn
|
||||
Last string `json:"last,omitempty"` // who answered the conversation last
|
||||
LastTurn int `json:"lastTurn,omitempty"`
|
||||
At time.Time `json:"at,omitempty"` // when
|
||||
CacheRead int `json:"cacheRead,omitempty"` // tokens that answer read from the vendor's cache
|
||||
Kept bool `json:"kept,omitempty"` // Last was put first for it
|
||||
Mode string `json:"mode"` // the provider's or group's: "", session, turn, off
|
||||
Turn int `json:"turn"` // the user's turns in the conversation so far
|
||||
Within bool `json:"within,omitempty"` // the agent sending tool results back: mid-turn
|
||||
Last string `json:"last,omitempty"` // who answered the conversation last
|
||||
LastTurn int `json:"lastTurn,omitempty"`
|
||||
At time.Time `json:"at,omitempty"` // when
|
||||
CacheRead int `json:"cacheRead,omitempty"` // tokens that answer read from the vendor's cache
|
||||
CacheWrite int `json:"cacheWrite,omitempty"` // and wrote to it
|
||||
Kept bool `json:"kept,omitempty"` // Last was put first for it
|
||||
// Why it was kept — "session", "turn", "cache" — or not: "off", "first"
|
||||
// (nobody has answered it yet), "new-turn", "no-cache" (the vendor
|
||||
// read too little from its cache to keep), "cold" (too long ago),
|
||||
// "resting", "spent", "gone" (no longer one to route to).
|
||||
// read and wrote too little of its cache to keep), "cold" (too long
|
||||
// ago), "resting", "spent", "gone" (no longer one to route to).
|
||||
Why string `json:"why"`
|
||||
}
|
||||
|
||||
type stick struct {
|
||||
rest string
|
||||
who string // the key or account, however many were on
|
||||
model string // the model it answered as: a group may have several on one account
|
||||
effort string // the effort the group's member it answered as is fixed at
|
||||
turn int
|
||||
at time.Time
|
||||
cacheRead int
|
||||
rest string
|
||||
who string // the key or account, however many were on
|
||||
model string // the model it answered as: a group may have several on one account
|
||||
effort string // the effort the group's member it answered as is fixed at
|
||||
turn int
|
||||
at time.Time
|
||||
cacheRead int
|
||||
cacheWrite int
|
||||
}
|
||||
|
||||
var sticks = struct {
|
||||
@@ -104,6 +110,9 @@ type savedStick struct {
|
||||
Turn int `json:"turn,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
CacheRead int `json:"cacheRead,omitempty"`
|
||||
// CacheWrite is absent from a file written before it was kept, and
|
||||
// reads as 0: such a stick is judged by what was read, as it was then
|
||||
CacheWrite int `json:"cacheWrite,omitempty"`
|
||||
}
|
||||
|
||||
func sticksPath() string { return filepath.Join(filepath.Dir(provider.Path()), "affinity.json") }
|
||||
@@ -136,7 +145,7 @@ func stickOf(key string) (stick, bool) {
|
||||
if st, ok := sticks.m[k]; ok && !st.at.Before(v.At) {
|
||||
continue
|
||||
}
|
||||
sticks.m[k] = stick{rest: v.Rest, who: v.Who, model: v.Model, effort: v.Effort, turn: v.Turn, at: v.At, cacheRead: v.CacheRead}
|
||||
sticks.m[k] = stick{rest: v.Rest, who: v.Who, model: v.Model, effort: v.Effort, turn: v.Turn, at: v.At, cacheRead: v.CacheRead, cacheWrite: v.CacheWrite}
|
||||
}
|
||||
st, ok := sticks.m[key]
|
||||
return st, ok
|
||||
@@ -156,7 +165,7 @@ func saveSticks() {
|
||||
sticks.Lock()
|
||||
for k, st := range sticks.m {
|
||||
if now.Sub(st.at) <= stickKeep {
|
||||
ks = append(ks, kept{k, savedStick{st.rest, st.who, st.model, st.effort, st.turn, st.at, st.cacheRead}})
|
||||
ks = append(ks, kept{k, savedStick{st.rest, st.who, st.model, st.effort, st.turn, st.at, st.cacheRead, st.cacheWrite}})
|
||||
}
|
||||
}
|
||||
sticks.Unlock()
|
||||
@@ -345,7 +354,7 @@ func affine(scope, mode string, rotate bool, in http.Header, from provider.Proto
|
||||
had = false
|
||||
}
|
||||
if had {
|
||||
a.Last, a.LastTurn, a.At, a.CacheRead = st.rest, st.turn, st.at, st.cacheRead
|
||||
a.Last, a.LastTurn, a.At, a.CacheRead, a.CacheWrite = st.rest, st.turn, st.at, st.cacheRead, st.cacheWrite
|
||||
}
|
||||
// the account and the model that answered: a group with Opus and
|
||||
// Sonnet both on one Claude account, a rule sending the turn to Opus,
|
||||
@@ -387,7 +396,9 @@ func affine(scope, mode string, rotate bool, in http.Header, from provider.Proto
|
||||
a.Why = "turn"
|
||||
case mode == provider.AffinityTurn, rotate:
|
||||
a.Why = "new-turn"
|
||||
case st.cacheRead < cacheWorth:
|
||||
case st.cacheRead+st.cacheWrite < cacheWorth:
|
||||
// what it wrote counts with what it read: the cache a first turn
|
||||
// built is there for the next to read
|
||||
a.Why = "no-cache"
|
||||
case time.Since(st.at) > cacheCold:
|
||||
a.Why = "cold"
|
||||
@@ -513,11 +524,11 @@ func after(cs []candidate, pl planned, at int) ([]candidate, planned) {
|
||||
}
|
||||
|
||||
// answered remembers who answered a conversation, and what it read from
|
||||
// the vendor's cache doing so.
|
||||
func answered(key string, c candidate, turn, cacheRead int) {
|
||||
// the vendor's cache and wrote to it doing so.
|
||||
func answered(key string, c candidate, turn, cacheRead, cacheWrite int) {
|
||||
now := time.Now()
|
||||
sticks.Lock()
|
||||
sticks.m[key] = stick{rest: c.rest, who: c.who(), model: c.model, effort: c.effort, turn: turn, at: now, cacheRead: cacheRead}
|
||||
sticks.m[key] = stick{rest: c.rest, who: c.who(), model: c.model, effort: c.effort, turn: turn, at: now, cacheRead: cacheRead, cacheWrite: cacheWrite}
|
||||
delete(sticks.opening, key)
|
||||
if len(sticks.m) > 4096 {
|
||||
for k, st := range sticks.m {
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// cacheWriter is an Anthropic Messages upstream that answers as each key,
|
||||
// reporting the cache as Anthropic does: a first turn writes the prompt
|
||||
// (cache_creation_input_tokens) and reads none of it.
|
||||
type cacheWriter struct {
|
||||
mu sync.Mutex
|
||||
tried []string
|
||||
read, wrote int
|
||||
}
|
||||
|
||||
func (c *cacheWriter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
io.ReadAll(r.Body)
|
||||
key := r.Header.Get("x-api-key")
|
||||
if key == "" {
|
||||
key = strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.tried = append(c.tried, key)
|
||||
read, wrote := c.read, c.wrote
|
||||
c.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
usage := `"cache_read_input_tokens":` + itoa(read) + `,"cache_creation_input_tokens":` + itoa(wrote)
|
||||
for _, ev := range []string{
|
||||
`{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"m","content":[],"usage":{"input_tokens":12,"output_tokens":1,` + usage + `}}}`,
|
||||
`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
|
||||
`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"from ` + key + `"}}`,
|
||||
`{"type":"content_block_stop","index":0}`,
|
||||
`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`,
|
||||
`{"type":"message_stop"}`,
|
||||
} {
|
||||
var t struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
json.Unmarshal([]byte(ev), &t)
|
||||
io.WriteString(w, "event: "+t.Type+"\ndata: "+ev+"\n\n")
|
||||
}
|
||||
}
|
||||
|
||||
// What the last reply wrote to the vendor's cache counts with what it
|
||||
// read: the first turn of a conversation reads nothing and writes the
|
||||
// whole prompt, and its second turn stays to read it (vilicvane on
|
||||
// Discord: 「会话保持 → 自动」 moved the second turn as "no-cache", and the
|
||||
// cache just built was thrown away). Kept across a restart too, as the
|
||||
// file has it; a reply that neither read nor wrote enough still moves.
|
||||
func TestAffinityKeepsACacheJustWritten(t *testing.T) {
|
||||
const (
|
||||
first = `{"model":"cw/m","messages":[{"role":"user","content":"hi"}]}`
|
||||
again = `{"model":"cw/m","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"yo"},{"role":"user","content":"more"}]}`
|
||||
)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
read, wrote int
|
||||
restart bool
|
||||
why string
|
||||
}{
|
||||
{"written", 0, 3000, false, "cache"},
|
||||
{"written, restarted", 0, 3000, true, "cache"},
|
||||
{"read and written together", 600, 600, false, "cache"},
|
||||
{"too little either way", 300, 300, false, "no-cache"},
|
||||
} {
|
||||
fresh(t)
|
||||
v := &cacheWriter{read: c.read, wrote: c.wrote}
|
||||
up := httptest.NewServer(v)
|
||||
t.Cleanup(up.Close)
|
||||
p := provider.Provider{ID: "cw", Name: "CW", Key: "k1", Models: []string{"m"}, Anthropic: up.URL + "/v1",
|
||||
Keys: []provider.KeyAccount{{Key: "k2"}}}
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
if code, body := postAs(t, s, "s1", first); code != 200 {
|
||||
t.Fatalf("%s: first turn %d %s", c.name, code, body)
|
||||
}
|
||||
if c.restart {
|
||||
sticks.Lock()
|
||||
sticks.m, sticks.from, sticks.mod = map[string]stick{}, "", time.Time{}
|
||||
sticks.Unlock()
|
||||
s = New()
|
||||
}
|
||||
if code, body := postAs(t, s, "s1", again); code != 200 {
|
||||
t.Fatalf("%s: second turn %d %s", c.name, code, body)
|
||||
}
|
||||
a := s.trace.routes[len(s.trace.routes)-1].Affinity
|
||||
if a == nil || a.Why != c.why || a.Kept != (c.why == "cache") {
|
||||
t.Fatalf("%s: affinity %+v, want %s", c.name, a, c.why)
|
||||
}
|
||||
if a.CacheRead != c.read || a.CacheWrite != c.wrote {
|
||||
t.Fatalf("%s: trace tells read %d wrote %d, want %d and %d", c.name, a.CacheRead, a.CacheWrite, c.read, c.wrote)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3007,7 +3007,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
// a compaction a rule sent to a model of its own leaves the
|
||||
// conversation, and the turn's size, where they were
|
||||
if hit == nil || !hit.Compact {
|
||||
answered(stuck, c, aff.Turn, call.Usage.CacheRead)
|
||||
answered(stuck, c, aff.Turn, call.Usage.CacheRead, call.Usage.CacheWrite)
|
||||
}
|
||||
if hit != nil && !hit.Compact {
|
||||
ruleAnswered(ruleAt, call.Usage)
|
||||
|
||||
@@ -96,8 +96,8 @@ func TestUnansweredForgetsTheAccountWhenItsModelIsGone(t *testing.T) {
|
||||
fresh(t)
|
||||
const key = "group/g|s1"
|
||||
flaky := candidate{p: provider.Provider{ID: "flaky", Key: "broken"}, rest: "flaky"}
|
||||
answered(key, candidate{p: provider.Provider{ID: "flaky", Key: "broken"}, model: "m", rest: "flaky"}, 1, 0)
|
||||
answered(key+"-other", candidate{p: provider.Provider{ID: "steady", Key: "fine"}, model: "m", rest: "steady"}, 1, 0)
|
||||
answered(key, candidate{p: provider.Provider{ID: "flaky", Key: "broken"}, model: "m", rest: "flaky"}, 1, 0, 0)
|
||||
answered(key+"-other", candidate{p: provider.Provider{ID: "steady", Key: "fine"}, model: "m", rest: "steady"}, 1, 0, 0)
|
||||
unanswered(key, candidate{p: flaky.p, model: "m2", rest: flaky.rest}) // the model that answered is gone from the group; the account isn't
|
||||
sticks.Lock()
|
||||
_, kept := sticks.m[key]
|
||||
|
||||
@@ -31,7 +31,7 @@ func TestLoginSwitchKeepsEachAccountItself(t *testing.T) {
|
||||
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
|
||||
pl := planned{order: make([]Weighed, 2)}
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, h, provider.Anthropic, body, []candidate{a, b}, pl)
|
||||
answered(key, a, 1, 0)
|
||||
answered(key, a, 1, 0, 0)
|
||||
servedCandidate(a, 5000)
|
||||
|
||||
// signed in to b now
|
||||
|
||||
@@ -70,7 +70,7 @@ func TestLoneSpentKeyKeepsItsConversation(t *testing.T) {
|
||||
h.Set("x-claude-code-session-id", "lone-spent-1016")
|
||||
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, h, provider.Chat, body, cs, pl)
|
||||
answered(key, c, 1, 0)
|
||||
answered(key, c, 1, 0, 0)
|
||||
t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() })
|
||||
got, _, aff, _ := affine("t", provider.AffinitySession, false, h, provider.Chat, body, cs, pl)
|
||||
if got[0].rest != "kimi-code-cn" || aff.Why == "spent" || !aff.Kept {
|
||||
|
||||
@@ -3757,13 +3757,13 @@ const I18N = {
|
||||
"{agent} asked for the routing group {name}: {members}": "{agent} 请求了路由组 {name}:{members}",
|
||||
"Kept on {who}: it answered this conversation before, and affinity keeps a session with one account.": "留在 {who}:此会话之前由它回答,亲和性使会话保持同一账号。",
|
||||
"Kept on {who}: {agent} is handing back tool results within turn {n}, and moving now would lose what the vendor cached of it.": "留在 {who}:{agent} 正在第 {n} 轮内回传工具结果,此时换账号会丢掉厂商为它缓存的内容。",
|
||||
"Kept on {who}: the vendor read {n} tokens of this conversation from its cache {d} ago; anyone else would be sent them afresh and paid in full.": "留在 {who}:{d}前厂商从缓存读取了此会话的 {n} tokens;换账号需重新发送并全价计费。",
|
||||
"Kept on {who}: {d} ago the vendor read {r} tokens of this conversation from its cache and wrote {w} to it; anyone else would be sent them afresh and paid in full.": "留在 {who}:{d}前厂商从缓存读取了此会话的 {r} tokens,并写入了 {w} tokens;换账号需重新发送并全价计费。",
|
||||
"Turn {n} begins: in turn, it goes to the one after {who}, which answered the last turn — {next}.": "第 {n} 轮开始:轮流交给上一轮回答者 {who} 的下一个,即 {next}。",
|
||||
"Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.": "第 {n} 轮开始:亲和性仅在一轮内保持,路由重新决定。",
|
||||
"{who} answered this conversation last, but it is resting, so the conversation moves.": "此会话上次由 {who} 回答,但它在休息,已换账号。",
|
||||
"{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.": "此会话上次由 {who} 回答,但其额度将尽,已换账号。",
|
||||
"{who} answered this conversation last, but it is no longer one to route to.": "此会话上次由 {who} 回答,但它已不可路由。",
|
||||
"{who} answered this conversation last, but the vendor read only {n} tokens of it from its cache then — not worth staying for.": "此会话上次由 {who} 回答,但当时厂商只从缓存读取了 {n} tokens,不值得保留。",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "此会话上次由 {who} 回答,但当时厂商只从缓存读取了 {r} tokens、写入了 {w} tokens,不值得保留。",
|
||||
"{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.": "此会话 {d}前由 {who} 回答,已超过厂商缓存提示词的 5 分钟,路由重新决定。",
|
||||
"Affinity is off: each request is routed afresh, whoever answered its conversation before.": "亲和性已关闭:每个请求都重新路由,不论之前由谁回答。",
|
||||
"{status} · {fail} · passed to {agent}": "{status} · {fail} · 已交给 {agent}",
|
||||
@@ -7938,13 +7938,13 @@ const I18N = {
|
||||
"{agent} asked for the routing group {name}: {members}": "{agent} 請求了路由組 {name}:{members}",
|
||||
"Kept on {who}: it answered this conversation before, and affinity keeps a session with one account.": "留在 {who}:此會話之前由它回答,親和性使會話保持同一帳號。",
|
||||
"Kept on {who}: {agent} is handing back tool results within turn {n}, and moving now would lose what the vendor cached of it.": "留在 {who}:{agent} 正在第 {n} 輪內回傳工具結果,此時換帳號會丟掉廠商為它快取的內容。",
|
||||
"Kept on {who}: the vendor read {n} tokens of this conversation from its cache {d} ago; anyone else would be sent them afresh and paid in full.": "留在 {who}:{d}前廠商從快取讀取了此會話的 {n} tokens;換帳號需重新發送並全價計費。",
|
||||
"Kept on {who}: {d} ago the vendor read {r} tokens of this conversation from its cache and wrote {w} to it; anyone else would be sent them afresh and paid in full.": "留在 {who}:{d}前廠商從快取讀取了此會話的 {r} tokens,並寫入了 {w} tokens;換帳號需重新發送並全價計費。",
|
||||
"Turn {n} begins: in turn, it goes to the one after {who}, which answered the last turn — {next}.": "第 {n} 輪開始:輪流交給上一輪迴答者 {who} 的下一個,即 {next}。",
|
||||
"Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.": "第 {n} 輪開始:親和性僅在一輪內保持,路由重新決定。",
|
||||
"{who} answered this conversation last, but it is resting, so the conversation moves.": "此會話上次由 {who} 回答,但它在休息,已換帳號。",
|
||||
"{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.": "此會話上次由 {who} 回答,但其額度將盡,已換帳號。",
|
||||
"{who} answered this conversation last, but it is no longer one to route to.": "此會話上次由 {who} 回答,但它已不可路由。",
|
||||
"{who} answered this conversation last, but the vendor read only {n} tokens of it from its cache then — not worth staying for.": "此會話上次由 {who} 回答,但當時廠商只從快取讀取了 {n} tokens,不值得保留。",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "此會話上次由 {who} 回答,但當時廠商只從快取讀取了 {r} tokens、寫入了 {w} tokens,不值得保留。",
|
||||
"{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.": "此會話 {d}前由 {who} 回答,已超過廠商快取提示詞的 5 分鐘,路由重新決定。",
|
||||
"Affinity is off: each request is routed afresh, whoever answered its conversation before.": "親和性已關閉:每個請求都重新路由,不論之前由誰回答。",
|
||||
"{status} · {fail} · passed to {agent}": "{status} · {fail} · 已交給 {agent}",
|
||||
@@ -12134,13 +12134,13 @@ const I18N = {
|
||||
"{agent} asked for the routing group {name}: {members}": "{agent} がルーティンググループ {name} をリクエスト:{members}",
|
||||
"Kept on {who}: it answered this conversation before, and affinity keeps a session with one account.": "{who} に固定:以前この会話に応答しており、アフィニティによってセッションは 1 つのアカウントに保たれます。",
|
||||
"Kept on {who}: {agent} is handing back tool results within turn {n}, and moving now would lose what the vendor cached of it.": "{who} に固定:{agent} はターン {n} の中でツール結果を返しており、今切り替えるとベンダーがキャッシュした内容が失われます。",
|
||||
"Kept on {who}: the vendor read {n} tokens of this conversation from its cache {d} ago; anyone else would be sent them afresh and paid in full.": "{who} に固定:{d} 前にベンダーがこの会話の {n} トークンをキャッシュから読みました。他の相手に送ると新たに送信され、全額請求されます。",
|
||||
"Kept on {who}: {d} ago the vendor read {r} tokens of this conversation from its cache and wrote {w} to it; anyone else would be sent them afresh and paid in full.": "{who} に固定:{d} 前にベンダーがこの会話の {r} トークンをキャッシュから読み、{w} トークンを書き込みました。他の相手に送ると新たに送信され、全額請求されます。",
|
||||
"Turn {n} begins: in turn, it goes to the one after {who}, which answered the last turn — {next}.": "ターン {n} の開始:交互モードでは、前のターンに応答した {who} の次 — {next} に回ります。",
|
||||
"Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.": "ターン {n} の開始:アフィニティは 1 ターン内でのみ会話を保つため、ルーティングを新たに決めます。",
|
||||
"{who} answered this conversation last, but it is resting, so the conversation moves.": "この会話に前回応答したのは {who} ですが、休止中のため会話は移ります。",
|
||||
"{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.": "この会話に前回応答したのは {who} ですが、利用枠をほぼ使い切っているため会話は移ります。",
|
||||
"{who} answered this conversation last, but it is no longer one to route to.": "この会話に前回応答したのは {who} ですが、もうルーティング対象ではありません。",
|
||||
"{who} answered this conversation last, but the vendor read only {n} tokens of it from its cache then — not worth staying for.": "この会話に前回応答したのは {who} ですが、そのときベンダーがキャッシュから読んだのは {n} トークンだけでした — 留まる価値はありません。",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "この会話に前回応答したのは {who} ですが、そのときベンダーがキャッシュから読んだのは {r} トークン、書き込んだのは {w} トークンだけでした — 留まる価値はありません。",
|
||||
"{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.": "この会話に {who} が応答したのは {d} 前で、ベンダーがプロンプトをキャッシュする 5 分を超えています — そのためルーティングを新たに決めます。",
|
||||
"Affinity is off: each request is routed afresh, whoever answered its conversation before.": "アフィニティはオフです:以前誰が会話に応答したかに関係なく、各リクエストを新たにルーティングします。",
|
||||
"{status} · {fail} · passed to {agent}": "{status} · {fail} · {agent} に渡しました",
|
||||
@@ -16342,13 +16342,13 @@ const I18N = {
|
||||
"{agent} asked for the routing group {name}: {members}": "{agent} hat die Weiterleitungsgruppe {name} angefragt: {members}",
|
||||
"Kept on {who}: it answered this conversation before, and affinity keeps a session with one account.": "Bei {who} belassen: Es hat diese Unterhaltung bereits beantwortet, und die Affinität hält eine Sitzung bei einem Konto.",
|
||||
"Kept on {who}: {agent} is handing back tool results within turn {n}, and moving now would lose what the vendor cached of it.": "Bei {who} belassen: {agent} gibt innerhalb von Runde {n} Tool-Ergebnisse zurück, und ein Wechsel würde jetzt verlieren, was der Anbieter davon im Cache hat.",
|
||||
"Kept on {who}: the vendor read {n} tokens of this conversation from its cache {d} ago; anyone else would be sent them afresh and paid in full.": "Bei {who} belassen: Der Anbieter hat vor {d} {n} Token dieser Unterhaltung aus seinem Cache gelesen; jedes andere Konto bekäme sie neu gesendet und voll berechnet.",
|
||||
"Kept on {who}: {d} ago the vendor read {r} tokens of this conversation from its cache and wrote {w} to it; anyone else would be sent them afresh and paid in full.": "Bei {who} belassen: Der Anbieter hat vor {d} {r} Token dieser Unterhaltung aus seinem Cache gelesen und {w} hineingeschrieben; jedes andere Konto bekäme sie neu gesendet und voll berechnet.",
|
||||
"Turn {n} begins: in turn, it goes to the one after {who}, which answered the last turn — {next}.": "Runde {n} beginnt: Reihum geht sie an das Konto nach {who}, das die letzte Runde beantwortet hat – {next}.",
|
||||
"Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.": "Runde {n} beginnt: Die Affinität hält eine Unterhaltung nur innerhalb einer Runde, daher entscheidet die Weiterleitung neu.",
|
||||
"{who} answered this conversation last, but it is resting, so the conversation moves.": "{who} hat diese Unterhaltung zuletzt beantwortet, pausiert aber, daher wechselt die Unterhaltung.",
|
||||
"{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.": "{who} hat diese Unterhaltung zuletzt beantwortet, aber sein Kontingent ist fast aufgebraucht, daher wechselt die Unterhaltung.",
|
||||
"{who} answered this conversation last, but it is no longer one to route to.": "{who} hat diese Unterhaltung zuletzt beantwortet, kommt aber für die Weiterleitung nicht mehr in Frage.",
|
||||
"{who} answered this conversation last, but the vendor read only {n} tokens of it from its cache then — not worth staying for.": "{who} hat diese Unterhaltung zuletzt beantwortet, aber der Anbieter hat damals nur {n} Token davon aus seinem Cache gelesen – das lohnt das Bleiben nicht.",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "{who} hat diese Unterhaltung zuletzt beantwortet, aber der Anbieter hat damals nur {r} Token davon aus seinem Cache gelesen und {w} hineingeschrieben – das lohnt das Bleiben nicht.",
|
||||
"{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.": "{who} hat diese Unterhaltung vor {d} beantwortet, länger als die 5 Minuten, die ein Anbieter einen Prompt im Cache hält – daher entscheidet die Weiterleitung neu.",
|
||||
"Affinity is off: each request is routed afresh, whoever answered its conversation before.": "Affinität ist aus: Jede Anfrage wird neu weitergeleitet, egal wer ihre Unterhaltung vorher beantwortet hat.",
|
||||
"{status} · {fail} · passed to {agent}": "{status} · {fail} · an {agent} übergeben",
|
||||
|
||||
@@ -615,7 +615,7 @@
|
||||
switch (a.why) {
|
||||
case "session": return t("Kept on {who}: it answered this conversation before, and affinity keeps a session with one account.", { who: last });
|
||||
case "turn": return t("Kept on {who}: {agent} is handing back tool results within turn {n}, and moving now would lose what the vendor cached of it.", { who: last, agent: agentName(r.agent), n: a.turn });
|
||||
case "cache": return t("Kept on {who}: the vendor read {n} tokens of this conversation from its cache {d} ago; anyone else would be sent them afresh and paid in full.", { who: last, n: tokens(a.cacheRead), d: ago });
|
||||
case "cache": return t("Kept on {who}: {d} ago the vendor read {r} tokens of this conversation from its cache and wrote {w} to it; anyone else would be sent them afresh and paid in full.", { who: last, r: tokens(a.cacheRead || 0), w: tokens(a.cacheWrite || 0), d: ago });
|
||||
case "new-turn": return routing === "rotate"
|
||||
? t("Turn {n} begins: in turn, it goes to the one after {who}, which answered the last turn — {next}.", { n: a.turn, who: last, next: who(r.order[0]) })
|
||||
: lead ? null : t("Turn {n} begins: affinity keeps a conversation only within a turn, so routing decides afresh.", { n: a.turn });
|
||||
@@ -625,7 +625,7 @@
|
||||
case "resting": return t("{who} answered this conversation last, but it is resting, so the conversation moves.", { who: last });
|
||||
case "spent": return t("{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.", { who: last });
|
||||
case "gone": return t("{who} answered this conversation last, but it is no longer one to route to.", { who: last });
|
||||
case "no-cache": return t("{who} answered this conversation last, but the vendor read only {n} tokens of it from its cache then — not worth staying for.", { who: last, n: tokens(a.cacheRead || 0) });
|
||||
case "no-cache": return t("{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.", { who: last, r: tokens(a.cacheRead || 0), w: tokens(a.cacheWrite || 0) });
|
||||
case "cold": return t("{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.", { who: last, d: ago });
|
||||
case "off": return t("Affinity is off: each request is routed afresh, whoever answered its conversation before.");
|
||||
case "rule": {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
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");
|
||||
|
||||
// Auto affinity counts what the vendor wrote to its cache with what it
|
||||
// read (vilicvane on Discord: a first turn reads nothing and writes the
|
||||
// whole prompt). The Routing page says both: a conversation kept for a
|
||||
// cache just written doesn't read as "read 0 tokens", and one moved says
|
||||
// it wrote too little as well.
|
||||
const words = {
|
||||
en: { kept: ["read 0 tokens", "wrote 3.0k"], moved: ["read only 300 tokens", "wrote 200"] },
|
||||
zh: { kept: ["读取了此会话的 0 tokens", "写入了 3.0k tokens"], moved: ["只从缓存读取了 300 tokens", "写入了 200 tokens"] },
|
||||
"zh-TW": { kept: ["讀取了此會話的 0 tokens", "寫入了 3.0k tokens"], moved: ["只從快取讀取了 300 tokens", "寫入了 200 tokens"] },
|
||||
ja: { kept: ["0 トークンをキャッシュから読み", "3.0k トークンを書き込みました"], moved: ["300 トークン", "書き込んだのは 200 トークン"] },
|
||||
de: { kept: ["0 Token dieser Unterhaltung", "3.0k hineingeschrieben"], moved: ["nur 300 Token", "200 hineingeschrieben"] },
|
||||
};
|
||||
|
||||
function routes(now, why, read, wrote) {
|
||||
const time = new Date(now.getTime() - 5000).toISOString();
|
||||
const at = new Date(now.getTime() - 65000).toISOString();
|
||||
const k1 = { id: "cw#k1", provider: "cw", name: "CW", kind: "key", who: "k1", model: "m" };
|
||||
const k2 = { id: "cw#k2", provider: "cw", name: "CW", kind: "key", who: "k2", model: "m" };
|
||||
const order = why === "cache" ? [k1, k2] : [k2, k1];
|
||||
return [{ id: 1, seq: 1, time, agent: "claude", model: "cw/m", provider: "cw", order, done: true, status: 200, ms: 20,
|
||||
affinity: { mode: "", turn: 2, last: "cw#k1", lastTurn: 1, at, cacheRead: read, cacheWrite: wrote, kept: why === "cache", why },
|
||||
tries: [{ id: order[0].id, model: "m", start: time, done: true, status: 200, ms: 20 }] }];
|
||||
}
|
||||
|
||||
function serve(lang, getRoutes, now) {
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs={lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window={};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.has("wait")) return;
|
||||
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1, rerouted: 0, errors: 0 }, routes: getRoutes() });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
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" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]) {
|
||||
for (const width of [1100, 420]) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
test(`${engine} ${width} ${lang}: affinity says what the vendor wrote to its cache`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await browser.newPage({ viewport: { width, height: 900 } });
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const now = new Date();
|
||||
let rs = routes(now, "cache", 0, 3000);
|
||||
await page.route("**/*", serve(lang, () => rs, now));
|
||||
const story = async () => {
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
await page.waitForFunction(() => /\d/.test(document.body.innerText) && document.querySelector(".rt-cap")?.textContent);
|
||||
return page.evaluate(() => document.body.innerText + "\n" + document.querySelector(".rt-cap").textContent);
|
||||
};
|
||||
let text = await story();
|
||||
for (const w of words[lang].kept) assert.ok(text.includes(w), `kept: ${w} not in\n${text}`);
|
||||
assert.doesNotMatch(text, /\{[rwn]\}/);
|
||||
|
||||
rs = routes(now, "no-cache", 300, 200);
|
||||
text = await story();
|
||||
for (const w of words[lang].moved) assert.ok(text.includes(w), `moved: ${w} not in\n${text}`);
|
||||
assert.doesNotMatch(text, /\{[rwn]\}/);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user