diff --git a/internal/cli/accounts_cli.go b/internal/cli/accounts_cli.go index d9f517f62..2227aab50 100644 --- a/internal/cli/accounts_cli.go +++ b/internal/cli/accounts_cli.go @@ -221,6 +221,7 @@ func accountsCmd(args []string) error { if err := provider.SwitchLogin(id, args[3]); err != nil { return err } + provider.NoteReordered() if _, plug := provider.PluginOf(id); plug || id == "gemini" || id == "antigravity" || id == "copilot" { fmt.Println(green.Render("✓"), "magpie now uses", args[3], "for", id) return nil diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index bbc6ba74f..54f1cb18a 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -571,6 +571,14 @@ func affine(scope, mode string, rotate, spread, inOrder, hoursOver bool, in http if had && time.Since(st.at) > stickKeep { had = false } + if had && mode == "" && !a.Within && st.at.Before(provider.ReorderedAt()) { + // the user put the accounts in another order after this + // conversation was last answered: the order they chose counts at + // its next turn, whatever the old answerer cached (Richyisaflower + // on X: B moved above A, the conversation went on to A). Session + // and Strict, the user's own, and a turn under way keep it + had = false + } if had { a.Last, a.LastTurn, a.At, a.CacheRead, a.CacheWrite = st.rest, st.turn, st.at, st.cacheRead, st.cacheWrite } diff --git a/internal/gateway/reorder_breaks_stick_test.go b/internal/gateway/reorder_breaks_stick_test.go new file mode 100644 index 000000000..0d87c1552 --- /dev/null +++ b/internal/gateway/reorder_breaks_stick_test.go @@ -0,0 +1,73 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// Richyisaflower on X: B moved above A in the pool, and the Codex +// conversation still went to A, kept there by its cache. The order the user +// just chose counts at the conversation's next turn (provider.NoteReordered +// in SetAccountOrder, Make first); a turn under way, and Stays: Session, +// keep it where it is. +func TestReorderedAccountsTakeTheConversationAtItsNextTurn(t *testing.T) { + for _, c := range []struct { + name, mode string + reorder bool + want string + }{ + {"reordered", "", true, "k1 k2 k2"}, + {"not reordered keeps its cache", "", false, "k1 k1 k1"}, + {"session keeps it", provider.AffinitySession, true, "k1 k1 k1"}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + up := &cacheWriter{wrote: 3000} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + p := provider.Provider{ID: "ord", Name: "Ord", Key: "k1", Keys: []provider.KeyAccount{{Key: "k2"}}, + Models: []string{"m1"}, Anthropic: srv.URL + "/v1", Affinity: c.mode} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + forgetRouting() + s := New() + t.Cleanup(s.subscription.abortAll) + conv := `{"role":"user","content":"fix the bug"}` + var got []string + for i := range 3 { + if i == 1 && c.reorder { + ids := p.KeyList() + if err := provider.SetAccountOrder("ord", []string{ids[1].ID, ids[0].ID}); err != nil { + t.Fatal(err) + } + forgetRouting() + } + body := `{"model":"ord/m1","max_tokens":100,"messages":[` + conv + `]}` + r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)) + r.Header.Set("x-claude-code-session-id", "s-reorder") + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, r) + if rec.Code != 200 { + t.Fatalf("request %d: %d %s", i, rec.Code, rec.Body) + } + out := rec.Body.String() + switch { + case strings.Contains(out, "from k1"): + got = append(got, "k1") + case strings.Contains(out, "from k2"): + got = append(got, "k2") + default: + t.Fatalf("request %d answered by nobody known: %s", i, out) + } + conv += `,{"role":"assistant","content":"done"},{"role":"user","content":"and more"}` + } + if g := strings.Join(got, " "); g != c.want { + t.Fatalf("answered by %s, want %s", g, c.want) + } + }) + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index a12fcddf9..efab87f18 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -3037,7 +3037,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) { var change func() error switch r.PathValue("action") { case "switch": - change = func() error { return provider.SwitchLogin(in.Agent, in.User) } + change = func() error { + err := provider.SwitchLogin(in.Agent, in.User) + if err == nil { + provider.NoteReordered() + } + return err + } case "forget": change = func() error { return provider.ForgetLogin(in.Agent, in.User) } case "on", "off": diff --git a/internal/provider/account_order.go b/internal/provider/account_order.go index 251685de5..5a4f5d7b2 100644 --- a/internal/provider/account_order.go +++ b/internal/provider/account_order.go @@ -1,11 +1,41 @@ package provider -import "fmt" +import ( + "fmt" + "sync/atomic" + "time" +) + +var reorderedAt atomic.Int64 + +// NoteReordered records that the user just changed which account goes +// first (a drag in the pool, Make first, the CLI), so a conversation +// last answered before it is routed anew at its next turn (the gateway's +// affine) instead of staying with the account the user moved down. +func NoteReordered() { reorderedAt.Store(time.Now().UnixNano()) } + +// ReorderedAt is when NoteReordered was last called in this process; the +// zero time before. +func ReorderedAt() time.Time { + n := reorderedAt.Load() + if n == 0 { + return time.Time{} + } + return time.Unix(0, n) +} // SetAccountOrder changes the order used by routing, not just its presentation. // The first enabled account becomes first through the same switch used by Make // first, unless the agent is kept signed in to another (KeepLoginAs). Disabled accounts can be moved, but never silently enabled by a drag. func SetAccountOrder(id string, order []string) error { + err := setAccountOrder(id, order) + if err == nil { + NoteReordered() + } + return err +} + +func setAccountOrder(id string, order []string) error { p, err := Find(id) if err != nil { return err