diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 1469f7529..cb4cf9ab8 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -353,6 +353,8 @@ The GUI's plugin integration includes `subOf`, `pluginSubs`, and `startPluginSig A plugin may expose `auth.accountConcurrency(getAuth, { signal })`, returning a positive integer for the account passed to `getAuth`. During `providers`, [`host.js`](../../internal/plugin/host.js) runs the hook separately for every account, in that account's scope and through its proxy, after the normal credential refresh. The calls run beside model discovery and share the provider-list deadline. The returned value is listed as `plugin.Account.MaxConcurrency`; `Cached` retains the last listed value across cache rebuilds. +The optional `auth.accountPlan(getAuth, { signal })` hook follows the same account scope, proxy, refresh and deadline rules, returning a short subscription name. It is listed as `plugin.Account.Plan` and shown beside the account in the provider editor. When the account is automatic, its concurrency menu names the plan and recommended limit. A missing or failed plan hook leaves the account's existing plan and numeric concurrency behavior unchanged. Plugins can share one subscription request between the two hooks; keeping them separate lets a new plugin retain numeric automatic concurrency on an older core that ignores `accountPlan`. + [`Provider.LaneLimit`](../../internal/provider/concurrency.go) applies an account's manual `AccountConcurrency` first, then the provider's manual `MaxConcurrency`, then the plugin account value, and finally the plugin's static `magpie.maxConcurrency`/`auth.maxConcurrency`. An automatic value is never saved into either manual map. `/api/providers` exposes the automatic values separately as `accountPluginConcurrency`, keyed by lowercase account reference, so the editor can show an account-specific Automatic choice. A missing hook, timeout, failed read, or invalid result leaves that entry absent and preserves the old static-default behavior. The auxiliary read must not mark the account's sign-in expired. `TestProvidersListEachAccountsConcurrency`, `TestPluginAccountLaneLimits`, and `provider-concurrency.test.cjs` cover the host handoff, priority and restoration to automatic, and GUI presentation. ## Verification diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 50f16db8e..d763f2b00 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -14748,6 +14748,11 @@ function laneManualBase(p) { function laneAutomatic(p, ref) { return laneManualBase(p) == null && Object.prototype.hasOwnProperty.call(p?.accountPluginConcurrency || {}, String(ref).toLowerCase()); } +function lanePlan(p, ref) { + const account = p?.account, key = String(ref).toLowerCase(); + if (String(account?.user || "").toLowerCase() === key && account.plan) return account.plan; + return account?.logins?.find((l) => String(l.user).toLowerCase() === key)?.plan || ""; +} function laneBase(p, ref) { const manual = laneManualBase(p); if (manual != null) return manual; @@ -14793,8 +14798,9 @@ function laneLimitPill(p, ref, who, name) { pill.onclick = (e) => { e.stopPropagation(); if (pill.classList.contains("open")) return closeProtoMenu(); - const base = laneBase(p, ref), automatic = laneAutomatic(p, ref); - const opts = [{ v: "default", name: automatic ? t("Automatic") : "Provider's", note: base ? t("{n} at once", { n: base }) : t("No limit") }, { v: 0, name: "No limit", note: "Any number at once" }]; + const base = laneBase(p, ref), automatic = laneAutomatic(p, ref), plan = automatic ? lanePlan(p, ref) : ""; + const automaticNote = plan && base ? t("{plan} · recommended: {n} at once", { plan, n: base }) : base ? t("{n} at once", { n: base }) : t("No limit"); + const opts = [{ v: "default", name: automatic ? t("Automatic") : "Provider's", note: automaticNote }, { v: 0, name: "No limit", note: "Any number at once" }]; const nums = own == null || own === 0 || LANE_LIMITS.includes(own) ? LANE_LIMITS : [...LANE_LIMITS, own].sort((a, b) => a - b); for (const n of nums) opts.push({ v: n, name: String(n), note: "", literalName: true }); opts.push({ v: -1, name: "Other…", note: "A number of your own, up to 1000" }); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 24d8b7ea1..a63a02799 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3010,6 +3010,7 @@ const I18N = { "{n}/{max} running": "{n}/{max} 运行中", "{n} running": "{n} 运行中", "{n} at once": "并发 {n}", + "{plan} · recommended: {n} at once": "{plan} · 推荐并发 {n}", "No limit at once": "并发不限", "its own": "单独设置", "the provider's": "沿用提供商设置", @@ -8532,6 +8533,7 @@ const I18N = { "{n}/{max} running": "{n}/{max} 執行中", "{n} running": "{n} 執行中", "{n} at once": "並行 {n}", + "{plan} · recommended: {n} at once": "{plan} · 建議並行 {n}", "No limit at once": "並行不限", "its own": "單獨設定", "the provider's": "沿用提供商設定", @@ -14025,6 +14027,7 @@ const I18N = { "{n}/{max} running": "{n}/{max} 実行中", "{n} running": "{n} 実行中", "{n} at once": "同時 {n}", + "{plan} · recommended: {n} at once": "{plan} · 推奨同時リクエスト数 {n}", "No limit at once": "同時数 無制限", "its own": "個別設定", "the provider's": "プロバイダーの設定", @@ -19561,6 +19564,7 @@ const I18N = { "{n}/{max} running": "{n}/{max} laufen", "{n} running": "{n} laufen", "{n} at once": "{n} gleichzeitig", + "{plan} · recommended: {n} at once": "{plan} · empfohlen: {n} gleichzeitig", "No limit at once": "Gleichzeitig unbegrenzt", "its own": "eigene Einstellung", "the provider's": "die des Anbieters", diff --git a/internal/gui/tests/provider-concurrency.test.cjs b/internal/gui/tests/provider-concurrency.test.cjs index cf90c7057..5106c4b9c 100644 --- a/internal/gui/tests/provider-concurrency.test.cjs +++ b/internal/gui/tests/provider-concurrency.test.cjs @@ -39,9 +39,9 @@ const lemon = { const kimi = { id: "kimi-work", name: "Kimi Work", icon: "generic", chat: "plugin://kimi-work/v1", responses: "", anthropic: "", catalog: "", models: [{ id: "k3-agent", name: "K3", on: true }], agents: [], fallback: [], headers: {}, keyList: [], - account: { agent: "kimi-work", agentName: "Kimi Work", user: "a@example.com", plan: "", logins: [ - { user: "a@example.com", plan: "", active: true, on: true }, - { user: "b@example.com", plan: "", on: true }, + account: { agent: "kimi-work", agentName: "Kimi Work", user: "a@example.com", plan: "Moderato", logins: [ + { user: "a@example.com", plan: "Moderato", active: true, on: true }, + { user: "b@example.com", plan: "Allegro", on: true }, ] }, proxy: "", maxConcurrency: null, pluginConcurrency: 1, accountPluginConcurrency: { "a@example.com": 2, "b@example.com": 4 }, @@ -197,14 +197,20 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const { page, errors } = await open(t, "Kimi Work"); assert.equal(await box(page).inputValue(), ""); assert.equal(await box(page).getAttribute("placeholder"), w.automatic); - const a = page.locator('.editor .accts .acc[data-account-id="a@example.com"] .alane'); - const b = page.locator('.editor .accts .acc[data-account-id="b@example.com"] .alane'); + const rowA = page.locator('.editor .accts .acc[data-account-id="a@example.com"]'); + const rowB = page.locator('.editor .accts .acc[data-account-id="b@example.com"]'); + const a = rowA.locator('.alane'); + const b = rowB.locator('.alane'); + assert.equal(await rowA.locator('.acc-line > .plan').textContent(), "Moderato"); + assert.equal(await rowB.locator('.acc-line > .plan').textContent(), "Allegro"); assert.equal(await a.textContent(), lang === "zh" ? "并发 2" : "2 at once"); assert.equal(await b.textContent(), lang === "zh" ? "并发 4" : "4 at once"); await a.click(); const option = page.locator(".proto-menu .pm-item", { has: page.locator(".pm-name", { hasText: w.automaticMenu }) }); assert.equal(await option.count(), 1); - assert.equal(await option.locator(".pm-note").textContent(), lang === "zh" ? "并发 2" : "2 at once"); + assert.equal(await option.locator(".pm-note").textContent(), lang === "zh" ? "Moderato · 推荐并发 2" : "Moderato · recommended: 2 at once"); + const translated = await page.evaluate(() => ["zh", "zh-TW", "ja", "de"].every((lang) => I18N[lang]["{plan} · recommended: {n} at once"])); + assert.equal(translated, true, "every GUI language translates the plan recommendation"); assert.deepEqual(errors, []); }); diff --git a/internal/plugin/account_concurrency_test.go b/internal/plugin/account_concurrency_test.go index 22dc99b1d..a6f00f1ce 100644 --- a/internal/plugin/account_concurrency_test.go +++ b/internal/plugin/account_concurrency_test.go @@ -48,14 +48,19 @@ func TestProvidersListEachAccountsConcurrency(t *testing.T) { t.Fatal(err) } got := map[string]any{} + plans := map[string]any{} for _, a := range accounts { got[a["accountId"].(string)] = a["maxConcurrency"] + plans[a["accountId"].(string)] = a["plan"] } if got["a@example.com"] != float64(2) || got["b@example.com"] != float64(4) { t.Errorf("per-account limits = %v, want A=2 and B=4; raw %s", got, b) } - if got["bad@example.com"] != nil { - t.Errorf("a failed subscription read passed a limit instead of the static fallback: %v", got) + if plans["a@example.com"] != "Moderato" || plans["b@example.com"] != "Allegro" { + t.Errorf("per-account plans = %v, want A=Moderato and B=Allegro; raw %s", plans, b) + } + if got["bad@example.com"] != nil || plans["bad@example.com"] != nil { + t.Errorf("a failed subscription read passed automatic values instead of the static fallback: limit=%v plan=%v", got["bad@example.com"], plans["bad@example.com"]) } if by["plan"].MaxConcurrency != 1 || by["legacy"].MaxConcurrency != 3 { t.Errorf("static plugin limits changed: plan=%d legacy=%d", by["plan"].MaxConcurrency, by["legacy"].MaxConcurrency) diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 17fae33c2..d5493d0c6 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -2544,6 +2544,27 @@ async function accountConcurrency(id, a, key, through, signal) { } } +// accountPlan asks for the subscription name shown beside the account and +// its automatic limit. It is optional and independent of the numeric hook, +// so a new plugin on an old core still supplies automatic concurrency. +async function accountPlan(id, a, key, through, signal) { + if (typeof a.auth.accountPlan !== "function") return "" + const ctl = new AbortController(), stop = () => ctl.abort() + if (signal?.aborted) stop() + else signal?.addEventListener("abort", stop, { once: true }) + try { + return await inTime(() => via.run(through(key), () => inScope(id, key, async () => { + await fresh(id, key) + const name = await a.auth.accountPlan(async () => authCopy(key), { signal: ctl.signal }) + return typeof name === "string" ? name.trim().slice(0, 100) : "" + })), listWait, "the plugin's account plan", ctl) + } catch { + return "" + } finally { + signal?.removeEventListener("abort", stop) + } +} + // atOnceOf is how many of its accounts the plugin says may take requests // at the same time, magpie's own field: the auth hook's maxAccounts, else // package.json's magpie.maxAccounts, as concurrencyOf reads its own. The @@ -2603,13 +2624,13 @@ async function providers({ proxies, off } = {}, signal) { const gen = infoGen if (quiet.has(id)) { const p = await info(id, undefined, false, listWait, true) - return rowOf(id, a, keys, stored, p, [], []) + return rowOf(id, a, keys, stored, p, [], [], []) } // every account is listed side by side, each hook given listWait: a // second account no longer waits behind the first, where two // listWaits back to back took one provider past refreshDeadline twice // over (#4065) - const [p, own, limits] = await Promise.all([ + const [p, own, limits, plans] = await Promise.all([ via.run(through(), () => info(id, undefined, false, listWait, false, signal)).then((q) => (keepInfo(keys[0] ?? id, q, gen), q)), // each account's own models, as the built-ins read each account's: a // plan may serve fewer, or others, than the first account's. One that @@ -2617,16 +2638,17 @@ async function providers({ proxies, off } = {}, signal) { // told to have, as a built-in account whose fetch failed keeps its own. Promise.all(keys.slice(1).map((k) => via.run(through(k), () => info(id, k, true, listWait, false, signal)).then((q) => (keepInfo(k, q, gen), q)).catch((e) => ({ failed: true, listError: e?.message ?? String(e) })))), Promise.all(keys.map((k) => accountConcurrency(id, a, k, through, signal))), + Promise.all(keys.map((k) => accountPlan(id, a, k, through, signal))), ]) - return rowOf(id, a, keys, stored, p, own, limits) + return rowOf(id, a, keys, stored, p, own, limits, plans) } return Promise.all([...auths()].map(row)) } // rowOf is the providers row of id (registered as a), its accounts keys -// of stored, p its info and own the other accounts' infos. limits are the -// accounts' automatic request limits, in the same order as keys. -function rowOf(id, a, keys, stored, p, own, limits) { +// of stored, p its info and own the other accounts' infos. limits and plans +// are the accounts' automatic request limits and plan names, in key order. +function rowOf(id, a, keys, stored, p, own, limits, plans) { const models = { ...p.models } for (const q of own) for (const [k, m] of Object.entries(q?.models ?? {})) models[k] ??= m const ids = (q) => Object.values(q.models).filter((m) => m.status !== "deprecated").map((m) => m.id) @@ -2682,6 +2704,7 @@ function rowOf(id, a, keys, stored, p, own, limits) { fellBack: i === 0 ? !!p.fellBack : !!(own[i - 1]?.fellBack || own[i - 1]?.failed), listError: (i === 0 ? p.fellBack && p.listError : own[i - 1]?.listError) || "", maxConcurrency: limits[i] || undefined, + plan: plans[i] || undefined, })), models: Object.values(models) .filter((m) => m.status !== "deprecated") diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 847a37fa7..d898afa42 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -298,6 +298,8 @@ type Account struct { // MaxConcurrency is this account's automatic limit from the plugin's // accountConcurrency hook; 0 leaves the provider's static plugin default. MaxConcurrency int `json:"maxConcurrency,omitempty"` + // Plan is the account's subscription name from the optional accountPlan hook. + Plan string `json:"plan,omitempty"` } var ( @@ -751,7 +753,7 @@ func Cached() []Provider { for _, w := range was { if w.Key == a.Key { p.Accounts[i].Models, p.Accounts[i].FellBack, p.Accounts[i].ListError = w.Models, w.FellBack, w.ListError - p.Accounts[i].MaxConcurrency = w.MaxConcurrency + p.Accounts[i].MaxConcurrency, p.Accounts[i].Plan = w.MaxConcurrency, w.Plan } } } diff --git a/internal/plugin/testdata/accountconcurrency/index.js b/internal/plugin/testdata/accountconcurrency/index.js index 71d5ab30f..414f36437 100644 --- a/internal/plugin/testdata/accountconcurrency/index.js +++ b/internal/plugin/testdata/accountconcurrency/index.js @@ -7,6 +7,11 @@ export const Plan = async () => ({ if (auth.accountId === "bad@example.com") throw new Error("subscription unavailable") return auth.accountId === "a@example.com" ? 2 : 4 }, + accountPlan: async (getAuth) => { + const auth = await getAuth() + if (auth.accountId === "bad@example.com") throw new Error("subscription unavailable") + return auth.accountId === "a@example.com" ? "Moderato" : "Allegro" + }, methods: [{ type: "api", label: "API key" }], }, }) diff --git a/internal/provider/account_plugin_concurrency_test.go b/internal/provider/account_plugin_concurrency_test.go index fada172a9..0628f6179 100644 --- a/internal/provider/account_plugin_concurrency_test.go +++ b/internal/provider/account_plugin_concurrency_test.go @@ -7,6 +7,18 @@ import ( "github.com/yetone/magpie/internal/plugin" ) +func TestPluginAccountPlanReachesProvider(t *testing.T) { + pp := plugin.Provider{ID: "kimi-work", Accounts: []plugin.Account{{Key: "kimi-work", AccountID: "a@example.com", Plan: "Moderato"}}} + login := pluginLogin{sideLogin: sideLogin{Login: Login{User: "a@example.com", Plan: "Saved plan"}}, acct: pp.Accounts[0]} + if got := pluginProvider(pp, login).Account.Plan; got != "Moderato" { + t.Errorf("plugin account plan = %q, want Moderato over the saved plan", got) + } + login.acct.Plan = "" + if got := pluginProvider(pp, login).Account.Plan; got != "Saved plan" { + t.Errorf("account without a plugin plan = %q, want the saved plan", got) + } +} + func TestPluginAccountLaneLimits(t *testing.T) { var pp plugin.Provider if err := json.Unmarshal([]byte(`{ diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index 1b744c110..36c93ec76 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -576,7 +576,11 @@ func pluginProviderServing(pp plugin.Provider, l pluginLogin, keys []string) Pro if name == "" { name = pp.ID } - a := &Account{Agent: "plugin", User: user, Plan: l.Plan, Stream: true, plugin: &pp, pluginKey: acct.Key} + plan := acct.Plan + if plan == "" { + plan = l.Plan + } + a := &Account{Agent: "plugin", User: user, Plan: plan, Stream: true, plugin: &pp, pluginKey: acct.Key} if pp.ID == "grok" { // Codex's namespaced tools go to Grok flat, as the built-in sends // them (#404): the plugin's own rewrite would leave them out; and