Files
magpie/internal/provider/workbuddy_ai_test.go
T
yetone 5e5b6a5ac3 provider: every account of a provider keeps its queue, limits and routing, not only the first (#1899)
A second WorkBuddy AI account queued requests for 62s with the provider's
queue wait set to 1s. The gateway takes each candidate's QueueLimit,
QueueWait, LaneLimit (MaxConcurrency) and Routing from the Provider value
it is handed. The account the agent is signed in to comes from All, which
lays the user's saved picks from providers.json over it. The other accounts
on beside it come from AlsoOn. For Claude and Codex, AlsoOn copies p, so they
had the picks. Every other sign-in builds its extra accounts afresh: all
plugin accounts (pluginAlsoOn) and the built-in extras (WorkBuddy, Grok,
Copilot, ZCode, Kiro, Devin, Command Code, Qoder, Zed, Factory, MiMo, the
Gemini sign-ins). They had none of the picks. A few getters (LaneLimit,
RPMLimit, AccountCap, proxy) already fell back to providers.json. The queue,
the provider-wide concurrency and routing did not, so an extra account
waited forever on a full lane.

The overlay All does is now withPicks. AlsoOn calls it on every account it
returns, from p as All has it. This one choke point covers every sign-in's
extra accounts, plugin and built-in, moved or not. The LaneLimit, RPMLimit
and AccountCap comments now say what still reads providers.json, and so
does gateway-routing.md's Limits row.

Tests:
- TestPluginSecondAccountKeepsTheQueue (gateway, fake plugin under bun):
  two accounts, one at once each, a queue of 1 and a wait of 1s, every
  request pinned to the second account. The third request gets 429 "queue
  is full" at once, and the queued one gets 429 "waited" after its second.
  The vendor sees only the second key.
- TestWorkBuddyAI: the second account from AlsoOn has the provider's
  queue 1/1s, MaxRPM 7, Routing ordered and LaneLimit 2.

Broken by hand (AlsoOn returning alsoOn's accounts as they are):
- The gateway test fails at its AlsoOn check. With that check off, it
  fails on "no reply in 10s", which is the reporter's symptom.
- TestWorkBuddyAI fails with "queue 0, wait 0s, rpm 0, routing "", at once 0".

Run (sandbox HOME, private GOCACHE, worktree): gofmt -l; go test -tags
nogui on ./internal/provider, ./internal/gateway, ./internal/gui,
./internal/cli and ./internal/agent; GOOS=linux and GOOS=windows go vet
-tags nogui on internal/provider and internal/gateway. Not tried with a
real WorkBuddy AI account.
2026-10-13 12:34:48 +08:00

174 lines
6.5 KiB
Go

package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// WorkBuddy AI, the international build, is a subscription of its own: its
// own account file, its own endpoint and sign-in platform, its own models,
// and its accounts kept apart from the Chinese build's.
func TestWorkBuddyAI(t *testing.T) {
home := signIn(t)
wbTokens.Lock()
wbTokens.m = map[string]wbCreds{}
wbTokens.Unlock()
future := time.Now().Add(24 * time.Hour).UnixMilli()
own := func(path, uid, name, access, domain string) {
writeFile(t, path, map[string]any{
"account": map[string]any{"uid": uid, "nickname": name},
"auth": map[string]any{"accessToken": access, "refreshToken": "r",
"expiresAt": future, "refreshExpiresAt": future, "domain": domain},
})
}
aiFile := filepath.Join(filepath.Dir(wbAuthFile(home)), "workbuddy-desktop-ai.info")
own(wbAuthFile(home), "cn1", "国内", "cn-access", "www.codebuddy.cn")
own(aiFile, "ai1", "Abroad", "ai-access", "www.codebuddy.ai")
cn := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("WorkBuddy AI asked the Chinese endpoint: %s", r.URL)
w.WriteHeader(500)
}))
defer cn.Close()
var platform string
ai := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ok := func(data any) { json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": data}) }
switch r.URL.Path {
case "/v2/plugin/auth/state":
platform = r.URL.Query().Get("platform")
ok(map[string]any{"state": "s1", "authUrl": "https://www.workbuddy.ai/login?platform=workbuddy-ai&state=s1"})
case "/v2/plugin/auth/token":
ok(map[string]any{"accessToken": "ai2-access", "refreshToken": "ai2-refresh",
"expiresIn": 3600, "refreshExpiresIn": 7200, "domain": "www.codebuddy.ai"})
case "/v2/plugin/login/account":
ok(map[string]any{"uid": "ai2", "nickname": "Second"})
case "/billing/meter/get-user-resource-summary":
if r.Header.Get("Authorization") != "Bearer ai-access" || r.Header.Get("X-Domain") != "www.codebuddy.ai" {
w.WriteHeader(401)
return
}
ok(map[string]any{"IsPaidUser": false, "Packages": []any{
map[string]any{"CycleTotalCapacity": "1000", "CycleUsedCapacity": "100"},
}})
default:
w.WriteHeader(404)
}
}))
defer ai.Close()
oldCN, oldAI, oldInt := wbEndpoint, wbAIEndpoint, wbPollInterval
wbEndpoint, wbAIEndpoint, wbPollInterval = cn.URL, ai.URL, 5*time.Millisecond
defer func() { wbEndpoint, wbAIEndpoint, wbPollInterval = oldCN, oldAI, oldInt }()
st, err := StartSignIn(WorkBuddyAIID)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if st, _ = WaitSignIn(ctx, st.ID); st.State != "done" || st.User != "Second" {
t.Fatalf("sign-in: %+v", st)
}
if platform != "workbuddy-ai" {
t.Fatalf("platform %q", platform)
}
names := func(agent string) (out []string) {
for _, l := range Logins(agent) {
out = append(out, l.User)
}
return out
}
if got := names(WorkBuddyAIID); len(got) != 2 || got[0] != "Abroad" || got[1] != "Second" {
t.Fatalf("WorkBuddy AI logins: %v", got)
}
if got := names("workbuddy"); len(got) != 1 || got[0] != "国内" {
t.Fatalf("WorkBuddy logins: %v", got)
}
p, ok := find(All(), WorkBuddyAIID)
if !ok || p.Name != "WorkBuddy AI" || p.Account.User != "Abroad" || p.Chat != ai.URL+"/v2" || p.Account.Agent != WorkBuddyAIID {
t.Fatalf("provider: %+v", p)
}
if ms := p.Account.models(); len(ms) != len(wbAIModels) || ms[0].ID != "default-model" {
t.Fatalf("models: %+v", ms)
}
req, _ := http.NewRequest("POST", p.Chat+"/chat/completions", nil)
if err := p.Sign(context.Background(), req, Chat, []byte(`{}`)); err != nil ||
req.Header.Get("Authorization") != "Bearer ai-access" || req.Header.Get("X-Domain") != "www.codebuddy.ai" {
t.Fatalf("sign: %v %v", err, req.Header)
}
// a chat with no system prompt is given one (#124)
if got := string(p.Prepare([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`))); !strings.HasPrefix(got, `{"messages":[{"content":"`+wbSystem+`","role":"system"},{"content":"hi","role":"user"}]`) {
t.Errorf("prepare: %s", got)
}
// what WorkBuddy's own chats carry besides the account's
for h, want := range map[string]string{"X-Requested-With": "XMLHttpRequest", "X-Agent-Intent": "craft",
"X-IDE-Type": "WorkBuddy", "X-IDE-Name": "WorkBuddy", "X-IDE-Version": wbUAVersion, "X-Product": "SaaS"} {
if got := req.Header.Get(h); got != want {
t.Errorf("%s: %q, want %q", h, got, want)
}
}
for _, h := range []string{"X-Conversation-ID", "X-Conversation-Request-ID", "X-Conversation-Message-ID", "X-Request-ID"} {
if len(req.Header.Get(h)) != 32 {
t.Errorf("%s: %q", h, req.Header.Get(h))
}
}
if req.Header.Get("X-Request-ID") == req.Header.Get("X-Conversation-ID") {
t.Error("the request id is the conversation's")
}
if also := p.AlsoOn(); len(also) != 1 || also[0].Account.User != "Second" || also[0].ID != WorkBuddyAIID {
t.Fatalf("also on: %+v", also)
}
// the second account keeps what was set on the provider, as the first
// does: its queue (#1899), how many go at once, its routing
if err := SetQueue(WorkBuddyAIID, 1, 1); err != nil {
t.Fatal(err)
}
if err := SetRPM(WorkBuddyAIID, 7); err != nil {
t.Fatal(err)
}
if err := SetRouting(WorkBuddyAIID, Ordered); err != nil {
t.Fatal(err)
}
two := 2
pk, _ := Find(WorkBuddyAIID)
pk.MaxConcurrency = &two
if err := Save(*pk); err != nil {
t.Fatal(err)
}
p, _ = find(All(), WorkBuddyAIID)
for _, q := range append([]Provider{p}, p.AlsoOn()...) {
if q.QueueLimit != 1 || q.QueueWait != 1 || q.MaxRPM != 7 || q.Routing != Ordered || q.LaneLimit() != 2 {
t.Errorf("%s: queue %d, wait %ds, rpm %d, routing %q, at once %d; want the provider's 1, 1s, 7, %q, 2",
q.Account.User, q.QueueLimit, q.QueueWait, q.MaxRPM, q.Routing, q.LaneLimit(), Ordered)
}
}
if cnp, ok := find(All(), "workbuddy"); !ok || cnp.Account.User != "国内" || cnp.Chat != cn.URL+"/v2" {
t.Fatalf("WorkBuddy: %+v", cnp)
}
q := LoginUsage(context.Background(), WorkBuddyAIID)["Abroad"]
if q.Error != "" || q.Provider != WorkBuddyAIID || q.Plan != "Free" || len(q.Windows) != 1 || q.Windows[0].Used != 10 {
t.Fatalf("usage: %+v", q)
}
if err := ForgetLogin(WorkBuddyAIID, "Second"); err != nil {
t.Fatal(err)
}
os.Remove(aiFile)
if _, ok := find(All(), WorkBuddyAIID); ok {
t.Fatal("WorkBuddy AI without an account")
}
if _, ok := find(All(), "workbuddy"); !ok {
t.Fatal("WorkBuddy went with it")
}
}