From 2ad38c8b3e367133be4f1b848d82fb26bb60e284 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 16 Nov 2026 10:45:44 +0800 Subject: [PATCH] provider: Baidu Qianfan's ended console sign-in asks for a new one in the editor, and a renewed cookie is kept (yuushabu_buyinn on X, #5860) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit yuushabu_buyinn asked for AccessKey + SecretKey in place of the console cookie, which expires. Baidu has no such route. Its documented OpenAPI has no read for a Token Plan Personal: - the Qianfan API catalog (doc/qianfan/s/Smownk4en): 量包 v2/charge?Action=DescribePackageResources lists token packs by series, with no Token Plan; - Finance's API (doc/Finance/s/ojxecslph): bills, balance, orders, vouchers; - the Token Plan Enterprise's seat APIs (tokenplan?Action=... DescribeTeamSeatUsageDetail), which take an API key and are for team seats only. The Token Plan Personal doc (doc/qianfan/s/Dmrabu8b6) shows usage only on the console's 我的订阅 page. So the cookie stays, and what is mended is what happens when it ends: - Before, a session the console refused showed "Signed out of the Baidu Cloud console" on the card, while the provider's editor still said "Signed in" with only Sign out. Now the kept sign-in is marked ended (qianfanSession.Ended, set the first time only, and not when a newer paste has replaced the cookie the read used). /api/providers says qianfanPlan.ended, and qianfanplan.js draws "Baidu Cloud ended this sign-in. Bring a new one:" above the bookmarklet and paste steps. A new paste, or a later read the console takes, clears the mark. - A cookie the console sets in a reply that read the plan (on the resource's path) is merged into the kept Cookie header as a browser would: replaced in place, added, or taken out when deleted or expired (mergeQianfanCookies). A session Baidu renews as it is used then stays the one magpie holds. The paste check keeps what its reply set too. The StepFun sibling (the same "still Signed in" gap, drawn by renderStepPlan in app.js) is #6808. The Qianfan fix adds no app.js bytes. Run (mote, at 3b643f397 plus this change; go test, vet, gofmt, qianfan-plan and i18n-keys again after rebasing on f64c7e54f, all ok): - gofmt -l, go vet (darwin, GOOS=linux -tags nogui, GOOS=windows) for internal/provider and internal/gui: clean. - go test -count=1 ./internal/provider ./internal/gui: ok. - node --test qianfan-plan, i18n-keys, i18n-en-no-cjk: 12/12 (chromium + webkit, en + zh). stepfun-per-provider and qianwen-plan: all ok. old-webkit 4 and 5 are red the same on a clean 3b643f397 copy (#6030, #5919). - Broken by hand: without the ended mark, TestQianfanSessionEnded fails "an ended sign-in should be kept, marked ended". Without the merge it fails "renewed cookie kept as ...s-1". Not tried: no real Baidu Cloud account. How long the console's cookie lasts was not measured (a third-party tool reports a few weeks), and whether the console sets renewed cookies on this request is not known. The merge does nothing if it doesn't. --- docs/subsystems/providers-accounts.md | 2 +- internal/gui/assets/app.css | 1 + internal/gui/assets/i18n.js | 4 + internal/gui/assets/qianfanplan.js | 18 ++-- internal/gui/providers.go | 7 +- internal/gui/qianfan_api_test.go | 16 ++- internal/gui/tests/qianfan-plan.test.cjs | 23 +++- internal/provider/qianfan_plan.go | 128 +++++++++++++++++++---- internal/provider/qianfan_plan_test.go | 82 +++++++++++++++ 9 files changed, 247 insertions(+), 34 deletions(-) diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 31f53293b..a7ae54968 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -82,7 +82,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | A lab's models | models.dev keeps two catalogs: `api.json`, each provider's models with that host's prices, and `models.json`, each lab's models with only what is the model's on every host (name, window, reply limit, thinking, inputs, release), no price. `Sync` keeps the second beside the first as `labs.json` (`LabsPath`, `syncLabs`: best effort, through a rename, a failed fetch keeping the last; a catalog with none beside it is `Stale` once a process, so it comes at the next look). A model only a lab lists, no provider (models.dev took the gated Claude Mythos 5.1 out of anthropic's list in #11327 and kept its lab file), is voted into the same tables as a listed one (`loadGen`, `labs`), so `ContextOf`, `OutputOf`, `NameOf`, `Thinks`, `SeesImages` and every entry built on them know it wherever a vendor's or an account's list has it; a thinking one with no levels takes the levels of the newest of its family a provider gives them (`labKinEfforts`: Mythos 5.1 takes Mythos 5's). A model a provider lists keeps what providers say of it. `catalog.Describe` builds a model from these for a list that names an id alone. `TestLabOnlyModelIsKnown`, `TestLabsLeaveListedModels`, `TestSyncKeepsLabs`, `TestAnthropicKeyGatedModelDescribed` (iebb on Discord). | [`labs.go`](../../internal/catalog/labs.go), [`catalog.go`](../../internal/catalog/catalog.go) | | models.dev unreachable | The catalog (`CachePath`, `models.json`) is written whole through a rename (`writeWhole`), so a reader never sees it half written and a fetch that fails (refused, hanging past `fetchBound`, a page that isn't the catalog) keeps the last good copy. `loadGen` reads magpie's copy, then OpenCode's, then the copy the binary ships with (`bundled/api.json.gz`, `bundledAt`), passing over one it can't parse. `Seed` (the app's backend, `magpie serve`, the plugin host) writes the shipped copy into `CachePath` dated `bundledAt` when there is no catalog file or the one there is older, so the plugin host's `mdev` reads it too and `Stale` still has the real one fetched. The app's backend fetches beside the vendors' lists rather than before them, and `KeepFresh` tries a failed fetch again after `retryFirst` (2 minutes), doubling up to the hour (`nextRetry`). The fetch goes through `http.DefaultClient`, so through the proxy in Settings, `*_PROXY` or the system's (`netproxy.Install`). A test binary has the shipped copy off (`bundledOn`). Refresh it with `go generate ./internal/catalog` and set `bundledAt` (creeksuen on X). `TestFailedSyncKeepsLastGood`, `TestFirstRunOfflineAnswersFromShippedCopy`, `TestUnreadableCacheFallsBackToShippedCopy`, `TestSeed`, `TestSyncWritesThroughRename`, `TestFailedFetchRetriedSoon`. | [`bundled.go`](../../internal/catalog/bundled.go), [`fresh.go`](../../internal/catalog/fresh.go), [`catalog.go`](../../internal/catalog/catalog.go), [`backend.go`](../../internal/gui/backend.go) | | A Claude account's models | magpie never asks Anthropic with a Claude sign-in, so a Claude account's list is models.dev's anthropic list and what Anthropic told the account's Claude Code beyond it. Claude Code keeps that in its `.claude.json` from its own bootstrap: `additionalModelOptionsCache` (models its /model picker offers beyond its own; a `null` value or a `disabled` one is not a model), `modelAccessCache` (`entitled` per API id) and `additionalModelCostsCache` (Anthropic's prices). Claude Code 2.1.323 and later also keep a version-2 catalog per account, `/cache/model-catalog/--cc.json` (`catalog.config.models`: id, name, `runtime` window, reply limit, effort levels, `mm_images`); `readClaudeCodeModels` adds the models of the catalog of the account its `.claude.json` names, from that config directory or Claude Code's own (which keeps every account's that signed in there), the one fetched last, and fills a window, limit or levels models.dev doesn't have from it. Another account's catalog in the folder is never read, a file of another version or surface is unknown, and a `.claude.json` or catalog that doesn't parse (halfway through a write) is what it said last (`readKeepingGood`; #6418, `TestClaudeCodeCatalogV2Models`). `claudeModels` reads the file of Claude Code's own sign-in (`claudeProfilePath`) and of each saved account's directory (`claudeAccountDir`), through `filememo`, and adds each model none of them lists, described by `catalog.Describe` and priced as Anthropic told it. `Account.Lists` for a Claude account goes by its own file (`claudeLists`: the saved directory's, or Claude Code's own when its `oauthAccount` is that account, the one Anthropic answered last): a model it isn't entitled to is out, so routing tries the accounts entitled to a gated model first; with no file, every model is taken to be in, as before. `ListPrice` of a provider whose catalogs include anthropic falls back to that price after every catalog (`claudeCodePrice`). The agent's own Claude Code model picker (`claudeOwn`) offers what `ClaudeCodeModels` gives for the account signed in here; a WSL distro's keeps the catalog's. A fetch of the list in the app or `magpie serve` (Fetch models, the accounts' relist) fetches models.dev's catalog first when it is older than `askedAfter` (10 minutes) and wasn't tried in that time (`catalog.Asked`), only in a process that keeps the catalog fresh: the daily sync alone left a model launched since off the list the user had just fetched, while Claude Code's own /model, built from the catalog baked into its binary (`latest_per_family`), had it (hhdaxia on X: Fable 5.2, `TestClaudeFetchAsksModelsDevForANewModel`). Not done: a Claude Code that never started on a saved account has no file, so its gated models show only once it has run there. `TestClaudeAccountListsGatedModels`. | [`claude_code_models.go`](../../internal/provider/claude_code_models.go), [`claude_code_catalog.go`](../../internal/provider/claude_code_catalog.go), [`account.go`](../../internal/provider/account.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`claude.go`](../../internal/agent/claude.go), [`fresh.go`](../../internal/catalog/fresh.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`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `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, Ollama Cloud, Mistral: `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`). Kimi Code's `/usages` (`readKimiCode`) is read as kimi-cli and kimi-code read it: the week's `usage` and each `limits[]` window as counts, and the shares in `usages` (`limit_5h`, `limit_7d`, and `limit_month_total` as a *Month* window renewing at its `reset_time`, lidazi2016 on Discord); a window told both ways is the share's, and `limit_month_code`, the part of the month code used, is no window. `TestReadKimiCode`, `TestReadKimiCodeMonth`. A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. On Go, GOAT and Pro the month is counted in Command Code's usage-value credits, not dollars (GOAT's 70 are $100 of a model like DeepSeek V4.1 Flash, $70 of GLM-5.2), so the window says "28.80 / 70.00 credits" with bought credits as "+ $5.00 extra" beside it; Max, Ultra and Teams Pro keep the CLI's dollar pool, and Provider, pay as you go, has no month (`cmdPlans`, as the plugin since 0.1.20, plugins #556). Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. A Mistral key is told its organization's month at `api.mistral.ai/v1/billing/budget`, as Mistral's Vibe CLI reads it (`mistral_plan.go`, dhanyqaz on Discord). The budget is the organization's, so every key of it gets the same `vibe_budget` and `api_budget`; which one a key spends is its kind, asked once a key of `console.mistral.ai/api/vibe/whoami` (`plan_type`). A Vibe key (`chat`) has `vibe_budget` as one *Month* window, a Studio key made in the console (`api`) has `api_budget` as *API · Month*, so the accounts' strip never adds the two; each is in the currency billing names (none when it names none), Aside while pay-as-you-go is on (the budget's own, else the subscription's `vibe_payg_enabled` for Vibe and `payg_enabled` for Studio), with the plan's name from `billing/subscription` (EDU is Student). A key whoami can't place (a failed read, no `plan_type`, Mistral Code's key) or whose budget is 0 has no card, and Le Chat's own message limits are told nowhere. ModelScope's API-Inference token is told its 魔粒 at the OpenAPI's `modelscope.cn/openapi/v1/magicubes/balance` (`readModelScope`, jiabubu on Discord): `available_balance`, which leaves out what running tasks have frozen, as the balance card; the page's daily list (`/magicubes/transactions`) isn't in the OpenAPI, so what is spent a day is the card's own trend. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. The Qwen AI platform's Token Plan is read the same way, through a platform sign-in kept by provider id in `qianwen-auth.json` (`qianwen_plan.go`; see the Alibaba Cloud Token Plan below). Baidu Qianfan's Token Plan Personal (a provider at `qianfan.baidubce.com/v2/tokenplan/personal`, `QianfanPlan`; yuushabu_buyinn on X, #5860) is read as StepFun's is, by the same bookmarklet and paste (`renderStepPlan`, its field in `qianfanplan.js`, imported when such a provider's editor opens): the user's Baidu Cloud console cookie, checked with a real read before it is kept by provider id in `qianfan-auth.json` (0600; a raw `Cookie:` header or a copied cURL is taken too, for the HttpOnly cookies `document.cookie` leaves out), asks `console.bce.baidu.com/api/qianfan/charge/tokenPlanPersonal/resource` (`qianfan_plan.go`). The running plan's credits (`billingMode` credit) or tokens are one *Month* window up to its `expiresAt`, with its auto-renew; the per-plan `apiKey` in the reply is never kept. A redirect, 401, 403, an HTML page or a refusal naming the login is a signed-out session, an error card and never 0 left. The Enterprise plan has no card: the console reads it through seat and admin APIs, not a `tokenPlanTeam/resource`. Built from the console's own script and field names; never read with a real account here. `TestReadQianfanPlan`, `TestSaveQianfanPaste`, `TestQianfanPlanCard`, `TestQianfanSignInRoutes`, `qianfan-plan.test.cjs`. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.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`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `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, Ollama Cloud, Mistral: `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`). Kimi Code's `/usages` (`readKimiCode`) is read as kimi-cli and kimi-code read it: the week's `usage` and each `limits[]` window as counts, and the shares in `usages` (`limit_5h`, `limit_7d`, and `limit_month_total` as a *Month* window renewing at its `reset_time`, lidazi2016 on Discord); a window told both ways is the share's, and `limit_month_code`, the part of the month code used, is no window. `TestReadKimiCode`, `TestReadKimiCodeMonth`. A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. On Go, GOAT and Pro the month is counted in Command Code's usage-value credits, not dollars (GOAT's 70 are $100 of a model like DeepSeek V4.1 Flash, $70 of GLM-5.2), so the window says "28.80 / 70.00 credits" with bought credits as "+ $5.00 extra" beside it; Max, Ultra and Teams Pro keep the CLI's dollar pool, and Provider, pay as you go, has no month (`cmdPlans`, as the plugin since 0.1.20, plugins #556). Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. A Mistral key is told its organization's month at `api.mistral.ai/v1/billing/budget`, as Mistral's Vibe CLI reads it (`mistral_plan.go`, dhanyqaz on Discord). The budget is the organization's, so every key of it gets the same `vibe_budget` and `api_budget`; which one a key spends is its kind, asked once a key of `console.mistral.ai/api/vibe/whoami` (`plan_type`). A Vibe key (`chat`) has `vibe_budget` as one *Month* window, a Studio key made in the console (`api`) has `api_budget` as *API · Month*, so the accounts' strip never adds the two; each is in the currency billing names (none when it names none), Aside while pay-as-you-go is on (the budget's own, else the subscription's `vibe_payg_enabled` for Vibe and `payg_enabled` for Studio), with the plan's name from `billing/subscription` (EDU is Student). A key whoami can't place (a failed read, no `plan_type`, Mistral Code's key) or whose budget is 0 has no card, and Le Chat's own message limits are told nowhere. ModelScope's API-Inference token is told its 魔粒 at the OpenAPI's `modelscope.cn/openapi/v1/magicubes/balance` (`readModelScope`, jiabubu on Discord): `available_balance`, which leaves out what running tasks have frozen, as the balance card; the page's daily list (`/magicubes/transactions`) isn't in the OpenAPI, so what is spent a day is the card's own trend. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. The Qwen AI platform's Token Plan is read the same way, through a platform sign-in kept by provider id in `qianwen-auth.json` (`qianwen_plan.go`; see the Alibaba Cloud Token Plan below). Baidu Qianfan's Token Plan Personal (a provider at `qianfan.baidubce.com/v2/tokenplan/personal`, `QianfanPlan`; yuushabu_buyinn on X, #5860) is read as StepFun's is, by the same bookmarklet and paste (`renderStepPlan`, its field in `qianfanplan.js`, imported when such a provider's editor opens): the user's Baidu Cloud console cookie, checked with a real read before it is kept by provider id in `qianfan-auth.json` (0600; a raw `Cookie:` header or a copied cURL is taken too, for the HttpOnly cookies `document.cookie` leaves out), asks `console.bce.baidu.com/api/qianfan/charge/tokenPlanPersonal/resource` (`qianfan_plan.go`). The running plan's credits (`billingMode` credit) or tokens are one *Month* window up to its `expiresAt`, with its auto-renew; the per-plan `apiKey` in the reply is never kept. A redirect, 401, 403, an HTML page or a refusal naming the login is a signed-out session, an error card and never 0 left; the kept sign-in is then marked ended (`Ended`, the first time only), so the editor (`stepPlanJSON.ended`) says Baidu ended it and shows the bookmarklet and paste again, and a new paste or a read the console takes clears it. A cookie the console sets in a reply that read the plan (on the resource's path) is merged into the kept Cookie header as a browser would (`mergeQianfanCookies`), so a session Baidu renews as it is used stays the one magpie holds. There is no AccessKey/SecretKey route: Baidu's documented OpenAPI (the Qianfan API catalog, `v2/charge?Action=DescribePackageResources` for 量包, Finance's bill and balance APIs, the Enterprise plan's seat APIs on an API key) has no read for a Token Plan Personal. The Enterprise plan has no card: the console reads it through seat and admin APIs, not a `tokenPlanTeam/resource`. Built from the console's own script and field names; never read with a real account here. `TestReadQianfanPlan`, `TestSaveQianfanPaste`, `TestQianfanPlanCard`, `TestQianfanSessionEnded`, `TestMergeQianfanCookies`, `TestQianfanSignInRoutes`, `qianfan-plan.test.cjs`. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) | | A relay's balance found | A provider added by hand, or from a relay's preset, with a key and no Balance URL, at no host magpie knows a query for, is asked where relays tell a key its balance: the base's origin's `/v1/usage` (sub2api, `$remaining`), then `/api/usage/token` (new-api, `$data.total_available / 500000`), with the key's own auth and headers (`probesBalance`, `probeBalance`). A 200 whose field reads is the query; it is kept in memory for the origins and key for 24 hours and then looked for again, so a relay that moved to other software is not read at a query that now means something else. When the look finds nothing, the old query stays while it turns the key away (401/403, so the card says so) or the relay is down. Finding none is kept for 6 hours (5 minutes when the relay couldn't be reached). Nothing is written to the provider: the card reads the found URL, `BalanceQuery` names it, and the editor shows it under the Balance URL (`BalanceFound`, `balanceFound` in /api/providers and the check's reply; `balfound.js`), with Use to copy it into the fields so a wrong amount can be put right. None found means no card (`errNoBalance`) and, from the editor's check, *No balance at /v1/usage or /api/usage/token*. Never asked: a model vendor's or local server's preset host, this computer, OpenCode and the Cline API (`noProbeHosts`), a plan's windows (`planQuotaSourceOf`). A hand-added yylx.io relay showed no balance until its operator had the user import it again (11-05). | [`balance_probe.go`](../../internal/provider/balance_probe.go) | | Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A name picks its account wherever the account's own name does (`AccountByName`): the CLI's `accountNamed` (switch, forget, alias), the pool's `--accounts`, and `accountRef` (caps, models, weights, concurrency) after an exact name. It is refused when two accounts have it or it is another account's email or name, so it never picks by guess; `accountRef` then finds no account, as the GUI passes exact names (StringKe in #4532, `TestAccountsAliasPicksTheAccount`). A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else the plugin's, else `Seat`) with `Named` when it is the user's own, which Hide accounts leaves in sight (#3656), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. Records (a trace's `who`, usage's `ProviderAccount`) keep the vendor's name, the key the user's name is kept by, and every list of them looks the name up as it is shown (`AccountShown`, `AccountShownOf`, `AccountRef.Shown`), so a request from before a rename reads by the new name too: the Routing page's accounts and requests (`userShown` in `plugins/routing/client.js`, from `/api/providers`' `accountNames`), its Several accounts pools (`onOf`), the Usage page's Accounts and the request log's Account filter (`usageapi`), `magpie usage`, and a gateway key's accounts (`AccountNames`, `/api/caller-keys`). Before plugins#310 (a renamed Kiro account read by its old name on every request after) those showed the vendor's name. An account with no name of the user's own goes by the name its plugin's `usage()` gives it (`PluginUserOf`, the `user` of its last read: `loginUsageCache`, else `quotas.json`), else by its id: a Huawei Cloud CodeArts account kept by its IAM id `iam:::user:` reads as the masked phone its card shows (#4416). `AccountShown`, `AccountShownOf` and `AccountLabelOf` (cards' `Alias`, `magpie accounts`, usageapi's Account filter, the quota alert) apply it, and the GUI has it as `/api/providers`' `accountUsers` (`accountShownOf` in app.js: the editor's rows, the per-account proxy lines, Routing's `userShown`, Hide accounts). The id stays the key everything is kept by; nothing stored changes. A read that fails keeps the last good `user`; nothing read yet, or a plugin whose windows are all model pools (not kept in `quotas.json`) after a restart, is its id until the next read. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) | | Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) | diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 0f54077c5..2d6fe92fe 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3773,6 +3773,7 @@ body:not(.side-nav) #addSheet > .row-head.stuck::before { box-shadow: 0 1px 0 va .stepplan .state { flex: 1; min-width: 0; font-size: 12px; color: var(--muted); line-height: 1.4; } .stepplan .steps { margin: 0; padding-left: 18px; display: flex; flex-direction: column; gap: 8px; font-size: 12px; color: var(--muted); line-height: 1.5; } .stepplan .steps .pair { margin-top: 2px; } +.stepplan .ended { display: block; margin-bottom: 8px; color: var(--fg); } .stepplan .bookmarklet { display: inline-block; padding: 1px 8px; border: 1px solid var(--line); border-radius: 6px; color: var(--fg); background: var(--pill); text-decoration: none; cursor: grab; white-space: nowrap; } .editor input[type="text"], .editor input[type="password"], .editor input[type="url"], .editor input[type="number"], .acc .kf input, .acc input.rename-in { height: 27px; padding: 0 9px; border-radius: 7px; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 834c37439..b41a40684 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3960,6 +3960,7 @@ const I18N = { "Sign in to the Baidu Cloud console in your browser ↗": "在浏览器中登录百度智能云控制台 ↗", "Signed in to the Baidu Cloud console": "已登录百度智能云控制台", "Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "已退出百度智能云控制台 — 在服务商设置中重新带入登录", + "Baidu Cloud ended this sign-in. Bring a new one:": "百度智能云已结束这次登录,请重新带入:", "This Baidu Cloud account has no Token Plan Personal": "这个百度智能云账号没有 Token Plan 个人版", "A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "密钥不告知套餐用量。套餐本月的用量只告知百度智能云控制台的登录:在这里带入一次,magpie 会保存它,不作他用。如果 magpie 用不了书签复制的内容,请从浏览器开发者工具中复制控制台请求的 Cookie 请求头粘贴到这里。", "saved · paste a new one to replace it": "已保存 · 粘贴新的即可替换", @@ -9288,6 +9289,7 @@ const I18N = { "Sign in to the Baidu Cloud console in your browser ↗": "在瀏覽器中登入百度智慧雲主控台 ↗", "Signed in to the Baidu Cloud console": "已登入百度智慧雲主控台", "Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "已登出百度智慧雲主控台 — 在供應商設定中重新帶入登入", + "Baidu Cloud ended this sign-in. Bring a new one:": "百度智慧雲已結束這次登入,請重新帶入:", "This Baidu Cloud account has no Token Plan Personal": "這個百度智慧雲帳號沒有 Token Plan 個人版", "A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "金鑰不告知方案用量。方案本月的用量只告知百度智慧雲主控台的登入:在這裡帶入一次,magpie 會保存它,不作他用。如果 magpie 用不了書籤複製的內容,請從瀏覽器開發者工具中複製主控台請求的 Cookie 標頭貼到這裡。", "saved · paste a new one to replace it": "已儲存 · 貼上新的即可替換", @@ -14624,6 +14626,7 @@ const I18N = { "Sign in to the Baidu Cloud console in your browser ↗": "ブラウザで Baidu Cloud コンソールにサインイン ↗", "Signed in to the Baidu Cloud console": "Baidu Cloud コンソールにサインイン済み", "Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "Baidu Cloud コンソールからサインアウトしました — プロバイダの設定で新しいサインインを渡してください", + "Baidu Cloud ended this sign-in. Bring a new one:": "Baidu Cloud がこのサインインを終了しました。新しいサインインを渡してください:", "This Baidu Cloud account has no Token Plan Personal": "この Baidu Cloud アカウントには Token Plan 個人版がありません", "A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "キーはプランの使用量を伝えません。今月の使用量は Baidu Cloud コンソールへのサインインにのみ伝えられます。ここで一度渡せば magpie が保存し、ほかの用途には使いません。ブックマークレットのコピーが使えない場合は、ブラウザの開発者ツールからコンソールのリクエストの Cookie ヘッダーを貼り付けてください。", "saved · paste a new one to replace it": "保存済み · 新しいものを貼り付けると置き換えます", @@ -19969,6 +19972,7 @@ const I18N = { "Sign in to the Baidu Cloud console in your browser ↗": "Im Browser bei der Baidu-Cloud-Konsole anmelden ↗", "Signed in to the Baidu Cloud console": "Bei der Baidu-Cloud-Konsole angemeldet", "Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "Von der Baidu-Cloud-Konsole abgemeldet — bringen Sie in den Einstellungen des Anbieters eine neue Anmeldung mit", + "Baidu Cloud ended this sign-in. Bring a new one:": "Baidu Cloud hat diese Anmeldung beendet. Bringen Sie eine neue mit:", "This Baidu Cloud account has no Token Plan Personal": "Dieses Baidu-Cloud-Konto hat keinen Token Plan Personal", "A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "Ein Schlüssel verrät die Nutzung des Plans nicht. Sein Monat wird nur einer Anmeldung in der Baidu-Cloud-Konsole verraten: Bringen Sie Ihre einmal hierher, magpie bewahrt sie auf und nutzt sie für nichts anderes. Kann magpie nicht verwenden, was das Bookmarklet kopiert hat, fügen Sie den Cookie-Header der Konsolenanfrage aus den Entwicklertools Ihres Browsers ein.", "saved · paste a new one to replace it": "gespeichert · zum Ersetzen ein neues einfügen", diff --git a/internal/gui/assets/qianfanplan.js b/internal/gui/assets/qianfanplan.js index 7ca90950f..27e5cddb1 100644 --- a/internal/gui/assets/qianfanplan.js +++ b/internal/gui/assets/qianfanplan.js @@ -1,9 +1,15 @@ // Baidu Qianfan's Token Plan Personal: its month is told only to a sign-in // on Baidu Cloud's console, brought by the bookmarklet and paste StepFun's // Step Plan uses (renderStepPlan) and kept per provider id -// (qianfan_plan.go). app.js imports this when such a provider's editor -// opens, so it weighs nothing on the core. -window.qianfanPlanField = (p) => field(t("Token Plan usage"), renderStepPlan(p.qianfanPlan, p.id, { - route: "qianfan", bm: "magpie · Qianfan", state: t("Signed in · the Usage page shows the Token Plan"), - open: t("Sign in to the Baidu Cloud console in your browser ↗"), ok: t("Signed in to the Baidu Cloud console"), -}), t("A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.")); +// (qianfan_plan.go). A sign-in the console has ended (sp.ended) asks for a +// new one with the same steps, saying why. app.js imports this when such a +// provider's editor opens, so it weighs nothing on the core. +window.qianfanPlanField = (p) => { + const sp = p.qianfanPlan; + const box = renderStepPlan(sp.ended ? { ...sp, signedIn: false } : sp, p.id, { + route: "qianfan", bm: "magpie · Qianfan", state: t("Signed in · the Usage page shows the Token Plan"), + open: t("Sign in to the Baidu Cloud console in your browser ↗"), ok: t("Signed in to the Baidu Cloud console"), + }); + if (sp.ended) box.prepend(el("div", "state ended", t("Baidu Cloud ended this sign-in. Bring a new one:"))); + return field(t("Token Plan usage"), box, t("A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.")); +}; diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 036abfccf..1a5bf20ad 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -575,6 +575,9 @@ type stepPlanJSON struct { SignedIn bool `json:"signedIn"` URL string `json:"url"` Bookmarklet string `json:"bookmarklet"` + // Ended: the vendor has ended the kept sign-in, and a new one is asked + // for (Baidu Qianfan's alone tells it) + Ended bool `json:"ended,omitempty"` } // qianwenPlanJSON: whether magpie has a sign-in to the Qwen AI platform @@ -1043,13 +1046,13 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs } } if site := provider.StepFunSite(p); site != "" { - out.StepPlan = &stepPlanJSON{site, provider.StepFunSignedIn(p.ID), provider.StepFunSignInURL(site), provider.StepFunBookmarklet()} + out.StepPlan = &stepPlanJSON{site, provider.StepFunSignedIn(p.ID), provider.StepFunSignInURL(site), provider.StepFunBookmarklet(), false} } if provider.QianwenPlan(p) { out.QianwenPlan = &qianwenPlanJSON{provider.QianwenSignedIn(p.ID), provider.QianwenAccount(p.ID)} } if provider.QianfanPlan(p) { - out.QianfanPlan = &stepPlanJSON{"", provider.QianfanSignedIn(p.ID), provider.QianfanSignInURL, provider.QianfanBookmarklet()} + out.QianfanPlan = &stepPlanJSON{"", provider.QianfanSignedIn(p.ID), provider.QianfanSignInURL, provider.QianfanBookmarklet(), provider.QianfanEnded(p.ID)} } out.Key.Set = p.Key != "" out.Key.Masked = provider.Mask(p.Key) diff --git a/internal/gui/qianfan_api_test.go b/internal/gui/qianfan_api_test.go index a2d65852b..72a26e667 100644 --- a/internal/gui/qianfan_api_test.go +++ b/internal/gui/qianfan_api_test.go @@ -38,7 +38,7 @@ func TestQianfanSignInRoutes(t *testing.T) { mux := http.NewServeMux() providerRoutes(mux, nil) plans := func() map[string]struct { - SignedIn bool + SignedIn, Ended bool URL, Bookmarklet string } { t.Helper() @@ -48,7 +48,7 @@ func TestQianfanSignInRoutes(t *testing.T) { Providers []struct { ID string QianfanPlan *struct { - SignedIn bool + SignedIn, Ended bool URL, Bookmarklet string } } @@ -57,7 +57,7 @@ func TestQianfanSignInRoutes(t *testing.T) { t.Fatal(err) } out := map[string]struct { - SignedIn bool + SignedIn, Ended bool URL, Bookmarklet string }{} for _, p := range got.Providers { @@ -72,6 +72,16 @@ func TestQianfanSignInRoutes(t *testing.T) { !strings.HasPrefix(got["baidu-qianfan"].URL, "https://console.bce.baidu.com/") { t.Fatalf("before: %+v", got) } + if got["baidu-qianfan"].Ended { + t.Fatalf("a sign-in the console takes reads as ended: %+v", got) + } + // one the console has ended is told, so the editor asks for a new one + if err := os.WriteFile(auth, []byte(`{"baidu-qianfan":{"cookie":"BDUSS=x","ended":"2026-11-16T00:00:00Z"}}`), 0o600); err != nil { + t.Fatal(err) + } + if got := plans(); !got["baidu-qianfan"].SignedIn || !got["baidu-qianfan"].Ended { + t.Fatalf("ended: %+v", got) + } for _, id := range []string{"relay", "qianfan-team", "nobody"} { for _, path := range []string{"session", "signout"} { w := httptest.NewRecorder() diff --git a/internal/gui/tests/qianfan-plan.test.cjs b/internal/gui/tests/qianfan-plan.test.cjs index 68a558db3..1ae57d00a 100644 --- a/internal/gui/tests/qianfan-plan.test.cjs +++ b/internal/gui/tests/qianfan-plan.test.cjs @@ -3,7 +3,9 @@ // Baidu Cloud's console the way StepFun's does (yuushabu_buyinn on X, #5860): // the paste posts to /api/qianfan/{id}/session for that provider's id, and a // signed-in one's Sign out posts /api/qianfan/{id}/signout. A Qianfan -// provider without the plan has no such field. In English and Chinese. +// provider without the plan has no such field. One whose sign-in Baidu +// ended says so and asks for a new one with the same steps. In English and +// Chinese. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -15,11 +17,11 @@ const qianfan = (id, name, plan) => ({ id, name, icon: "baiducloud-color", preset: "baidu-qianfan", chat: "https://qianfan.baidubce.com/v2/tokenplan/personal", responses: "", anthropic: "", catalog: "", models: [{ id: "ernie-5.0", name: "ERNIE 5.0", on: true }], agents: [], fallback: [], headers: {}, key: { set: true, masked: "…ab12" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", - ...(plan ? { qianfanPlan: { site: "", signedIn: plan === "in", url: "https://console.bce.baidu.com/qianfan/resource/token-plan", bookmarklet: "javascript:void 0" } } : {}), + ...(plan ? { qianfanPlan: { site: "", signedIn: plan !== "out", ...(plan === "ended" ? { ended: true } : {}), url: "https://console.bce.baidu.com/qianfan/resource/token-plan", bookmarklet: "javascript:void 0" } } : {}), }); function serve(lang, posts) { - const providers = { providers: [qianfan("qianfan", "Qianfan Plan", "in"), qianfan("qianfan-2", "Qianfan Work", "out"), qianfan("qianfan-api", "Qianfan API", "")], presets: [], excluded: [], gateway: { running: true, window: true } }; + const providers = { providers: [qianfan("qianfan", "Qianfan Plan", "in"), qianfan("qianfan-2", "Qianfan Work", "out"), qianfan("qianfan-api", "Qianfan API", ""), qianfan("qianfan-old", "Qianfan Old", "ended")], 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()); @@ -40,7 +42,7 @@ function serve(lang, posts) { }; } -const words = { en: { out: "Sign out", cancel: "Cancel" }, zh: { out: "退出登录", cancel: "取消" } }; +const words = { en: { out: "Sign out", cancel: "Cancel", ended: "Baidu Cloud ended this sign-in" }, zh: { out: "退出登录", cancel: "取消", ended: "百度智能云已结束这次登录" } }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { for (const lang of ["en", "zh"]) { @@ -82,6 +84,19 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await wait(1); assert.equal(posts.length, 2); assert.equal(posts[1].path, "/api/qianfan/qianfan/signout"); + assert.equal(await page.locator(".editor .stepplan .ended").count(), 0); + + // the one Baidu ended says so and takes a new paste, for its own id + await page.locator(".editor .bar").getByRole("button", { name: words[lang].cancel, exact: true }).click(); + await page.locator(".editor").waitFor({ state: "detached" }); + await page.locator(".row.provider", { hasText: "Qianfan Old" }).click(); + assert.match(await page.locator(".editor .stepplan .ended").innerText(), new RegExp(words[lang].ended)); + const again = page.locator(".editor .stepplan input[type=password]"); + await again.fill("BDUSS=new"); + await again.press("Enter"); + await wait(2); + assert.equal(posts.length, 3); + assert.equal(posts[2].path, "/api/qianfan/qianfan-old/session"); assert.deepEqual(errors, []); }); } diff --git a/internal/provider/qianfan_plan.go b/internal/provider/qianfan_plan.go index 053578e41..62f693677 100644 --- a/internal/provider/qianfan_plan.go +++ b/internal/provider/qianfan_plan.go @@ -26,9 +26,16 @@ package provider // the browser's developer tools, where the HttpOnly ones are too. magpie // asks the console with it before keeping it, and keeps it in // qianfan-auth.json beside providers.json, readable by the user alone, one -// per provider: two can be two Baidu accounts. The console doesn't renew -// it for magpie: when Baidu ends it the card says so, and the user brings -// a new one. +// per provider: two can be two Baidu accounts. A cookie the console sets +// in a reply that read the plan is kept, as the browser keeps it, so a +// session Baidu renews as it is used stays the one magpie holds. When +// Baidu ends it the card says so, the sign-in is marked ended (Ended), and +// the provider's editor asks for a new one again; a later read the console +// takes clears the mark. +// +// There is no AccessKey/SecretKey way to this: Baidu's OpenAPI (the +// Qianfan API catalog, Finance's billing API, the Token Plan Enterprise's +// seat APIs with an API key) has no read for a Token Plan Personal. // // The Enterprise plan (tokenplan/team) is read on the console from its // seats' admin pages (tokenPlan/seat/admin/overview), not this one; it @@ -101,6 +108,9 @@ func QianfanBookmarklet() string { // Cookie header. type qianfanSession struct { Cookie string `json:"cookie"` + // Ended is when the console first sent this session to sign in again + // (RFC 3339), "" while it takes it + Ended string `json:"ended,omitempty"` } var qianfanMu sync.Mutex @@ -151,12 +161,87 @@ func qianfanSignIn(id string) (qianfanSession, bool) { return s, ok && s.Cookie != "" } -// QianfanSignedIn reports whether magpie has a sign-in for the provider. +// QianfanSignedIn reports whether magpie has a sign-in for the provider, +// ended or not. func QianfanSignedIn(id string) bool { _, ok := qianfanSignIn(id) return ok } +// QianfanEnded reports whether the console has ended the provider's +// sign-in, so the editor asks for a new one. +func QianfanEnded(id string) bool { + s, ok := qianfanSignIn(id) + return ok && s.Ended != "" +} + +// noteQianfan records what a read of the console with the provider's +// cookie said: the session ended, or the cookies its reply set. Nothing is +// written when the sign-in has changed since (a new paste) or nothing +// changes. +func noteQianfan(id, used string, ended bool, set []*http.Cookie) { + qianfanMu.Lock() + defer qianfanMu.Unlock() + all := loadQianfan() + s, ok := all[id] + if !ok || s.Cookie != used { + return + } + n := s + if ended { + if n.Ended == "" { + n.Ended = time.Now().UTC().Format(time.RFC3339) + } + } else { + n.Ended = "" + n.Cookie = mergeQianfanCookies(used, set) + } + if n == s { + return + } + all[id] = n + _ = saveQianfan(all) +} + +// mergeQianfanCookies is the Cookie header with what a console reply set +// (for the resource's path) put in, as a browser would: a value replaced +// where it stood, a new one added, one deleted or expired taken out. +func mergeQianfanCookies(header string, set []*http.Cookie) string { + type kv struct{ k, v string } + var jar []kv + for _, part := range strings.Split(header, ";") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + k, v, _ := strings.Cut(part, "=") + jar = append(jar, kv{k, v}) + } + now := time.Now() + for _, c := range set { + if c.Name == "" || strings.ContainsAny(c.Name+c.Value, ";\r\n") || + c.Path != "" && !strings.HasPrefix(qianfanResourcePath, c.Path) { + continue + } + gone := c.MaxAge < 0 || !c.Expires.IsZero() && !c.Expires.After(now) + i := slices.IndexFunc(jar, func(e kv) bool { return e.k == c.Name }) + switch { + case gone && i >= 0: + jar = slices.Delete(jar, i, i+1) + case gone: + case i >= 0: + jar[i].v = c.Value + default: + jar = append(jar, kv{c.Name, c.Value}) + } + } + out := make([]string, len(jar)) + for i, e := range jar { + out[i] = e.k + "=" + e.v + } + return strings.Join(out, "; ") +} + // SignOutQianfan forgets the provider's sign-in, and no other's. func SignOutQianfan(id string) error { qianfanMu.Lock() @@ -232,7 +317,8 @@ func SaveQianfanPaste(ctx context.Context, id, text string) error { if err != nil { return err } - if _, err := qianfanResource(ctx, cookie); err != nil { + _, set, err := qianfanResource(ctx, cookie) + if err != nil { if errors.Is(err, errQianfanSession) { // the bookmarklet sees only the cookies a page may read return errors.New("Baidu's console didn't take that sign-in: copy the Cookie header of the console's tokenPlanPersonal/resource request from your browser's developer tools (Network) and paste it here") @@ -241,7 +327,7 @@ func SaveQianfanPaste(ctx context.Context, id, text string) error { } qianfanMu.Lock() all := loadQianfan() - all[id] = qianfanSession{Cookie: cookie} + all[id] = qianfanSession{Cookie: mergeQianfanCookies(cookie, set)} err = saveQianfan(all) qianfanMu.Unlock() forgetPlanQuotas() @@ -260,11 +346,12 @@ func qianfanClient() *http.Client { } // qianfanResource asks the console for the account's Token Plan Personal -// as the session, and reads its result. -func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, error) { +// as the session, and reads its result and the cookies a reply that read it +// set. +func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, []*http.Cookie, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, qianfanConsole+qianfanResourcePath, nil) if err != nil { - return nil, err + return nil, nil, err } req.Header.Set("Cookie", cookie) req.Header.Set("Accept", "application/json;charset=UTF-8") @@ -273,16 +360,16 @@ func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, error req.Header.Set("User-Agent", qianfanUA) res, err := qianfanClient().Do(req) if err != nil { - return nil, err + return nil, nil, err } defer res.Body.Close() b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) switch { case res.StatusCode >= 300 && res.StatusCode < 400, res.StatusCode == http.StatusUnauthorized, res.StatusCode == http.StatusForbidden: - return nil, errQianfanSession + return nil, nil, errQianfanSession case res.StatusCode >= 400: - return nil, fmt.Errorf("Baidu's console answered %s", res.Status) + return nil, nil, fmt.Errorf("Baidu's console answered %s", res.Status) } var r struct { Success any `json:"success"` @@ -293,9 +380,9 @@ func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, error if json.Unmarshal(b, &r) != nil { // a sign-in page served as 200 is a session ended too if strings.Contains(strings.ToLower(string(b[:min(len(b), 2048)])), "" { msg = volcHead(b) } - return nil, fmt.Errorf("Baidu's console refused: %s", msg) + return nil, nil, fmt.Errorf("Baidu's console refused: %s", msg) } - return r.Result, nil + return r.Result, res.Cookies(), nil } // qianfanItem is one plan the console lists, its apiKey left out. @@ -433,7 +520,12 @@ func qianfanPlanQuota(ctx context.Context, p Provider) SubscriptionQuota { q.Error = errQianfanSession.Error() return q } - raw, err := qianfanResource(ctx, s.Cookie) + raw, set, err := qianfanResource(ctx, s.Cookie) + if errors.Is(err, errQianfanSession) { + noteQianfan(p.ID, s.Cookie, true, nil) + } else if err == nil && (len(set) > 0 || s.Ended != "") { + noteQianfan(p.ID, s.Cookie, false, set) + } if err != nil { q.Error = err.Error() return q diff --git a/internal/provider/qianfan_plan_test.go b/internal/provider/qianfan_plan_test.go index 813875ccc..75dbdc057 100644 --- a/internal/provider/qianfan_plan_test.go +++ b/internal/provider/qianfan_plan_test.go @@ -30,6 +30,9 @@ type fakeQianfanConsole struct { cookie atomic.Value // the Cookie header it takes now body atomic.Value asked atomic.Int32 + // renew, when set, is a session the console renews to as it answers: + // a reply sets its bce-session, and the old one is taken no longer + renew atomic.Value } func newFakeQianfanConsole(t *testing.T) *fakeQianfanConsole { @@ -47,6 +50,12 @@ func newFakeQianfanConsole(t *testing.T) *fakeQianfanConsole { http.Redirect(w, r, "https://login.bce.baidu.com/?redirect=x", http.StatusFound) return } + if r, _ := f.renew.Load().(string); r != "" { + w.Header().Add("Set-Cookie", "bce-session="+r+"; Path=/; Domain=.baidu.com; HttpOnly") + w.Header().Add("Set-Cookie", "elsewhere=1; Path=/qianfan/other") + f.cookie.Store("BDUSS=bd-1; bce-session=" + r + "; bce-user-info=u-1") + f.renew.Store("") + } w.Header().Set("Content-Type", "application/json") w.Write([]byte(f.body.Load().(string))) })) @@ -227,3 +236,76 @@ func TestQianfanPlanCard(t *testing.T) { t.Fatalf("forgotten: %v", err) } } + +// A session Baidu ends is marked ended, so the editor asks for a new one +// (QianfanEnded), and the card still says signed out; a new paste, or a +// read the console takes again, clears the mark. A cookie the console +// renews in a reply is kept, so the next read goes with it. +func TestQianfanSessionEnded(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + forgetPlanQuotas() + f := newFakeQianfanConsole(t) + ctx := context.Background() + p := Provider{ID: "baidu-qianfan", Name: "Baidu Qianfan", Key: "bce-v3/k", Chat: "https://qianfan.baidubce.com/v2/tokenplan/personal"} + first := f.cookie.Load().(string) + if err := SaveQianfanPaste(ctx, p.ID, first); err != nil || QianfanEnded(p.ID) { + t.Fatalf("saved: %v", err) + } + + // the console renews bce-session in its reply: magpie keeps the new one + f.renew.Store("s-2") + if q := qianfanPlanQuota(ctx, p); q.Error != "" { + t.Fatalf("renewing read: %+v", q) + } + if got := loadQianfan()[p.ID].Cookie; got != "BDUSS=bd-1; bce-session=s-2; bce-user-info=u-1" { + t.Fatalf("renewed cookie kept as %q", got) + } + if q := qianfanPlanQuota(ctx, p); q.Error != "" || QianfanEnded(p.ID) { + t.Fatalf("read after renewal: %+v", q) + } + + // Baidu ends it: the card says so, and the editor asks again + f.cookie.Store("BDUSS=someone-else") + if q := qianfanPlanQuota(ctx, p); q.Error != errQianfanSession.Error() { + t.Fatalf("ended: %+v", q) + } + if !QianfanEnded(p.ID) || !QianfanSignedIn(p.ID) { + t.Fatal("an ended sign-in should be kept, marked ended") + } + ended := loadQianfan()[p.ID].Ended + qianfanPlanQuota(ctx, p) + if got := loadQianfan()[p.ID].Ended; got != ended { + t.Fatalf("the time it ended moved: %q then %q", ended, got) + } + + // a new paste is a new sign-in, not ended + if err := SaveQianfanPaste(ctx, p.ID, "BDUSS=someone-else"); err != nil || QianfanEnded(p.ID) { + t.Fatalf("new paste: %v ended=%v", err, QianfanEnded(p.ID)) + } + + // a paste made while an older read was out isn't marked by that read + noteQianfan(p.ID, first, true, nil) + if QianfanEnded(p.ID) { + t.Fatal("a read with the old cookie marked the new sign-in ended") + } +} + +func TestMergeQianfanCookies(t *testing.T) { + past := time.Now().Add(-time.Hour) + for _, c := range []struct { + set []*http.Cookie + want string + }{ + {nil, "a=1; b=2"}, + {[]*http.Cookie{{Name: "b", Value: "3"}}, "a=1; b=3"}, + {[]*http.Cookie{{Name: "c", Value: "4", Path: "/api"}}, "a=1; b=2; c=4"}, + {[]*http.Cookie{{Name: "a", Value: "", MaxAge: -1}}, "b=2"}, + {[]*http.Cookie{{Name: "b", Value: "x", Expires: past}}, "a=1"}, + {[]*http.Cookie{{Name: "c", Value: "4", Path: "/qianfan/other"}}, "a=1; b=2"}, + {[]*http.Cookie{{Name: "c", Value: "4\r\nX: y"}}, "a=1; b=2"}, + } { + if got := mergeQianfanCookies("a=1; b=2", c.set); got != c.want { + t.Errorf("%v: %q, want %q", c.set, got, c.want) + } + } +}