gateway: a session's side call goes on the account its main conversation is on (#5655)
With two Claude accounts, Claude Desktop's own Sonnet calls beside an
Opus chat (desktop-beside), and Claude Code's auto mode classifier, ran
on account B while the chat was on A. Each model's conversation is kept
under its own scope (p.ID/model), so the side call was routed as a
session of its own: leastHeld, or Smart's order once its cache was cold,
put it on the account the fewest others held, and B's 5 hours drained on
calls the user never made there.
Decided (product call delegated): one session goes on one account. The
user picked one, the vendor sees one client, and the cost is one cache
write of the side call where the session goes on reading it.
withSession (affinity.go) puts first, for a request whose session a
header names, the key or account of that session's largest conversation
under another model's scope (answered within heldFor, at least
cacheWorth kept, larger than this one's own). It acts for Why first,
gone, cold, no-cache, cache and session; never mid-turn, under Strict,
for a subagent (withLead), past a rest, reserve, credits or a fallback
routing put first, nor to an account that isn't readyForNew. The trace
says Why "lead" with LeadModel, and the Routing page says "Put on
{first}, where this session's {model} is: one session goes on one
account." in en, zh, zh-TW, ja and de. docs/subsystems/gateway-routing.md
says the same.
Not fixed here: the classifier's ~110-130K cache write per call. That one
is ours too: in Claude Code's interactive mode the bridge pastes the
classifier's transcript as one block without the client's marks
(claudetui userPieces, clientCache.pasted), so only the fixed prefix
(Claude Code's system plus the appended rules, the 68,925) is read and
the rest is written again on every call. The cause and a candidate fix
are on #5585. It changes what a real Claude Code sends and can't be
checked without a real account.
Run (mote, through mote-run), at this head (aeeeed54a's tree, origin/main
0fc3455e2 unchanged after a fresh fetch):
- go test ./internal/gateway ./internal/gui -count=1 -timeout 45m: ok (964s, 157s).
- TestSessionSide*, TestGroupAccountsHoldEveryRoute,
TestPluginFactoryStandardOnlyCaps, TestWholeSession*, TestBusyModel*,
TestInOrderKeeps* -count=2: ok.
- gofmt -l: clean. go vet ./internal/gateway for darwin, linux, windows: ok.
- node --test routing-affinity-lead (new), routing-affinity-order,
routing-affinity-cache-write, i18n-keys, i18n-en-no-cjk: 67/68
(Chromium + WebKit, 1100 and 420, en/zh/zh-TW/ja/de). The one red is
i18n-keys "a plugin's words are its own", red on main for strings this
change doesn't touch (#5327/#5332, #5426, #5482).
- The first package run of this change failed TestGroupAccountsHoldEveryRoute
and TestPluginFactoryStandardOnlyCaps/auto (both green at 0fc3455e2):
without a session header the id is the opening's hash, so two
conversations that opened with "hi" were one session, and a main with
nothing cached led. Both are excluded now, each with a subtest.
- The full go test ./... under the suite lock was queued behind four
other sessions' suites and had not started when this was pushed.
Broken by hand, each red: the withSession call removed (both new tests;
"the session's m2 call went to k2 while its chat is on k1"); the named
session check removed (no session named); the cacheWorth bar removed
(main holds no cache, and TestPluginFactoryStandardOnlyCaps).
Not tried: real Claude accounts, real Claude Desktop. A session already
split before this release moves its side call at the side call's next
turn, writing its cache once on the main's account.
Reported-by: jerrychoi
Reported-by: iamnil (Discord)
This commit is contained in:
@@ -247,6 +247,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- 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, a provider's fallback while the provider's own leads (`standsIn`) 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.
|
||||
- Requests that come together spread (`burstSpread` in [`burst.go`](../../internal/gateway/burst.go), #5242: Moody-Sin and Tericerice sent four at once to three Antigravity accounts, In turn and By pace, and every one went to one account). Routing weighs what each seat served (`Tokens`) and its allowance, which move only once a reply ends, and a lane counts a request only once its try begins, so requests planned at the same moment were all planned on the same figures; In turn's next turn (`after`) reads a stick that moves only on an answer too. Once the plan is made (after affinity, rules, pinning, `roomy`, `behindOverflow`), `burstSpread` puts first, of the candidates alike to the first, the one with the fewest requests in flight (`inFlight`, by `candidate.who`), ties keeping routing's order, and counts the request there in the same hold of the lock; the count is given back when `serve` ends. Alike (`burstAlike`): ready as the first is (not resting, aside, reserved, barred, held, capped, a fallback standing in, credits-last or busy behind), the same fallback, fit, protocol, URL and `Via`, the rule's member when a group's rule picked one; In turn any of the round; By pace a pace within a tenth (`paceAlike`, routes.Pace's band), the same `Learns`, both with room (`burstTier` 0) and no wallet told apart (`sameBalance`); Least used within a point used, the same tier and known-ness. In a group, a provider routed its own way (`ownRouting`) is alike only to its own provider's keys, by its routing, and a group in the group to nothing. Smart, In order, By weight and the others keep their order. Not moved, only counted: a conversation kept (`Affinity.Kept`), Strict, an `X-Magpie-Account` pin, a sealed task's lead, a native compaction's reader, and a new conversation `leastHeld` spreads (In turn, `spreadsSessions`), which counts those in flight itself (`sticks.opening`). A plugin's provider and a remote magpie take the same path; the remote spreads over its own accounts, the sessions passed on to it (`passOnCaller`). Not done: putting a markedly slower account behind (speed is read only for Speed first, `speedOf`), as a first token's wait goes with the prompt's size and the vendor's queue more than with the account. `burst_spread_test.go`.
|
||||
- Stays: Session or Strict under a routing that picks by what is left (Smart, Least used first, Use before expiry: `spreadsSessions`) spreads new conversations the same way (connor_yang on Discord: three sessions over three accounts landed on two). `leastHeld` with `ready` passes over one routing keeps new conversations off (`readyForNew`: resting, a key for another protocol, a provider's fallback while its own model leads, one used past `lowShare`), counts only leads (a key without `|agent:`), and leaves the turn marks alone. A subagent's first request goes to its lead's key or account while that one is `readyForNew` (`withLead`), so a session keeps one account, its subagents included. Held is the last `heldFor` (30 minutes): a session idle longer counts no more. In order, By weight, Free first, Speed first, Cheapest, Manual and a plugin's routing keep their order. An answered conversation is kept as before; the spread only decides where a new one starts. `session_spread_test.go`.
|
||||
- A session's call to another model than its main conversation's goes to the key or account that main conversation is on (`withSession`, `Affinity.Why` `lead` with `LeadModel`; #5655, jerrychoi, and iamnil on Discord). Each model's conversation is kept under its own scope (`p.ID/model`), so Claude Desktop's own Sonnet calls beside an Opus chat (`desktop-beside`), Claude Code's auto mode classifier and a title were routed as sessions of their own: put by `leastHeld`, or by Smart's order once their cache was cold, on another account, they ran one session on two accounts at once and drained the second one's 5 hours. The main conversation is the session's largest stick (cache read plus written) under another scope by the session's own id, one a header names (`sessionNamed`: a conversation known only by its opening's hash has no session, since unrelated ones that open alike share it; no `|agent:`), answered within `heldFor`, holding at least `cacheWorth` (a main with nothing cached goes where its own next turn is sent), and it leads only while larger than the call's own, so the two never follow each other. It is followed for Why `first`, `gone`, `cold`, `no-cache`, `cache` and `session`, by the model routing put first (in a group, another member on that account is another model and is never picked), and only to one `readyForNew`. It is not followed mid-turn (a kept `Within`), under Strict, In turn, nor for a subagent (`withLead` does that), nor past a rest, a reserve, credits or a fallback routing put first. A call moved off its own cache writes it once where the session goes on reading it. The Routing page says so ("Put on {first}, where this session's {model} is…", `routing-affinity-lead.test.cjs`). `session_lead_test.go`.
|
||||
- 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. One let spend its credits, and holding some by its last `/wham/usage` (`credits.has_credits` with a balance over 0, or `unlimited`; `QuotaWindow.Credits`, `Limit.Credits`, `Allowance.OnCredits`), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429 `usage_limit_reached` before it spends the credits, and the next turn on them. So that 429 is asked again at once, once a request, on the same account, before a reset is looked at, on the routed path (`creditsAgain`, `creditsAsked`, `Try.Credits`) and on Codex's own sign-in's relay (`relayOnCredits`), rather than ended for the agent, which ended a running session while a new one worked. Refused again, it rests `fallbackCooldown` (`Rest.By` `credits`) and is read again, not until its window renews, and its full windows rest it nowhere else (`full` is zero for it, `spendsCredits`). Smart, Pace and Least used put such an account first of the spent tier (`routes.Seat.Credits`, `spentBefore`): after those with allowance left, ahead of those used up with nothing to go on with (`Weighed.Credits`, told on the Routing page). Switching to credits early, at a few percent left, was weighed and not done: the vendor spends credits only once the allowance is used up, so it would only waste what is left. `TestCodexCreditsAskedAgainAtTheEdge`, `TestCodexCreditsNoLongRest`, `TestCodexCreditsFirstOfTheSpent`, `TestCreditsFirstOfTheSpent`, `routing-codex-credits-again.test.cjs`.
|
||||
- A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): *Only after every other account, key and fallback* under the Usage card's *Use credits*, `magpie quota credits <account> last`, `settings.CodexCreditsLast` (`provider.CodexCreditsLast`, `SetCodexCreditsMode`; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is `creditsLast` while it goes on on its credits (`spendsCredits`) and a window for the model is used up where *off* would hold it (`Allowance.CapHeld` at `WindowCaps{Credits: true}`; a call ChatGPT counts in no window, `freeOnChatGPT`, stays). `restLast` then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (`Weighed.CreditsLast`). Affinity doesn't keep a conversation on one while one not on its credits leads (`Affinity.Why` `credits`, `lastBehind`), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (`after`, `leastHeld`, `readyForNew`). Strict affinity keeps it, as a rule, an `X-Magpie-Account` pin and a sealed task's lead (`leadFirst`) still put theirs first. A reset is still spent before its credits when the try reaches it (`resetBeforeCredits`). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as *on*. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. `TestCodexCreditsLastAfterTheOthers`, `TestCodexCreditsLastAfterTheFallback`, `TestCodexCreditsLastNotKept`, `TestCodexCreditsLastMode`, `codex-credits-last.test.cjs`.
|
||||
- A fourth, set per account, spends the credits before moving to another account (jojonas_xyz on X: the account ran out, magpie moved to another by itself, and no setting kept the first one's credits in use). *On* alone lets the vendor answer on credits, but Smart and Pace still put an account at `LowShare` (90%) or `SpentShare` (98%) behind every account with room (`tier`), Drain counts it used up at `SpentShareOf(Drain)`, and `NextLogin` moves Codex's own sign-in at the spent share, credits or not. *Before moving to another account* under *Use credits* (the Usage card, the menu bar panel, and the account's ⋯ in its provider's editor), `magpie quota credits <account> first`, `settings.CodexCreditsFirst` (`provider.CodexCreditsFirst`; one of first and last at most, on or off clears it) makes an account that spends credits (`spendsCredits`) a `routes.Seat.First`: Smart, Pace and Fastest weigh it at tier 0 (`seatTier`), Drain doesn't count it spent, affinity doesn't move a conversation off it as `spent`, and `readyForNew`/`standsInFor` treat it as having room (`Weighed.CreditsFirst`). `NextLogin` keeps Codex signed in to it while one of its windows says it holds credits (`spendsFirst`); with the credits gone it moves as before. The account magpie moved Codex off says where the setting is, on its *First again once it has room* tag. `TestCodexCreditsFirstKeepsItsPlace`, `TestCodexCreditsFirstDrainStays`, `TestCodexCreditsFirstMode`, `TestCodexStaysOnAnAccountSpendingCreditsFirst`, `codex-credits-first.test.cjs`.
|
||||
|
||||
@@ -122,13 +122,17 @@ type Affinity struct {
|
||||
// everything else, and one not on its credits leads: lastBehind),
|
||||
// "busy" (its plugin says the model is busier than settings.BusyLoad
|
||||
// and one that isn't leads, at a new turn: busyBehind),
|
||||
// "strict" (Stays: Strict, kept whatever it is).
|
||||
// "strict" (Stays: Strict, kept whatever it is), "lead" (put with the
|
||||
// key or account its session's main conversation is on: withSession).
|
||||
Why string `json:"why"`
|
||||
// Main is, for a conversation kept strictly on a provider's fallback,
|
||||
// the provider's own key or account that is ready again: it would have
|
||||
// gone back to it ("main") but for Stays: Strict, which the Routing
|
||||
// page says.
|
||||
Main *Weighed `json:"main,omitempty"`
|
||||
// LeadModel is, for Why "lead", the model of the session's main
|
||||
// conversation, whose key or account this call went to (withSession).
|
||||
LeadModel string `json:"leadModel,omitempty"`
|
||||
}
|
||||
|
||||
type stick struct {
|
||||
@@ -698,6 +702,9 @@ func affine(scope, mode string, rotate, spread, inOrder bool, in http.Header, fr
|
||||
cs, pl = leastHeld(scope, key, cs, pl, true)
|
||||
}
|
||||
}
|
||||
if !rotate {
|
||||
cs, pl = withSession(scope, key, sessionNamed(in), a, st, had, cs, pl)
|
||||
}
|
||||
return cs, pl, a, key
|
||||
}
|
||||
|
||||
@@ -911,6 +918,104 @@ func withLead(key string, cs []candidate, pl planned) ([]candidate, planned) {
|
||||
return cs, pl
|
||||
}
|
||||
|
||||
// withSession puts first, for a conversation of a session whose main
|
||||
// conversation is with another model, the key or account that main
|
||||
// conversation is on (#5655, jerrychoi; iamnil on Discord): Claude
|
||||
// Desktop's own Sonnet calls beside an Opus chat (desktop-beside), Claude
|
||||
// Code's auto mode classifier, a title. A model's conversation is kept
|
||||
// apart from the session's other models' (scope), so such a call was
|
||||
// routed as a session of its own: put by leastHeld, or by Smart's order
|
||||
// once its cache was cold, on the account the fewest others were on, it
|
||||
// ran the session on two accounts at once, and the second one's 5 hours
|
||||
// drained on calls the user never made there. One session is billed to
|
||||
// one account, as a user who picked one in the menu expects, and as the
|
||||
// vendor sees one client.
|
||||
//
|
||||
// The session's main conversation is its largest under another model's
|
||||
// scope (what its vendor read and wrote of it), answered within heldFor,
|
||||
// by the session's own id: a subagent (withLead) and a conversation known
|
||||
// only by its body's hash have none (sessionNamed), since two unrelated
|
||||
// conversations that open alike share a hash. A main conversation with
|
||||
// less than cacheWorth kept has no cache to stay for, and goes where its
|
||||
// own next turn is sent: it leads nothing. It leads only while larger than this
|
||||
// one's, so the two never take turns following each other. It is
|
||||
// followed while this conversation isn't held where it is otherwise:
|
||||
// Stays: Strict, mid-turn on the reasoning one account sealed, or a
|
||||
// rest, a reserve, credits a fallback routing put first for its own
|
||||
// reason; and only to one routing would put a new conversation on
|
||||
// (readyForNew), as the model routing put first. A conversation it moves
|
||||
// off its own cache writes that once, where the session goes on reading
|
||||
// it.
|
||||
func withSession(scope, key string, named bool, a *Affinity, own stick, had bool, cs []candidate, pl planned) ([]candidate, planned) {
|
||||
switch a.Why {
|
||||
case "first", "gone", "cold", "no-cache", "cache", "session":
|
||||
default:
|
||||
return cs, pl
|
||||
}
|
||||
if !named || a.Within && a.Kept || len(cs) < 2 || len(pl.order) < len(cs) || strings.Contains(key, "|agent:") {
|
||||
return cs, pl
|
||||
}
|
||||
id := strings.TrimPrefix(key, scope+"|")
|
||||
if id == key || id == "" {
|
||||
return cs, pl
|
||||
}
|
||||
size := 0
|
||||
if had {
|
||||
size = own.cacheRead + own.cacheWrite
|
||||
}
|
||||
now := time.Now()
|
||||
sticks.Lock()
|
||||
defer sticks.Unlock()
|
||||
var lead stick
|
||||
found := false
|
||||
for k, st := range sticks.m {
|
||||
if k == key || !strings.HasSuffix(k, "|"+id) || strings.Contains(k, "|agent:") || now.Sub(st.at) > heldFor {
|
||||
continue
|
||||
}
|
||||
if n := st.cacheRead + st.cacheWrite; n >= cacheWorth && n > size && (!found || n > lead.cacheRead+lead.cacheWrite) {
|
||||
lead, found = st, true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return cs, pl
|
||||
}
|
||||
// of the model routing put first: in a group, another member on the
|
||||
// lead's account is another model, which following never picks
|
||||
i := slices.IndexFunc(cs, func(c candidate) bool {
|
||||
return c.who() == lead.who && c.model == cs[0].model && c.effort == cs[0].effort
|
||||
})
|
||||
if i < 0 || i > 0 && !readyForNew(pl.order, i) {
|
||||
return cs, pl
|
||||
}
|
||||
if i > 0 {
|
||||
cs = append(append([]candidate{cs[i]}, cs[:i]...), cs[i+1:]...)
|
||||
pl.order = append(append([]Weighed{pl.order[i]}, pl.order[:i]...), pl.order[i+1:]...)
|
||||
for j := range pl.order {
|
||||
pl.order[j].Turn = false
|
||||
}
|
||||
if _, opening := sticks.opening[key]; opening {
|
||||
sticks.opening[key] = stick{rest: cs[0].rest, who: cs[0].who(), model: cs[0].model, effort: cs[0].effort, at: now}
|
||||
}
|
||||
}
|
||||
if a.Kept && i == 0 || !a.Kept && i == 0 && pl.order[0].Rest != nil {
|
||||
return cs, pl // where it is already
|
||||
}
|
||||
a.Kept, a.Why, a.LeadModel = false, "lead", lead.model
|
||||
return cs, pl
|
||||
}
|
||||
|
||||
// sessionNamed reports whether the request names its session in a header
|
||||
// (sessionHeaders or X-Magpie-Session), where affinityID would otherwise
|
||||
// be the hash of how the conversation opens.
|
||||
func sessionNamed(in http.Header) bool {
|
||||
for _, h := range sessionHeaders {
|
||||
if strings.TrimSpace(in.Get(h)) != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(in.Get(SessionHeader)) != ""
|
||||
}
|
||||
|
||||
// spreadsSessions says whether new conversations kept for the whole
|
||||
// session (Stays: Session or Strict) go to the key, account or member the
|
||||
// fewest others are on (leastHeld), under a routing that picks by what
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/routes"
|
||||
)
|
||||
|
||||
// #5655 (jerrychoi; iamnil on Discord): two accounts, one session. Claude
|
||||
// Desktop's own Sonnet calls beside an Opus chat were routed as a session
|
||||
// of their own, their model's conversations apart from the chat's: put
|
||||
// on the account the fewest others held, they ran on account B while the
|
||||
// chat was on A, and B's 5 hours drained on calls the user never made
|
||||
// there. A session's call to another model now goes to the account its
|
||||
// main conversation is on (withSession).
|
||||
func TestSessionSideCallGoesWithItsMainAccount(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &keyed{}
|
||||
serveOn(t, "sl", "k1", []string{"m1", "m2"}, up, "k2")
|
||||
if err := provider.SetAffinity("sl", provider.AffinitySession); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
routes.Forget("sl")
|
||||
s := New()
|
||||
post := func(session, model, msgs string) string {
|
||||
t.Helper()
|
||||
n := len(up.tried)
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"sl/`+model+`","messages":[`+msgs+`]}`))
|
||||
req.Header.Set("x-session-id", session)
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != 200 || len(up.tried) != n+1 {
|
||||
t.Fatalf("%s %s: %d %s, tried %v", session, model, rec.Code, rec.Body.String(), up.tried[n:])
|
||||
}
|
||||
return up.tried[n]
|
||||
}
|
||||
// another session holds the first account on m2
|
||||
other := post("s0", "m2", `{"role":"user","content":"another session's call"}`)
|
||||
// the session's chat, on m1
|
||||
main := post("s1", "m1", `{"role":"user","content":"the chat"}`)
|
||||
if main != other {
|
||||
t.Fatalf("setup: the chat went to %s, the other session's call to %s; both were to be on the first", main, other)
|
||||
}
|
||||
// its own call on m2: on the chat's account, not the one m2's fewest
|
||||
// sessions are on
|
||||
if k := post("s1", "m2", `{"role":"user","content":"a call of the session's own"}`); k != main {
|
||||
t.Errorf("the session's m2 call went to %s while its chat is on %s", k, main)
|
||||
}
|
||||
// the chat never follows its smaller side call
|
||||
if k := post("s1", "m1", `{"role":"user","content":"the chat"},{"role":"assistant","content":"ok"},{"role":"user","content":"more"}`); k != main {
|
||||
t.Errorf("the chat's next turn went to %s, not %s", k, main)
|
||||
}
|
||||
}
|
||||
|
||||
// A side call cached on another account than its session's main
|
||||
// conversation goes to the main's at its next turn, and says so; mid-turn
|
||||
// it stays on the reasoning it sealed, Strict keeps it, and a main
|
||||
// conversation no larger than its own leads nothing.
|
||||
func TestSessionSideCallFollowsItsMain(t *testing.T) {
|
||||
key := func(k string) candidate {
|
||||
return candidate{p: provider.Provider{ID: "sx", Key: k}, model: "m2", rest: "sx#" + k}
|
||||
}
|
||||
h := http.Header{}
|
||||
h.Set("x-claude-code-session-id", "session-lead")
|
||||
turn := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
|
||||
within := []byte(`{"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"f","arguments":"{}"}}]},{"role":"tool","tool_call_id":"c1","content":"ok"}]}`)
|
||||
set := func(t *testing.T, side, main int) {
|
||||
t.Helper()
|
||||
cs := []candidate{key("k1"), key("k2")}
|
||||
sticks.Lock()
|
||||
sticks.m["sx/m2|session-lead"] = stick{rest: cs[1].rest, who: cs[1].who(), model: "m2", turn: 1, at: time.Now(), cacheRead: side}
|
||||
sticks.m["sx/m1|session-lead"] = stick{rest: cs[0].rest, who: cs[0].who(), model: "m1", turn: 1, at: time.Now(), cacheRead: main}
|
||||
sticks.Unlock()
|
||||
t.Cleanup(func() {
|
||||
sticks.Lock()
|
||||
delete(sticks.m, "sx/m2|session-lead")
|
||||
delete(sticks.m, "sx/m1|session-lead")
|
||||
sticks.Unlock()
|
||||
})
|
||||
}
|
||||
run := func(mode string, body []byte) ([]candidate, *Affinity) {
|
||||
cs := []candidate{key("k1"), key("k2")}
|
||||
got, _, aff, _ := affine("sx/m2", mode, false, false, false, h, provider.Chat, body, body, cs, planned{order: make([]Weighed, 2)})
|
||||
return got, aff
|
||||
}
|
||||
t.Run("new turn", func(t *testing.T) {
|
||||
set(t, 60_000, 120_000)
|
||||
for _, mode := range []string{"", provider.AffinitySession} {
|
||||
got, aff := run(mode, turn)
|
||||
if got[0].rest != "sx#k1" || aff.Why != "lead" || aff.Kept || aff.LeadModel != "m1" {
|
||||
t.Errorf("%q: first %s, why %s, kept %v, lead %q; want sx#k1 with its main", mode, got[0].rest, aff.Why, aff.Kept, aff.LeadModel)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("within a turn", func(t *testing.T) {
|
||||
set(t, 60_000, 120_000)
|
||||
if got, aff := run("", within); got[0].rest != "sx#k2" || aff.Why != "turn" {
|
||||
t.Errorf("first %s, why %s; want kept on sx#k2", got[0].rest, aff.Why)
|
||||
}
|
||||
})
|
||||
t.Run("strict", func(t *testing.T) {
|
||||
set(t, 60_000, 120_000)
|
||||
if got, aff := run(provider.AffinityStrict, turn); got[0].rest != "sx#k2" || aff.Why != "strict" {
|
||||
t.Errorf("first %s, why %s; want kept on sx#k2", got[0].rest, aff.Why)
|
||||
}
|
||||
})
|
||||
t.Run("main no larger", func(t *testing.T) {
|
||||
set(t, 120_000, 60_000)
|
||||
if got, aff := run("", turn); got[0].rest != "sx#k2" || aff.Why != "cache" {
|
||||
t.Errorf("first %s, why %s; want kept on sx#k2", got[0].rest, aff.Why)
|
||||
}
|
||||
})
|
||||
// two conversations that only open alike are not one session: with no
|
||||
// session named, the id is the opening's hash
|
||||
t.Run("no session named", func(t *testing.T) {
|
||||
hashed := conversationID(http.Header{}, turn)
|
||||
cs := []candidate{key("k1"), key("k2")}
|
||||
sticks.Lock()
|
||||
sticks.m["sx/m2|"+hashed] = stick{rest: cs[1].rest, who: cs[1].who(), model: "m2", turn: 1, at: time.Now(), cacheRead: 60_000}
|
||||
sticks.m["sx/m1|"+hashed] = stick{rest: cs[0].rest, who: cs[0].who(), model: "m1", turn: 1, at: time.Now(), cacheRead: 120_000}
|
||||
sticks.Unlock()
|
||||
t.Cleanup(func() {
|
||||
sticks.Lock()
|
||||
delete(sticks.m, "sx/m2|"+hashed)
|
||||
delete(sticks.m, "sx/m1|"+hashed)
|
||||
sticks.Unlock()
|
||||
})
|
||||
got, _, aff, _ := affine("sx/m2", "", false, false, false, http.Header{}, provider.Chat, turn, turn, cs, planned{order: make([]Weighed, 2)})
|
||||
if got[0].rest != "sx#k2" || aff.Why != "cache" {
|
||||
t.Errorf("first %s, why %s; want kept on sx#k2", got[0].rest, aff.Why)
|
||||
}
|
||||
})
|
||||
// a main conversation with no cache worth keeping goes where its own
|
||||
// next turn is sent, and leads nothing
|
||||
t.Run("main holds no cache", func(t *testing.T) {
|
||||
set(t, 0, cacheWorth-1)
|
||||
if _, aff := run("", turn); aff.Why == "lead" {
|
||||
t.Errorf("why %s; a main with %d cached led", aff.Why, cacheWorth-1)
|
||||
}
|
||||
})
|
||||
t.Run("main's account resting", func(t *testing.T) {
|
||||
set(t, 60_000, 120_000)
|
||||
cs := []candidate{key("k2"), key("k1")}
|
||||
order := []Weighed{{}, {Rest: &Rest{}}}
|
||||
got, _, aff, _ := affine("sx/m2", "", false, false, false, h, provider.Chat, turn, turn, cs, planned{order: order})
|
||||
if got[0].rest != "sx#k2" || aff.Why != "cache" {
|
||||
t.Errorf("first %s, why %s; want kept on sx#k2", got[0].rest, aff.Why)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1109,6 +1109,7 @@ function routingPage(part) {
|
||||
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}: {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 "lead": return t("Put on {first}, where this session's {model} is: one session goes on one account.", { first: who(r.order[0]), model: a.leadModel || "" });
|
||||
case "strict": return a.main ? t("{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.", { who: last, first: who(a.main) }) : null;
|
||||
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]) })
|
||||
|
||||
@@ -623,6 +623,7 @@ magpie.strings({
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "此会话上次由备用 {who} 回答,但提供商自己的 {first} 已恢复可用,所以第 {n} 轮回到它。",
|
||||
"{who} took this conversation while {first}, listed ahead of it in the group, couldn't; {first} is ready again, so turn {n} goes back to it.": "此会话由 {who} 接手,当时组里排在它前面的 {first} 无法处理;{first} 已恢复可用,所以第 {n} 轮回到它。",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "此会话上次由备用 {who} 回答。提供商自己的 {first} 已恢复可用,但会话保持设为严格,从不移动会话,所以它留在备用上;新会话会走 {first}。",
|
||||
"Put on {first}, where this session's {model} is: one session goes on one account.": "放在 {first} 上,也就是这个会话的 {model} 所在的账号:一个会话只走一个账号。",
|
||||
"{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.": "亲和性已关闭:每个请求都重新路由,不论之前由谁回答。",
|
||||
@@ -1302,6 +1303,7 @@ magpie.strings({
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "此會話上次由備用 {who} 回答,但供應商自己的 {first} 已恢復可用,所以第 {n} 輪回到它。",
|
||||
"{who} took this conversation while {first}, listed ahead of it in the group, couldn't; {first} is ready again, so turn {n} goes back to it.": "此會話由 {who} 接手,當時群組裡排在它前面的 {first} 無法處理;{first} 已恢復可用,所以第 {n} 輪回到它。",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "此會話上次由備用 {who} 回答。供應商自己的 {first} 已恢復可用,但會話保持設為嚴格,從不移動會話,所以它留在備用上;新會話會走 {first}。",
|
||||
"Put on {first}, where this session's {model} is: one session goes on one account.": "放在 {first} 上,也就是這個會話的 {model} 所在的帳號:一個會話只走一個帳號。",
|
||||
"{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.": "親和性已關閉:每個請求都重新路由,不論之前由誰回答。",
|
||||
@@ -1979,6 +1981,7 @@ magpie.strings({
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "この会話に前回応答したのは代替の {who} ですが、プロバイダー自身の {first} が再び使えるため、ターン {n} はそちらに戻ります。",
|
||||
"{who} took this conversation while {first}, listed ahead of it in the group, couldn't; {first} is ready again, so turn {n} goes back to it.": "この会話は、グループでその前にある {first} が受けられなかったため {who} が引き継ぎました。{first} が再び使えるため、ターン {n} はそちらに戻ります。",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "この会話に前回応答したのは代替の {who} です。プロバイダー自身の {first} は再び使えますが、維持が「厳格」で会話を移さないため、代替のままです。新しい会話は {first} に行きます。",
|
||||
"Put on {first}, where this session's {model} is: one session goes on one account.": "このセッションの {model} がいる {first} に置きました。1 つのセッションは 1 つのアカウントで動きます。",
|
||||
"{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.": "アフィニティはオフです:以前誰が会話に応答したかに関係なく、各リクエストを新たにルーティングします。",
|
||||
@@ -2658,6 +2661,7 @@ magpie.strings({
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "{who}, ein Ersatz, hat diese Unterhaltung zuletzt beantwortet, aber {first} des Anbieters selbst ist wieder bereit, daher geht Runde {n} dorthin zurück.",
|
||||
"{who} took this conversation while {first}, listed ahead of it in the group, couldn't; {first} is ready again, so turn {n} goes back to it.": "{who} hat diese Unterhaltung übernommen, als {first}, in der Gruppe davor, sie nicht annehmen konnte; {first} ist wieder bereit, daher geht Runde {n} dorthin zurück.",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "{who}, ein Ersatz, hat diese Unterhaltung zuletzt beantwortet. {first} des Anbieters selbst ist wieder bereit, aber Bleibt steht auf Strikt, das eine Unterhaltung nie verschiebt, daher bleibt sie beim Ersatz; neue Unterhaltungen gehen an {first}.",
|
||||
"Put on {first}, where this session's {model} is: one session goes on one account.": "Auf {first} gelegt, wo das {model} dieser Sitzung läuft: eine Sitzung bleibt auf einem Konto.",
|
||||
"{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.",
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
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");
|
||||
|
||||
// #5655 (jerrychoi; iamnil on Discord): a session's call to another model
|
||||
// than its chat's (Claude Desktop's own Sonnet beside an Opus chat) goes
|
||||
// to the account the chat is on (withSession, why "lead"), and the
|
||||
// Routing page says so, naming the chat's model.
|
||||
const words = {
|
||||
en: ["where this session's", "claude-opus-5-5", "one account"],
|
||||
zh: ["这个会话的", "claude-opus-5-5", "一个账号"],
|
||||
"zh-TW": ["這個會話的", "claude-opus-5-5", "一個帳號"],
|
||||
ja: ["このセッションの", "claude-opus-5-5", "1 つのアカウント"],
|
||||
de: ["dieser Sitzung", "claude-opus-5-5", "einem Konto"],
|
||||
};
|
||||
|
||||
function routes(now) {
|
||||
const time = new Date(now.getTime() - 5000).toISOString();
|
||||
const at = new Date(now.getTime() - 65000).toISOString();
|
||||
const a = { id: "claude#a", provider: "claude", name: "Claude", kind: "account", who: "a@example.com", model: "claude-sonnet-5" };
|
||||
const b = { id: "claude#b", provider: "claude", name: "Claude", kind: "account", who: "b@example.com", model: "claude-sonnet-5" };
|
||||
return [{ id: 1, seq: 1, time, agent: "claude-desktop", model: "claude/claude-sonnet-5", provider: "claude", order: [a, b], done: true, status: 200, ms: 20,
|
||||
affinity: { mode: "", turn: 3, last: "claude#b", lastTurn: 2, at, cacheRead: 68925, cacheWrite: 110000, why: "lead", leadModel: "claude-opus-5-5" },
|
||||
tries: [{ id: a.id, model: "claude-sonnet-5", 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 a side call went with its session's account`, 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);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const now = new Date();
|
||||
await page.route("**/*", serve(lang, () => routes(now), now));
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
await page.waitForFunction(() => /\d/.test(document.body.innerText) && document.querySelector(".rt-cap")?.textContent);
|
||||
const text = await page.evaluate(() => document.body.innerText + "\n" + document.querySelector(".rt-cap").textContent);
|
||||
for (const w of words[lang]) assert.ok(text.includes(w), `${w} not in\n${text}`);
|
||||
assert.doesNotMatch(text, /\{(first|model)\}/);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user