diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go
index 43c6cd822..37ac4ddd3 100644
--- a/internal/gateway/fallback.go
+++ b/internal/gateway/fallback.go
@@ -465,6 +465,10 @@ func retryable(status int, body []byte) bool {
switch {
case status == 401, status == 402, status == 403, status == 404, status == 408, status == 429, status >= 500:
return true
+ case status >= 400 && provider.EdgeBlocked(body):
+ // the vendor's firewall blocked this address (Alibaba Cloud's 405
+ // in front of zcode.z.ai): another provider goes another way
+ return true
case status == 400, status == 422:
return quotaWords.Match(body) || unservedWords.Match(body) || refusedWords.Match(body) || shapeWords.Match(body)
}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index dc830abf1..e74a98951 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -545,7 +545,7 @@ func unprefixed(id string) string {
// estimatedMoved are the built-ins that estimated a count, as their
// plugins do once moved; Command Code's whatever its plan, as the plugin
// alone knows a Go key.
-var estimatedMoved = []string{"cursor", "grok", "devin", "kiro", "qoder", "zed", "factory", provider.CommandCodePlanID}
+var estimatedMoved = []string{"cursor", "grok", "devin", "kiro", "qoder", "zed", "factory", "zcode", provider.CommandCodePlanID}
// countTokens answers Anthropic's count_tokens: through the provider when
// it implements counting, else a rough estimate. A failed connection or
@@ -566,9 +566,17 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) {
w, body, unmask := redacted(w, body)
defer unmask()
p, model, ok := provider.Resolve(unprefixed(model))
+ s.countOn(w, r, p, model, ok, body)
+}
+
+// countOn counts body's tokens for model on p, resolved when ok.
+func (s *Server) countOn(w http.ResponseWriter, r *http.Request, p provider.Provider, model string, ok bool, body []byte) {
// Claude Subscription generations run through the Claude Code binary. Its
// OAuth token must not take a direct HTTP side path just for token counting.
- if ok && p.Account != nil && (p.Account.Agent == "claude" || p.Account.Agent == "cursor" || p.Account.Agent == "grok" || p.Account.Agent == "devin" || p.Account.Agent == "kiro" || p.Account.Agent == "qoder" || p.Account.Agent == provider.QoderCNID || p.Account.Agent == "zed" || p.Account.Agent == "factory" || p.Account.Agent == "gemini" || p.Account.Agent == "antigravity") ||
+ if ok && p.Account != nil && (p.Account.Agent == "claude" || p.Account.Agent == "cursor" || p.Account.Agent == "grok" || p.Account.Agent == "devin" || p.Account.Agent == "kiro" || p.Account.Agent == "qoder" || p.Account.Agent == provider.QoderCNID || p.Account.Agent == "zed" || p.Account.Agent == "factory" || p.Account.Agent == "gemini" || p.Account.Agent == "antigravity" ||
+ // ZCode itself never counts, and zcode.z.ai answers count_tokens
+ // with an error every time: one more request its firewall weighs
+ p.Account.Agent == "zcode") ||
ok && p.Account != nil && p.Account.Agent == provider.CommandCodePlanID && cmdGoing(r.Context(), p) ||
ok && p.IsPlugin() && slices.Contains(estimatedMoved, p.ID) {
req, err := parseAnthropic(body)
diff --git a/internal/gateway/zcode_blocked_test.go b/internal/gateway/zcode_blocked_test.go
new file mode 100644
index 000000000..c4396be6b
--- /dev/null
+++ b/internal/gateway/zcode_blocked_test.go
@@ -0,0 +1,133 @@
+package gateway
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// countAsked is an upstream that counts tokens, noting each time it's asked.
+type countAsked struct {
+ mu sync.Mutex
+ paths []string
+}
+
+func (c *countAsked) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ c.mu.Lock()
+ c.paths = append(c.paths, r.URL.Path)
+ c.mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ io.WriteString(w, `{"input_tokens":999}`)
+}
+
+func (c *countAsked) asked() []string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return append([]string(nil), c.paths...)
+}
+
+func estimated(t *testing.T, rec *httptest.ResponseRecorder) int {
+ t.Helper()
+ var got struct {
+ InputTokens int `json:"input_tokens"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &got); rec.Code != 200 || err != nil || got.InputTokens == 0 {
+ t.Fatalf("count_tokens: %d %s", rec.Code, rec.Body)
+ }
+ return got.InputTokens
+}
+
+// Claude Code asks count_tokens before each turn; ZCode itself never does,
+// and zcode.z.ai answers it with an error every time. A ZCode account's
+// count is estimated, the vendor not asked.
+func TestZCodeCountTokensEstimated(t *testing.T) {
+ fresh(t)
+ up := &countAsked{}
+ srv := httptest.NewServer(up)
+ t.Cleanup(srv.Close)
+ p := provider.Provider{ID: "zcode", Name: "ZCode", Anthropic: srv.URL + "/api/v1/zcode-plan/anthropic", Models: []string{"glm-5.1"},
+ Account: &provider.Account{Agent: "zcode", User: "trial@example.com", Plan: "Start Plan"}}
+ body := []byte(`{"model":"glm-5.1","messages":[{"role":"user","content":"hello there"}]}`)
+ rec := httptest.NewRecorder()
+ New().countOn(rec, httptest.NewRequest("POST", "/v1/messages/count_tokens", nil), p, "glm-5.1", true, body)
+ if n := estimated(t, rec); n == 999 || len(up.asked()) > 0 {
+ t.Fatalf("zcode.z.ai was asked to count: %v, %d", up.asked(), n)
+ }
+}
+
+// ZCode moved onto its plugin estimates as the built-in does.
+func TestMovedZCodeCountTokensEstimated(t *testing.T) {
+ up := &countAsked{}
+ movedFake(t, "zcode", up)
+ rec := httptest.NewRecorder()
+ New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages/count_tokens",
+ strings.NewReader(`{"model":"zcode/fake-claude","messages":[{"role":"user","content":"hello there"}]}`)))
+ if n := estimated(t, rec); n == 999 || len(up.asked()) > 0 {
+ t.Fatalf("the vendor was asked to count: %v, %d", up.asked(), n)
+ }
+}
+
+// edgeBlockPage is Alibaba Cloud's ESA block page, as zcode.z.ai served it.
+const edgeBlockPage = `
+
405
+Sorry, your request has been blocked due to unusual activity.
+
Request ID: 0bd6a2b417592xxxx
+
errors.aliyun.com `
+
+// A vendor's edge firewall blocking this address answers an HTML page: the
+// agent and the trace are told so in plain words, not the page, and the
+// group's next member is asked, as for another provider's failure.
+func TestEdgeBlockedSaidPlainly(t *testing.T) {
+ fresh(t)
+ blocked := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/html")
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ io.WriteString(w, edgeBlockPage)
+ }))
+ t.Cleanup(blocked.Close)
+ var other int
+ fine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ other++
+ w.Header().Set("Content-Type", "application/json")
+ io.WriteString(w, `{"id":"ok","choices":[{"message":{"role":"assistant","content":"from b"}}]}`)
+ }))
+ t.Cleanup(fine.Close)
+ for _, p := range []provider.Provider{
+ {ID: "za", Name: "ZA", Key: "k", Models: []string{"m"}, Chat: blocked.URL + "/v1"},
+ {ID: "zb", Name: "ZB", Key: "k", Models: []string{"m"}, Chat: fine.URL + "/v1"},
+ } {
+ if err := provider.Save(p); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ // alone: the agent is told what happened
+ s := New()
+ code, reply := postAs(t, s, "", `{"model":"za/m","messages":[{"role":"user","content":"hi"}]}`)
+ if code != http.StatusMethodNotAllowed || !strings.Contains(reply, provider.BlockedHint) || strings.Contains(reply, "<") {
+ t.Fatalf("blocked reply: %d %s", code, reply)
+ }
+ if tr := s.trace.routes[len(s.trace.routes)-1].Tries[0]; !strings.HasSuffix(tr.Error, " — "+provider.BlockedHint) || strings.Contains(tr.Error, "<") {
+ t.Fatalf("trace: %+v", tr)
+ }
+
+ // in a group: the next member answers
+ if err := provider.SaveGroup(provider.Group{Name: "Z", Members: []string{"za/m", "zb/m"}, Routing: provider.Ordered}); err != nil {
+ t.Fatal(err)
+ }
+ s = New()
+ code, reply = postAs(t, s, "", `{"model":"group/z","messages":[{"role":"user","content":"hi"}]}`)
+ if code != http.StatusOK || !strings.Contains(reply, "from b") || other != 1 {
+ t.Fatalf("group reply: %d %s (next asked %d)", code, reply, other)
+ }
+ tries := s.trace.routes[len(s.trace.routes)-1].Tries
+ if len(tries) != 2 || tries[0].Rest == nil || !strings.Contains(tries[0].Error, provider.BlockedHint) {
+ t.Fatalf("tries: %+v", tries)
+ }
+}
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index e751634b0..77edcad86 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -1367,6 +1367,7 @@ const I18N = {
"errors your agent saw": "Agent 收到的错误",
"It said: {error}": "原话:{error}",
"WorkBuddy refuses chats from Codex and Claude Code (their system prompt); use it from Hermes, OpenCode or Pi, or add another provider to this group": "WorkBuddy 会拒绝来自 Codex 和 Claude Code 的对话(因为它们的系统提示词);请在 Hermes、OpenCode 或 Pi 里使用它,或在这个分组里再加一个供应商",
+ "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy": "供应商的网络防火墙拦截了来自这个 IP 的请求;请稍等一会儿,或换个网络或代理",
"Show the latest request that failed": "查看最近一个失败的请求",
"rate limited": "限流",
"out of credit": "余额不足",
diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js
index 365fda1d7..01b62a5e2 100644
--- a/internal/gui/assets/routing.js
+++ b/internal/gui/assets/routing.js
@@ -449,6 +449,9 @@
// (provider.WBRefusedHint, #182): the agent gets it in English, the page
// says it apart from the vendor's words, in its own language
const WB_REFUSED = "WorkBuddy refuses chats from Codex and Claude Code (their system prompt); use it from Hermes, OpenCode or Pi, or add another provider to this group";
+ // what it adds to a vendor's edge firewall's block page (provider.BlockedHint)
+ const BLOCKED = "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy";
+ const HINTS = [WB_REFUSED, BLOCKED];
function trySaid(r, i) {
const tr = r.tries[i], w = tried(r, tr), agent = agentName(r.agent);
@@ -959,10 +962,10 @@
items.push([tryWhy(r, i), tr.done ? (tr.status < 400 ? "ok" : "bad") : "wait"]);
// what the vendor said, word for word: the why above is magpie's reading of it
if (tr.done && tr.status >= 400 && tr.error) {
- const hinted = tr.error.endsWith(" — " + WB_REFUSED);
- const said = hinted ? tr.error.slice(0, -(WB_REFUSED.length + 3)) : tr.error;
+ const hint = HINTS.find((h) => tr.error.endsWith(" — " + h));
+ const said = hint ? tr.error.slice(0, -(hint.length + 3)) : tr.error;
items.push([t("It said: {error}", { error: said.length > 600 ? said.slice(0, 600) + "…" : said }), "aside said"]);
- if (hinted) items.push([t(WB_REFUSED), "aside"]);
+ if (hint) items.push([t(hint), "aside"]);
}
// the reply said another model answered it
if (tr.done && tr.status < 400 && tr.swapped) items.push([swapWhy(tr), "swap", tr]);
diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md
index f4cf081b5..0ffa64c44 100644
--- a/internal/gui/tests/README.md
+++ b/internal/gui/tests/README.md
@@ -439,6 +439,13 @@ vendor's words are given without the hint the gateway adds, and the hint is
on its own line in English and Chinese; another 400 gets none, and picking
the request leaves the page where it is. Chromium and WebKit, API faked.
+`routing-blocked.test.cjs` opens a request a vendor's edge firewall blocked
+(Alibaba Cloud's 405 page in front of zcode.z.ai) on the Routing page: what
+the gateway made of it is given without the hint it adds, and the hint (the
+firewall blocked this IP; wait, or switch network or proxy) is on its own
+line in English and Chinese; another 405 gets none, and picking the request
+leaves the page where it is. Chromium and WebKit, API faked.
+
`routing-shape.test.cjs` opens a group request whose first member answered
422 because its API couldn't read the request (#350: SuperGrok and Codex's
additional_tools item) and whose next member answered: the Routing page says
@@ -647,7 +654,7 @@ with `/api/plugins` faked.
With Node.js and Playwright available:
```sh
-node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/rollup-short.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs internal/gui/tests/library-loading.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-usage-asked.test.cjs internal/gui/tests/claude-risk.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs internal/gui/tests/omp-roles.test.cjs internal/gui/tests/claude-effort.test.cjs internal/gui/tests/remote-magpie.test.cjs internal/gui/tests/qoder-cn-tile.test.cjs internal/gui/tests/provider-levels-scroll.test.cjs internal/gui/tests/signin-paste-codex.test.cjs internal/gui/tests/usage-alert.test.cjs internal/gui/tests/quota-families.test.cjs internal/gui/tests/provider-search.test.cjs internal/gui/tests/webdav-settings-refresh.test.cjs internal/gui/tests/lan-docker.test.cjs internal/gui/tests/plugin-key-hint.test.cjs internal/gui/tests/update-hide.test.cjs internal/gui/tests/tray-logos.test.cjs internal/gui/tests/routing-proxy.test.cjs internal/gui/tests/sse-body.test.cjs internal/gui/tests/remote-group-served.test.cjs internal/gui/tests/plugin-move-overflow.test.cjs
+node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/rollup-short.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs internal/gui/tests/library-loading.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-blocked.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-usage-asked.test.cjs internal/gui/tests/claude-risk.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs internal/gui/tests/omp-roles.test.cjs internal/gui/tests/claude-effort.test.cjs internal/gui/tests/remote-magpie.test.cjs internal/gui/tests/qoder-cn-tile.test.cjs internal/gui/tests/provider-levels-scroll.test.cjs internal/gui/tests/signin-paste-codex.test.cjs internal/gui/tests/usage-alert.test.cjs internal/gui/tests/quota-families.test.cjs internal/gui/tests/provider-search.test.cjs internal/gui/tests/webdav-settings-refresh.test.cjs internal/gui/tests/lan-docker.test.cjs internal/gui/tests/plugin-key-hint.test.cjs internal/gui/tests/update-hide.test.cjs internal/gui/tests/tray-logos.test.cjs internal/gui/tests/routing-proxy.test.cjs internal/gui/tests/sse-body.test.cjs internal/gui/tests/remote-group-served.test.cjs internal/gui/tests/plugin-move-overflow.test.cjs
```
If Playwright is installed outside the repository, set `NODE_PATH` to the
diff --git a/internal/gui/tests/routing-blocked.test.cjs b/internal/gui/tests/routing-blocked.test.cjs
new file mode 100644
index 000000000..41d26c8f4
--- /dev/null
+++ b/internal/gui/tests/routing-blocked.test.cjs
@@ -0,0 +1,103 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// A vendor's edge firewall blocking this address (Alibaba Cloud's 405 page
+// in front of zcode.z.ai, "request has been blocked due to unusual
+// activity"): the Routing page's story gives what the gateway made of it,
+// and what it means apart from that, in the page's language.
+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 at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString();
+const hint = "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy";
+const vendor = "ZCode: 405 Method Not Allowed";
+const key = { id: "zcode", provider: "zcode", name: "ZCode", kind: "provider", model: "glm-5.1" };
+// newest first: the block, then another 405 with nothing to add
+const errs = [vendor + " — " + hint, "ZCode: 405 Method Not Allowed", "", "", "", ""];
+const routes = errs.map((error, i) => {
+ const status = error ? 405 : 200;
+ return {
+ id: 100 - i, seq: 100 - i, time: at(i), agent: "claude", model: "zcode/glm-5.1", provider: "zcode",
+ order: [key], tries: [{ id: key.id, model: key.model, start: at(i), done: true, status, ms: 400, ...(error ? { error } : {}) }],
+ done: true, status, ms: 400, ...(error ? { error } : {}),
+ };
+});
+
+function serve(lang) {
+ const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/settings.json", 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/groups") return json({ groups: [] });
+ if (url.pathname === "/api/providers") return json({ providers: [], 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: { said: "It said: " + vendor, hint },
+ zh: { said: "原话:" + vendor, hint: "供应商的网络防火墙拦截了来自这个 IP 的请求;请稍等一会儿,或换个网络或代理" },
+};
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ for (const lang of ["en", "zh"]) {
+ test(`${engine} ${lang}: a firewall's block says what it means`, async (t) => {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ const context = await browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: "reduce" });
+ const page = await context.newPage();
+ page.setDefaultTimeout(5000);
+ const errors = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", serve(lang));
+ 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}-blocked.png`), fullPage: true });
+ }
+ await browser.close();
+ });
+ await page.goto("http://magpie.test/?view=routing");
+ await page.locator(".rt-day").nth(1).click();
+ await page.locator(".rt-req").nth(errs.length - 1).waitFor();
+
+ const steps = async () => page.locator(".rt-steps li").evaluateAll((ls) => ls.map((l) => [l.className, l.textContent]));
+ const row = page.locator(".rt-req").nth(0);
+ const was = await row.evaluate((e) => e.getBoundingClientRect().top);
+ await row.click();
+ await page.waitForTimeout(400);
+ assert(Math.abs((await row.evaluate((e) => e.getBoundingClientRect().top)) - was) <= 1, "picking the request moved the page");
+ let got = await steps();
+ // the vendor's words as they were, without magpie's hint in them
+ assert.deepEqual(got.filter(([c]) => c === "aside said").map(([, s]) => s), [want[lang].said]);
+ // and the hint on its own line, in the page's language
+ assert.deepEqual(got.filter(([, s]) => s === want[lang].hint).map(([c]) => c), ["aside"]);
+
+ // another 405 gets no hint
+ await page.locator(".rt-req").nth(1).click();
+ await page.waitForTimeout(300);
+ got = await steps();
+ assert.equal(got.filter(([c]) => c === "aside said").length, 1);
+ assert(!got.some(([, s]) => s.includes("firewall") || s.includes("防火墙")), JSON.stringify(got));
+ assert.deepEqual(errors, []);
+ });
+ }
+}
diff --git a/internal/provider/test.go b/internal/provider/test.go
index ce579d325..3978441c8 100644
--- a/internal/provider/test.go
+++ b/internal/provider/test.go
@@ -315,10 +315,33 @@ func probe(ctx context.Context, p Provider, proto Protocol, url string, body []b
return r
}
+// BlockedHint is what a vendor's edge firewall blocking magpie's address
+// means, in plain words: Alibaba Cloud's (ESA, in front of zcode.z.ai)
+// answers a 405 HTML page, "Sorry, your request has been blocked due to
+// unusual activity", linking errors.aliyun.com. Nothing in the request is
+// at fault and magpie changes nothing about it: the address is.
+const BlockedHint = "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy"
+
+// edgeBlocked matches such a block page, whoever's firewall served it.
+var edgeBlocked = regexp.MustCompile(`(?i)request has been blocked|errors\.aliyun\.com`)
+
+// EdgeBlocked says whether an error body is a firewall's block page rather
+// than the vendor's API answering, or one already put in plain words.
+func EdgeBlocked(b []byte) bool {
+ return edgeBlocked.Match(b) || bytes.Contains(b, []byte(BlockedHint))
+}
+
// APIError pulls the human message out of an error body when there is one.
-// Google's "verify your account" refusal also says what to do about it,
-// with the link it gave.
+// A firewall's block page is put in plain words (BlockedHint); Google's
+// "verify your account" refusal also says what to do about it, with the
+// link it gave.
func APIError(b []byte, fallback string) string {
+ if edgeBlocked.Match(b) {
+ if fallback == "" {
+ return BlockedHint
+ }
+ return fallback + " — " + BlockedHint
+ }
if link, ok := Verification(b); ok {
return VerifyMessage(apiError(b, fallback), link)
}