diff --git a/internal/gateway/rest_error_test.go b/internal/gateway/rest_error_test.go new file mode 100644 index 000000000..ca9c5e341 --- /dev/null +++ b/internal/gateway/rest_error_test.go @@ -0,0 +1,48 @@ +package gateway + +import ( + "encoding/json" + "strings" + "testing" + "unicode/utf8" + + "github.com/yetone/magpie/internal/provider" +) + +// A rest after a failure that names no kind ("failed") carries what the +// vendor said, kept with the rest and sent to the app, which shows it +// beside the row (GanHei37443 on X: three WorkBuddy accounts each +// "failed · back in 16s", and nothing on the page said why). +func TestRestCarriesTheVendorsWords(t *testing.T) { + clineRestsCleared(t) + s := &Server{} + p := provider.Provider{ID: "custom", Chat: "https://relay.example/v1", Key: "k"} + c := candidate{p: p, model: "deepseek-v4.1-flash", rest: p.ID} + + r := s.restAfter(c, 500, nil, []byte(`{"error":{"message":"model deepseek-v4.1-flash is not available for your plan","type":"server_error"}}`)) + if r.Why != failOther || r.Status != 500 { + t.Fatalf("rests %s at %d, want a plain failure at 500", r.Why, r.Status) + } + if !strings.Contains(r.Error, "not available for your plan") { + t.Fatalf("the rest says %q, not the vendor's words", r.Error) + } + kept, ok := restOf(p.ID) + if !ok || kept.Error != r.Error { + t.Fatalf("the kept rest says %q (resting %v), want %q", kept.Error, ok, r.Error) + } + b, _ := json.Marshal(r) + if !strings.Contains(string(b), `"error":"`) { + t.Fatalf("the app isn't sent the words: %s", b) + } + + // a body with no words of its own says its status; a long one is cut + // short on a rune, the request's details keeping it whole + if r := s.restAfter(c, 502, nil, nil); !strings.HasPrefix(r.Error, "Bad Gateway") { + t.Errorf("an empty 502 rests saying %q, want its status text", r.Error) + } + long := strings.Repeat("服务", 400) + r = s.restAfter(c, 500, nil, []byte(`{"error":{"message":"`+long+`"}}`)) + if n := utf8.RuneCountInString(r.Error); n > restErrorRunes+1 || n < restErrorRunes || !utf8.ValidString(r.Error) { + t.Errorf("a long error is kept as %d runes (valid %v), want %d", n, utf8.ValidString(r.Error), restErrorRunes) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 849545bbe..58b8feea1 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -643,6 +643,10 @@ type Rest struct { // vendor unreachable) is asked again in the background, and its rest // lifted as soon as it answers (rest_probe.go) Probed bool `json:"probed,omitempty"` + // Error: what the vendor said, for the app to show beside "failed" + // (GanHei37443 on X: three WorkBuddy accounts each "failed · back in + // 16s", and nothing on the row said why) + Error string `json:"error,omitempty"` // the subscription account resting, when it is one; agent "" and its // provider.KeyAllowanceID for a key out of its own windows @@ -1108,6 +1112,14 @@ func resetsWritten(body []byte, now time.Time) time.Duration { return 0 } +// restError is the vendor's words a rest is shown with, cut short: the +// request's details keep them whole +func restError(status int, body []byte) string { + return clipRunes(strings.TrimSpace(provider.APIError(body, http.StatusText(status))), restErrorRunes) +} + +const restErrorRunes = 300 + // restAfter sets a failed candidate aside for as long as its failure says. func (s *Server) restAfter(c candidate, status int, header http.Header, body []byte) Rest { return s.restAfterMarked(c, status, header, body, openRouterSharedPool(body)) @@ -1160,7 +1172,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo // trial entry zcode.z.ai's firewall blocked (zcodeTrialBlocked): the // account's GLM Coding Plan goes to another host unserved := why == failOther && (modelRefused(status, body) || codeAssistModelMissing(c.p, status, body) || zcodeTrialBlocked(c, status, body)) - r := Rest{Why: why, Status: status, By: "cooldown"} + r := Rest{Why: why, Status: status, By: "cooldown", Error: restError(status, body)} // out of allowance or credit for as long as magpie guessed: the vendor // named no time, nor did the user (asksAt) guessed := false diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index d8e697f47..be378dfbe 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -510,6 +510,11 @@ function routingPage(part) { 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", sight: "images not taken", proxy: "proxy not reachable", effort: "reasoning effort not in its plan", overflow: "too long for its model", room: "reply asked past the window left", slow: "slow to start", prompt: "agent's prompt turned away", restricted: "account restricted by the vendor" }; const failWord = (why) => t(FAIL[why] || "failed"); + // a resting row: a failure that names no kind says the status it + // answered, and the vendor's own words are over it (restTip), as + // "failed · back in 16s" alone said nothing of why (GanHei37443 on X) + const restSay = (rest) => `${!FAIL[rest.why] || rest.why === "other" ? (rest.status ? rest.status + " · " : "") : ""}${failWord(rest.why)} · ${restWhen(rest)}`; + const restTip = (rest) => (typeof rest.error === "string" && rest.error) || ""; // 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 const tryOk = (tr) => tr.status < 400 && !tr.fail; @@ -2557,7 +2562,7 @@ function routingPage(part) { const smart = r.order[0] && id === seat(r.order[0]) && smartFor(r), said = smart ? t("picked for “{intent}”", { intent: smart }) : ""; let s, b; if (w.unlisted) s = unlistedWord(w); - else if (resting) s = `${failWord(rest.why)} · ${restWhen(rest)}`; + else if (resting) s = restSay(rest); else if (w.window) s = t("request longer than its {n} window · passed over", { n: ctxShort(w.window) }); // a row another request weighed, answering that one: the header // tells of this request, so it says the answer is not this one's @@ -2590,7 +2595,7 @@ function routingPage(part) { if (row.st.textContent !== s) row.st.textContent = s; // the intent is the user's own words, of any length: cut short on // the row (routing.css), read whole over it - const full = said && s.includes(said) ? s : ""; + const full = said && s.includes(said) ? s : resting && !w.unlisted ? restTip(rest) : ""; if (row.st.title !== full) { if (full) row.st.title = full; else row.st.removeAttribute("title"); } // an empty title would hide the row's own // an account's windows each, with when they reset, in its tooltip // (#1835): the row says the fullest one while idle and what it is @@ -4010,7 +4015,7 @@ function routingPage(part) { // a line of their own, naming them, under what the account has left const parts = resting ? [] : [...a.mrests].filter(([, x]) => at(x.rest.until) > n) .sort(([m, x], [l, y]) => at(x.rest.until) - at(y.rest.until) || m.localeCompare(l)); - if (resting) { st = `${failWord(a.rest.why)} · ${restWhen(a.rest)}`; cls = "rest"; } + if (resting) { st = restSay(a.rest); cls = "rest"; } else if (w.unlisted) { st = unlistedWord(w); cls = "left"; } else if (w.noURL) st = noURLWord(w); else if (w.known) { @@ -4026,10 +4031,14 @@ function routingPage(part) { el("span", "ok", t("answered {n}", { n: a.ok })), ...(fails.length ? [el("span", "bad", fails.join(", "))] : []), ...(a.last ? [el("span", "", t("last answered {time}", { time: clock(a.last) }))] : [])); - row.append(name, el("div", "st " + cls, st)); + const stEl = el("div", "st " + cls, st); + if (resting && restTip(a.rest)) stEl.title = restTip(a.rest); + row.append(name, stEl); if (parts.length) { const r0 = parts[0][1].rest; - row.append(el("div", "st rest part", `${parts.map(([m]) => m).join(", ")} · ${failWord(r0.why)} · ${restWhen(r0)}`)); + const part = el("div", "st rest part", `${parts.map(([m]) => m).join(", ")} · ${restSay(r0)}`); + if (restTip(r0)) part.title = restTip(r0); + row.append(part); } // a subscription account's windows each, with when they reset, as // the Usage page read them (#1833): the figure above is the one diff --git a/internal/gui/tests/routing-rest-error.test.cjs b/internal/gui/tests/routing-rest-error.test.cjs new file mode 100644 index 000000000..947d747a2 --- /dev/null +++ b/internal/gui/tests/routing-rest-error.test.cjs @@ -0,0 +1,111 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An account resting after a failure that names no kind says the status +// it answered, and the vendor's words are over the row, on the stage and +// in the Accounts table (GanHei37443 on X: three WorkBuddy accounts each +// "failed · back in 16s", and nothing on the page said why). A rest that +// names its kind (quota used up) reads as before. In every language, at a +// wide and a narrow window, in both engines. +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 start = new Date(now.getTime() - 60e3).toISOString(); +const soon = new Date(now.getTime() + 16e3).toISOString(); +const later = new Date(now.getTime() + 10 * 3600e3).toISOString(); +const said = "WorkBuddy: model deepseek-v4.1-flash is not available right now"; +const seat = (user, rest) => ({ + id: "workbuddy@" + user, provider: "workbuddy", name: "WorkBuddy", kind: "account", icon: "workbuddy", + who: user, plan: "Free", model: "deepseek-v4.1-flash", rest, +}); +const failed = (user) => ({ why: "other", status: 500, until: soon, by: "cooldown", key: "workbuddy@" + user, error: said }); +const spent = { why: "quota", status: 429, until: later, by: "window", key: "workbuddy@d@x.test" }; + +function routes() { + const order = [], tries = []; + for (const user of ["a@x.test", "b@x.test", "c@x.test"]) { + const rest = failed(user), s = seat(user, rest); + order.push(s); + tries.push({ id: s.id, model: s.model, start, done: true, status: 500, ms: 300, fail: "other", rest, error: said }); + } + const d = seat("d@x.test", spent); + order.push(d); + tries.push({ id: d.id, model: d.model, start, done: true, status: 429, ms: 300, fail: "quota", rest: spent, error: "quota" }); + return [{ id: 1, seq: 1, time: start, agent: "codex", model: "group/g", provider: "workbuddy", order, tries, done: true, status: 500, ms: 2000, error: said }]; +} + +function serve(lang) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.has("wait")) return; + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1, rerouted: 1, errors: 1 }, routes: routes() }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType }); + }; +} + +const sideways = (page) => page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 1); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}px: a plain failure's rest says its status and the vendor's words`, 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); + page.setDefaultNavigationTimeout(60000); + 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}-${width}-rest-error.png`), fullPage: true }); + } + await browser.close(); + }); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-act").first().waitFor(); + + const stage = (user) => page.locator("li", { has: page.locator("code.mdl") }).filter({ has: page.locator(".who", { hasText: user }) }); + for (const user of ["a@x.test", "b@x.test", "c@x.test"]) { + const li = stage(user); + await li.first().waitFor({ state: "attached" }); + await li.first().evaluate((e) => new Promise((done) => { const ok = () => e.classList.contains("rest") ? done() : requestAnimationFrame(ok); setTimeout(done, 5000); ok(); })); + assert.equal(await li.count(), 1, `${user}: one stage row`); + const em = li.locator("em"); + const text = (await em.textContent()).trim(); + assert(text.startsWith("500 · "), `${user}: the stage row says ${text}`); + assert.equal(await em.getAttribute("title"), said, `${user}: the stage row's words`); + + const act = page.locator(".rt-act", { hasText: user }); + assert.equal(await act.count(), 1); + const st = act.locator(".st.rest"); + assert((await st.textContent()).startsWith("500 · "), `${user}: the Accounts table says ${await st.textContent()}`); + assert.equal(await st.getAttribute("title"), said, `${user}: the Accounts table's words`); + } + const d = stage("d@x.test").locator("em"); + assert(!(await d.textContent()).trim().startsWith("429"), `a quota rest says its status: ${await d.textContent()}`); + assert.equal(await d.getAttribute("title"), null, "a rest without words has a tooltip"); + assert(!(await sideways(page)), "the page scrolls sideways"); + assert.deepEqual(errors, []); + }); + } + } +}