From 091593f7d37c8b37da7507d475bc1e7c3621c304 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 13 Oct 2026 02:47:29 +0800 Subject: [PATCH] gateway, gui: a WorkBuddy account the vendor restricted (403 11140) rests 2 hours as restricted, and Routing names the appeal as the way back (#1849) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WorkBuddy answers an account it restricted for unusual activity with 403 {"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",...}}. failure() read it as an unknown failure, so the account rested 1-10 minutes and was asked again, refused, all day. What changed: - provider: WBRestricted knows the refusal by code 11140 (top level, data or error; number or string; whole, so 111400 isn't it) or by its displayMsg words. wbExplain ends the built-in's error with WBRestrictedHint. - gateway: a new failRestricted ("restricted") rests restrictedRest, 2h: one refused request per account per 2h, and a lifted restriction (or a misread refusal) comes back the same afternoon; Unrest lifts it at once. It is read from the hint in the error (restrictedSaid; both the built-in and the plugin translate the vendor's body before failure() sees it, so the raw JSON never reaches it in a chat try), or from the raw body only for a WorkBuddy candidate (restrictedRefused, isWorkBuddy), since another vendor's 11140 is its own. Bare "request illegal" is not matched. 11128 stays promptRefused and rests nobody. The stale-allowance shortcut skips it, as it does model refusals. drawsWorkBuddy now uses isWorkBuddy. - plugin: @magpie-community/opencode-workbuddy-auth 0.1.17 (plugins caf3908) ends the error with the same hint; the mover's min is 0.1.17 so keepMovedCurrent brings moved users to it. - gui: Routing labels the try "account restricted by the vendor", says it rests because only the vendor lifting it brings it back and to appeal, shows the hint translated, and the account's row has "The restriction is lifted — try it again" (POST /api/gateway/unrest). en, zh, zh-TW, ja, de. - docs/subsystems/gateway-routing.md says the above. Run: gofmt -l (clean); go vet darwin, GOOS=linux -tags nogui, GOOS=windows on gateway, provider, gui; go test ./internal/gateway ./internal/provider ./internal/gui (ok). New Go tests use the reporter's literal body through the vendor's shape, the built-in's and the plugin's, a string code and the words alone; another vendor's 11140, a non-WorkBuddy account with the same body, 11128/14018/111400 not restricted; an e2e through the fake plugin host where the restricted account is skipped by the next request. Broken by hand, each went red: rest case removed, restrictedSaid removed, the match unscoped, the raw match removed, the provider hint removed. GUI: routing-wb-restricted (chromium and webkit x en/zh/zh-TW/ja/de x 1100/420px, 20 pass), routing-wb-refused, i18n-keys; after the rebase every GUI test of the Routing page (107 files, both engines): 103 green. The 4 red ones fail the same in WebKit on origin/main 689edbd6b run alone and are filed: group-member-info (#1745), routing-sessions (#1307, #1672), routing-steady (#1804, passed on this head on a rerun), routing-group-fold's group-of-eight (#1672). Rebased onto 2c30e5cee (with #1672's test fixes) and run again: vet x3, go test ./internal/gateway ./internal/provider ok. On the final base 5756651e3 (only GUI assets and READMEs changed since): routing-wb-restricted 20/20, routing-wb-refused, i18n-keys, routing-held-dot, mono-icon-redraw, routing-sessions 38/38, routing-group-fold 40/40; routing-steady's WebKit case red again, the flake filed as #1804. Not tried against a real restricted account; plugin users on <0.1.17 rest by minutes until their plugin updates. --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/draw_workbuddy.go | 9 +- internal/gateway/routing.go | 62 +++- internal/gateway/workbuddy_restricted_test.go | 276 ++++++++++++++++++ internal/gui/assets/i18n.js | 16 + internal/gui/assets/routing.js | 19 +- .../gui/tests/routing-wb-restricted.test.cjs | 129 ++++++++ internal/provider/migrate_workbuddy.go | 2 +- internal/provider/workbuddy.go | 54 +++- internal/provider/workbuddy_refused_test.go | 8 + 10 files changed, 557 insertions(+), 20 deletions(-) create mode 100644 internal/gateway/workbuddy_restricted_test.go create mode 100644 internal/gui/tests/routing-wb-restricted.test.cjs diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 401cf9459..dceb0fca1 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -45,7 +45,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). - A rule by folder (`Rule.Folders`, `folders=~/work/acme,~/oss`; Cario0x on X: routing by the project being worked on) matches when the folder the agent works in is one of them or inside one (`provider.FolderUnder`, [`rulefolder.go`](../../internal/provider/rulefolder.go)): at a path's boundary, so `/a/b` is not under `/a/bc`; `~` is the home folder; a Windows drive is one with its WSL mount (`C:\work` is `/mnt/c/work`) and a `\\wsl$\` or `\\wsl.localhost\` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (`Rule.ExceptFolders`, `except-folders=~/big-task`; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (`Rule.ByFolder`, `inFolders`). The folder is read from the request only when a rule of the group has folders or except-folders (`workDir` in [`workdir.go`](../../internal/gateway/workdir.go)), in each agent's own words, taken from captured requests: Claude Code's ` - Primary working directory: ` (its `<`/`>` as entities; ` (was )` after a change dropped), Codex's `` ``, Pi's `` in the system prompt, and OpenCode's `Working directory:` inside its `` block. Only the system prompt and the user's and system messages' text count, never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no `folders=` rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works ([provider-plugins](provider-plugins.md#where-the-agent-works-for-a-plugins-fetch)). A pause rule may hold by folder too (below). The trace's `RuleHit.Folder` is the folder read, and the Routing page tells it beside the rule's `folder …` condition. `TestFolderUnder`, `TestRuleMatchesByFolder`, `TestParseRuleFolders`, `TestWorkDirOfEachAgent`, `TestRuleByFolder`, `TestRuleMatchesExceptFolders`, `routing-folder.test.cjs`. Rules by folder are never in a shared group (`ShareGroup` drops every `ByFolder` rule). - A pause rule (`Rule.Pause`, `pause=`; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (`provider.PausedOut`, on `ruleClock`): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (`cleanRules` refuses another condition), and is not a send-to rule: `Matches`, `MatchRule`, `ThenUses`, `Ruled` and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (`GroupRef.Paused`), and the Routing page says so. Every model paused answers 503 (`pausedError`) naming each rule. Embeddings go by the same pauses; manual groups have no rules (`Live`), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder, `pause= except-folders=~/big-task`) reads the folder only when such a pause is on the way (`provider.PausesByFolder`, then `workDir`): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; with `folders=`, only requests known to be in them. Embeddings and System One's decision calls have no folder. `Paused.Folder`/`ByFolder` carry what was read, and the Routing page says the folder or that none was said. `rules_pause_test.go`, `TestPauseByFolder`, `TestPauseByFolderRule`, `TestParsePauseByFolder`, `routing-pause-folder.test.cjs`. 3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`); otherwise a capped or barred set returns `cappedError` or `barredError`. Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. -4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged. siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. +4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged. siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. 5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`). When every member has failed in a way that passes (`busy`: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota or response protection, or a 429 that is a short rate limit, not a plan or credit), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest` (30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on for at most `replanRounds` (6) rounds and only while the group's `Patience` lasts, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 is `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error. While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider keeps only the same-one retries `passing` gives the last one left. A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. ## Constraints and failure behavior diff --git a/internal/gateway/draw_workbuddy.go b/internal/gateway/draw_workbuddy.go index 8a8b67754..fd5503e87 100644 --- a/internal/gateway/draw_workbuddy.go +++ b/internal/gateway/draw_workbuddy.go @@ -43,14 +43,7 @@ const ( // drawsWorkBuddy is whether p is a WorkBuddy plan, the China build's or // WorkBuddy AI's: the built-in's, or the WorkBuddy plugin's. func drawsWorkBuddy(p provider.Provider) bool { - if p.Account == nil || p.Base(provider.Chat) == "" { - return false - } - id := p.PluginProvider() - if id == "" { - id = p.Account.Agent - } - return id == "workbuddy" || id == provider.WorkBuddyAIID + return isWorkBuddy(p) && p.Base(provider.Chat) != "" } // wbImageModel is an image model a WorkBuddy config lists. diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 5b4bb45ab..0a0d43afd 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -110,6 +110,15 @@ const ( // is answered that way by magpie without asking again: an agent's // reconnects don't all land on the account Google has stopped verifyHold = time.Minute + // restrictedRest: an account its vendor restricted (WorkBuddy's 403 + // 11140, #1849) is out until the vendor lifts it, which takes an + // appeal, not a wait: hours, not the minutes of a backoff, so a group + // stops walking every restricted account on every request. Two hours + // costs one refused request per account every two hours, and a + // restriction lifted (or a refusal read wrong) is back the same + // afternoon without anyone acting; the Routing page lifts it at once + // (Unrest) for a user whose appeal went through + restrictedRest = 2 * time.Hour ) var ( @@ -206,6 +215,10 @@ const ( // failLoop: the reply was ended stuck in a loop (#1359) — the agent // is told, and nobody rests, as the model, not the account, looped failLoop = "loop" + // failRestricted: the vendor restricted the account itself (WorkBuddy's + // 403 11140, "账号存在异常行为,已被限制使用", #1849) — the next is + // asked, and it rests restrictedRest, until the vendor lifts it + failRestricted = "restricted" ) // loopErrType is the usage log's ErrType for a reply ended for looping @@ -260,6 +273,8 @@ func failure(status int, body []byte) string { // the words are matched decoded, too body = wordsOf(body) switch { + case restrictedSaid(status, body): + return failRestricted case overflowed(status, body): // Kimi's "exceeded model token limit" is the conversation's // length, not the plan's @@ -294,9 +309,46 @@ func failureOf(c candidate, status int, body []byte) string { if provider.RevokedAccount(c.p.Account) && provider.SignInRevoked(status, body) { return failAuth } + if restrictedRefused(c.p, status, body) { + return failRestricted + } return failure(status, body) } +// restrictedSaid says an error is one magpie already put in words as an +// account its vendor restricted: WorkBuddy's 11140 as the built-in +// translates it, or as the plugin does, both ending in +// provider.WBRestrictedHint. magpie's own words, which no vendor says, so +// they are read whoever answered. +func restrictedSaid(status int, body []byte) bool { + return status >= 400 && bytes.Contains(body, []byte(provider.WBRestrictedHint)) +} + +// restrictedRefused says p's vendor restricted the account: magpie's words +// for it (restrictedSaid), or WorkBuddy's own answer as it came — its code +// 11140 or its displayMsg's words — from a WorkBuddy account, the +// built-in's or the plugin's. Another vendor's code 11140 is its own, and +// isn't read so. +func restrictedRefused(p provider.Provider, status int, body []byte) bool { + if restrictedSaid(status, body) { + return true + } + return isWorkBuddy(p) && provider.WBRestricted(status, wordsOf(body)) +} + +// isWorkBuddy is whether p is a WorkBuddy account, either build's: the +// built-in's, or the WorkBuddy plugin's. +func isWorkBuddy(p provider.Provider) bool { + if p.Account == nil { + return false + } + id := p.PluginProvider() + if id == "" { + id = p.Account.Agent + } + return id == "workbuddy" || id == provider.WorkBuddyAIID +} + // openRouterSharedPool says an OpenRouter free model was refused by the // provider's shared pool, rather than by OpenRouter's account-wide free tier. func openRouterSharedPool(body []byte) bool { @@ -319,7 +371,8 @@ type Rest struct { // vendor's own headers), "resets" (the time Claude Code gave), "window" // (the allowance window it filled renews), "quota" (no word of when), // "cooldown" (a minute), "backoff" (longer each time it fails again, - // or is rate limited again as soon as it is back). + // or is rate limited again as soon as it is back), "restricted" (the + // vendor restricted the account: two hours, or until lifted by hand). By string `json:"by"` Failures int `json:"failures,omitempty"` // in a row, for a backoff // Key is what it rests by, for the app to lift the rest (Unrest) @@ -526,6 +579,9 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo if c.full(now).IsZero() && !(c.isOpenRouterFree() && sharedPool) { sink(c.restKey(), now) } + case failRestricted: + // out until the vendor lifts it: an appeal, not a wait (#1849) + d, r.By = restrictedRest, "restricted" case failVerify: d, r.By = verifyRest, "verify" // the error as the agent was given it, and the link in it @@ -557,9 +613,9 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo } // an account is kept by the agent its usage is asked of: a plugin's // by the plugin's provider ("plugin:grok"), not by "plugin" - if a := c.p.Account; a != nil && why != failOther && why != failVerify { + if a := c.p.Account; a != nil && why != failOther && why != failVerify && why != failRestricted { staleAllowance(a.UsageAgent(), a.User) // ask again what it has left - } else if a == nil && why != failOther && why != failVerify { + } else if a == nil && why != failOther && why != failVerify && why != failRestricted { staleKeyAllowance(c.p) // a key that reads its windows, too } r.Until = now.Add(d) diff --git a/internal/gateway/workbuddy_restricted_test.go b/internal/gateway/workbuddy_restricted_test.go new file mode 100644 index 000000000..229d5faca --- /dev/null +++ b/internal/gateway/workbuddy_restricted_test.go @@ -0,0 +1,276 @@ +package gateway + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// wbRestrictedBody is WorkBuddy's 403 for an account it restricted, byte +// for byte as #1849 gives it. +const wbRestrictedBody = `{"code":11140,"msg":"request illegal", + "displayMsg":{"en":"Your account has been restricted due to unusual activity", + "zh":"账号存在异常行为,已被限制使用","zh-hant":"帳號存在異常行為,已被限制使用"}, + "displayTips":{"en":"We detected unusual activity on this account. Submit feedback to appeal this restriction", + "zh":"系统检测到该账号存在异常使用行为,如需申诉请提交反馈"}, + "actions":["EDIT_INPUT","SUBMIT_FEEDBACK"]}` + +// wbAISignedIn signs WorkBuddy AI's desktop app in under the test's HOME +// and gives its provider, its chat endpoint at base. +func wbAISignedIn(t *testing.T, base string) provider.Provider { + t.Helper() + home := os.Getenv("HOME") + t.Setenv("USERPROFILE", home) + dir := filepath.Join(home, ".local", "share") + switch runtime.GOOS { + case "darwin": + dir = filepath.Join(home, "Library", "Application Support") + case "windows": + dir = filepath.Join(home, "AppData", "Local") + } + future := strconv.FormatInt(time.Now().Add(24*time.Hour).UnixMilli(), 10) + info := `{"account":{"uid":"u1","nickname":"me"},"auth":{"accessToken":"a","refreshToken":"r","expiresAt":` + future + + `,"refreshExpiresAt":` + future + `,"domain":"www.codebuddy.ai"}}` + auth := filepath.Join(dir, "CodeBuddyExtension", "Data", "Public", "auth", "workbuddy-desktop-ai.info") + if err := os.MkdirAll(filepath.Dir(auth), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(auth, []byte(info), 0o600); err != nil { + t.Fatal(err) + } + for _, p := range provider.All() { + if p.ID == provider.WorkBuddyAIID && p.Account != nil { + p.Chat = base + "/v2" // never the real endpoint + return p + } + } + t.Fatal("WorkBuddy AI isn't signed in") + return provider.Provider{} +} + +// restedFor is how long r rests from when it was decided. +func restedFor(r Rest, from time.Time) time.Duration { return r.Until.Sub(from) } + +// WorkBuddy's 403 11140 says the account itself is restricted (#1849): in +// each shape the gateway reads it — the vendor's JSON as it came, the +// built-in's translation of it, and the plugin's — the account rests two +// hours, as "restricted", not a minute's backoff; and the agent and the +// Routing page are told what brings it back. +func TestWorkBuddyRestrictedRestsHours(t *testing.T) { + fresh(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(403) + w.Write([]byte(wbRestrictedBody)) + })) + defer up.Close() + p := wbAISignedIn(t, up.URL) + s := New() + + // the built-in: what the agent is given, and what the gateway reads + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + var u Usage + status, msg := s.translate(w, r, p, provider.Chat, provider.Chat, "deepseek-v4.1-flash", + []byte(`{"model":"deepseek-v4.1-flash","messages":[{"role":"user","content":"hi"}],"stream":true}`), &u) + if status != 403 || msg != p.Name+": request illegal — "+provider.WBRestrictedHint { + t.Fatalf("the built-in says %d %q", status, msg) + } + translated := w.Body.Bytes() + if !strings.Contains(string(translated), provider.WBRestrictedHint) { + t.Fatalf("the agent gets %s", translated) + } + + // the plugin's explained(), as it puts the same answer + // (@magpie-community/opencode-workbuddy-auth 0.1.17) + plugin := []byte(`{"error":{"message":"request illegal — ` + provider.WBRestrictedHint + `","type":"permission_error","code":11140}}`) + + escaped := []byte(`{"code":"11140","msg":"request illegal","displayMsg":{"zh":"账号存在异常行为,已被限制使用"}}`) + worded := []byte(`{"msg":"request illegal","displayMsg":{"zh-hant":"帳號存在異常行為,已被限制使用"}}`) + c := candidate{p: p, model: "deepseek-v4.1-flash", rest: p.ID + "#u1"} + for name, body := range map[string][]byte{ + "vendor's JSON": []byte(wbRestrictedBody), "built-in's translation": translated, "plugin's": plugin, + "code as a string, Chinese escaped": escaped, "words alone": worded, + } { + fresh(t) + now := time.Now() + rest := s.restAfter(c, 403, nil, body) + if rest.Why != failRestricted || rest.By != "restricted" { + t.Fatalf("%s: rests %+v", name, rest) + } + if d := restedFor(rest, now); d < restrictedRest-time.Minute || d > restrictedRest+time.Minute { + t.Fatalf("%s: rests %v", name, d) + } + // the account, not one model of it + if rest.Key != c.restKey() { + t.Fatalf("%s: rests %q, not the account %q", name, rest.Key, c.restKey()) + } + // a user whose appeal went through lifts it at once + if !s.Unrest(rest.Key) { + t.Fatalf("%s: its rest can't be lifted", name) + } + if _, ok := restOf(rest.Key); ok { + t.Fatalf("%s: still resting once lifted", name) + } + } +} + +// Another vendor's code 11140, and WorkBuddy's other refusals, aren't an +// account restricted: a key's 403 with code 11140 rests as any failure +// does, and WorkBuddy's 11128 "unapproved channel" (#182) still rests +// nobody, as the agent's prompt is at fault. +func TestOnlyWorkBuddyRestrictedRestsAsRestricted(t *testing.T) { + fresh(t) + s := New() + other := candidate{p: provider.Provider{ID: "acme", Name: "Acme"}, model: "m", rest: "acme"} + for _, body := range []string{ + `{"code":11140,"msg":"request illegal"}`, + `{"error":{"code":11140,"message":"forbidden"}}`, + `{"error":{"message":"Acme: request illegal","type":"permission_error"},"type":"error"}`, + } { + if f := failureOf(other, 403, []byte(body)); f == failRestricted { + t.Fatalf("another vendor's %s read as restricted", body) + } + rest := s.restAfter(other, 403, nil, []byte(body)) + if rest.Why != failOther || rest.By == "restricted" || restedFor(rest, time.Now()) > longestRetry { + t.Fatalf("another vendor's %s rests %+v", body, rest) + } + } + // another plugin's account (fakeco) with WorkBuddy's own body is that + // vendor's answer too + if restrictedRefused(provider.Provider{ID: "fakeco", Account: &provider.Account{Agent: "plugin"}}, 403, []byte(wbRestrictedBody)) { + t.Fatal("a non-WorkBuddy account's 11140 read as restricted") + } + + wb := provider.Provider{ID: provider.WorkBuddyAIID, Account: &provider.Account{Agent: provider.WorkBuddyAIID, User: "u1"}} + for _, body := range []string{ + `{"code":11128,"msg":"Illegal API invocation from an unapproved channel"}`, + `{"code":14018,"msg":"Credits exhausted. Please visit the link to purchase."}`, + `{"code":111400,"msg":"something else"}`, + } { + if restrictedRefused(wb, 403, []byte(body)) || restrictedRefused(wb, 400, []byte(body)) { + t.Fatalf("WorkBuddy's %s read as restricted", body) + } + } + // 11128 is still the agent's prompt, which rests nobody + if !promptRefused(400, []byte(`{"code":11128,"msg":"Illegal API invocation from an unapproved channel"}`)) { + t.Fatal("11128 no longer read as the agent's prompt turned away") + } + // an answer that went through is nobody's refusal + if restrictedRefused(wb, 200, []byte(wbRestrictedBody)) { + t.Fatal("a 200 read as restricted") + } +} + +// Through a plugin, as the moved WorkBuddy is served: an account whose +// answer is the plugin's restricted refusal rests two hours and the next +// account answers, on this request and on the ones after it, which don't +// ask the restricted one again (before #1849 it was back within minutes +// and asked by every request). The same vendor's raw 11140 from a plugin +// that isn't WorkBuddy's (fakeco) rests as any failure does. +func TestPluginRestrictedAccountSkipped(t *testing.T) { + bun := testenv.Bun(t) + for _, tc := range []struct { + name, body, why string + }{ + {"WorkBuddy plugin's words", `{"error":{"message":"request illegal — ` + provider.WBRestrictedHint + `","type":"permission_error","code":11140}}`, failRestricted}, + {"another vendor's 11140", wbRestrictedBody, failOther}, + } { + t.Run(tc.name, func(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + var mu sync.Mutex + var tried []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + who := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer fresh-r-") + mu.Lock() + tried = append(tried, who) + mu.Unlock() + if who == "a" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(403) + fmt.Fprint(w, tc.body) + return + } + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"from `+who+`"},"finish_reason":null}]}`+"\n\n") + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n") + })) + defer up.Close() + t.Setenv("FAKE_BASE", up.URL+"/v1") + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + for _, team := range []string{"a", "b"} { + st, err := provider.StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": team}) + if err != nil { + t.Fatal(err) + } + if err := provider.SubmitSignInCallback(st.ID, "good"); err != nil { + t.Fatal(err) + } + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + if err := provider.SwitchLogin("fakeco", "a@fake"); err != nil { + t.Fatal(err) + } + s := New() + code, body := postAs(t, s, "", `{"model":"fakeco/fake-1","messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "from b") { + t.Fatalf("%d %s", code, body) + } + r := s.trace.routes[len(s.trace.routes)-1] + if len(r.Tries) != 2 { + t.Fatalf("tries %+v", r.Tries) + } + f := r.Tries[0] + if f.Fail != tc.why || f.Rest == nil || f.Rest.Why != tc.why { + t.Fatalf("a's try %+v rest %+v", f, f.Rest) + } + d := f.Rest.Until.Sub(time.Now()) + if tc.why == failRestricted && (d < restrictedRest-time.Minute || f.Rest.By != "restricted") { + t.Fatalf("a rests %v by %q", d, f.Rest.By) + } + if tc.why == failOther && (d > longestRetry || f.Rest.By != "backoff") { + t.Fatalf("another vendor's 11140 rests %v by %q", d, f.Rest.By) + } + // the next request doesn't ask a again + mu.Lock() + tried = nil + mu.Unlock() + if code, body := postAs(t, s, "", `{"model":"fakeco/fake-1","messages":[{"role":"user","content":"hi"}]}`); code != 200 || !strings.Contains(body, "from b") { + t.Fatalf("again: %d %s", code, body) + } + mu.Lock() + defer mu.Unlock() + if strings.Join(tried, ",") != "b" { + t.Fatalf("the next request asked %v", tried) + } + }) + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7ce3e2076..295146b41 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3368,6 +3368,10 @@ const I18N = { "{who} answered {status}: the vendor wants the account verified before it serves it again, and nobody is left to try, so {agent} gets the error with how to verify it. For a minute {agent}'s retries get the same answer without asking the vendor.": "{who} 返回 {status}:服务商要求先验证账号,且无其他可试,{agent} 收到此错误及验证方法。一分钟内 {agent} 的重试直接得到相同回复,不再请求服务商。", "Verify the account ↗": "去验证账号 ↗", "It's verified — try it again": "已验证,重新使用", + "account restricted by the vendor": "账号被服务商限制", + "The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here": "服务商限制了这个账号:它休息 {d},因为只有服务商解除限制才能让它恢复。请向服务商申诉;解除后,在这里重新使用", + "The restriction is lifted — try it again": "限制已解除,重新使用", + "WorkBuddy restricted this account for unusual activity; it stays out until WorkBuddy lifts that, which an appeal (Submit feedback in WorkBuddy) asks for": "WorkBuddy 因异常行为限制了这个账号;在 WorkBuddy 解除之前它不会再被使用,可在 WorkBuddy 中提交反馈申诉", "{who} turned away the reasoning effort changed mid-conversation as an update that keeps its cache, so it is asked again at the new effort the usual way, before any of the reply reaches {agent}.": "{who} 不接受对话中途以保留缓存的「更新」方式切换推理强度,已在回复到达 {agent} 前按常规方式以新强度重问。", "{who} takes no request for a reply as short as this one asked for, so it is asked again for the shortest it gives, before any of the reply reaches {agent}.": "{who} 不接受这么短的回复长度(max_tokens),已在回复到达 {agent} 前按其允许的最小值重问。", "{who} couldn't read the reasoning another account wrote earlier in this conversation, so it is asked again without it, before any of the reply reaches {agent}.": "{who} 无法读取此会话中另一个账号先前写下的推理,已在回复到达 {agent} 前去掉这部分重问。", @@ -7848,6 +7852,10 @@ const I18N = { "{who} answered {status}: the vendor wants the account verified before it serves it again, and nobody is left to try, so {agent} gets the error with how to verify it. For a minute {agent}'s retries get the same answer without asking the vendor.": "{who} 返回 {status}:服務商要求先驗證帳號,且無其他可試,{agent} 收到此錯誤及驗證方法。一分鐘內 {agent} 的重試直接得到相同回覆,不再請求服務商。", "Verify the account ↗": "去驗證帳號 ↗", "It's verified — try it again": "已驗證,重新使用", + "account restricted by the vendor": "帳號被服務商限制", + "The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here": "服務商限制了這個帳號:它休息 {d},因為只有服務商解除限制才能讓它恢復。請向服務商申訴;解除後,在這裡重新使用", + "The restriction is lifted — try it again": "限制已解除,重新使用", + "WorkBuddy restricted this account for unusual activity; it stays out until WorkBuddy lifts that, which an appeal (Submit feedback in WorkBuddy) asks for": "WorkBuddy 因異常行為限制了這個帳號;在 WorkBuddy 解除之前它不會再被使用,可在 WorkBuddy 中提交回饋申訴", "{who} turned away the reasoning effort changed mid-conversation as an update that keeps its cache, so it is asked again at the new effort the usual way, before any of the reply reaches {agent}.": "{who} 不接受對話中途以保留快取的「更新」方式切換推理強度,已在回覆到達 {agent} 前按常規方式以新強度重問。", "{who} takes no request for a reply as short as this one asked for, so it is asked again for the shortest it gives, before any of the reply reaches {agent}.": "{who} 不接受這麼短的回覆長度(max_tokens),已在回覆到達 {agent} 前按其允許的最小值重問。", "{who} couldn't read the reasoning another account wrote earlier in this conversation, so it is asked again without it, before any of the reply reaches {agent}.": "{who} 無法讀取此會話中另一個帳號先前寫下的推理,已在回覆到達 {agent} 前去掉這部分重問。", @@ -12345,6 +12353,10 @@ const I18N = { "{who} answered {status}: the vendor wants the account verified before it serves it again, and nobody is left to try, so {agent} gets the error with how to verify it. For a minute {agent}'s retries get the same answer without asking the vendor.": "{who} が {status} を返しました。ベンダーは再び応答する前にアカウントの確認を求めており、他に試せる相手もいないため、{agent} には確認方法付きでこのエラーが届きます。1 分間、{agent} の再試行にはベンダーに問い合わせず同じ応答が返ります。", "Verify the account ↗": "アカウントを確認 ↗", "It's verified — try it again": "確認済み — もう一度試す", + "account restricted by the vendor": "ベンダーがアカウントを制限", + "The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here": "ベンダーがこのアカウントを制限しました:制限を解除できるのはベンダーだけなので、{d} 休止します。ベンダーに異議を申し立て、解除されたらここでもう一度試してください", + "The restriction is lifted — try it again": "制限が解除された — もう一度試す", + "WorkBuddy restricted this account for unusual activity; it stays out until WorkBuddy lifts that, which an appeal (Submit feedback in WorkBuddy) asks for": "WorkBuddy が不審なアクティビティを理由にこのアカウントを制限しました。WorkBuddy が解除するまで使われません。解除は WorkBuddy のフィードバック送信から申し立てられます", "{who} turned away the reasoning effort changed mid-conversation as an update that keeps its cache, so it is asked again at the new effort the usual way, before any of the reply reaches {agent}.": "{who} は会話の途中で推理レベルをキャッシュを保つ「更新」として変更することを受け付けなかったため、通常の方法で新しい推理レベルで再度リクエストします。応答が {agent} に届く前に処理されます。", "{who} takes no request for a reply as short as this one asked for, so it is asked again for the shortest it gives, before any of the reply reaches {agent}.": "{who} はこのリクエストほど短い応答長を受け付けないため、許容される最短の長さで再度リクエストします。応答が {agent} に届く前に処理されます。", "{who} couldn't read the reasoning another account wrote earlier in this conversation, so it is asked again without it, before any of the reply reaches {agent}.": "{who} はこの会話で以前に別のアカウントが書いた推論を読めなかったため、それを除いて再度リクエストします。応答が {agent} に届く前に処理されます。", @@ -16839,6 +16851,10 @@ const I18N = { "{who} answered {status}: the vendor wants the account verified before it serves it again, and nobody is left to try, so {agent} gets the error with how to verify it. For a minute {agent}'s retries get the same answer without asking the vendor.": "{who} antwortete mit {status}: Der Anbieter verlangt eine Verifizierung des Kontos, bevor er es wieder bedient, und es bleibt niemand zum Versuchen, daher erhält {agent} den Fehler samt Anleitung zur Verifizierung. Eine Minute lang erhalten Wiederholungen von {agent} dieselbe Antwort, ohne den Anbieter zu fragen.", "Verify the account ↗": "Konto verifizieren ↗", "It's verified — try it again": "Verifiziert – erneut versuchen", + "account restricted by the vendor": "Konto vom Anbieter gesperrt", + "The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here": "Der Anbieter hat das Konto gesperrt: Es pausiert {d}, denn nur die Aufhebung der Sperre durch den Anbieter bringt es zurück. Legen Sie beim Anbieter Einspruch ein; sobald sie aufgehoben ist, versuchen Sie es hier erneut", + "The restriction is lifted — try it again": "Die Sperre ist aufgehoben – erneut versuchen", + "WorkBuddy restricted this account for unusual activity; it stays out until WorkBuddy lifts that, which an appeal (Submit feedback in WorkBuddy) asks for": "WorkBuddy hat dieses Konto wegen ungewöhnlicher Aktivität gesperrt; es bleibt außen vor, bis WorkBuddy die Sperre aufhebt, was ein Einspruch (Feedback senden in WorkBuddy) beantragt", "{who} turned away the reasoning effort changed mid-conversation as an update that keeps its cache, so it is asked again at the new effort the usual way, before any of the reply reaches {agent}.": "{who} hat den mitten in der Unterhaltung als cache-erhaltendes Update geänderten Reasoning-Effort abgelehnt, daher wird es auf normalem Weg mit dem neuen Effort erneut gefragt, bevor etwas von der Antwort {agent} erreicht.", "{who} takes no request for a reply as short as this one asked for, so it is asked again for the shortest it gives, before any of the reply reaches {agent}.": "{who} nimmt keine Anfrage nach einer so kurzen Antwort wie verlangt an, daher wird es erneut nach der kürzesten möglichen gefragt, bevor etwas von der Antwort {agent} erreicht.", "{who} couldn't read the reasoning another account wrote earlier in this conversation, so it is asked again without it, before any of the reply reaches {agent}.": "{who} konnte das Reasoning nicht lesen, das ein anderes Konto zuvor in dieser Unterhaltung geschrieben hat, daher wird es ohne dieses erneut gefragt, bevor etwas von der Antwort {agent} erreicht.", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index f294ab27b..627d26a41 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -373,7 +373,7 @@ // (WorkBuddy's credits, #659): "355 / 500 credits · 71% used" const quota = (w, used, left, vars) => (w.limit > 0 ? quotaCount(w) + " · " : "") + t(quotaLeft ? left : used, { n: pct(share(w)), ...vars }); const fill = (w) => Math.max(0, Math.min(100, share(w))) + "%"; - const FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", canceled: "canceled", foreign: "another account's reasoning", floor: "reply too short", verify: "needs verification", refused: "refused (safety filter)", shape: "request not understood", proxy: "proxy not reachable", effort: "reasoning effort not in its plan", overflow: "too long for its model", slow: "slow to start", prompt: "agent's prompt turned away" }; + const FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", canceled: "canceled", foreign: "another account's reasoning", floor: "reply too short", verify: "needs verification", refused: "refused (safety filter)", shape: "request not understood", proxy: "proxy not reachable", effort: "reasoning effort not in its plan", overflow: "too long for its model", slow: "slow to start", prompt: "agent's prompt turned away", restricted: "account restricted by the vendor" }; const failWord = (why) => t(FAIL[why] || "failed"); // a try that answered: one whose reply broke off after it began (its 200 // sent, then the vendor's error, #733) didn't, and has a fail @@ -452,6 +452,9 @@ case "resets": return t("It rests until {time}, when the vendor says the limit resets", { time }); case "quota": return t("It rests 15 minutes: out of quota, with no word of when it resets"); case "verify": return t("The vendor wants the account verified first: it rests half an hour, or until you say it's verified"); + // the vendor restricted the account itself (#1849): only its lifting, + // which the vendor's appeal asks for, brings it back + case "restricted": return t("The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here", { d }); case "backoff": return rest.why === "rate" ? t("It was rate limited again as soon as it was back ({n} times in a row): it rests {d}, longer each time until it answers", { n: rest.failures, d }) : rest.failures > 1 @@ -796,7 +799,10 @@ // what it adds to Antigravity's 429 for Claude Code's and the Agent SDK's // system prompt (antigravityTurnedAwayHint, #666, #1425) const AG_TURNED_AWAY = "Antigravity answers this 429 to the system prompt of Claude Code and the Claude Agent SDK (Claude Desktop's chats) whatever quota is left, so it is not a quota and waiting won't help; use another provider for these chats, or put one after Antigravity in a routing group"; - const HINTS = [WB_REFUSED, BLOCKED, ZCODE_BLOCKED, AG_TURNED_AWAY]; + // what it adds to WorkBuddy's 403 11140 for an account it restricted + // (provider.WBRestrictedHint, #1849) + const WB_RESTRICTED = "WorkBuddy restricted this account for unusual activity; it stays out until WorkBuddy lifts that, which an appeal (Submit feedback in WorkBuddy) asks for"; + const HINTS = [WB_REFUSED, BLOCKED, ZCODE_BLOCKED, AG_TURNED_AWAY, WB_RESTRICTED]; function trySaid(r, i) { const tr = r.tries[i], w = tried(r, tr), agent = agentName(r.agent); @@ -2443,12 +2449,13 @@ ms.append(...mdls.map((m) => el("code", "mdl", m))); row.append(ms); } - if (resting && a.rest.why === "verify") { - // the vendor wants the account verified (#152): where, and a way to - // stop its rest once it is + if (resting && (a.rest.why === "verify" || a.rest.why === "restricted")) { + // the vendor wants the account verified (#152), or restricted it + // until an appeal lifts it (#1849): where, and a way to stop its + // rest once it is const fix = el("div", "fix"), rest = a.rest; if (rest.link) { const b = el("button", "link", t("Verify the account ↗")); b.onclick = () => api("open", { url: rest.link }).catch(() => {}); fix.append(b); } - const go = el("button", "link", t("It's verified — try it again")); + const go = el("button", "link", t(rest.why === "restricted" ? "The restriction is lifted — try it again" : "It's verified — try it again")); go.onclick = async () => { try { await api("gateway/unrest", { key: rest.key }); rest.until = new Date().toISOString(); render(); } catch (e) { go.textContent = e.message; } }; diff --git a/internal/gui/tests/routing-wb-restricted.test.cjs b/internal/gui/tests/routing-wb-restricted.test.cjs new file mode 100644 index 000000000..9f7d22a91 --- /dev/null +++ b/internal/gui/tests/routing-wb-restricted.test.cjs @@ -0,0 +1,129 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// WorkBuddy's 403 11140 "request illegal" for an account it restricted +// (#1849): the Routing page tells the try as the account restricted, not +// "failed", says it rests two hours because only the vendor lifting the +// restriction brings it back, after an appeal; gives magpie's hint apart +// from the vendor's words; and the resting account's row lifts its rest by +// hand once the appeal went through — in every language the page speaks. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const now = new Date(); +const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const start = new Date(now.getTime() - 60e3).toISOString(); +const hint = "WorkBuddy restricted this account for unusual activity; it stays out until WorkBuddy lifts that, which an appeal (Submit feedback in WorkBuddy) asks for"; +const vendor = "WorkBuddy AI: request illegal"; +const a = { id: "workbuddy-ai#a", provider: "workbuddy-ai", name: "WorkBuddy AI", kind: "account", who: "a@x", model: "deepseek-v4.1-flash" }; +const b = { id: "workbuddy-ai#b", provider: "workbuddy-ai", name: "WorkBuddy AI", kind: "account", who: "b@x", model: "deepseek-v4.1-flash" }; +const rest = { why: "restricted", by: "restricted", status: 403, key: "workbuddy-ai@a", until: new Date(now.getTime() + 2 * 3600e3 - 60e3).toISOString() }; +const routes = [{ + id: 100, seq: 100, time: start, agent: "codex", model: "workbuddy-ai/deepseek-v4.1-flash", provider: "workbuddy-ai", + order: [a, b], + tries: [ + { id: a.id, model: a.model, start, done: true, status: 403, ms: 900, fail: "restricted", rest, error: vendor + " — " + hint }, + { id: b.id, model: b.model, start, done: true, status: 200, ms: 1200 }, + ], + done: true, status: 200, ms: 2100, +}]; + +function serve(lang, lifted) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + 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(state); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") { + const d = url.searchParams.get("day"); + return json({ cut: false, days: [{ day, requests: routes.length }], routes: d ? routes : [] }); + } + if (url.pathname === "/api/gateway/unrest") { + lifted.push(JSON.parse(route.request().postData() || "{}")); + return json({ lifted: true }); + } + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], 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", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const want = { + en: { label: "account restricted by the vendor", why: "only the vendor lifting the restriction brings it back. Appeal with the vendor", hint, lift: "The restriction is lifted — try it again" }, + zh: { label: "账号被服务商限制", why: "只有服务商解除限制才能让它恢复。请向服务商申诉", hint: "WorkBuddy 因异常行为限制了这个账号;在 WorkBuddy 解除之前它不会再被使用,可在 WorkBuddy 中提交反馈申诉", lift: "限制已解除,重新使用" }, + "zh-TW": { label: "帳號被服務商限制", why: "只有服務商解除限制才能讓它恢復。請向服務商申訴", hint: "WorkBuddy 因異常行為限制了這個帳號;在 WorkBuddy 解除之前它不會再被使用,可在 WorkBuddy 中提交回饋申訴", lift: "限制已解除,重新使用" }, + ja: { label: "ベンダーがアカウントを制限", why: "制限を解除できるのはベンダーだけなので", hint: "WorkBuddy が不審なアクティビティを理由にこのアカウントを制限しました。WorkBuddy が解除するまで使われません。解除は WorkBuddy のフィードバック送信から申し立てられます", lift: "制限が解除された — もう一度試す" }, + de: { label: "Konto vom Anbieter gesperrt", why: "denn nur die Aufhebung der Sperre durch den Anbieter bringt es zurück. Legen Sie beim Anbieter Einspruch ein", hint: "WorkBuddy hat dieses Konto wegen ungewöhnlicher Aktivität gesperrt; es bleibt außen vor, bis WorkBuddy die Sperre aufhebt, was ein Einspruch (Feedback senden in WorkBuddy) beantragt", lift: "Die Sperre ist aufgehoben – erneut versuchen" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(want)) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}px: a restricted WorkBuddy account is told as one, with the way back`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = [], lifted = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, lifted)); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-wb-restricted.png`), fullPage: true }); + } + await browser.close(); + }); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-days .rt-day").nth(1).click(); + await page.locator(".rt-req").first().waitFor(); + await page.locator(".rt-req").first().click(); + await page.locator(".rt-steps li").first().waitFor(); + await page.waitForTimeout(300); + const w = want[lang]; + const steps = await page.locator(".rt-steps li").evaluateAll((ls) => ls.map((l) => [l.className, l.textContent])); + // the try: the label, and why it rests as long as it does + const told = steps.map(([, s]) => s).filter((s) => s.includes(w.label)); + assert.equal(told.length, 1, JSON.stringify(steps)); + assert(told[0].includes(w.why), told[0]); + // the vendor's words as they were, and magpie's hint on its own line + assert.equal(steps.filter(([c]) => c === "aside said").length, 1, JSON.stringify(steps)); + assert(steps.find(([c]) => c === "aside said")[1].endsWith(vendor), JSON.stringify(steps)); + assert.deepEqual(steps.filter(([, s]) => s === w.hint).map(([c]) => c), ["aside"]); + if (lang !== "en") assert(!steps.some(([, s]) => s.includes("unusual activity")), JSON.stringify(steps)); + + // the account's row: resting, restricted, and a way to lift it + const row = page.locator(".rt-act").filter({ hasText: w.label }).first(); + await row.waitFor(); + assert((await row.locator(".st.rest").textContent()).includes(w.label)); + const go = row.locator(".fix button", { hasText: w.lift }); + await go.waitFor(); + // nothing of it runs past the page's width + assert(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), "the page scrolls sideways"); + // scrolled to where a reader sees it, it is the button under the + // pointer, not the footer + // a reader scrolls down to it with the wheel + await page.mouse.move(200, 400); + for (let i = 0; i < 20 && !(await go.evaluate((e) => e.getBoundingClientRect().bottom < innerHeight - 80)); i++) await page.mouse.wheel(0, 200); + await page.waitForTimeout(200); + assert(await go.evaluate((e) => { const r = e.getBoundingClientRect(); return e.contains(document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2)); }), "the button can't be reached"); + await go.click(); + await page.waitForTimeout(300); + assert.deepEqual(lifted, [{ key: rest.key }]); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/migrate_workbuddy.go b/internal/provider/migrate_workbuddy.go index 03eaf083e..5e7ae3df4 100644 --- a/internal/provider/migrate_workbuddy.go +++ b/internal/provider/migrate_workbuddy.go @@ -16,7 +16,7 @@ func init() { for _, w := range []*wbSite{wbCN, wbAI} { movers[w.id] = &mover{ pkg: "@magpie-community/opencode-workbuddy-auth", - min: "0.1.16", // WorkBuddy AI's GLM models are text-only, so magpie's image-describing model reads their images (Yirasumi on Discord); 0.1.15: a system prompt sent as a developer message passes the channel check, an object tool_choice is sent as WorkBuddy takes it, and max_completion_tokens goes as max_tokens so the cap holds (plugins #96); 0.1.14: the Credits window says when the soonest credits left run out, for Smart routing to spend them first (cdredfox on X); an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659) + min: "0.1.17", // a restricted account's 403 11140 ends in provider.WBRestrictedHint, so it rests 2h as restricted (#1849); 0.1.16: WorkBuddy AI's GLM models are text-only, so magpie's image-describing model reads their images (Yirasumi on Discord); 0.1.15: a system prompt sent as a developer message passes the channel check, an object tool_choice is sent as WorkBuddy takes it, and max_completion_tokens goes as max_tokens so the cap holds (plugins #96); 0.1.14: the Credits window says when the soonest credits left run out, for Smart routing to spend them first (cdredfox on X); an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659) agents: []string{w.id}, out: func() ([]Moving, error) { var out []Moving diff --git a/internal/provider/workbuddy.go b/internal/provider/workbuddy.go index 13fb9ed60..a89295608 100644 --- a/internal/provider/workbuddy.go +++ b/internal/provider/workbuddy.go @@ -452,11 +452,63 @@ const WBRefusedHint = "WorkBuddy refuses chats from Codex and Claude Code (their // wbRefused matches that refusal in what WorkBuddy answered. var wbRefused = regexp.MustCompile(`(?i)unapproved channel|illegal api invocation`) -// wbExplain adds WBRefusedHint to WorkBuddy's refusal of the client. +// WBRestrictedHint is what magpie adds to WorkBuddy's 403 code 11140 +// "request illegal" (#1849), whose displayMsg says "Your account has been +// restricted due to unusual activity": the account, not the request, is +// out until WorkBuddy lifts the restriction, which its appeal asks for. +// The gateway reads it as the account restricted (failRestricted), the +// plugin adds the same words, and the Routing page says it apart. +const WBRestrictedHint = "WorkBuddy restricted this account for unusual activity; it stays out until WorkBuddy lifts that, which an appeal (Submit feedback in WorkBuddy) asks for" + +// wbRestrictedWords are the restriction as WorkBuddy's 11140 words it in +// its displayMsg and displayTips: English, Simplified and Traditional +// Chinese. +var wbRestrictedWords = regexp.MustCompile(`(?i)account has been restricted due to unusual activity|账号存在异常行为|帳號存在異常行為`) + +// wbRestrictedCode is WorkBuddy's code for an account it restricted. +const wbRestrictedCode = 11140 + +// WBRestricted says body is WorkBuddy's refusal of a restricted account: +// its code 11140 (top level, or under data or error, as a number or a +// string), or its displayMsg's words. Only for a WorkBuddy answer: another +// vendor's 11140 is its own. +func WBRestricted(status int, body []byte) bool { + if status < 400 { + return false + } + var v map[string]any + if json.Unmarshal(body, &v) == nil { + codes := []any{v["code"]} + for _, k := range []string{"data", "error"} { + if in, ok := v[k].(map[string]any); ok { + codes = append(codes, in["code"]) + } + } + for _, c := range codes { + switch c := c.(type) { + case float64: + if c == wbRestrictedCode { + return true + } + case string: + if c == strconv.Itoa(wbRestrictedCode) { + return true + } + } + } + } + return wbRestrictedWords.Match(body) +} + +// wbExplain adds WBRefusedHint to WorkBuddy's refusal of the client, and +// WBRestrictedHint to its refusal of a restricted account. func wbExplain(status int, body []byte) string { if status >= 400 && wbRefused.Match(body) { return WBRefusedHint } + if WBRestricted(status, body) { + return WBRestrictedHint + } return "" } diff --git a/internal/provider/workbuddy_refused_test.go b/internal/provider/workbuddy_refused_test.go index ae2377796..af956260a 100644 --- a/internal/provider/workbuddy_refused_test.go +++ b/internal/provider/workbuddy_refused_test.go @@ -31,5 +31,13 @@ func TestWorkBuddyRefusedHint(t *testing.T) { if got := p.Explain(p.Name+": bad", 400, []byte(`{"code":1,"msg":"first message is not system prompt"}`)); got != p.Name+": bad" { t.Errorf("%s, another error: %q", id, got) } + // an account WorkBuddy restricted (#1849), its 403 as it came + restricted := []byte(`{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity","zh":"账号存在异常行为,已被限制使用"}}`) + if got := p.Explain(p.Name+": request illegal", 403, restricted); got != p.Name+": request illegal — "+WBRestrictedHint { + t.Errorf("%s, restricted: %q", id, got) + } + if got := p.Explain(p.Name+": Illegal API invocation from an unapproved channel", 400, refused); strings.Contains(got, WBRestrictedHint) { + t.Errorf("%s: 11128 told as restricted: %q", id, got) + } } }