providers, gui: a partner listed since the add sheet last showed the partners puts a small dot on the "+ Add provider" button, its name in the title, until the sheet shows it (yetone: 有了新的合作伙伴的时候,这里能否有个小小的精致优雅的提醒吸引用户点击查看)

Ran: go test ./internal/provider ./internal/gui ./internal/tui .;
partners.test.cjs (chromium + webkit, en/zh at 900 and 440), i18n-keys,
gui-ja, gui-de; GOOS=linux -tags nogui and GOOS=windows builds.
This commit is contained in:
yetone
2026-10-09 01:45:43 +08:00
parent 7d663a2769
commit 05b5965872
10 changed files with 151 additions and 11 deletions
+2 -2
View File
@@ -30,7 +30,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Cursor, Grok and a Kiro key keep the page's cards only. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go) |
| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go) |
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570). | [`served.go`](../../internal/provider/served.go) |
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) |
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) |
| Protocol detection | Works out which of Chat, Responses and Anthropic Messages a base URL speaks when a provider is added; a Gemini URL is not detected, and the editor hides Detect while Gemini is the Base URL's API. Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. User-supplied headers still apply through `Sign`. | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) |
## Runtime path
@@ -63,7 +63,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
go test -tags nogui ./internal/provider -run 'TestAccount|TestCodex|TestGroup|TestQuota|TestLogin|TestSignIn|TestSeveralKeys|TestKeyProtocol|TestSetKeyWeight|TestReadSub2APIKeyLimits|TestSub2APIKeyLimitsOnItsCard|TestKeyAllowance|TestPlanKeyAllowance|TestPayAsYouGoKeyAskedSeldom|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed'
go test -tags nogui ./internal/provider -run 'TestVolcengine|TestQianfan|TestBedrock'
go test -tags nogui ./internal/provider -run '^TestProviderProbesUseProtocolHeaders$'
go test -tags nogui ./internal/provider -run '^Test(Partners|CountPartner)'
go test -tags nogui ./internal/provider -run '^Test(Partners|CountPartner|NoticePartners)'
go test -tags nogui ./internal/provider -run 'TestGeminiBase|TestCustomGeminiProvider|TestFactoryGeminiUnchanged'
node --test internal/gui/tests/partners.test.cjs site/worker.test.mjs
go test -tags nogui ./internal/provider
+5
View File
@@ -1482,6 +1482,11 @@ body.panel .foot { min-height: 0; padding: 5px 8px 7px 14px; border-top: 1px sol
.text.primary { color: var(--accent-fg); background: var(--accent); font-weight: 500; }
.text.primary:hover { filter: brightness(1.08); }
.text.danger:hover { color: var(--red); background: var(--red-soft); }
/* a partner listed since the add sheet last showed them (markNewPartners) */
#addProvider.has-new::after { content: ""; display: inline-block; width: 6px; height: 6px; margin: 0 0 0 5px; border-radius: 50%; background: var(--accent); vertical-align: 6px; box-shadow: 0 0 0 0 var(--accent); animation: new-dot-in .4s cubic-bezier(.3, 1.6, .5, 1), new-dot-ring 2.4s ease-out .4s 2; }
@keyframes new-dot-in { from { transform: scale(0); } }
@keyframes new-dot-ring { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 45%, transparent); } 70%, 100% { box-shadow: 0 0 0 5px transparent; } }
@media (prefers-reduced-motion: reduce) { #addProvider.has-new::after { animation: none; } }
.chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 4px 0 6px; min-height: 12px; }
.chip {
display: inline-flex; align-items: center; gap: 2px;
+16
View File
@@ -4687,6 +4687,7 @@ function renderProviders() {
// scroll to the top; put it back so closing the editor leaves the reader
// where they were.
const view = $("#view-providers"), top = view.scrollTop;
markNewPartners();
keepIcons($("#providers"), $("#offProviders"), $("#addSheet"), $("#excluded"));
view.classList.remove("loading");
view.removeAttribute("aria-busy");
@@ -6505,6 +6506,9 @@ function renderAdd() {
const fresh = partners.filter((p) => !partnersCounted.has(p.id));
for (const p of fresh) partnersCounted.add(p.id);
countPartner("shown", fresh.map((p) => p.id));
// shown, they are new no more (provider.NoticePartners)
for (const p of partners) p.new = false;
markNewPartners();
}
if (subs.length || inPlugins) {
any = true;
@@ -6740,6 +6744,18 @@ function countPartner(what, ids) {
if (ids.length) api("partner", { what, ids }).catch(() => {});
}
// a partner listed since the add sheet last showed the partners puts a
// small dot on the add button, its name in the button's title, until the
// sheet shows it (yetone: 有了新的合作伙伴的时候…提醒吸引用户点击查看)
function markNewPartners() {
const b = $("#addProvider");
if (!b) return;
const fresh = adding ? [] : (providers?.presets || []).filter((p) => p.kind === "partner" && p.new && !p.added && partnerShown(p));
b.classList.toggle("has-new", fresh.length > 0);
if (fresh.length) b.title = t("New in Partners: {names}", { names: fresh.map((p) => p.name).join(", ") });
else b.removeAttribute("title");
}
// a partner's row: its own section says it is sponsored, so no badge
function partnerTile(pr) {
const b = tile({ ...pr, sponsored: false, note: "" });
+4
View File
@@ -1007,6 +1007,7 @@ const I18N = {
"sign in, no key": "登录即可,无需密钥",
"Partners": "合作伙伴",
"magpie's sponsors": "赞助 magpie 的服务",
"New in Partners: {names}": "合作伙伴有新成员:{names}",
"Relays": "中转",
"one key, many vendors": "一个密钥,多家模型",
"Removed from magpie": "已从 magpie 移除",
@@ -4790,6 +4791,7 @@ const I18N = {
"sign in, no key": "登入即可,無需金鑰",
"Partners": "合作夥伴",
"magpie's sponsors": "贊助 magpie 的服務",
"New in Partners: {names}": "合作夥伴有新成員:{names}",
"Relays": "中轉",
"one key, many vendors": "一個金鑰,多家模型",
"Removed from magpie": "已從 magpie 移除",
@@ -8547,6 +8549,7 @@ const I18N = {
"sign in, no key": "サインインのみ、キー不要",
"Partners": "パートナー",
"magpie's sponsors": "magpie のスポンサー",
"New in Partners: {names}": "新しいパートナー:{names}",
"Relays": "中継サービス",
"one key, many vendors": "1 つのキーで複数のベンダー",
"Removed from magpie": "magpie から削除済み",
@@ -12323,6 +12326,7 @@ const I18N = {
"sign in, no key": "anmelden, kein Schlüssel",
"Partners": "Partner",
"magpie's sponsors": "Sponsoren von magpie",
"New in Partners: {names}": "Neu bei den Partnern: {names}",
"Relays": "Relays",
"one key, many vendors": "ein Schlüssel, viele Anbieter",
"Removed from magpie": "Aus magpie entfernt",
+9 -2
View File
@@ -289,6 +289,9 @@ type presetJSON struct {
// a partner's tagline by language, and the languages it is listed in
Notes map[string]string `json:"notes,omitempty"`
Langs []string `json:"langs,omitempty"`
// New: a partner listed since the add sheet last showed the partners,
// and not added; the add button marks it
New bool `json:"new,omitempty"`
}
type gatewayJSON struct {
@@ -645,7 +648,7 @@ func providersState() providersJSON {
}
// partners first, as the add sheet lists them
for _, pa := range provider.Partners() {
s.Presets = append(s.Presets, presetJSON{PresetDef: pa.PresetDef, Added: have[pa.ID], Notes: pa.Notes, Langs: pa.Langs})
s.Presets = append(s.Presets, presetJSON{PresetDef: pa.PresetDef, Added: have[pa.ID], Notes: pa.Notes, Langs: pa.Langs, New: !have[pa.ID] && !provider.PartnerNoticed(pa.ID)})
}
for _, pr := range provider.Presets() {
team := provider.TakesZhipuTeam(provider.Provider{Chat: pr.Chat, Responses: pr.Responses, Anthropic: pr.Anthropic})
@@ -1730,7 +1733,8 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
rw.WriteHeader(http.StatusNoContent)
})
// the add sheet counts what it showed of the partners and what was
// opened of them (provider.CountPartner); only listed partners count
// opened of them (provider.CountPartner); only listed partners count.
// Those shown are no longer new (provider.NoticePartners).
mux.HandleFunc("POST /api/partner", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
What string
@@ -1739,6 +1743,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
_ = json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&in)
if len(in.IDs) <= provider.MaxPartners {
provider.CountPartner(in.What, in.IDs...)
if in.What == provider.PartnerShown {
provider.NoticePartners(in.IDs...)
}
}
rw.WriteHeader(http.StatusNoContent)
})
+39 -1
View File
@@ -36,7 +36,9 @@ function server(lang, list, counted) {
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers, presets: [...list, ...presets], excluded: [], gateway: { running: true, window: true } });
// a partner the sheet showed is new no more, as provider.NoticePartners keeps
const shown = new Set((counted || []).filter((c) => c.what === "shown").flatMap((c) => c.ids));
if (url.pathname === "/api/providers") return json({ providers, presets: [...list.map((p) => (shown.has(p.id) ? { ...p, new: false } : p)), ...presets], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/gateway/trace") return json({ routes: [] });
if (url.pathname.startsWith("/api/")) return json({});
@@ -136,6 +138,42 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(counted.slice(1), [{ what: "opened", ids: ["acme"] }, { what: "keys", ids: ["acme"] }]);
await page.context().close();
});
// a partner listed since the sheet last showed them puts a small dot on
// the add button, named in its title, until the sheet shows it; one
// added, or not listed in the page's language, doesn't
for (const [lang, title] of [["en", "New in Partners: Acme AI"], ["zh", "合作伙伴有新成员:Acme AI, China Only"]]) for (const width of [900, 440]) {
await t.test("new partner dot " + lang + " " + width, async () => {
const page = await (await browser.newContext({ viewport: { width, height: 800 } })).newPage();
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const counted = [];
const list = partners.map((p) => ({ ...p, new: true }));
await page.route("**/*", server(lang, list, counted));
await page.goto("http://magpie.test/?view=providers");
const add = page.locator("#addProvider");
await add.waitFor();
await page.waitForFunction(() => document.querySelector("#addProvider").classList.contains("has-new"));
assert.equal(await add.getAttribute("title"), title);
const dot = await add.evaluate((b) => { const s = getComputedStyle(b, "::after"); const r = b.getBoundingClientRect(); return { w: s.width, h: s.height, bg: s.backgroundColor, over: b.scrollWidth > b.clientWidth + 1, right: r.right <= innerWidth }; });
assert.deepEqual([dot.w, dot.h, dot.over, dot.right], ["6px", "6px", false, true]);
assert.notEqual(dot.bg, "rgba(0, 0, 0, 0)");
// the sheet shows them: no dot, then or after the page comes back
await add.click();
await page.locator("#addSheet .tile").first().waitFor();
assert.equal(await add.evaluate((b) => b.classList.contains("has-new")), false);
await page.keyboard.press("Escape");
await page.locator("#addSheet").waitFor({ state: "hidden" });
assert.equal(await add.evaluate((b) => b.classList.contains("has-new")), false);
assert.equal(await add.getAttribute("title"), null);
await page.reload();
await add.waitFor();
await page.waitForTimeout(200);
assert.equal(await add.evaluate((b) => b.classList.contains("has-new")), false);
assert.deepEqual(errors, []);
await page.context().close();
});
}
await t.test("no partners, no heading", async () => {
const page = await (await browser.newContext({ viewport: { width: 900, height: 800 } })).newPage();
await page.route("**/*", server("en", []));
+45 -5
View File
@@ -11,6 +11,7 @@ import (
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"testing"
@@ -70,6 +71,9 @@ type partnerCache struct {
At time.Time `json:"at"`
Partners []Partner `json:"partners"`
Seen map[string]Partner `json:"seen,omitempty"`
// Noticed are the partners the add sheet has listed to the user; one
// listed since is new, and the add button says so (NoticePartners).
Noticed []string `json:"noticed,omitempty"`
}
var (
@@ -206,13 +210,49 @@ func refreshPartners() {
partnerState.Seen[p.ID] = p
}
partnerNext = now.Add(partnerEvery)
if b, err := json.Marshal(partnerState); err == nil {
_ = os.MkdirAll(filepath.Dir(partnerCacheFile()), 0o755)
tmp := partnerCacheFile() + ".tmp"
if os.WriteFile(tmp, b, 0o644) == nil {
_ = os.Rename(tmp, partnerCacheFile())
savePartners()
}
// savePartners writes what is held to disk; partnerMu held.
func savePartners() {
b, err := json.Marshal(partnerState)
if err != nil {
return
}
_ = os.MkdirAll(filepath.Dir(partnerCacheFile()), 0o755)
tmp := partnerCacheFile() + ".tmp"
if os.WriteFile(tmp, b, 0o644) == nil {
_ = os.Rename(tmp, partnerCacheFile())
}
}
// NoticePartners keeps that the user has been shown the partners ids, so
// they are no longer new. It is kept whether or not they are counted.
func NoticePartners(ids ...string) {
if partnersSource() == "off" {
return
}
partnerMu.Lock()
defer partnerMu.Unlock()
loadPartners()
changed := false
for _, id := range ids {
if _, ok := partnerState.Seen[id]; ok && !slices.Contains(partnerState.Noticed, id) {
partnerState.Noticed = append(partnerState.Noticed, id)
changed = true
}
}
if changed {
savePartners()
}
}
// PartnerNoticed reports whether the user has been shown the partner id.
func PartnerNoticed(id string) bool {
partnerMu.Lock()
defer partnerMu.Unlock()
loadPartners()
return slices.Contains(partnerState.Noticed, id)
}
func fetchPartners(ctx context.Context, src string) ([]Partner, error) {
+26
View File
@@ -241,3 +241,29 @@ func TestPartnersNow(t *testing.T) {
t.Fatalf("PartnersNow waited %v, want its bound", d)
}
}
// A partner is new until the add sheet has shown it; that is kept on disk,
// and only for partners listed at some time.
func TestNoticePartners(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
resetPartners()
t.Cleanup(resetPartners)
var body atomic.Value
body.Store(`{"partners":[{"id":"acme","name":"Acme","chat":"https://a.example/v1"},{"id":"beta","name":"Beta","chat":"https://b.example/v1"}]}`)
t.Setenv("MAGPIE_PARTNERS", partnerFeedServer(t, &body).URL)
fetchPartnersNow()
if PartnerNoticed("acme") || PartnerNoticed("beta") {
t.Fatal("noticed before shown")
}
NoticePartners("acme", "nobody")
resetPartners()
if !PartnerNoticed("acme") || PartnerNoticed("beta") || PartnerNoticed("nobody") {
t.Fatalf("after a restart: acme %v beta %v nobody %v", PartnerNoticed("acme"), PartnerNoticed("beta"), PartnerNoticed("nobody"))
}
// a fetch keeps what was noticed
body.Store(`{"partners":[{"id":"acme","name":"Acme","chat":"https://a.example/v1"},{"id":"gamma","name":"Gamma","chat":"https://g.example/v1"}]}`)
fetchPartnersNow()
if !PartnerNoticed("acme") || PartnerNoticed("gamma") {
t.Fatalf("after a fetch: acme %v gamma %v", PartnerNoticed("acme"), PartnerNoticed("gamma"))
}
}
+4 -1
View File
@@ -407,7 +407,10 @@ func (m *model) openPresets() {
items = append(items, agent.Option{Value: d.ID, Note: d.Name + " · partner (sponsor)"})
shown = append(shown, d.ID)
}
go provider.CountPartner(provider.PartnerShown, shown...)
go func() {
provider.CountPartner(provider.PartnerShown, shown...)
provider.NoticePartners(shown...)
}()
for _, d := range provider.Presets() {
items = append(items, agent.Option{Value: d.ID, Note: d.Name + " · " + string(d.Kind)})
}
+1
View File
@@ -198,6 +198,7 @@ func presets() error {
shown = append(shown, pa.ID)
}
provider.CountPartner(provider.PartnerShown, shown...)
provider.NoticePartners(shown...)
for _, pr := range append(all, provider.Presets()...) {
if pr.Kind != kind {
kind = pr.Kind