diff --git a/internal/gateway/history.go b/internal/gateway/history.go index f73c3ef7e..b5f71c479 100644 --- a/internal/gateway/history.go +++ b/internal/gateway/history.go @@ -508,7 +508,8 @@ type Tally struct { Tried int `json:"tried"` OK int `json:"ok"` Fails map[string]int `json:"fails,omitempty"` - Last int64 `json:"last,omitempty"` // ms, of its latest answer + Last int64 `json:"last,omitempty"` // ms, of its latest answer + AuthAt int64 `json:"authAt,omitempty"` // ms, of its latest try refused for its sign-in (failAuth) Models []string `json:"models,omitempty"` Rest *Rest `json:"rest,omitempty"` // how its latest try left it RestAt int64 `json:"restAt,omitempty"` // ms, of when it did @@ -681,6 +682,9 @@ func foldTally(tallies map[string]*Tally, line []byte) { a.Fails = map[string]int{} } a.Fails[f]++ + if f == failAuth { + a.AuthAt = max(a.AuthAt, end) + } } if tr.Rest != nil && tr.Rest.Model == "" && end >= a.RestAt { rest := *tr.Rest diff --git a/internal/gateway/history_tallies_test.go b/internal/gateway/history_tallies_test.go index 10eed9f9b..fafa1d13d 100644 --- a/internal/gateway/history_tallies_test.go +++ b/internal/gateway/history_tallies_test.go @@ -91,3 +91,35 @@ func TestDayTalliesFoldOnlyWhatWasAdded(t *testing.T) { t.Errorf("another folder's day: %v", got) } } + +// The Routing page asks to sign an account in again while its latest +// refusal for its sign-in is newer than its latest answer (adorable_piglet +// on Discord: "2 需要重新登录" and nowhere to sign in): the day's tally +// says when that refusal was, beside when it last answered. +func TestDayTalliesSayWhenSignInWasRefused(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + now := historyNoon(t) + route := func(i int, status int, fail string) Route { + w := Weighed{ID: "codex@b", Provider: "codex", Name: "Codex", Kind: "account", Who: "b@example.com", Agent: "codex", Model: "gpt-5"} + tr := Try{ID: w.ID, Start: now.Add(time.Duration(i) * time.Minute), Done: true, Millis: 100, Status: status, Fail: fail} + return Route{ID: int64(i + 1), Time: tr.Start, Done: true, Model: "gpt-5", Provider: "codex", Order: []Weighed{w}, Tries: []Try{tr}} + } + saveRoute(route(0, 200, "")) + saveRoute(route(1, 401, failAuth)) + saveRoute(route(2, 502, "other")) + a := DayTallies()[`["codex","b@example.com"]`] + refused := now.Add(time.Minute).UnixMilli() + 100 + if a.AuthAt != refused || a.Fails[failAuth] != 1 { + t.Fatalf("refused at %d (%d of them), want %d", a.AuthAt, a.Fails[failAuth], refused) + } + if a.Last >= a.AuthAt { + t.Fatalf("answered at %d, after the refusal at %d", a.Last, a.AuthAt) + } + // it answers again: the refusal is older than that answer, and stays + // when it was + saveRoute(route(3, 200, "")) + a = DayTallies()[`["codex","b@example.com"]`] + if a.AuthAt != refused || a.Last <= a.AuthAt { + t.Errorf("after an answer: refused at %d, answered at %d", a.AuthAt, a.Last) + } +} diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 070b8ec26..533a80b43 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -4167,14 +4167,14 @@ function routingPage(part) { // picked, counts its own list as before. const seed = !day && !purpose.length && tallies && Object.keys(tallies).length ? tallies : null; if (seed) for (const [k, x] of Object.entries(seed)) { - by.set(k, { w: x, tried: x.tried, ok: x.ok, fails: { ...x.fails }, last: x.last || 0, + by.set(k, { w: x, tried: x.tried, ok: x.ok, fails: { ...x.fails }, last: x.last || 0, authAt: x.authAt || 0, rest: x.rest || null, restAt: x.restAt || 0, seen: 0, pos: 0, at: 0, models: new Set(x.models || []), mrests: new Map() }); } for (const r of [...rs].reverse()) { // oldest first, so the latest wins const candidates = new Map(); r.order.forEach((w, i) => { const key = keyOf(w); - const a = by.get(key) || { w, tried: 0, ok: 0, fails: {}, last: 0, rest: null, restAt: 0, seen: 0, pos: 0, models: new Set(), mrests: new Map() }; + const a = by.get(key) || { w, tried: 0, ok: 0, fails: {}, last: 0, authAt: 0, rest: null, restAt: 0, seen: 0, pos: 0, models: new Set(), mrests: new Map() }; a.w = w; a.seen++; a.pos = i; a.at = r.time; // a later request found it resting, or not: the account as a // whole, or one of its models alone (#1960), which leaves the @@ -4190,6 +4190,9 @@ function routingPage(part) { const a = candidates.get(tr.id); if (!a || !tr.done || tr.fail === "canceled") continue; // the agent's doing, not its const end = at(tr.start) + (tr.ms || 0); + // refused for its sign-in: asked to sign in again until it answers + // after that (adorable_piglet on Discord) + if (tr.fail === "auth" && !tryOk(tr)) a.authAt = Math.max(a.authAt, end); if (seed) { // counted from the day already; when it last answered is news all the same if (tryOk(tr)) a.last = Math.max(a.last, end); } else { @@ -4279,7 +4282,12 @@ function routingPage(part) { } else if (w.kind === "account") st = t("what's left not known yet"); else st = ""; const tally = el("div", "tally"); - const fails = Object.entries(a.fails).map(([k, v]) => `${v} ${failWord(k)}`); + // refused for its sign-in, and not answered since: it is to be signed + // in again, here where the card says so. Answered since, the + // refusals are the day's past, not what it needs now (adorable_piglet + // on Discord: "2 需要重新登录" on an account the editor showed in use) + const signIn = w.kind === "account" && a.authAt > a.last; + const fails = Object.entries(a.fails).map(([k, v]) => `${v} ${k === "auth" && a.authAt && !signIn ? t("sign-in refused (answered since)") : failWord(k)}`); tally.append( el("span", "", t("tried {n}", { n: a.tried })), el("span", "ok", t("answered {n}", { n: a.ok })), @@ -4335,6 +4343,13 @@ function routingPage(part) { fix.append(go); row.append(fix); } + if (signIn && !day) { + let fix = row.querySelector(".fix"); + if (!fix) row.append(fix = el("div", "fix")); + const again = el("button", "link rt-signin", t("Sign in again")); + again.onclick = () => signInAgain(w); + fix.append(again); + } if (w.known && w.balance == null) { const bar = el("div", "bar"), bi = el("i"); bi.style.width = fill(w); @@ -4347,6 +4362,16 @@ function routingPage(part) { patch(acts, out); } + // signInAgain signs the account of seat w in again, in its provider's + // editor on the Providers page, where the sign-in's steps are drawn: as + // the editor's own Sign in again does. Codex's own sign-in (relayed as + // Codex sent it) is Codex's provider's, its account the one signed in. + async function signInAgain(w) { + const own = w.provider === "openai" && w.agent === "codex"; + await openProvider(own ? "codex" : w.provider); + startSignIn(own ? "codex" : w.agent || w.provider, false, undefined, own ? {} : { user: w.who }); + } + // keysRow sums a provider's keys up over the requests listed: how many, // how many rest now, and what they were tried and answered together // The row is kept from one drawing to the next, as the one clicked is diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 340d48946..f14cf807b 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -2,6 +2,7 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "sign-in refused (answered since)": "登录曾被拒(之后已应答)", "Free first uses it before paid ones, and Cheapest first counts it as costing nothing": "免费优先会先用它再用付费的,最便宜优先把它算作不花钱", "{name}, {n} accounts: {windows}": "{name}({n} 个账号):{windows}", "What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "本组可用的这家供应商账号合起来还剩多少:同一单位的额度相加,百分比取同一套餐账号的平均值。各账号详情在用量页。", @@ -656,6 +657,7 @@ magpie.strings({ "This group may spend every account of {provider}": "这个组可以消耗 {provider} 的每个账号", }, "zh-TW": { + "sign-in refused (answered since)": "登入曾被拒(之後已應答)", "Free first uses it before paid ones, and Cheapest first counts it as costing nothing": "免費優先會先用它再用付費的,最便宜優先把它算作不花錢", "{name}, {n} accounts: {windows}": "{name}({n} 個帳號):{windows}", "What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "本組可用的這家供應商帳號合起來還剩多少:同一單位的額度相加,百分比取同一方案帳號的平均值。各帳號詳情在用量頁。", @@ -1310,6 +1312,7 @@ magpie.strings({ "This group may spend every account of {provider}": "這個組可以消耗 {provider} 的每個帳號", }, ja: { + "sign-in refused (answered since)": "サインイン拒否(その後は応答あり)", "Free first uses it before paid ones, and Cheapest first counts it as costing nothing": "無料優先は有料より先にこれを使い、最安優先はこれを費用ゼロとして数えます", "{name}, {n} accounts: {windows}": "{name}({n} アカウント):{windows}", "What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "このグループが使えるこのプロバイダーのアカウントの残りの合計:同じ単位の量は足し合わせ、割合は同じプランのアカウントの平均。各アカウントは使用量ページにあります。", @@ -1964,6 +1967,7 @@ magpie.strings({ "This group may spend every account of {provider}": "このグループは {provider} のすべてのアカウントを使えます", }, de: { + "sign-in refused (answered since)": "Anmeldung abgelehnt (seitdem beantwortet)", "Free first uses it before paid ones, and Cheapest first counts it as costing nothing": "„Kostenlos zuerst“ nutzt es vor bezahlten, „Günstigste zuerst“ zählt es als kostenlos", "{name}, {n} accounts: {windows}": "{name}, {n} Konten: {windows}", "What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "Was von den Konten dieses Anbieters, die die Gruppe nutzen kann, zusammen übrig ist: Mengen derselben Einheit addiert, ein Anteil als Mittelwert der Konten mit demselben Tarif. Die einzelnen Konten stehen auf der Seite Nutzung.", diff --git a/internal/gui/tests/routing-sign-in-again.test.cjs b/internal/gui/tests/routing-sign-in-again.test.cjs new file mode 100644 index 000000000..586461af9 --- /dev/null +++ b/internal/gui/tests/routing-sign-in-again.test.cjs @@ -0,0 +1,104 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// adorable_piglet on Discord: the Routing page's Codex card said "2 需要重新登录" +// (sign-in required) on an account the editor showed in use, with nowhere +// to sign it in again. Now an account refused for its sign-in and not +// answered since has Sign in again on its card, which signs it in again +// on the Providers page as the editor does; one that has answered since +// says its refusals were before that, with no button. Both engines, wide +// and narrow, every 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 = Date.now(); +const seat = (who) => ({ id: "codex@" + who, provider: "codex", name: "Codex", who, kind: "account", agent: "codex", model: "gpt-6.1-sol" }); +const tallies = { + // refused at 10:45, last answered at 10:41 + '["codex","stale@example.com"]': { ...seat("stale@example.com"), tried: 14, ok: 8, fails: { auth: 2, other: 4 }, last: now - 600000, authAt: now - 360000 }, + // refused, then answered + '["codex","fine@example.com"]': { ...seat("fine@example.com"), tried: 10, ok: 8, fails: { auth: 2 }, last: now - 60000, authAt: now - 360000 }, +}; +// one request the gateway still keeps: the fine account answering it +const iso = (ms) => new Date(ms).toISOString(); +const routes = [{ id: 100, seq: 100, time: iso(now - 61000), agent: "codex", model: "gpt-6.1-sol", provider: "codex", done: true, status: 200, ms: 300, + order: [seat("fine@example.com")], tries: [{ id: "codex@fine@example.com", model: "gpt-6.1-sol", start: iso(now - 61000), done: true, ms: 250, status: 200 }] }]; +const words = { + en: ["2 sign-in required, 4 failed", "Sign in again", "2 sign-in refused (answered since)"], + zh: ["2 需要重新登录, 4 失败", "重新登录", "2 登录曾被拒(之后已应答)"], + "zh-TW": ["2 需要重新登入, 4 失敗", "重新登入", "2 登入曾被拒(之後已應答)"], + ja: ["2 サインインが必要です, 4 失敗", "再度サインイン", "2 サインイン拒否(その後は応答あり)"], + de: ["2 Anmeldung erforderlich, 4 fehlgeschlagen", "Erneut anmelden", "2 Anmeldung abgelehnt (seitdem beantwortet)"], +}; + +function serve(lang, signins) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light", quotaLeft: false } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes + return json({ mine: true, now: new Date().toISOString(), seq: 100, totals: { requests: 24, rerouted: 0, errors: 8 }, routes }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [{ day: new Date(now).toISOString().slice(0, 10), requests: 24 }], routes: [], tallies }); + if (url.pathname === "/api/signin" && r.request().method() === "POST") { + signins.push(r.request().postDataJSON()); + return json({ id: "s1", agent: "codex", state: "waiting", linkOnly: true }); + } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage/quotas/history") return json([]); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + 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 r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: an account refused for its sign-in is signed in again from its card`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const width of [1100, 420]) for (const lang of Object.keys(words)) { + await t.test(`${lang} at ${width}px`, async () => { + const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + try { + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], signins = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, signins)); + await page.goto("http://magpie.test/?view=routing"); + const [needs, again, past] = words[lang]; + const stale = page.locator(".rt-act", { hasText: "stale@example.com" }).first(); + await stale.locator(".tally .bad", { hasText: needs }).waitFor(); + // answered since: its refusals are past, and nothing to do + const fine = page.locator(".rt-act", { hasText: "fine@example.com" }).first(); + assert.equal(await fine.locator(".tally .bad").textContent(), past); + assert.equal(await fine.locator("button").count(), 0); + // not answered since: Sign in again, where the card says it + const b = stale.locator("button.rt-signin"); + assert.equal(await b.textContent(), again); + const box = await b.boundingBox(); + assert.ok(box && box.x >= 0 && box.x + box.width <= width, `the button is on the screen at ${width}px: ${JSON.stringify(box)}`); + await b.click(); + await page.locator("#view-providers").waitFor({ state: "visible" }); + for (let i = 0; i < 50 && !signins.length; i++) await page.waitForTimeout(100); + // the account the card is of (a page served remotely signs Codex + // in by its device code, as the editor's button does) + assert.deepEqual(signins.map((b) => [b.agent, b.user]), [["codex", "stale@example.com"]]); + assert.deepEqual(errors, []); + } finally { + await ctx.close(); + } + }); + } + }); +}