diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index cc2853e8f..0a2bf54db 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -3320,6 +3320,21 @@ function drawEditor(p, presetID) { // magpie's, the Usage page shows them if (p?.stepPlan) ed.append(...field(t("Step Plan usage"), renderStepPlan(p.stepPlan), t("A key tells only the balance. The Step Plan's 5-hour, weekly and credit windows are told only to a StepFun sign-in: bring yours here once and magpie keeps it (for 30 days), used for nothing else."))); + // a key on a team's GLM Coding Plan is told the team's windows only with + // the team's organization and project, which the console shows (#236) + const team = p ? !!p.zhipuTeam : !!pr?.zhipuTeam; + if (team) { + draft.zhipuTeam = draft.zhipuTeam || { org: p?.zhipuTeam?.org || "", project: p?.zhipuTeam?.project || "" }; + const org = input(draft.zhipuTeam.org, t("optional · only for a team plan")); + org.classList.add("team-org"); + org.oninput = () => { draft.zhipuTeam.org = org.value; }; + const proj = input(draft.zhipuTeam.project, t("optional · only for a team plan")); + proj.classList.add("team-project"); + proj.oninput = () => { draft.zhipuTeam.project = proj.value; }; + ed.append(...field(t("Team org ID"), org, "")); + ed.append(...field(t("Team project ID"), proj, t("Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.", { p: pr?.name || p.name }))); + } + // a relay that offers several regional endpoints, or a vendor whose plans // are served at their own: one selector, and the provider's base URLs follow it let refreshEndpoints = () => {}; @@ -3478,6 +3493,12 @@ function drawEditor(p, presetID) { if (body.proxy === null) { ed.querySelector(".proxy-url")?.focus(); return editorError(t("Proxy: type its address, like http://127.0.0.1:7890"), "warn"); } if (draft.balanceToken) body.balanceToken = draft.balanceToken; else if (draft.clearBalanceToken) body.clearBalanceToken = true; + if (team) { + // both or neither: {} clears them + const org = (draft.zhipuTeam.org || "").trim(), project = (draft.zhipuTeam.project || "").trim(); + if (!org !== !project) { ed.querySelector(org ? ".team-project" : ".team-org")?.focus({ preventScroll: true }); return editorError(t("Team plan: give both the organization ID and the project ID"), "warn"); } + body.zhipuTeam = org ? { org, project } : {}; + } if (isNew && custom && !body.name) { name.focus(); return editorError(t("Give it a name"), "warn"); } if (isNew && custom && !body.chat && !body.anthropic && !body.responses) { url.focus(); return editorError(t("A base URL is needed"), "warn"); } if (endpoint && !body.chat && !body.responses) { endpoint.focus(); return editorError(t("Your resource's endpoint is needed"), "warn"); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index e7ec71afa..68362109c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -902,6 +902,11 @@ const I18N = { "AiHubMix didn't take the access token — paste a new one in the provider's settings": "AiHubMix 不认这个访问令牌,请在供应商设置里重新填入", "Account balance": "账户余额", "Step Plan usage": "Step Plan 用量", + "Team org ID": "团队组织 ID", + "Team project ID": "团队项目 ID", + "optional · only for a team plan": "可选 · 仅团队套餐需要", + "Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.": "仅团队 GLM Coding Plan 的 Key 需要:两者都在 {p} 控制台的团队组织与项目里。填写后,用量页会显示团队的 5 小时与每周额度。", + "Team plan: give both the organization ID and the project ID": "团队套餐:请同时填写组织 ID 和项目 ID", "A key tells only the balance. The Step Plan's 5-hour, weekly and credit windows are told only to a StepFun sign-in: bring yours here once and magpie keeps it (for 30 days), used for nothing else.": "API Key 只能查到余额。Step Plan 的 5 小时、每周和积分额度只对 StepFun 的网页登录开放:把你的登录带过来一次,magpie 会保存它(30 天),只用来查额度。", "Signed in · the Usage page shows the Step Plan": "已登录 · 用量页会显示 Step Plan 额度", "Sign out": "退出登录", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index c462bc9b0..d6676e0a0 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -69,6 +69,9 @@ type providerJSON struct { // a StepFun provider's Step Plan windows, told only to a platform // sign-in: which site's, and whether one is kept StepPlan *stepPlanJSON `json:"stepPlan,omitempty"` + // a Zhipu or Z.ai key's team, for a team's GLM Coding Plan (#236): + // set, if empty, for those providers alone, which the editor asks it of + ZhipuTeam *provider.ZhipuTeam `json:"zhipuTeam,omitempty"` Key struct { Set bool `json:"set"` @@ -124,6 +127,9 @@ type providerAgent struct { type presetJSON struct { provider.PresetDef Added bool `json:"added"` + // ZhipuTeam: a key of it may be on a team's GLM Coding Plan, whose + // organization and project the editor offers to take + ZhipuTeam bool `json:"zhipuTeam,omitempty"` } type gatewayJSON struct { @@ -219,6 +225,12 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { out.Key.Optional = pr.NoKey } out.BalanceToken.Takes, out.BalanceToken.Set = provider.TakesBalanceToken(p), p.BalanceToken != "" + if provider.TakesZhipuTeam(p) { + out.ZhipuTeam = &provider.ZhipuTeam{} + if p.ZhipuTeam != nil { + *out.ZhipuTeam = *p.ZhipuTeam + } + } if site := provider.StepFunSite(p); site != "" { out.StepPlan = &stepPlanJSON{site, provider.StepFunSignedIn(site), provider.StepFunSignInURL(site), provider.StepFunBookmarklet()} } @@ -344,7 +356,8 @@ func providersState() providersJSON { s.Providers = append(s.Providers, providerInfo(p, uses)) } for _, pr := range provider.Presets() { - s.Presets = append(s.Presets, presetJSON{PresetDef: pr, Added: have[pr.ID]}) + team := provider.TakesZhipuTeam(provider.Provider{Chat: pr.Chat, Responses: pr.Responses, Anthropic: pr.Anthropic}) + s.Presets = append(s.Presets, presetJSON{PresetDef: pr, Added: have[pr.ID], ZhipuTeam: team}) } cat := provider.Catalog() s.Gateway = gatewayJSON{URL: gateway.URL(), Models: len(cat), Calls: []gateway.Call{}, Groups: []gwGroupJSON{}} @@ -499,6 +512,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // its key when the form left it blank if pr, err := provider.FromPreset(in.Preset); err == nil && in.Chat == "" && in.Responses == "" && in.Anthropic == "" { pr.Key, pr.Models, pr.Fallback, pr.Headers, pr.BalanceToken, pr.Contexts = in.Key, in.Models, in.Fallback, in.Headers, in.BalanceToken, in.Contexts + pr.ZhipuTeam = in.ZhipuTeam if in.Name != "" { pr.Name = in.Name } @@ -546,6 +560,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if in.AccountProxies == nil && old != nil { in.AccountProxies = old.AccountProxies } + // a Zhipu key's team likewise: {} clears it + if in.ZhipuTeam == nil && old != nil { + in.ZhipuTeam = old.ZhipuTeam + } if in.Key == "" && old != nil { in.Key = old.Key } diff --git a/internal/gui/tests/zhipu-team.test.cjs b/internal/gui/tests/zhipu-team.test.cjs new file mode 100644 index 000000000..badfdb8f8 --- /dev/null +++ b/internal/gui/tests/zhipu-team.test.cjs @@ -0,0 +1,184 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A Zhipu key on a team's GLM Coding Plan (#236): the editor of a Zhipu or +// Z.ai key provider, saved or being added, has Team org ID and Team +// project ID, which Save posts trimmed as zhipuTeam, {} when both are +// empty; one without the other is refused before anything is posted. +// Other providers have neither and post none. A click in them leaves the +// page where it is. In English and Chinese. +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 zhipu = { + id: "zhipu", name: "Zhipu GLM", icon: "zhipu-color", preset: "zhipu", chat: "https://open.bigmodel.cn/api/coding/paas/v4", responses: "", anthropic: "", catalog: "zhipuai", + models: [{ id: "glm-5", name: "GLM-5", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "…ab12" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", + zhipuTeam: { org: "org-0", project: "proj-0" }, +}; +const relay = { + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", +}; +const presets = [ + { id: "zhipu", name: "Zhipu GLM", icon: "zhipu-color", kind: "vendor", chat: "https://open.bigmodel.cn/api/paas/v4", added: true, zhipuTeam: true, + regionLabel: "Plan", regions: [{ id: "api", name: "Pay as you go", chat: "https://open.bigmodel.cn/api/paas/v4" }, { id: "coding", name: "Coding Plan", chat: "https://open.bigmodel.cn/api/coding/paas/v4" }] }, + { id: "zai", name: "Z.ai", icon: "zai", kind: "vendor", chat: "https://api.z.ai/api/paas/v4", added: false, zhipuTeam: true }, + { id: "deepseek", name: "DeepSeek", icon: "deepseek", kind: "vendor", chat: "https://api.deepseek.com/v1", added: false }, +]; + +function serve(lang, posts) { + const providers = { providers: [zhipu, relay], presets, excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], 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/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") { + posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() }); + return json(providers); + } + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const words = { + en: { org: "Team org ID", project: "Team project ID", save: "Save", add: "Add", cancel: "Cancel", one: "Team plan: give both the organization ID and the project ID", console: "Zhipu GLM's console" }, + zh: { org: "团队组织 ID", project: "团队项目 ID", save: "保存", add: "添加", cancel: "取消", one: "团队套餐:请同时填写组织 ID 和项目 ID", console: "Zhipu GLM 控制台" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + const start = async (t, name) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + 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}-${name}-zhipu-team.png`) }); + } + await browser.close(); + }); + // short, so the editor scrolls and a click that moved it would show + const page = await (await browser.newContext({ viewport: { width: 900, height: 560 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + return { page, errors, posts }; + }; + const edit = async (page, name) => { + await page.locator(".row.provider", { hasText: name }).click(); + await page.locator(".editor .proxy-mode").waitFor(); + }; + const org = (page) => page.locator(".editor .team-org"); + const proj = (page) => page.locator(".editor .team-project"); + // a click in a field, the page left where it was + const click = async (page, loc) => { + await loc.scrollIntoViewIfNeeded(); + await page.waitForTimeout(200); + const before = await loc.evaluate((e) => e.getBoundingClientRect().top); + await loc.click(); + await page.waitForTimeout(250); + const after = await loc.evaluate((e) => e.getBoundingClientRect().top); + assert(Math.abs(after - before) <= 1, `moved from ${before} to ${after}`); + }; + const press = async (page, posts, label) => { + const n = posts.length; + const b = page.locator(".editor .bar").getByRole("button", { name: label, exact: true }); + await b.scrollIntoViewIfNeeded(); + await b.click(); + for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50); + return posts.length > n ? posts.at(-1) : null; + }; + + test(`${engine} ${lang}: a Zhipu key's team is shown, typed and saved`, async (t) => { + const { page, errors, posts } = await start(t, "saved"); + await edit(page, "Zhipu GLM"); + const labels = await page.locator(".editor label").allTextContents(); + assert(labels.includes(w.org) && labels.includes(w.project), labels.join(" | ")); + assert.equal(await org(page).inputValue(), "org-0", "what it has is shown"); + assert.equal(await proj(page).inputValue(), "proj-0"); + const hint = await proj(page).locator("xpath=following-sibling::div[contains(@class,'hint')]").textContent(); + assert(hint.includes(w.console), hint); + + await click(page, org(page)); + await org(page).fill(" org-1 "); + await click(page, proj(page)); + await proj(page).fill("proj-1\t"); + let saved = await press(page, posts, w.save); + assert.equal(saved.action, "save"); + assert.equal(saved.body.id, "zhipu"); + assert.deepEqual(saved.body.zhipuTeam, { org: "org-1", project: "proj-1" }); + + // one without the other is refused, nothing posted + await edit(page, "Zhipu GLM"); + await proj(page).fill(""); + assert.equal(await press(page, posts, w.save), null); + assert.equal(await page.locator(".editor .editor-error").textContent(), w.one); + assert.equal(posts.length, 1); + + // both empty clears them + await org(page).fill(""); + saved = await press(page, posts, w.save); + assert.deepEqual(saved.body.zhipuTeam, {}); + + const missing = await page.evaluate(() => [ + "Team org ID", "Team project ID", "optional · only for a team plan", + "Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.", + "Team plan: give both the organization ID and the project ID", + ].filter((k) => !I18N.zh[k])); + assert.deepEqual(missing, [], "every string has its Chinese"); + const border = await page.evaluate(() => [...document.querySelectorAll(".editor, .editor *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1)); + assert.deepEqual(border, [], "no border stripes"); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: another provider has no team fields and posts none`, async (t) => { + const { page, errors, posts } = await start(t, "relay"); + await edit(page, "Relay"); + assert.equal(await org(page).count(), 0); + assert.equal(await proj(page).count(), 0); + const saved = await press(page, posts, w.save); + assert.equal(saved.body.id, "relay"); + assert(!("zhipuTeam" in saved.body)); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: a Zhipu key being added takes its team, DeepSeek's doesn't`, async (t) => { + const { page, errors, posts } = await start(t, "add"); + await page.locator("#addProvider").click(); + const sheet = page.locator("#addSheet"); + await sheet.locator('.tile[data-pick="DeepSeek"]').click(); + await page.locator(".editor.new").waitFor(); + assert.equal(await org(page).count(), 0, "DeepSeek has none"); + await page.locator(".editor .bar").getByRole("button", { name: w.cancel, exact: true }).click(); + await page.locator(".editor").waitFor({ state: "detached" }); + + // the sheet is still open under it + await sheet.locator('.tile[data-pick="Z.ai"]').click(); + await org(page).waitFor(); + await page.locator(".editor.new input[type=password]").fill("zk-1"); + await click(page, org(page)); + await org(page).fill("org-9"); + await proj(page).fill(" proj-9 "); + const saved = await press(page, posts, w.add); + assert.equal(saved.body.new, true); + assert.equal(saved.body.preset, "zai"); + assert.deepEqual(saved.body.zhipuTeam, { org: "org-9", project: "proj-9" }); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index 7f96521d3..24b073ea4 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -361,7 +361,7 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota { if zhipu := strings.HasSuffix(j.src.url, "/api/monitor/usage/quota/limit"); zhipu && (err != nil || len(ws) == 0) { // no plan of the key's own: a team's key, whose windows are // asked with type=2 (zcode_team.go) - if tplan, tws, terr := zhipuKeyTeamWindows(j.p.Via(ctx), j.src.url, j.key); terr == nil && len(tws) > 0 { + if tplan, tws, terr := zhipuKeyTeamWindows(j.p.Via(ctx), j.src.url, j.key, j.p.ZhipuTeam); terr == nil && len(tws) > 0 { plan, ws, err, team = tplan, tws, nil, true } } @@ -397,20 +397,74 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota { return out } +// ZhipuTeam is the team a Zhipu or Z.ai key's GLM Coding Plan belongs to: +// its organization and project IDs, as the BigModel console shows them. +type ZhipuTeam struct { + Org string `json:"org,omitempty"` + Project string `json:"project,omitempty"` +} + +// normal is t as it is kept: trimmed, nil when neither is given. +func (t *ZhipuTeam) normal() *ZhipuTeam { + if t == nil { + return nil + } + n := ZhipuTeam{strings.TrimSpace(t.Org), strings.TrimSpace(t.Project)} + if n.Org == "" && n.Project == "" { + return nil + } + return &n +} + +// TakesZhipuTeam says p is a key of Zhipu's or Z.ai's, whose editor then +// offers the team's organization and project (#236). +func TakesZhipuTeam(p Provider) bool { + if p.Account != nil { + return false + } + src, ok := planQuotaSourceOf(p) + return ok && strings.HasSuffix(src.url, "/api/monitor/usage/quota/limit") +} + // zhipuKeyTeamWindows is a GLM key's windows on a team's GLM Coding Plan: // the quota asked with type=2 where ZCode asks it (bigmodel.cn, api.z.ai), -// with the team's organization and project in the headers when the key is -// a ZCode account's team key magpie holds (a key pasted alone is asked -// without them, which is a guess: ZCode always sends them). -func zhipuKeyTeamWindows(ctx context.Context, quotaURL, key string) (string, []QuotaWindow, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, zcodeBizRoot(quotaURL)+"/api/monitor/usage/quota/limit?type=2", nil) +// with the team's organization and project in the headers: those the user +// gave the provider, else those of a ZCode account's team key magpie holds +// (a key pasted alone is asked without them, which is a guess: ZCode +// always sends them). +func zhipuKeyTeamWindows(ctx context.Context, quotaURL, key string, team *ZhipuTeam) (plan string, ws []QuotaWindow, err error) { + // the key's own host first (open.bigmodel.cn, as CC Switch asks it), + // then where ZCode asks it + for _, root := range zhipuTeamRoots(quotaURL) { + if plan, ws, err = zhipuKeyTeamAt(ctx, root, quotaURL, key, team); err == nil && len(ws) > 0 { + return + } + } + return +} + +// zhipuTeamRoots are the hosts a team's quota is asked at, each once. +func zhipuTeamRoots(quotaURL string) []string { + own := strings.TrimSuffix(quotaURL, "/api/monitor/usage/quota/limit") + if biz := zcodeBizRoot(quotaURL); biz != own { + return []string{own, biz} + } + return []string{own} +} + +func zhipuKeyTeamAt(ctx context.Context, root, quotaURL, key string, team *ZhipuTeam) (string, []QuotaWindow, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, root+"/api/monitor/usage/quota/limit?type=2", nil) if err != nil { return "", nil, err } req.Header.Set("Authorization", key) req.Header.Set("Accept", "application/json") req.Header.Set("Accept-Language", "en-US,en") - if org, project := zhipuTeamOf(key); org != "" { + org, project := zhipuTeamOf(key) + if team != nil && team.Org != "" && team.Project != "" { + org, project = team.Org, team.Project + } + if org != "" { for k, v := range zcodeTeamHeaders(quotaURL, org, project) { req.Header.Set(k, v) } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index cad9b82e9..356814850 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -118,6 +118,11 @@ type Provider struct { // BalanceURL (see TakesBalanceToken). It is asked with nothing else but // the provider's headers, when the endpoint is one named. BalanceToken string `json:"balanceToken,omitempty"` + // ZhipuTeam, for a Zhipu or Z.ai key on a team's GLM Coding Plan, is + // the team's organization and project, from the BigModel console: the + // team's windows are told to the key only with them (see + // zhipuKeyTeamWindows). nil for a key of the user's own plan. + ZhipuTeam *ZhipuTeam `json:"zhipuTeam,omitempty"` // ModelsURL, when set, is where the vendor lists its models, for one // that lists them away from the base URL requests go to (Xiaomi MiMo's @@ -531,6 +536,7 @@ func normalize(p Provider) Provider { p.Key = strings.TrimSpace(p.Key) p.Proxy = strings.TrimSpace(p.Proxy) p.AccountProxies = normalAccountProxies(p.AccountProxies) + p.ZhipuTeam = p.ZhipuTeam.normal() for _, u := range []*string{&p.Chat, &p.Responses, &p.Anthropic, &p.Decide, &p.Website, &p.KeysURL} { *u = strings.TrimRight(strings.TrimSpace(*u), "/") if *u != "" && !strings.Contains(*u, "://") { diff --git a/internal/provider/zcode_team_test.go b/internal/provider/zcode_team_test.go index 6e379e24f..f1feab3a4 100644 --- a/internal/provider/zcode_team_test.go +++ b/internal/provider/zcode_team_test.go @@ -254,7 +254,7 @@ func TestZhipuKeyTeamWindows(t *testing.T) { if err := addSideLogin(savedLogin{Agent: "zcode", User: "team@example.com", Plan: plan, Auth: auth}, "", func(savedLogin) {}); err != nil { t.Fatal(err) } - plan, ws, err := zhipuKeyTeamWindows(context.Background(), ZCodeBigModelBase, "tk.ts") + plan, ws, err := zhipuKeyTeamWindows(context.Background(), ZCodeBigModelBase, "tk.ts", nil) if err != nil || plan != "GLM Coding Team" || len(ws) != 2 || ws[0].Name != "5 hours" || ws[0].Used != 42 || ws[0].Span != 5*time.Hour || ws[1].Name != "7 days" { t.Fatalf("windows: %v %q %+v", err, plan, ws) } @@ -262,7 +262,7 @@ func TestZhipuKeyTeamWindows(t *testing.T) { t.Fatalf("asked with: %v", u.quota.Header) } // a key that isn't a seat magpie holds is asked without them, and has none - if _, ws, err := zhipuKeyTeamWindows(context.Background(), ZCodeBigModelBase, "other.key"); err != nil || len(ws) != 0 { + if _, ws, err := zhipuKeyTeamWindows(context.Background(), ZCodeBigModelBase, "other.key", nil); err != nil || len(ws) != 0 { t.Fatalf("another key: %v %+v", err, ws) } } diff --git a/internal/provider/zhipu_team_key_test.go b/internal/provider/zhipu_team_key_test.go new file mode 100644 index 000000000..c4602c95b --- /dev/null +++ b/internal/provider/zhipu_team_key_test.go @@ -0,0 +1,118 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" +) + +// #236: a Zhipu key on a team's GLM Coding Plan, added as a key and not +// through ZCode, has the team's organization and project typed into its +// provider: its windows are asked with type=2 and those two headers. A +// key without them is asked as before, with no team headers. +func TestZhipuKeyTeamFields(t *testing.T) { + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("PATH", h) + for _, v := range []string{"CLAUDE_CONFIG_DIR", "CODEX_HOME"} { + t.Setenv(v, "") + } + asked := map[string]http.Header{} + hosts := map[string][]string{} // where each key's team quota was asked + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + key := r.Header.Get("Authorization") + switch r.Header.Get("X-Host") + r.URL.Path { + case "open.bigmodel.cn/api/monitor/usage/quota/limit", "bigmodel.cn/api/monitor/usage/quota/limit": + if r.URL.Query().Get("type") != "2" { + // a team's key has no plan of its own + w.Write([]byte(`{"code":500,"msg":"no plan","success":false}`)) + return + } + hosts[key] = append(hosts[key], r.Header.Get("X-Host")) + asked[key] = r.Header.Clone() + if r.Header.Get("Bigmodel-Organization") != "org-1" || r.Header.Get("Bigmodel-Project") != "proj-1" { + w.Write([]byte(`{"code":1001,"msg":"no team","success":false}`)) + return + } + w.Write([]byte(`{"code":200,"success":true,"data":{"limits":[ + {"type":"CREDIT_LIMIT","unit":3,"percentage":42,"currentValue":420,"usage":1000,"nextResetTime":1790000000000}, + {"type":"CREDIT_LIMIT","unit":6,"number":1,"percentage":10,"nextResetTime":1790500000000}]}}`)) + default: + t.Errorf("asked %s%s with %q", r.Header.Get("X-Host"), r.URL.Path, key) + w.WriteHeader(http.StatusUnauthorized) + } + })) + defer srv.Close() + old := http.DefaultClient.Transport + http.DefaultClient.Transport = rewrite{srv} + t.Cleanup(func() { http.DefaultClient.Transport = old }) + forget := func() { + planQuotaCache.Lock() + planQuotaCache.data = nil + planQuotaCache.Unlock() + } + forget() + t.Cleanup(forget) + + for _, p := range []Provider{ + {ID: "team", Name: "Team", Chat: "https://open.bigmodel.cn/api/coding/paas/v4", Key: "team-k", ZhipuTeam: &ZhipuTeam{" org-1 ", "proj-1\n"}}, + {ID: "bare", Name: "Bare", Chat: "https://open.bigmodel.cn/api/coding/paas/v4", Key: "bare-k"}, + {ID: "blank", Name: "Blank", Chat: "https://open.bigmodel.cn/api/paas/v4", Key: "blank-k", ZhipuTeam: &ZhipuTeam{" ", ""}}, + } { + if err := Save(p); err != nil { + t.Fatal(err) + } + } + if p, _ := Find("team"); p.ZhipuTeam == nil || *p.ZhipuTeam != (ZhipuTeam{"org-1", "proj-1"}) { + t.Fatalf("kept: %+v", p.ZhipuTeam) + } + if p, _ := Find("blank"); p.ZhipuTeam != nil { + t.Fatalf("blank kept: %+v", p.ZhipuTeam) + } + if p, _ := Find("team"); !TakesZhipuTeam(*p) { + t.Fatal("a Zhipu key takes a team") + } + if TakesZhipuTeam(Provider{Chat: "https://api.z.ai/api/coding/paas/v4"}) != true || + TakesZhipuTeam(Provider{Chat: "https://api.deepseek.com/v1"}) { + t.Fatal("takes a team: Z.ai does, DeepSeek doesn't") + } + + got := map[string]SubscriptionQuota{} + for _, q := range PlanQuotas(context.Background()) { + got[q.Provider] = q + } + q, ok := got["team"] + if !ok || q.Error != "" || q.Plan != "GLM Coding Team" || len(q.Windows) != 2 || + q.Windows[0].Name != "5 hours" || q.Windows[0].Used != 42 || q.Windows[0].Span != 5*time.Hour || + q.Windows[1].Name != "7 days" || q.Windows[1].Used != 10 { + t.Fatalf("team: %+v", q) + } + if hd := asked["team-k"]; hd.Get("Bigmodel-Organization") != "org-1" || hd.Get("Bigmodel-Project") != "proj-1" || hd.Get("Set-Language") != "zh" { + t.Fatalf("team asked with %v", hd) + } + // at the key's own host, as CC Switch asks it; bigmodel.cn only when + // that one has no windows + if h := strings.Join(hosts["team-k"], ","); h != "open.bigmodel.cn" { + t.Fatalf("team asked at %s", h) + } + if h := strings.Join(hosts["bare-k"], ","); h != "open.bigmodel.cn,bigmodel.cn" { + t.Fatalf("bare asked at %s", h) + } + // without them nothing changes: asked with no team headers, no windows + if hd, ok := asked["bare-k"]; !ok || hd.Get("Bigmodel-Organization") != "" || hd.Get("Bigmodel-Project") != "" { + t.Fatalf("bare asked with %v (%v)", hd, ok) + } + if q := got["bare"]; len(q.Windows) != 0 || q.Error == "" { + t.Fatalf("bare: %+v", q) + } + if _, ok := got["blank"]; ok { + t.Fatalf("a pay-as-you-go key with no team has no card: %+v", got["blank"]) + } +}