diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 18dd1568b..363c2cc85 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -81,7 +81,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. 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). 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) | @@ -414,7 +414,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - A sub2api key's windows are fixed: each starts at the key's first request after it was empty, aligned to the relay's day, and a window not started yet says `used 0` with no `reset_at`, so it is taken to renew a span from now. They count this key's spend only, not the relay's accounts behind it. `ForgetBalances` (a key or Balance URL changed) has every key's windows read again at its next ask, a read begun before dropped; until then the last reading stands, fresher than the card's, which routing's reads never write. A key changed is another key (`keyID`), with windows of its own. - A Volcengine Ark provider's access key (`TakesVolcAccessKey`: any of its bases on `ark..volces.com`) is kept with its keys and never sent to the GUI: `/api/providers` tells the editor its ID and whether a Secret is saved (`accessKey`). A save that leaves the Secret blank keeps it, one that leaves the ID out or sends it blank keeps both (an editor opened before the key was given sends `""`, #1821), and `clearAccessKey` drops both. The ID and Secret go together everywhere the keys go: a copy takes them, also when its form sends the source's ID without the Secret (`AddCopy`), a backup or sync without keys has neither (`withoutKeys`), and a restore, mirror or sync keeps this machine's (`KeepSecrets` in `Restore`, `Mirror`, davsync's `take`) when it came without keys, or with the same key and no access key at all, as a magpie before v0.1.1142 or one the access key was never given on sends it (#1821); another key is another account and brings its own. A copy without keys keeps this machine's secret headers (`SecretHeader`) the same way. A plan endpoint with no provider on it holding the access key is a card that says which to give (`accessKeyCard`, `needsAccessKey`), with a button to the provider's settings, not a card left out. A `providers.json` saved with a UTF-8 BOM is read through it, not taken for a broken file whose `.bak` stands in. The plan read is the endpoint's: `/api/coding` asks `GetCodingPlanUsage`, `/api/plan` asks `GetAFPUsage`, pay-as-you-go (`/api/v3`) has no card; the region is the host's. One card is read for each access key and plan. `GetCodingPlanUsage`'s reply (`QuotaUsage[]` with `Level`, `Percent`, `ResetTimestamp` in seconds) is the one three tools built on it read; `GetAFPUsage`'s buckets are read in each form those tools read (`Used` of `Quota` or `Total`, or `Percent`; `ResetTime` or `ResetTimestamp`), none of them seen from a real account here. A reply none of that reads says so on the card with the reply's head. Changing the access key drops the cached cards (`ForgetPlanQuotas`). - A Tencent Cloud provider's SecretId and SecretKey are kept, listed and saved the same way, in the same fields (`AccessKeyVendor` tells the editor whose: `accessKey.vendor`, the preset's `accessKeyVendor`). Only the Token Plan's endpoints are read with them (`TakesTencentAccessKey`: `/plan` on `tokenhub.tencentmaas.com`, region `ap-guangzhou`, or `tokenhub-intl.tencentmaas.com`, `ap-singapore`). Since 10-22 Tencent serves 个人版 and 企业版 in China at the same `/plan` endpoints with the same `sk-tp-` keys (product/1823/130060, 130659), so they are one region, `plan` (a key saved on `enterprise` is on it, `regionAliases`/`RegionID`); 个人版 has no usage API, so a Guangzhou provider without a SecretId gets no card asking for one (`tcSharedRegion`), while Singapore's does. A Tencent Cloud provider saved at the old personal host `api.lkeap.cloud.tencent.com/plan/...` is moved to TokenHub's at load (`movedEndpoints`, `moveEndpoints` in `normalize`), with Responses added; one of no preset keeps the address its user typed, and an app imported at the old host lands on the plan. TokenHub's pay as you go has no plan and no card. A custom provider (no preset) at a Token Plan's or Ark plan's address is the user's own: its editor and Usage page ask it for no access key (`AsksAccessKey`) until one is saved on it, and its key goes as typed, `Authorization: Bearer` on chat and Responses (ysm119). The preset lists its regions that take one (`accessKeyRegions`, `presetAccessKey`), and the editor shows SecretId and SecretKey at those alone. `DescribeTokenPlanList` gives the account's team plans (a sub-user sees the ones it made); each is asked `DescribeTokenPlan` for its `PackageInfo` and `TokenSummary`, the list's kept for what the reply leaves out. The card's one window is `TotalUsed` of `CycleQuota` (else `TotalQuota`), resetting at `TokenSummary.CycleEndTime`, else counted in months from `StartTime` and never past `ExpireTime`. A plan not `enable` says its status beside the plan's name. Errors come back as 200 with `Response.Error`; an `AuthFailure…` or `UnauthorizedOperation` one says to check the key. Built from the API docs (api/1823/132270 and siblings) and the signing doc's worked example; never seen from a real account here. -- An Alibaba Cloud Token Plan provider's AccessKey ID and Secret are kept in the same fields (`AccessKeyVendor` "alibaba"). Only the plan's two hosts at `token-plan..maas.aliyuncs.com` take them (`TakesAlibabaAccessKey`, `aliPlanSite`: `cn-beijing` is `bailian-token-plan`, `ap-southeast-1` is `alibaba-token-plan`, #2940); the Qwen AI platform's (`qianwenaiapi.com`) and Qwen Cloud's plans have no read here (their console takes a browser sign-in, #5829). The plan key only authorizes inference. The usage is on the console's gateway behind a console token, which `POST modelstudio..aliyuncs.com/modelstudio/cli/generateAccessToken` (ACS3-HMAC-SHA256, `aliACSSign`; Action `GenerateCLIAccessToken`, version `2026-02-10`; reply `cliAccessToken`) makes from the AccessKey, as Alibaba's own `bl` CLI does. The token is kept 20 minutes per AccessKey and region and made again once when the gateway answers `BailianGateway.Login.NotLogined`. The gateway call is `POST /cli/api.json?action=BroadScopeAspnGateway|IntlBroadScopeAspnGateway&product=sfm_bailian&api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage` with `Bearer` and a form `params`, `region`; the windows are the `perPercentage` (a share used, 0 to 1) and `ResetTime` (ms) fields of `data.DataV2.data.data`, so 5 hours, Weekly and Month show as the plan has them. A RAM user's key gets `BailianGateway.Team.NotAuthorised` until the main account grants what Alibaba's Token Plan docs ask for RAM users: the `AliyunTokenPlanReadOnlyAccess` and `AliyunBSSReadOnlyAccess` system policies (the `AliyunBailian*` and `AliyunModelStudio*` ones don't cover the Token Plan) and the Administrator or Subscribe Plan permission on Model Studio's Account Management page; the card and the editor's hint name all three (`aliRAMHint`, #6506). The same API serves the main account and RAM users; `bl` has no other route. Another refusal shows the console's `errorMsg`. Team plans (团队版) use other APIs and have no card. The gateway has no public doc: built from the official client's source; never seen from a real account here, and the international gateway host (`bailian-singapore-cs.alibabacloud.com`) is the least certain part. +- An Alibaba Cloud Token Plan provider's AccessKey ID and Secret are kept in the same fields (`AccessKeyVendor` "alibaba"). Only the plan's two hosts at `token-plan..maas.aliyuncs.com` take them (`TakesAlibabaAccessKey`, `aliPlanSite`: `cn-beijing` is `bailian-token-plan`, `ap-southeast-1` is `alibaba-token-plan`, #2940); Qwen Cloud's plan has no read here (its console takes a browser sign-in, #5829). The Qwen AI platform's plan (`qwen-token-plan`, `token-plan.maas.qianwenaiapi.com`) is read through a sign-in to the platform instead, as the QianWen CLI 1.10.0 reads it (`qianwen_plan.go`, @imthe99galaxy on X): a device sign-in with PKCE at `t.qianwenai.com/cli/device/code` and `/cli/device/token`, the editor's *Sign in to the Qwen AI platform* (`qianwenplan.js`, imported when such a provider's editor opens) opening the approval page and polling it; the session is the provider's own, kept by provider id in `qianwen-auth.json` (0600) and moved or dropped with the provider. From it `cli.qianwenai.com/data/v2/api.json` (`GenerateCLIAccessToken`) mints a console token, kept and minted once more when the gateway answers `NotLogined`; the usage is the same `BroadScopeAspnGateway` call at `cs-data.qianwenai.com` with consoleSite `QIANWENAI` and region `cn-beijing`, read by `aliAskUsage` and `aliReadWindows`. The plan key (`sk-sp-`) is never sent there. Not signed in, the card says so with *Open settings* (`NeedsAccessKey`); a session the platform refuses is signed out. `TestQianwenSignIn`, `TestQianwenPlanQuotas`, `TestQianwenFollowsProvider`, `TestQianwenSignInRoutes`, `qianwen-plan.test.cjs`. Built from the CLI's source and the device endpoint's live replies; never signed in with a real account here. The plan key only authorizes inference. The usage is on the console's gateway behind a console token, which `POST modelstudio..aliyuncs.com/modelstudio/cli/generateAccessToken` (ACS3-HMAC-SHA256, `aliACSSign`; Action `GenerateCLIAccessToken`, version `2026-02-10`; reply `cliAccessToken`) makes from the AccessKey, as Alibaba's own `bl` CLI does. The token is kept 20 minutes per AccessKey and region and made again once when the gateway answers `BailianGateway.Login.NotLogined`. The gateway call is `POST /cli/api.json?action=BroadScopeAspnGateway|IntlBroadScopeAspnGateway&product=sfm_bailian&api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage` with `Bearer` and a form `params`, `region`; the windows are the `perPercentage` (a share used, 0 to 1) and `ResetTime` (ms) fields of `data.DataV2.data.data`, so 5 hours, Weekly and Month show as the plan has them. A RAM user's key gets `BailianGateway.Team.NotAuthorised` until the main account grants what Alibaba's Token Plan docs ask for RAM users: the `AliyunTokenPlanReadOnlyAccess` and `AliyunBSSReadOnlyAccess` system policies (the `AliyunBailian*` and `AliyunModelStudio*` ones don't cover the Token Plan) and the Administrator or Subscribe Plan permission on Model Studio's Account Management page; the card and the editor's hint name all three (`aliRAMHint`, #6506). The same API serves the main account and RAM users; `bl` has no other route. Another refusal shows the console's `errorMsg`. Team plans (团队版) use other APIs and have no card. The gateway has no public doc: built from the official client's source; never seen from a real account here, and the international gateway host (`bailian-singapore-cs.alibabacloud.com`) is the least certain part. - Whether a Codex account spends its credits (`CodexNoCredits` in settings, opt-out, by lower-cased email) is the gateway's routing only. It never changes which account Codex is signed in to: `NextLogin` moves off an account at its routing's spent share, 100% at most, credits or not. - Whether a Claude account spends Anthropic's extra usage past its plan (`ClaudeNoExtraUsage` in settings, one switch for every Claude account, opt-out: Spend extra usage in the Claude editor's Advanced, or `magpie settings set claudeNoExtraUsage off`) is the gateway's routing and the warm-up only; a cap on an account's Usage credits window holds that account the same way once its extra usage reaches it (`provider/claude_extra.go`). magpie can't turn extra usage off at Anthropic: a Claude Code signed in on its own, not through magpie, still spends it. `NextLogin` already moves Claude Code off an account on overages, as the Extra usage row reads 100 (`claudeOveragesWindow`, `usedPast`). Claude Code's hidden `/limit-reset` is not driven: it spends or resets limits through a flow Anthropic hasn't made public, and calling its endpoints would be Claude Code's client imitated. - A Vertex AI provider's credentials are read only when a request is signed (`Sign`), so adding, listing and showing one ask Google nothing. With no `credentials` given and no file where Application Default Credentials are looked for, the request fails with `no Google credentials at `, naming `gcloud auth application-default login` and the provider's credentials file as the ways to give it some. A `credentials` file that isn't there fails with the same words, saying to correct it or clear it. When Google refuses a person's sign-in (revoked, or past the organization's session length), the error says how to sign in again for the file used (`signInAgain`): gcloud's Application Default Credentials with `gcloud auth application-default login`, adding `--impersonate-service-account=` when the file impersonates one; a file under gcloud's `legacy_credentials//` with `gcloud auth login `; any other file by writing it anew or giving the provider another. The new file is read at the next request, with no restart. diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 8adb44640..e26761f2e 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -484,6 +484,10 @@ var notYet = map[string]string{ "POST /api/signin/export": P, // providers.go "POST /api/stepfun/{id}/session": P, // providers.go "POST /api/stepfun/{id}/signout": P, // providers.go + "GET /api/qianwen/{id}/signin": P, // providers.go + "POST /api/qianwen/{id}/signin": P, // providers.go + "POST /api/qianwen/{id}/signin/cancel": P, // providers.go + "POST /api/qianwen/{id}/signout": P, // providers.go "GET /api/speeds": U, // sessions_manage.go: the Sessions row's speed curve "GET /api/sessions/manage": U, // sessions_manage.go "GET /api/sessions/search": U, // sessions_manage.go diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index d6cb404e2..4cc756d17 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -10037,6 +10037,8 @@ function drawEditor(p, presetID) { // a Step Plan's windows are told only to a StepFun sign-in if (p?.stepPlan) ed.append(...field(t("Step Plan allowances"), renderStepPlan(p.stepPlan, p.id), 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."))); + // and a Qwen AI platform plan's to a sign-in there, in qianwenplan.js + if (p?.qianwenPlan) { const at = el("span"); ed.append(at); import("./qianwenplan.js").then(() => at.replaceWith(...qianwenPlanField(p)), () => {}); } // a team's GLM Coding Plan windows need its org and project (#236) const team = p ? !!p.zhipuTeam : !!pr?.zhipuTeam; @@ -14006,6 +14008,8 @@ function quotaError(err, q) { // a Volcengine or Tencent plan with no access key (#1821) if (/^this plan's usage is read with the account's access key: give its SecretId/.test(err)) return t("This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings"); if (/^this plan's usage is read with the account's access key/.test(err)) return t("This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings"); + // a Qwen AI platform plan (qianwen_plan.go) + if (/^(this plan's usage is told only to a sign-in on|signed out of) the Qwen AI platform/.test(err)) return t("This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings"); // ZCode with no plan left, not a failed read (#1001) if (/^this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started$/.test(err)) return t("ZCode: no GLM Coding Plan, and no free Start Plan — subscribe to a GLM Coding Plan to use this account"); // an OpenCode Go key's windows (planquota.go) diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 33417e376..35ca92e52 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3874,6 +3874,12 @@ const I18N = { "AiHubMix didn't take the access token — paste a new one in the provider's settings": "AiHubMix 不认这个访问令牌,请在供应商设置里重新填入", "Account balance": "账户余额", "Step Plan allowances": "Step Plan 额度", + "Token Plan allowances": "Token Plan 额度", + "The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else.": "这个套餐的用量只告诉千问 AI 平台的登录。magpie 保存这次登录,只用于读取用量。", + "Approve the sign-in in your browser…": "请在浏览器里批准登录…", + "Sign in to the Qwen AI platform ↗": "登录千问 AI 平台 ↗", + "Signed in to the Qwen AI platform": "已登录千问 AI 平台", + "This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings": "这个套餐的用量需要登录千问 AI 平台——在提供商设置里登录", "Team org ID": "团队组织 ID", "Team project ID": "团队项目 ID", "optional · only for a team plan": "可选 · 仅团队套餐需要", @@ -9115,6 +9121,12 @@ const I18N = { "AiHubMix didn't take the access token — paste a new one in the provider's settings": "AiHubMix 不認這個存取權杖,請在供應商設定裡重新填入", "Account balance": "帳戶餘額", "Step Plan allowances": "Step Plan 額度", + "Token Plan allowances": "Token Plan 額度", + "The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else.": "這個方案的用量只告訴千問 AI 平台的登入。magpie 保存這次登入,只用於讀取用量。", + "Approve the sign-in in your browser…": "請在瀏覽器裡核准登入…", + "Sign in to the Qwen AI platform ↗": "登入千問 AI 平台 ↗", + "Signed in to the Qwen AI platform": "已登入千問 AI 平台", + "This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings": "這個方案的用量需要登入千問 AI 平台——在供應商設定裡登入", "Team org ID": "團隊組織 ID", "Team project ID": "團隊專案 ID", "optional · only for a team plan": "可選 · 僅團隊套餐需要", @@ -14364,6 +14376,12 @@ const I18N = { "AiHubMix didn't take the access token — paste a new one in the provider's settings": "AiHubMix がアクセストークンを受け付けませんでした — プロバイダの設定で新しいものを貼り付けてください", "Account balance": "アカウント残高", "Step Plan allowances": "Step Plan の利用枠", + "Token Plan allowances": "Token Plan の利用枠", + "The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else.": "このプランの利用量は Qwen AI プラットフォームへのサインインにしか伝えられません。magpie はそれを利用量の読み取りだけに使います。", + "Approve the sign-in in your browser…": "ブラウザでサインインを承認してください…", + "Sign in to the Qwen AI platform ↗": "Qwen AI プラットフォームにサインイン ↗", + "Signed in to the Qwen AI platform": "Qwen AI プラットフォームにサインインしました", + "This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings": "このプランの利用量には Qwen AI プラットフォームへのサインインが必要です — プロバイダの設定でサインインしてください", "Team org ID": "チーム組織 ID", "Team project ID": "チームプロジェクト ID", "optional · only for a team plan": "任意 · チームプランのみ", @@ -19622,6 +19640,12 @@ const I18N = { "AiHubMix didn't take the access token — paste a new one in the provider's settings": "AiHubMix hat das Zugriffstoken nicht akzeptiert – fügen Sie in den Anbietereinstellungen ein neues ein", "Account balance": "Kontoguthaben", "Step Plan allowances": "Step-Plan-Kontingente", + "Token Plan allowances": "Token-Plan-Kontingente", + "The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else.": "Die Nutzung des Plans erfährt nur eine Anmeldung bei der Qwen-AI-Plattform. magpie nutzt sie für nichts anderes.", + "Approve the sign-in in your browser…": "Bestätige die Anmeldung im Browser …", + "Sign in to the Qwen AI platform ↗": "Bei der Qwen-AI-Plattform anmelden ↗", + "Signed in to the Qwen AI platform": "Bei der Qwen-AI-Plattform angemeldet", + "This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings": "Die Nutzung dieses Plans braucht eine Anmeldung bei der Qwen-AI-Plattform — melde dich in den Einstellungen des Anbieters an", "Team org ID": "Team-Organisations-ID", "Team project ID": "Team-Projekt-ID", "optional · only for a team plan": "optional · nur für einen Team-Plan", diff --git a/internal/gui/assets/qianwenplan.js b/internal/gui/assets/qianwenplan.js new file mode 100644 index 000000000..b790fb6db --- /dev/null +++ b/internal/gui/assets/qianwenplan.js @@ -0,0 +1,76 @@ +// The Qwen AI platform's Token Plan: its usage is told only to a sign-in +// on the platform, approved in the user's browser and kept per provider +// id (qianwen_plan.go). app.js imports this when such a provider's +// editor opens, so it weighs nothing on the core. +window.qianwenPlanField = (p) => field(t("Token Plan allowances"), renderQianwenPlan(p.qianwenPlan, p.id), t("The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else.")); + +// renderQianwenPlan: a sign-in to the Qwen AI platform, approved in the +// user's browser, per provider id (qianwen_plan.go) +const qianwenWaiting = new Set(); +function renderQianwenPlan(qp, id) { + const box = el("div", "stepplan"); + const path = "qianwen/" + encodeURIComponent(id); + const row = el("div", "pair"); + const side = el("div", "side"); + if (qp.signedIn) { + const out = el("button", "text", t("Sign out")); + out.onclick = async () => { + try { providers = await api(path + "/signout", {}); renderProviders(); } catch (e) { statusErr(e); } + }; + side.append(out); + row.append(el("span", "state", qp.account ? t("Signed in as {user}", { user: qp.account }) : t("Signed in")), side); + box.append(row); + return box; + } + if (qianwenWaiting.has(id)) { + const stop = el("button", "text", t("Cancel")); + stop.onclick = () => { + qianwenWaiting.delete(id); + api(path + "/signin/cancel", {}).catch(() => {}); + renderProviders(); + }; + side.append(stop); + row.append(el("span", "state", t("Approve the sign-in in your browser…")), side); + box.append(row); + return box; + } + const go = el("button", "link", t("Sign in to the Qwen AI platform ↗")); + go.onclick = async () => { + go.disabled = true; + try { + const r = await api(path + "/signin", {}); + qianwenWaiting.add(id); + api("open", { url: r.url }).catch(() => {}); + renderProviders(); + qianwenWatch(id); + } catch (e) { + go.disabled = false; + statusErr(e); + } + }; + box.append(go); + return box; +} + +// qianwenWatch waits on the provider's sign-in, which magpie finishes +// once the user approves it in their browser +async function qianwenWatch(id) { + const path = "qianwen/" + encodeURIComponent(id) + "/signin"; + while (qianwenWaiting.has(id)) { + await new Promise((r) => setTimeout(r, 1500)); + if (!qianwenWaiting.has(id)) return; + let s; + try { s = await api(path); } catch (_) { continue; } + if (s?.state === "pending") continue; + qianwenWaiting.delete(id); + if (s?.state === "done") { + try { providers = await api("providers"); } catch (_) { /* keep the last known list */ } + status(t("Signed in to the Qwen AI platform"), "ok"); + } else if (s?.error) { + statusErr(new Error(s.error)); + } + renderProviders(); + return; + } +} + diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 1f9d98353..510f75fc5 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -18,7 +18,7 @@ import ( // `git log -L` of this file. const ( appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had - coreScriptBudget = 1_269_531 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to + coreScriptBudget = 1_269_857 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to ) // codeBytes is how many bytes of b are code: its blank lines, its lines diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 71c535a7d..9da636a78 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -319,6 +319,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 Qwen AI platform Token Plan's windows, told only to a sign-in on + // the platform: whether magpie has one, and whose + QianwenPlan *qianwenPlanJSON `json:"qianwenPlan,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"` @@ -570,6 +573,13 @@ type stepPlanJSON struct { Bookmarklet string `json:"bookmarklet"` } +// qianwenPlanJSON: whether magpie has a sign-in to the Qwen AI platform +// for the provider, and its account +type qianwenPlanJSON struct { + SignedIn bool `json:"signedIn"` + Account string `json:"account,omitempty"` +} + type accountJSON struct { provider.Account Agent string `json:"agent"` // the agent's id @@ -1013,6 +1023,9 @@ 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()} } + if provider.QianwenPlan(p) { + out.QianwenPlan = &qianwenPlanJSON{provider.QianwenSignedIn(p.ID), provider.QianwenAccount(p.ID)} + } out.Key.Set = p.Key != "" out.Key.Masked = provider.Mask(p.Key) out.ProxyGone = provider.ProxyGone(p) @@ -3562,6 +3575,62 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } writeProvidersJSON(rw, providersState()) }) + // the Qwen AI platform's Token Plan windows: a sign-in to the + // platform, approved in the user's browser, the provider's own + qianwenOf := func(rw http.ResponseWriter, r *http.Request) (string, bool) { + p, err := provider.Find(r.PathValue("id")) + if err != nil || !provider.QianwenPlan(*p) { + http.NotFound(rw, r) + return "", false + } + return p.ID, true + } + mux.HandleFunc("POST /api/qianwen/{id}/signin", func(rw http.ResponseWriter, r *http.Request) { + id, ok := qianwenOf(rw, r) + if !ok { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + u, err := provider.StartQianwenSignIn(ctx, id) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, struct { + URL string `json:"url"` + }{u}) + }) + mux.HandleFunc("GET /api/qianwen/{id}/signin", func(rw http.ResponseWriter, r *http.Request) { + id, ok := qianwenOf(rw, r) + if !ok { + return + } + state, why := provider.QianwenSignInState(id) + writeJSON(rw, struct { + State string `json:"state"` + Error string `json:"error,omitempty"` + }{state, why}) + }) + mux.HandleFunc("POST /api/qianwen/{id}/signin/cancel", func(rw http.ResponseWriter, r *http.Request) { + id, ok := qianwenOf(rw, r) + if !ok { + return + } + provider.CancelQianwenSignIn(id) + rw.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("POST /api/qianwen/{id}/signout", func(rw http.ResponseWriter, r *http.Request) { + id, ok := qianwenOf(rw, r) + if !ok { + return + } + if err := provider.SignOutQianwen(id); err != nil { + fail(rw, err) + return + } + writeProvidersJSON(rw, providersState()) + }) // the page copies through here first: in the app's window the // clipboard API is refused or missing, depending on the system mux.HandleFunc("POST /api/copy", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/qianwen_api_test.go b/internal/gui/qianwen_api_test.go new file mode 100644 index 000000000..edeaff445 --- /dev/null +++ b/internal/gui/qianwen_api_test.go @@ -0,0 +1,97 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A Qwen AI platform Token Plan's sign-in (@imthe99galaxy on X: no quota +// for the plan) is its provider's own: the editor is told each one's and +// whose, and signing one out leaves the other signed in. A provider that +// isn't on the plan has no sign-in to start, ask or end. +func TestQianwenSignInRoutes(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + const base = "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1" + for _, p := range []provider.Provider{ + {ID: "qwen-token-plan", Name: "Qwen Token Plan", Key: "sk-sp-1", Chat: base}, + {ID: "qwen-work", Name: "Qwen Work", Key: "sk-sp-2", Chat: base}, + {ID: "bailian", Name: "Bailian", Key: "sk-sp-3", Chat: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + auth := filepath.Join(filepath.Dir(provider.Path()), "qianwen-auth.json") + if err := os.WriteFile(auth, []byte(`{"qwen-token-plan":{"access":"a1","email":"a@example.com"},"qwen-work":{"access":"a2"}}`), 0o600); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + providerRoutes(mux, nil) + plans := func() map[string]string { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil)) + var got struct { + Providers []struct { + ID string + QianwenPlan *struct { + SignedIn bool + Account string + } + } + } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + out := map[string]string{} + for _, p := range got.Providers { + if q := p.QianwenPlan; q != nil { + out[p.ID] = "out" + if q.SignedIn { + out[p.ID] = "in " + q.Account + } + } + } + return out + } + if got := plans(); got["qwen-token-plan"] != "in a@example.com" || got["qwen-work"] != "in " || len(got) != 2 { + t.Fatalf("before: %v", got) + } + for _, id := range []string{"bailian", "nobody"} { + for _, c := range []struct{ method, path string }{{"POST", "/signin"}, {"GET", "/signin"}, {"POST", "/signin/cancel"}, {"POST", "/signout"}} { + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest(c.method, "/api/qianwen/"+id+c.path, strings.NewReader("{}"))) + if w.Code != http.StatusNotFound { + t.Errorf("%s %s for %s: %d, want 404", c.method, c.path, id, w.Code) + } + } + } + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/qianwen/qwen-work/signin", nil)) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"state":""`) { + t.Errorf("no sign-in under way: %d %s", w.Code, w.Body) + } + w = httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/qianwen/qwen-work/signin/cancel", nil)) + if w.Code != http.StatusNoContent { + t.Errorf("cancel: %d", w.Code) + } + w = httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/qianwen/qwen-token-plan/signout", strings.NewReader("{}"))) + if w.Code != 200 { + t.Fatalf("signout: %d %s", w.Code, w.Body) + } + if got := plans(); got["qwen-token-plan"] != "out" || got["qwen-work"] != "in " { + t.Fatalf("after signing one out: %v", got) + } +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 98f904753..6b1345392 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -185,7 +185,7 @@ test("compat.js is the first of the page's own scripts", async () => { // appearance.js when Settings draws General or the look changes; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "plugininstalled.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js", "keyrates.js", "updatetrust.js", "currencyprefs.js", "appearance.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "plugininstalled.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js", "keyrates.js", "qianwenplan.js", "updatetrust.js", "currencyprefs.js", "appearance.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/qianwen-plan.test.cjs b/internal/gui/tests/qianwen-plan.test.cjs new file mode 100644 index 000000000..c4ac9d015 --- /dev/null +++ b/internal/gui/tests/qianwen-plan.test.cjs @@ -0,0 +1,131 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A Qwen AI platform Token Plan (qwen-token-plan) had no quota card at all +// (@imthe99galaxy on X): its usage is told only to a sign-in on the +// platform. The card now says so, also when the sign-in ended, in the user's +// language, with the button to the provider's settings; there the user +// signs in through their browser, magpie waits for the approval, and the +// editor then says whose sign-in it is, with Sign out for that provider's +// id. No backend, the API is faked here. +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"); +// qianwen_plan.go's words +const NONE = "this plan's usage is told only to a sign-in on the Qwen AI platform: sign in in Qwen Token Plan's settings"; +const ENDED = "signed out of the Qwen AI platform: sign in again in the provider's settings"; + +const quotas = [ + { provider: "qwen-token-plan", name: "Qwen Token Plan", icon: "qwen-color", plan: "Token Plan", error: NONE, needsAccessKey: true, windows: [] }, + { provider: "qwen-work", name: "Qwen Work", icon: "qwen-color", plan: "Token Plan", error: ENDED, needsAccessKey: true, windows: [] }, +]; +const qwen = (id, name, signedIn, account) => ({ + id, name, icon: "qwen-color", preset: "qwen-token-plan", chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1", responses: "", anthropic: "https://token-plan.maas.qianwenaiapi.com/apps/anthropic", catalog: "", + models: [{ id: "qwen3.6-plus", name: "Qwen3.6 Plus", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-sp-…ab12" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", + qianwenPlan: { signedIn, ...(account ? { account } : {}) }, +}); + +function serve(lang, posts, flow) { + const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" }; + const list = () => ({ providers: [qwen("qwen-token-plan", "Qwen Token Plan", flow.done, flow.done ? "a@example.com" : ""), qwen("qwen-work", "Qwen Work", false)], presets: [], excluded: [], gateway: { running: true, window: true } }); + return async (route) => { + const url = new URL(route.request().url()); + const json = (body) => route.fulfill({ json: body }); + // the platform's page, opened in a tab of its own: never the network + if (url.host !== "magpie.test") { + posts.push({ method: "TAB", path: url.href }); + return route.fulfill({ contentType: "text/html", body: "" }); + } + 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({ agents: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json(list()); + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/usage/quotas/history") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/qianwen/")) { + const method = route.request().method(); + posts.push({ method, path: url.pathname, body: method === "POST" ? route.request().postDataJSON() : null }); + if (url.pathname.endsWith("/signin") && method === "POST") return json({ url: "https://account.qianwenai.com/sso/OIDCAuth?auth_token=t1" }); + if (url.pathname.endsWith("/signin")) { + // pending once, then approved + flow.asked++; + if (flow.asked > 1) flow.done = true; + return json({ state: flow.done ? "done" : "pending" }); + } + if (url.pathname.endsWith("/signout")) return json(list()); + return json({}); + } + 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: { none: "This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings", open: "Open settings", signIn: "Sign in to the Qwen AI platform ↗", approve: "Approve the sign-in in your browser…", as: "Signed in as a@example.com", out: "Sign out" }, + zh: { none: "这个套餐的用量需要登录千问 AI 平台——在提供商设置里登录", open: "打开设置", signIn: "登录千问 AI 平台 ↗", approve: "请在浏览器里批准登录…", as: "已登录 a@example.com", out: "退出登录" }, + "zh-TW": { none: "這個方案的用量需要登入千問 AI 平台——在供應商設定裡登入", open: "開啟設定", signIn: "登入千問 AI 平台 ↗", approve: "請在瀏覽器裡核准登入…", as: "已登入 a@example.com", out: "退出登入" }, + ja: { none: "このプランの利用量には Qwen AI プラットフォームへのサインインが必要です — プロバイダの設定でサインインしてください", open: "設定を開く", signIn: "Qwen AI プラットフォームにサインイン ↗", approve: "ブラウザでサインインを承認してください…", as: "a@example.com としてサインインしました", out: "サインアウト" }, + de: { none: "Die Nutzung dieses Plans braucht eine Anmeldung bei der Qwen-AI-Plattform — melde dich in den Einstellungen des Anbieters an", open: "Einstellungen öffnen", signIn: "Bei der Qwen-AI-Plattform anmelden ↗", approve: "Bestätige die Anmeldung im Browser …", as: "Angemeldet als a@example.com", out: "Abmelden" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, w] of Object.entries(words)) { + for (const width of [900, 420]) { + test(`${engine} ${lang} ${width}px: a Qwen AI platform plan's card asks for the sign-in, which the editor makes`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const errors = []; + const ctx = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" }); + const page = await ctx.newPage(); + page.setDefaultTimeout(8000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + const flow = { asked: 0, done: false }; + await ctx.route("**/*", serve(lang, posts, flow)); + await page.goto("http://magpie.test/?view=usage"); + + // the card says why it has no windows, the reason in its tooltip + const err = page.locator('.subscription-card[data-provider="qwen-token-plan"] .subscription-error'); + await err.waitFor(); + assert.equal(await err.getAttribute("title"), NONE); + assert.ok((await err.textContent()).includes(w.none), await err.textContent()); + const ended = page.locator('.subscription-card[data-provider="qwen-work"] .subscription-error'); + assert.ok((await ended.textContent()).includes(w.none), await ended.textContent()); + const go = err.locator(".quota-fix"); + assert.equal((await go.textContent()).trim(), w.open); + const [e, b] = [await err.boundingBox(), await go.boundingBox()]; + assert.ok(e.x + e.width <= width && b.x + b.width <= width, "the error and its button fit the page"); + + // to the provider's own settings, where the sign-in starts + await go.click(); + await page.waitForURL(/view=providers/); + assert.equal(new URL(page.url()).searchParams.get("edit"), "qwen-token-plan"); + const box = page.locator(".editor .stepplan"); + const signIn = box.getByRole("button", { name: w.signIn, exact: true }); + await signIn.click(); + // the platform's page opens in the browser, and magpie waits + await box.getByText(w.approve, { exact: true }).waitFor(); + for (let i = 0; i < 50 && !posts.some((p) => p.method === "TAB"); i++) await page.waitForTimeout(50); + assert.deepEqual(posts.slice(0, 2).map((p) => p.method + " " + p.path), ["POST /api/qianwen/qwen-token-plan/signin", "TAB https://account.qianwenai.com/sso/OIDCAuth?auth_token=t1"]); + // approved: whose sign-in it is, and Sign out for this provider + await box.getByText(w.as, { exact: true }).waitFor({ timeout: 15000 }); + const sb = await box.boundingBox(); + assert.ok(sb.x + sb.width <= width, "the sign-in fits the editor"); + await box.getByRole("button", { name: w.out, exact: true }).click(); + for (let i = 0; i < 50 && !posts.some((p) => p.path.endsWith("/signout")); i++) await page.waitForTimeout(50); + assert.ok(posts.some((p) => p.path === "/api/qianwen/qwen-token-plan/signout"), JSON.stringify(posts)); + assert.ok(!posts.some((p) => p.path.includes("qwen-work")), "nothing for the other provider"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/alibaba_usage.go b/internal/provider/alibaba_usage.go index 305afed26..33bf9749f 100644 --- a/internal/provider/alibaba_usage.go +++ b/internal/provider/alibaba_usage.go @@ -22,9 +22,10 @@ package provider // // The gateway has no public documentation: the fields are read as the // client does, from whichever per pairs the reply has. Only the -// personal plan's API is known; the Qwen AI platform's and Qwen Cloud's -// plans sit behind a console of their own that takes a browser sign-in, so -// they have no card (#5829). +// personal plan's API is known. The Qwen AI platform's plan is read the +// same way at its own console, with a sign-in to the platform instead of +// an access key (qianwen_plan.go); Qwen Cloud's sits behind a console that +// takes a browser sign-in, so it has no card (#5829). // // A RAM user's key is refused by the console (BailianGateway.Team. // NotAuthorised) until the main account grants what Alibaba's Token Plan @@ -324,20 +325,40 @@ func aliMintToken(ctx context.Context, ak, sk string, site aliSite, now time.Tim // aliGateway asks the console's usage API with token and gives the // business data of the reply (data.DataV2.data.data). func aliGateway(ctx context.Context, token string, site aliSite) ([]byte, error) { + u := "https://" + site.gateway + "/cli/api.json?action=" + site.action + "&product=sfm_bailian&api=" + url.QueryEscape(aliUsageAPI) + return aliAskUsage(ctx, token, aliConsole{url: u, region: site.region, site: "BAILIAN_ALIYUN", who: "Alibaba Cloud's console", denied: aliRAMHint}) +} + +// aliConsole is a console gateway the Token Plan's usage API is asked +// at: Alibaba Cloud's (aliGateway) or the Qwen AI platform's +// (qianwen_plan.go), which answer alike. +type aliConsole struct { + url, region string + site string // cornerstoneParam's consoleSite + who string // the console, as an error names it + denied string // what to do when the console says NotAuthorised + ua string // the User-Agent its own client sends, if any +} + +// aliAskUsage posts the usage API's form to the console with token, and +// gives the reply's business data. +func aliAskUsage(ctx context.Context, token string, c aliConsole) ([]byte, error) { params, _ := json.Marshal(map[string]any{ "Api": aliUsageAPI, "V": "1.0", "Data": map[string]any{"cornerstoneParam": map[string]any{ - "protocol": "V2", "console": "ONE_CONSOLE", "productCode": "p_efm", "switchUserType": 3, "consoleSite": "BAILIAN_ALIYUN"}}, + "protocol": "V2", "console": "ONE_CONSOLE", "productCode": "p_efm", "switchUserType": 3, "consoleSite": c.site}}, }) - form := url.Values{"params": {string(params)}, "region": {site.region}} - u := "https://" + site.gateway + "/cli/api.json?action=" + site.action + "&product=sfm_bailian&api=" + url.QueryEscape(aliUsageAPI) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader([]byte(form.Encode()))) + form := url.Values{"params": {string(params)}, "region": {c.region}} + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader([]byte(form.Encode()))) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Accept", "*/*") + if c.ua != "" { + req.Header.Set("User-Agent", c.ua) + } res, err := Keyed(http.DefaultClient).Do(req) if err != nil { return nil, err @@ -348,7 +369,7 @@ func aliGateway(ctx context.Context, token string, site aliSite) ([]byte, error) return nil, err } if res.StatusCode >= 300 { - return nil, fmt.Errorf("Alibaba Cloud's console: %s: %s", res.Status, volcHead(raw)) + return nil, fmt.Errorf("%s: %s: %s", c.who, res.Status, volcHead(raw)) } var env struct { Data struct { @@ -359,20 +380,20 @@ func aliGateway(ctx context.Context, token string, site aliSite) ([]byte, error) } `json:"data"` } if json.Unmarshal(raw, &env) != nil { - return nil, fmt.Errorf("Alibaba Cloud's console answered in a form magpie doesn't know: %s", volcHead(raw)) + return nil, fmt.Errorf("%s answered in a form magpie doesn't know: %s", c.who, volcHead(raw)) } if env.Data.Success != nil && !*env.Data.Success && len(env.Data.ErrorCode) > 0 { code := strings.Trim(string(env.Data.ErrorCode), `"`) switch { case strings.Contains(code, "NotLogined"): return nil, errAliNotLogged - case strings.Contains(code, "NotAuthorised"), strings.Contains(code, "NotAuthorized"): - return nil, fmt.Errorf("Alibaba Cloud's console: %s: %s", code, aliRAMHint) + case c.denied != "" && (strings.Contains(code, "NotAuthorised") || strings.Contains(code, "NotAuthorized")): + return nil, fmt.Errorf("%s: %s: %s", c.who, code, c.denied) } if msg := strings.TrimSpace(strings.Trim(string(env.Data.ErrorMsg), `"`)); msg != "" && msg != "null" { - return nil, fmt.Errorf("Alibaba Cloud's console: %s: %s", code, msg) + return nil, fmt.Errorf("%s: %s: %s", c.who, code, msg) } - return nil, fmt.Errorf("Alibaba Cloud's console: %s", code) + return nil, fmt.Errorf("%s: %s", c.who, code) } // the reply holds it in two envelopes, one less in some replies var node json.RawMessage = env.Data.DataV2 diff --git a/internal/provider/key_allowance.go b/internal/provider/key_allowance.go index 1fe26aab6..ca5095d16 100644 --- a/internal/provider/key_allowance.go +++ b/internal/provider/key_allowance.go @@ -74,8 +74,9 @@ func readsKeyWindows(p Provider) bool { // account tells, not the key: Volcengine Ark's Coding and Agent Plans and // Tencent Cloud's Token Plan Enterprise and Alibaba Cloud's Token Plan, read // with the account's access key (volcengine_usage.go, tencent_usage.go, -// alibaba_usage.go), and StepFun's Step Plan, -// read with magpie's sign-in to its platform (stepfun_plan.go). The +// alibaba_usage.go), and StepFun's Step Plan and the Qwen AI platform's +// Token Plan, read with magpie's sign-in to the platform (stepfun_plan.go, +// qianwen_plan.go). The // Usage page had their windows while routing had none, and the Routing // page said "one key" of a plan with them (chen on Discord). "" for any // other key, or one whose access key magpie isn't given; said without @@ -97,6 +98,9 @@ func accountPlanOf(p Provider) string { if StepFunSite(p) != "" { return "stepfun" } + if QianwenPlan(p) { + return "qianwen" + } return "" } @@ -124,6 +128,11 @@ func accountPlanWindows(ctx context.Context, q Provider) (keyReading, error) { return keyReading{}, nil } c = stepPlanQuota(q.Via(ctx), q) + case "qianwen": + if !QianwenSignedIn(q.ID) { + return keyReading{}, nil + } + c = qianwenPlanQuota(q.Via(ctx), q) } if c.Error != "" { return keyReading{}, errors.New(c.Error) @@ -291,6 +300,8 @@ func keyCardTag(p Provider) string { return keyTag("alibaba "+site.region, p.AccessKeyID) case "stepfun": return keyTag("stepfun", p.ID) + case "qianwen": + return keyTag("qianwen", p.ID) } } if _, ok := planQuotaSourceOf(p); ok && !sub2APIKeyLimits(p) { diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index 289109f2b..e688b43cf 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -6,7 +6,8 @@ package provider // Vibe, StepFun's Step Plan, Volcengine Ark's Coding and Agent Plans and // Tencent Cloud's Token Plan 企业版 — has windows of allowance like a // subscription's, which the vendor tells to the key (StepFun only to a -// sign-in, stepfun_plan.go; Volcengine and Tencent Cloud only to the +// sign-in, stepfun_plan.go, as is the Qwen AI platform's Token Plan, +// qianwen_plan.go; Volcengine and Tencent Cloud only to the // account's access key, volcengine_usage.go and tencent_usage.go): the // Usage page shows them beside the subscriptions'. @@ -888,6 +889,8 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota { go func() { tencent <- tencentPlanQuotas(ctx) }() ali := make(chan []SubscriptionQuota, 1) go func() { ali <- aliPlanQuotas(ctx) }() + qianwen := make(chan []SubscriptionQuota, 1) + go func() { qianwen <- qianwenPlanQuotas(ctx) }() wg.Wait() out := []SubscriptionQuota{} for i, q := range got { @@ -897,8 +900,9 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota { out = append(out, *q) } } - // StepFun's, Volcengine's, Tencent's and Alibaba's, read just now too - for _, qs := range [][]SubscriptionQuota{<-stepfun, <-volc, <-tencent, <-ali} { + // StepFun's, Volcengine's, Tencent's, Alibaba's and the Qwen AI + // platform's, read just now too + for _, qs := range [][]SubscriptionQuota{<-stepfun, <-volc, <-tencent, <-ali, <-qianwen} { for _, q := range qs { out = append(out, readNow(q)) } diff --git a/internal/provider/presets.go b/internal/provider/presets.go index 816ae2842..a6dd12d3d 100644 --- a/internal/provider/presets.go +++ b/internal/provider/presets.go @@ -412,10 +412,10 @@ var presets = []PresetDef{ // token-plan.maas.qianwenaiapi.com, and on Alibaba Cloud Bailian // (bailian.console.aliyun.com) at token-plan.cn-beijing.maas.aliyuncs.com // (#1506). The models given are the plans' text models as their - // overviews list them, for when the host gives no list. Only the - // two at aliyuncs.com have a way to read the plan's credits, with the - // account's AccessKey (alibaba_usage.go); the Qwen AI platform's console - // takes a browser sign-in (#5829). + // overviews list them, for when the host gives no list. The two at + // aliyuncs.com read the plan's credits with the account's AccessKey + // (alibaba_usage.go); the Qwen AI platform's with a sign-in to the + // platform, as its own QianWen CLI does (qianwen_plan.go). {ID: "qwen-token-plan", Name: "Qwen Token Plan", Short: "Qwen Plan", Icon: "qwen-color", Kind: KindVendor, Chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1", Anthropic: "https://token-plan.maas.qianwenaiapi.com/apps/anthropic", Note: "Qwen AI platform · subscription", diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 236ed79ab..5c1fcc8e4 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -1805,9 +1805,12 @@ func Delete(id string) error { if err := store(f); err != nil { return err } - // its StepFun sign-in goes with it, not to a provider added later - // under the same id - return forgetStepFun(id) + // its StepFun and Qwen AI platform sign-ins go with it, not to a + // provider added later under the same id + if err := forgetStepFun(id); err != nil { + return err + } + return forgetQianwen(id) } // keyOptional is true for a server on this computer or on the user's own diff --git a/internal/provider/qianwen_plan.go b/internal/provider/qianwen_plan.go new file mode 100644 index 000000000..80e948aac --- /dev/null +++ b/internal/provider/qianwen_plan.go @@ -0,0 +1,592 @@ +package provider + +// The Qwen AI platform's Token Plan (platform.qianwenai.com, sk-sp- keys at +// token-plan.maas.qianwenaiapi.com) tells its monthly or weekly window only +// to a sign-in on the platform, never to the plan's key: the console's +// usage API answers the key BailianGateway.Login.NotLogined. magpie signs in +// and reads it as the platform's own client, the QianWen CLI +// (@qianwenai/qianwen-cli, `qianwen auth login` and its Token Plan usage), +// does: +// +// 1. POST t.qianwenai.com/cli/device/code?client_id&code_challenge +// &code_challenge_method=S256 gives a page for the user to approve the +// sign-in on, in their own browser, and a token to wait on; +// 2. POST t.qianwenai.com/cli/device/token?client_id&token&code_verifier, +// every Interval seconds, answers Status authorization_pending until +// the user approves, then complete with Credentials{AccessToken, +// ExpireTime, User}. There is no refresh token: when it runs out the +// user signs in again, as the CLI asks; +// 3. POST cli.qianwenai.com/data/v2/api.json with Bearer the access token +// and {product: ModelStudioRegional, action: GenerateCLIAccessToken} +// gives a console token, cliAccessToken; +// 4. POST cs-data.qianwenai.com/cli/api.json?action=BroadScopeAspnGateway +// &product=sfm_bailian&api=…/tokenplan/personal/api/v2/usage with Bearer +// that token answers as Alibaba Cloud's console does (aliAskUsage), with +// consoleSite QIANWENAI: per1MonthPercentage or per1WeekPercentage and +// their reset times. +// +// The sign-in is kept in qianwen-auth.json beside providers.json, readable +// by the user alone, one per provider, as StepFun's is (stepfun_plan.go). + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/filememo" + "github.com/yetone/magpie/internal/lastgood" +) + +const ( + qianwenAuthHost = "t.qianwenai.com" + qianwenAPIHost = "cli.qianwenai.com" + qianwenDataHost = "cs-data.qianwenai.com" + // qianwenUA is the User-Agent the platform's own client sends + qianwenUA = "qianwen-cli/1.10.0" + qianwenRegion = "cn-beijing" + qianwenPlanHost = "token-plan.maas.qianwenaiapi.com" +) + +// QianwenPlan says p is on the Qwen AI platform's Token Plan, whose usage +// magpie reads with a sign-in to the platform. +func QianwenPlan(p Provider) bool { + if p.Account != nil { + return false + } + for _, base := range []string{p.Chat, p.Anthropic, p.Responses} { + if hostOf(base) == qianwenPlanHost { + return true + } + } + return false +} + +// qianwenSession is a sign-in on the platform. +type qianwenSession struct { + Access string `json:"access"` + // Expires is when the platform said the access token runs out; zero + // when it said nothing magpie could read + Expires time.Time `json:"expires,omitzero"` + Email string `json:"email,omitempty"` + User string `json:"user,omitempty"` + ClientID string `json:"clientId,omitempty"` +} + +var qianwenMu sync.Mutex + +func qianwenPath() string { return filepath.Join(filepath.Dir(Path()), "qianwen-auth.json") } + +// loadQianwen is every provider's sign-in, by provider id; the caller holds +// qianwenMu. A file that doesn't parse is no sign-in, and is left as it +// is (saveQianwen keeps it aside before a sign-in writes over it). +func loadQianwen() map[string]qianwenSession { + out := map[string]qianwenSession{} + b, err := os.ReadFile(qianwenPath()) + if err != nil { + return out + } + if json.Unmarshal(b, &out) != nil { + return map[string]qianwenSession{} + } + return out +} + +func saveQianwen(all map[string]qianwenSession) error { + defer filememo.Forget() // read again, where a request holds it + b, err := json.MarshalIndent(all, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(qianwenPath()), 0o700); err != nil { + return err + } + if err := lastgood.KeepUnparsed(qianwenPath(), lastgood.Into[map[string]qianwenSession]); err != nil { + return err + } + return writeFileAtomic(qianwenPath(), b) +} + +// QianwenSignedIn reports whether magpie has a sign-in for the provider, +// reading the file once until it changes: a provider list asks it on +// every poll. +func QianwenSignedIn(id string) bool { + s, ok := qianwenSignIn(id) + return ok && s.Access != "" +} + +// QianwenAccount is who the provider's sign-in is, as the platform named +// them: an email, or "" when it gave none. +func QianwenAccount(id string) string { + s, _ := qianwenSignIn(id) + return s.Email +} + +func qianwenSignIn(id string) (qianwenSession, bool) { + all, err := filememo.Read("qianwen-auth", qianwenPath(), func(b []byte) (map[string]qianwenSession, error) { + m := map[string]qianwenSession{} + return m, json.Unmarshal(b, &m) + }) + if err != nil { + return qianwenSession{}, false + } + s, ok := all[id] + return s, ok +} + +// SignOutQianwen forgets the provider's sign-in, and no other's. +func SignOutQianwen(id string) error { + CancelQianwenSignIn(id) + qianwenMu.Lock() + all := loadQianwen() + _, had := all[id] + delete(all, id) + var err error + if had { + err = saveQianwen(all) + } + qianwenMu.Unlock() + qianwenForgetToken(id) + forgetPlanQuotas() + return err +} + +// forgetQianwen drops the provider's sign-in, when it is removed. +func forgetQianwen(id string) error { return SignOutQianwen(id) } + +// renameQianwen moves the provider's sign-in with it to its new id. +func renameQianwen(from, to string) error { + qianwenMu.Lock() + defer qianwenMu.Unlock() + all := loadQianwen() + s, ok := all[from] + if !ok { + return nil + } + delete(all, from) + all[to] = s + qianwenForgetToken(from) + return saveQianwen(all) +} + +// a sign-in under way, by provider id +type qianwenFlow struct { + url string + state string // "pending", "done" or "failed" + err string + cancel context.CancelFunc +} + +var qianwenFlows = struct { + sync.Mutex + m map[string]*qianwenFlow +}{m: map[string]*qianwenFlow{}} + +// qianwenPoll is how often the platform is asked whether the user has +// approved, when it says nothing itself; a test shortens it. +var qianwenPoll = 2 * time.Second + +func qianwenUUID() string { + b := make([]byte, 16) + _, _ = rand.Read(b) + b[6] = b[6]&0x0f | 0x40 + b[8] = b[8]&0x3f | 0x80 + h := hex.EncodeToString(b) + return h[:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:] +} + +// qianwenPKCE is a code verifier and its S256 challenge. +func qianwenPKCE() (verifier, challenge string) { + b := make([]byte, 32) + _, _ = rand.Read(b) + verifier = base64.RawURLEncoding.EncodeToString(b) + sum := sha256.Sum256([]byte(verifier)) + return verifier, base64.RawURLEncoding.EncodeToString(sum[:]) +} + +// qianwenPost posts to the platform as its client does, the reply read +// whole (up to 1MB). +func qianwenPost(ctx context.Context, u, contentType string, body []byte, bearer string) (int, []byte, error) { + var rd io.Reader + if body != nil { + rd = bytes.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, rd) + if err != nil { + return 0, nil, err + } + req.Header.Set("User-Agent", qianwenUA) + if contentType != "" { + req.Header.Set("Content-Type", contentType) + } + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + res, err := Keyed(http.DefaultClient).Do(req) + if err != nil { + return 0, nil, err + } + defer res.Body.Close() + b, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + return res.StatusCode, b, err +} + +// StartQianwenSignIn starts a sign-in to the Qwen AI platform for the +// provider id: the page the user approves it on, in their browser. magpie +// waits for the approval itself (QianwenSignInState), until the page runs +// out. +func StartQianwenSignIn(ctx context.Context, id string) (string, error) { + clientID := qianwenUUID() + verifier, challenge := qianwenPKCE() + q := url.Values{"client_id": {clientID}, "code_challenge": {challenge}, "code_challenge_method": {"S256"}} + code, raw, err := qianwenPost(ctx, "https://"+qianwenAuthHost+"/cli/device/code?"+q.Encode(), "", nil, "") + if err != nil { + return "", fmt.Errorf("couldn't reach the Qwen AI platform: %w", err) + } + var r struct { + Success bool + Data *struct { + Token string + VerificationURL string `json:"VerificationUrl"` + ExpiresIn float64 + Interval float64 + } + } + if code >= 300 || json.Unmarshal(raw, &r) != nil || !r.Success || r.Data == nil || r.Data.Token == "" || r.Data.VerificationURL == "" { + return "", fmt.Errorf("the Qwen AI platform didn't start a sign-in: %d %s", code, volcHead(raw)) + } + life := time.Duration(r.Data.ExpiresIn) * time.Second + if life <= 0 || life > 15*time.Minute { + life = 5 * time.Minute + } + every := time.Duration(r.Data.Interval) * time.Second + if every <= 0 { + every = qianwenPoll + } + every = min(every, qianwenPoll) + wait, cancel := context.WithTimeout(context.Background(), life) + f := &qianwenFlow{url: r.Data.VerificationURL, state: "pending", cancel: cancel} + qianwenFlows.Lock() + if old := qianwenFlows.m[id]; old != nil && old.cancel != nil { + old.cancel() + } + qianwenFlows.m[id] = f + qianwenFlows.Unlock() + go func() { + defer cancel() + err := qianwenWait(wait, id, clientID, r.Data.Token, verifier, every) + qianwenFlows.Lock() + defer qianwenFlows.Unlock() + if qianwenFlows.m[id] != f { + return // a newer sign-in, or one cancelled + } + if err != nil { + f.state, f.err = "failed", err.Error() + return + } + f.state = "done" + }() + return f.url, nil +} + +// QianwenSignInState is how the provider's sign-in under way goes: +// "pending", "done" or "failed" with why, or "" when none is. +func QianwenSignInState(id string) (state, why string) { + qianwenFlows.Lock() + defer qianwenFlows.Unlock() + f := qianwenFlows.m[id] + if f == nil { + return "", "" + } + return f.state, f.err +} + +// CancelQianwenSignIn stops waiting on the provider's sign-in. +func CancelQianwenSignIn(id string) { + qianwenFlows.Lock() + defer qianwenFlows.Unlock() + if f := qianwenFlows.m[id]; f != nil { + if f.cancel != nil { + f.cancel() + } + delete(qianwenFlows.m, id) + } +} + +var qianwenStatusWord = regexp.MustCompile(`(?i)expired|access_denied|slow_down`) + +// qianwenWait asks the platform whether the user approved the sign-in, +// until they have, refused, or the page ran out, and keeps it. +func qianwenWait(ctx context.Context, id, clientID, token, verifier string, every time.Duration) error { + q := url.Values{"client_id": {clientID}, "token": {token}, "code_verifier": {verifier}} + u := "https://" + qianwenAuthHost + "/cli/device/token?" + q.Encode() + t := time.NewTimer(every) + defer t.Stop() + for { + select { + case <-ctx.Done(): + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return errors.New("the sign-in page ran out before it was approved: sign in again") + } + return ctx.Err() + case <-t.C: + } + code, raw, err := qianwenPost(ctx, u, "", nil, "") + status := "" + var r struct { + Data struct { + Status string + Credentials *struct { + AccessToken string + ExpireTime any + User *struct{ ID, Email, AliyunID string } + } + } + } + switch { + case err != nil: + if ctx.Err() != nil { + continue + } + status = "authorization_pending" // a dropped poll is asked again + case code >= 300: + // the client reads an error's text for these three + status = strings.ToLower(qianwenStatusWord.FindString(string(raw))) + if status == "expired" { + status = "expired_token" + } + if status == "" { + return fmt.Errorf("the Qwen AI platform: %d %s", code, volcHead(raw)) + } + default: + if json.Unmarshal(raw, &r) != nil { + return fmt.Errorf("the Qwen AI platform answered in a form magpie doesn't know: %s", volcHead(raw)) + } + status = strings.ToLower(r.Data.Status) + if status == "" { + status = "authorization_pending" + } + } + switch status { + case "authorization_pending": + case "slow_down": + every += every + case "complete": + c := r.Data.Credentials + if c == nil || c.AccessToken == "" { + return errors.New("the Qwen AI platform approved the sign-in but gave no token: sign in again") + } + s := qianwenSession{Access: c.AccessToken, Expires: qianwenTime(c.ExpireTime), ClientID: clientID} + if c.User != nil { + s.Email, s.User = c.User.Email, c.User.ID + } + qianwenMu.Lock() + all := loadQianwen() + all[id] = s + err := saveQianwen(all) + qianwenMu.Unlock() + qianwenForgetToken(id) + forgetPlanQuotas() + return err + case "expired_token": + return errors.New("the sign-in page ran out before it was approved: sign in again") + case "access_denied": + return errors.New("the sign-in was refused on the Qwen AI platform's page") + default: + return fmt.Errorf("the Qwen AI platform ended the sign-in: %s", status) + } + t.Reset(every) + } +} + +// qianwenTime reads ExpireTime as the client's Date.parse would: a date +// and time, or a number of seconds or milliseconds; zero when it can't. +func qianwenTime(v any) time.Time { + switch x := v.(type) { + case float64: + if t, ok := stepfunTime(x); ok { + return t + } + case string: + x = strings.TrimSpace(x) + if f, err := strconv.ParseFloat(x, 64); err == nil { + return qianwenTime(f) + } + for _, layout := range []string{time.RFC3339Nano, "2006-01-02T15:04:05", "2006-01-02 15:04:05", time.RFC1123, time.RFC1123Z} { + if t, err := time.ParseInLocation(layout, x, time.Local); err == nil { + return t + } + } + } + return time.Time{} +} + +// errQianwenSession is a sign-in the platform no longer takes, or one past +// its time: it has no refresh token, so the user signs in again. +var errQianwenSession = errors.New("signed out of the Qwen AI platform: sign in again in the provider's settings") + +// qianwenNoSignIn is why a Qwen AI platform plan's card has no windows +// while magpie has no sign-in for it. +func qianwenNoSignIn(p Provider) string { + return "this plan's usage is told only to a sign-in on the Qwen AI platform: sign in in " + p.Name + "'s settings" +} + +var ( + qianwenTokensMu sync.Mutex + qianwenTokens = map[string]aliToken{} +) + +func qianwenForgetToken(id string) { + qianwenTokensMu.Lock() + delete(qianwenTokens, id) + qianwenTokensMu.Unlock() +} + +// qianwenMint makes the console token from the sign-in's access token. +func qianwenMint(ctx context.Context, access string) (string, error) { + body, _ := json.Marshal(map[string]any{ + "product": "ModelStudioRegional", "action": aliACSAction, "region": qianwenRegion, + "params": map[string]any{}, "version": aliACSVersion, + }) + code, raw, err := qianwenPost(ctx, "https://"+qianwenAPIHost+"/data/v2/api.json", "application/json", body, access) + if err != nil { + return "", err + } + var r struct { + Code string `json:"code"` + Message string `json:"message"` + SuccessResponse bool `json:"successResponse"` + Data struct { + CliAccessToken string `json:"cliAccessToken"` + } `json:"data"` + } + _ = json.Unmarshal(raw, &r) + tok := strings.TrimSpace(r.Data.CliAccessToken) + switch { + case r.Code == "200" && r.SuccessResponse && tok != "" && tok != access: + return tok, nil + case strings.Contains(r.Code, "NeedLogin"), strings.Contains(r.Code, "NotLogin"), + code == http.StatusUnauthorized, code == http.StatusForbidden: + return "", errQianwenSession + case r.Code != "" || r.Message != "": + return "", fmt.Errorf("the Qwen AI platform's %s: %s %s", aliACSAction, r.Code, r.Message) + } + return "", fmt.Errorf("the Qwen AI platform's %s gave no token: %d %s", aliACSAction, code, volcHead(raw)) +} + +// qianwenConsole is the platform's console gateway. +func qianwenConsole() aliConsole { + return aliConsole{ + url: "https://" + qianwenDataHost + "/cli/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=" + url.QueryEscape(aliUsageAPI), + region: qianwenRegion, site: "QIANWENAI", who: "the Qwen AI platform's console", ua: qianwenUA, + } +} + +// qianwenReadUsage reads the plan's windows with the provider's sign-in: the +// console token kept for it, made again once when the console says it +// isn't logged in; a fresh one refused is a sign-in ended. +func qianwenReadUsage(ctx context.Context, id string, now func() time.Time) ([]QuotaWindow, error) { + s, ok := qianwenSignIn(id) + if !ok || s.Access == "" { + return nil, errQianwenSession + } + if !s.Expires.IsZero() && now().After(s.Expires) { + return nil, errQianwenSession + } + for try := 0; ; try++ { + qianwenTokensMu.Lock() + t, kept := qianwenTokens[id] + qianwenTokensMu.Unlock() + fresh := !kept || try > 0 || now().Sub(t.at) > aliTokenTTL + if fresh { + tok, err := qianwenMint(ctx, s.Access) + if err != nil { + return nil, err + } + t = aliToken{tok, now()} + qianwenTokensMu.Lock() + qianwenTokens[id] = t + qianwenTokensMu.Unlock() + } + raw, err := aliAskUsage(ctx, t.token, qianwenConsole()) + if err == errAliNotLogged { + qianwenForgetToken(id) + if !fresh { + continue + } + return nil, errQianwenSession + } + if err != nil { + return nil, err + } + ws := aliReadWindows(raw) + if len(ws) == 0 { + return nil, fmt.Errorf("the Qwen AI platform told no window for this account (it may have no personal Token Plan): %s", volcHead(raw)) + } + return ws, nil + } +} + +// qianwenPlanQuota is p's plan as a card, read with its sign-in. +func qianwenPlanQuota(ctx context.Context, p Provider) SubscriptionQuota { + q := SubscriptionQuota{Provider: p.ID, Name: p.Name, Icon: p.Icon, Plan: aliPlanName, Windows: []QuotaWindow{}} + if !QianwenSignedIn(p.ID) { + q.Error, q.NeedsAccessKey = qianwenNoSignIn(p), true + return q + } + q.User = QianwenAccount(p.ID) + ws, err := qianwenReadUsage(ctx, p.ID, time.Now) + if err != nil { + q.Error = err.Error() + q.NeedsAccessKey = errors.Is(err, errQianwenSession) + return q + } + q.Windows = ws + return q +} + +// qianwenPlanQuotas is a card for each Qwen AI platform plan in use: one +// per provider, as two can be two accounts. One magpie has no sign-in for +// says so, with the way to its settings. +func qianwenPlanQuotas(ctx context.Context) []SubscriptionQuota { + var jobs []Provider + for _, p := range All() { + if p.Hidden || p.Off || !QianwenPlan(p) || !wantsCard(ctx, p.ID, "") { + continue + } + jobs = append(jobs, p) + } + out := make([]SubscriptionQuota, len(jobs)) + var wg sync.WaitGroup + for i, p := range jobs { + wg.Add(1) + go func() { + defer wg.Done() + out[i] = qianwenPlanQuota(p.Via(ctx), p) + if out[i].Error == "" { + // what routing goes by, read just now (KeyAllowance) + noteKeyAllowance(p, out[i].Windows, time.Now()) + } + if QianwenSignedIn(p.ID) { + out[i] = keepReading(ctx, out[i], keyTag("qianwen", p.ID)) + } + }() + } + wg.Wait() + return out +} diff --git a/internal/provider/qianwen_plan_test.go b/internal/provider/qianwen_plan_test.go new file mode 100644 index 000000000..c624cf50d --- /dev/null +++ b/internal/provider/qianwen_plan_test.go @@ -0,0 +1,398 @@ +package provider + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/agentenv" +) + +// The replies below are the shapes the QianWen CLI (@qianwenai/qianwen-cli +// 1.10.0) reads: device/code's is a real one (its token changed), the +// rest are what its loginPoll, GenerateCLIAccessToken and cs-data usage +// readers take, with BailianGateway.Login.NotLogined and ConsoleNeedLogin +// as the platform answered them to a request with no sign-in. + +const qianwenCodeReply = `{"Data":{"Token":"devtok1","ExpiresIn":300,"VerificationUrl":"https://account.qianwenai.com/sso/OIDCAuth?app_type=qianwenai_cli&lang=en&auth_token=devtok1","Interval":2},"RequestId":"01A1D8E9-1E96-5A84-B19B-1EB6C862D2F9","Success":true}` + +func qianwenUsageReply(month float64) string { + b, _ := json.Marshal(map[string]any{ + "code": "200", "successResponse": true, + "data": map[string]any{"success": true, "DataV2": map[string]any{ + "ret": []string{"SUCCESS::调用成功"}, + "data": map[string]any{"code": "SUCCESS", "success": true, "data": map[string]any{"per1MonthPercentage": month, "per1MonthResetTime": 1780000000000}}, + }}, + }) + return string(b) +} + +const qianwenNotLogged = `{"code":"200","successResponse":true,"data":{"success":false,"errorCode":"BailianGateway.Login.NotLogined","errorMsg":"not logined"}}` + +// fakeQianwen is the platform's three hosts. polls is how many times +// device/token answers authorization_pending before its last reply. +type fakeQianwen struct { + mu sync.Mutex + t *testing.T + challenge string + polls int + last string // device/token's reply once pending is done + lastCode int + mints map[string]string // access token → console token ("" refuses) + usage map[string]string // console token → reply + minted int + reads int + asked []string +} + +func newFakeQianwen(t *testing.T) *fakeQianwen { + f := &fakeQianwen{t: t, mints: map[string]string{}, usage: map[string]string{}, lastCode: 200} + srv := httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(srv.Close) + old := http.DefaultClient.Transport + http.DefaultClient.Transport = rewrite{srv} + t.Cleanup(func() { http.DefaultClient.Transport = old }) + return f +} + +func (f *fakeQianwen) serve(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + f.mu.Lock() + defer f.mu.Unlock() + t := f.t + host := r.Header.Get("X-Host") + f.asked = append(f.asked, host+r.URL.Path) + if r.Method != http.MethodPost || r.Header.Get("User-Agent") != qianwenUA { + t.Errorf("%s %s%s as %q", r.Method, host, r.URL.Path, r.Header.Get("User-Agent")) + } + q := r.URL.Query() + switch host + r.URL.Path { + case qianwenAuthHost + "/cli/device/code": + if q.Get("client_id") == "" || q.Get("code_challenge_method") != "S256" || q.Get("code_challenge") == "" { + t.Errorf("device/code %s", r.URL.RawQuery) + } + f.challenge = q.Get("code_challenge") + io.WriteString(w, qianwenCodeReply) + case qianwenAuthHost + "/cli/device/token": + sum := sha256.Sum256([]byte(q.Get("code_verifier"))) + if q.Get("token") != "devtok1" || q.Get("client_id") == "" || base64.RawURLEncoding.EncodeToString(sum[:]) != f.challenge { + t.Errorf("device/token %s (challenge %s)", r.URL.RawQuery, f.challenge) + } + if f.polls > 0 { + f.polls-- + io.WriteString(w, `{"Data":{"Status":"authorization_pending"},"Success":true}`) + return + } + w.WriteHeader(f.lastCode) + io.WriteString(w, f.last) + case qianwenAPIHost + "/data/v2/api.json": + var m map[string]any + _ = json.Unmarshal(body, &m) + if r.Header.Get("Content-Type") != "application/json" || m["product"] != "ModelStudioRegional" || m["action"] != "GenerateCLIAccessToken" || m["region"] != "cn-beijing" || m["version"] != "2026-02-10" { + t.Errorf("mint %s %q", r.Header.Get("Content-Type"), body) + } + access := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + if strings.HasPrefix(access, "sk-sp-") { + t.Errorf("the plan's key was sent: %s", access) + } + tok, ok := f.mints[access] + if !ok || tok == "" { + io.WriteString(w, `{"code":"ConsoleNeedLogin","message":"Please login first","successResponse":false}`) + return + } + f.minted++ + io.WriteString(w, `{"code":"200","successResponse":true,"data":{"cliAccessToken":"`+tok+`"}}`) + case qianwenDataHost + "/cli/api.json": + f.reads++ + form, _ := url.ParseQuery(string(body)) + if q.Get("action") != "BroadScopeAspnGateway" || q.Get("product") != "sfm_bailian" || q.Get("api") != aliUsageAPI || + form.Get("region") != "cn-beijing" || !strings.Contains(form.Get("params"), "QIANWENAI") || !strings.Contains(form.Get("params"), aliUsageAPI) { + t.Errorf("usage %s with %q", r.URL, body) + } + reply, ok := f.usage[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")] + if !ok { + reply = qianwenNotLogged + } + io.WriteString(w, reply) + default: + t.Errorf("asked %s %s", host, r.URL) + w.WriteHeader(http.StatusNotFound) + } +} + +func qianwenHome(t *testing.T) { + t.Helper() + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", 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 agentenv.Vars { + t.Setenv(v, "") + } + old := qianwenPoll + qianwenPoll = 5 * time.Millisecond + t.Cleanup(func() { qianwenPoll = old }) + qianwenTokensMu.Lock() + qianwenTokens = map[string]aliToken{} + qianwenTokensMu.Unlock() + forgetPlanQuotas() + t.Cleanup(forgetPlanQuotas) +} + +// waitQianwen waits for the provider's sign-in to end, as the GUI does. +func waitQianwen(t *testing.T, id string) (string, string) { + t.Helper() + for end := time.Now().Add(20 * time.Second); time.Now().Before(end); time.Sleep(2 * time.Millisecond) { + if s, why := QianwenSignInState(id); s != "pending" { + return s, why + } + } + t.Fatal("the sign-in never ended") + return "", "" +} + +func TestQianwenPlanHost(t *testing.T) { + for base, want := range map[string]bool{ + "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1": true, + "https://token-plan.maas.qianwenaiapi.com/apps/anthropic": true, + "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1": false, + "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1": false, + "https://dashscope.aliyuncs.com/compatible-mode/v1": false, + } { + if got := QianwenPlan(Provider{Chat: base}); got != want { + t.Errorf("%s: %v", base, got) + } + } + if QianwenPlan(Provider{Chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1", Account: &Account{}}) { + t.Error("an account is a plan's") + } + p, err := FromPreset("qwen-token-plan") + if err != nil || !QianwenPlan(p) { + t.Fatalf("the preset isn't the platform's plan: %v %+v", err, p) + } + p.Key = "sk-sp-x" + if accountPlanOf(p) != "qianwen" { + t.Errorf("accountPlanOf %q", accountPlanOf(p)) + } +} + +func TestQianwenSignIn(t *testing.T) { + qianwenHome(t) + f := newFakeQianwen(t) + f.polls = 2 + f.last = `{"Data":{"Status":"complete","Credentials":{"AccessToken":"acc1","ExpireTime":"2099-01-02T03:04:05Z","User":{"Id":"u1","Email":"a@example.com","AliyunId":"x"}}},"Success":true}` + u, err := StartQianwenSignIn(context.Background(), "qwen-token-plan") + if err != nil || !strings.HasPrefix(u, "https://account.qianwenai.com/sso/OIDCAuth?") { + t.Fatalf("%q %v", u, err) + } + if s, why := waitQianwen(t, "qwen-token-plan"); s != "done" { + t.Fatalf("%s %s", s, why) + } + if !QianwenSignedIn("qwen-token-plan") || QianwenAccount("qwen-token-plan") != "a@example.com" || QianwenSignedIn("other") { + t.Fatal("not kept for the provider alone") + } + s, _ := qianwenSignIn("qwen-token-plan") + if s.Access != "acc1" || s.User != "u1" || !s.Expires.Equal(time.Date(2099, 1, 2, 3, 4, 5, 0, time.UTC)) { + t.Errorf("%+v", s) + } + if fi, err := os.Stat(qianwenPath()); err != nil || fi.Mode().Perm()&0o077 != 0 { + t.Errorf("qianwen-auth.json readable by others: %v %v", fi, err) + } + + for name, c := range map[string]struct { + code int + reply string + want string + }{ + "refused": {200, `{"Data":{"Status":"access_denied"},"Success":true}`, "refused"}, + "ran out": {200, `{"Data":{"Status":"expired_token"},"Success":true}`, "ran out"}, + "ran out, as error": {400, `{"Code":"DeviceCode.Expired","Message":"token expired"}`, "ran out"}, + "no token": {200, `{"Data":{"Status":"complete"},"Success":true}`, "gave no token"}, + "other error": {500, `{"Code":"InternalError"}`, "500"}, + } { + f.mu.Lock() + f.polls, f.lastCode, f.last = 1, c.code, c.reply + f.mu.Unlock() + if _, err := StartQianwenSignIn(context.Background(), "p2"); err != nil { + t.Fatal(err) + } + if s, why := waitQianwen(t, "p2"); s != "failed" || !strings.Contains(why, c.want) { + t.Errorf("%s: %s %q", name, s, why) + } + if QianwenSignedIn("p2") { + t.Errorf("%s: kept a sign-in", name) + } + } + // the first provider's sign-in is still there + if !QianwenSignedIn("qwen-token-plan") { + t.Fatal("another provider's failed sign-in dropped this one") + } + + // cancelled: nothing is kept, and the state is gone + f.mu.Lock() + f.polls = 1 << 20 + f.mu.Unlock() + if _, err := StartQianwenSignIn(context.Background(), "p3"); err != nil { + t.Fatal(err) + } + CancelQianwenSignIn("p3") + if s, _ := QianwenSignInState("p3"); s != "" { + t.Errorf("cancelled sign-in is %q", s) + } + + if err := SignOutQianwen("qwen-token-plan"); err != nil || QianwenSignedIn("qwen-token-plan") { + t.Fatalf("sign-out: %v", err) + } +} + +func saveQianwenSession(t *testing.T, id string, s qianwenSession) { + t.Helper() + qianwenMu.Lock() + defer qianwenMu.Unlock() + all := loadQianwen() + all[id] = s + if err := saveQianwen(all); err != nil { + t.Fatal(err) + } +} + +func TestQianwenPlanQuotas(t *testing.T) { + qianwenHome(t) + f := newFakeQianwen(t) + f.mints["acc1"] = "cli2" + f.usage["cli2"] = qianwenUsageReply(0.25) + // cli1 is a console token kept from before that the console no longer + // takes: the reader makes another once + qianwenTokensMu.Lock() + qianwenTokens["qwen-token-plan"] = aliToken{"cli1", time.Now()} + qianwenTokensMu.Unlock() + + const base = "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1" + for _, p := range []Provider{ + {ID: "qwen-token-plan", Name: "Qwen Token Plan", Chat: base, Key: "sk-sp-key"}, + // not signed in: a card that says where to sign in + {ID: "qwen-two", Name: "Qwen Two", Chat: base, Key: "sk-sp-key2"}, + // signed in, but the platform no longer takes the sign-in + {ID: "qwen-old", Name: "Qwen Old", Chat: base, Key: "sk-sp-key3"}, + // signed in, past the time the platform gave it + {ID: "qwen-late", Name: "Qwen Late", Chat: base, Key: "sk-sp-key4"}, + // Alibaba Cloud's plan: not this one + {ID: "bailian", Name: "Bailian", Chat: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", Key: "sk-sp-key5"}, + } { + if err := Save(p); err != nil { + t.Fatal(err) + } + } + saveQianwenSession(t, "qwen-token-plan", qianwenSession{Access: "acc1", Email: "a@example.com", Expires: time.Now().Add(time.Hour)}) + saveQianwenSession(t, "qwen-old", qianwenSession{Access: "gone"}) + saveQianwenSession(t, "qwen-late", qianwenSession{Access: "acc1", Expires: time.Now().Add(-time.Minute)}) + + got := map[string]SubscriptionQuota{} + for _, q := range PlanQuotas(context.Background()) { + if strings.HasPrefix(q.Provider, "qwen-") { + got[q.Provider] = q + } + } + if len(got) != 4 { + t.Fatalf("%+v", got) + } + q := got["qwen-token-plan"] + if q.Error != "" || len(q.Windows) != 1 || q.Windows[0].Name != "Month" || q.Windows[0].Used != 25 || + q.Windows[0].ResetsAt.UnixMilli() != 1780000000000 || q.User != "a@example.com" || q.NeedsAccessKey { + t.Fatalf("%+v", q) + } + if q := got["qwen-two"]; !q.NeedsAccessKey || !strings.HasPrefix(q.Error, "this plan's usage is told only to a sign-in on the Qwen AI platform") || !strings.Contains(q.Error, "Qwen Two") { + t.Errorf("not signed in: %+v", q) + } + for _, id := range []string{"qwen-old", "qwen-late"} { + if q := got[id]; !q.NeedsAccessKey || q.Error != errQianwenSession.Error() { + t.Errorf("%s: %+v", id, q) + } + } + f.mu.Lock() + minted, reads := f.minted, f.reads + f.mu.Unlock() + // cli1 refused, cli2 made and read; "gone" refused at the mint, the + // late one never asked + if minted != 1 || reads != 2 { + t.Errorf("minted %d, reads %d", minted, reads) + } + + // the console token is kept: a second read makes none + ws, err := qianwenReadUsage(context.Background(), "qwen-token-plan", time.Now) + if err != nil || len(ws) != 1 { + t.Fatalf("%v %+v", err, ws) + } + f.mu.Lock() + if f.minted != 1 { + t.Errorf("minted again: %d", f.minted) + } + // a fresh console token the console refuses is a sign-in ended, not a + // loop + f.usage = map[string]string{} + f.mu.Unlock() + qianwenForgetToken("qwen-token-plan") + if _, err := qianwenReadUsage(context.Background(), "qwen-token-plan", time.Now); !errors.Is(err, errQianwenSession) { + t.Errorf("fresh token refused: %v", err) + } + // an account with no Token Plan tells no window: said, not a 0% card + f.mu.Lock() + f.usage["cli2"] = strings.Replace(qianwenUsageReply(0), `"per1MonthPercentage":0,"per1MonthResetTime":1780000000000`, `"planName":null`, 1) + f.mu.Unlock() + if _, err := qianwenReadUsage(context.Background(), "qwen-token-plan", time.Now); err == nil || !strings.Contains(err.Error(), "told no window") { + t.Errorf("no window: %v", err) + } +} + +// the sign-in goes with its provider: renamed, it follows; removed, it is +// gone, and no provider added later under the id has it +func TestQianwenFollowsProvider(t *testing.T) { + qianwenHome(t) + const base = "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1" + if err := Save(Provider{ID: "qwen-a", Name: "Qwen A", Chat: base, Key: "sk-sp-a"}); err != nil { + t.Fatal(err) + } + saveQianwenSession(t, "qwen-a", qianwenSession{Access: "acc1"}) + saveQianwenSession(t, "keep", qianwenSession{Access: "acc2"}) + if err := Rename("qwen-a", "qwen-b"); err != nil { + t.Fatal(err) + } + if QianwenSignedIn("qwen-a") || !QianwenSignedIn("qwen-b") { + t.Fatal("the sign-in didn't follow the rename") + } + if err := Delete("qwen-b"); err != nil { + t.Fatal(err) + } + if QianwenSignedIn("qwen-b") || !QianwenSignedIn("keep") { + t.Fatal("removing the provider didn't drop its sign-in alone") + } +} + +func TestQianwenTime(t *testing.T) { + want := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC) + for _, v := range []any{float64(want.Unix()), float64(want.UnixMilli()), "2026-12-01T00:00:00Z", strconvInt(want.UnixMilli())} { + if got := qianwenTime(v); !got.Equal(want) { + t.Errorf("%v: %v", v, got) + } + } + if !qianwenTime("").IsZero() || !qianwenTime(nil).IsZero() || !qianwenTime("soon").IsZero() { + t.Error("a time from nothing") + } +} + +func strconvInt(n int64) string { b, _ := json.Marshal(n); return string(b) } diff --git a/internal/provider/rename.go b/internal/provider/rename.go index d3451caf9..02c8cf5ed 100644 --- a/internal/provider/rename.go +++ b/internal/provider/rename.go @@ -22,8 +22,8 @@ import ( // Rename gives a provider another id, the one its models are picked by // (/). What magpie keeps that names it by id follows: the // routing groups it is in and their rules and classifiers, the other -// providers' fallbacks, which agents are shown it, and its StepFun sign-in. The old id stays -// with it (Was), so an agent still running on a config that names it the +// providers' fallbacks, which agents are shown it, and its StepFun and +// Qwen AI platform sign-ins. The old id stays with it (Was), so an agent still running on a config that names it the // old way reaches it, and its usage so far is counted with it; the agents' // own files are the agent package's to rewrite (agent.RenameProvider). // A signed-in account keeps the id of its agent. @@ -101,10 +101,13 @@ func Rename(from, to string) error { if err := store(f); err != nil { return err } - // so is its StepFun sign-in, kept by provider id + // so are its StepFun and Qwen AI platform sign-ins, kept by provider id if err := renameStepFun(from, to); err != nil { return err } + if err := renameQianwen(from, to); err != nil { + return err + } s := settings.Load() changed := renameModelPrefs(&s, from, to) for a, names := range s.Visible {