provider: Baidu Qianfan's Token Plan Personal shows its month through a console sign-in (yuushabu_buyinn on X, #5860)

A Qianfan Token Plan key tells nothing of the plan's usage: Qianfan's
OpenAPI has no read for it, and the console's own page asks
console.bce.baidu.com/api/qianfan/charge/tokenPlanPersonal/resource with
the signed-in cookie. So the plan is read as StepFun's Step Plan is: the
editor of a provider at qianfan.baidubce.com/v2/tokenplan/personal has a
"Token Plan usage" field, drawn by the same renderStepPlan (now told
whose sign-in it brings) from qianfanplan.js, imported when such an
editor opens. The bookmarklet, run on the console, checks the session
with that same request and copies the console cookie; a raw Cookie
header or a copied cURL is taken too, since document.cookie leaves out
HttpOnly cookies. The paste is checked with a real read before it is
kept, by provider id, in qianfan-auth.json (0600, lastgood-guarded,
moved and dropped with the provider). POST /api/qianfan/{id}/session and
/signout serve it.

The Usage page's card (qianfanPlanQuotas in PlanQuotas) is the running
plan's credits (billingMode credit) or tokens as one Month window up to
expiresAt, the plan's tier as its name and auto-renew beside it;
released and past plans are skipped, and routing reads the same windows
(accountPlanWindows). A redirect, 401, 403, an HTML page or a refusal
naming the login is a signed-out session: an error card saying so, never
0 left; any other failure is an error card too, the last reading kept
only on a passing network error. The per-plan apiKey in the console's
reply is never kept, logged or shown.

Not done: the Enterprise (team) plan has no card. The console has no
tokenPlanTeam/resource; it reads team plans through seat and admin APIs.

Not tried with a real account: no one here is signed in to Baidu Cloud's
console, and #5860 has no reply bytes posted. The fixtures follow the
field names in the console's own script bundle and in the
dsh-qianfan-token-plan reader (planType, resourceStatus, billingMode,
usedCredits/totalCredits, usedTokens/totalTokens as numbers or strings,
expiresAt, autoRenew), not a captured reply.

core budget +35 (app.js and core): the field moved to qianfanplan.js;
what is left in the core is the import and two quotaError lines.

Run (at the pushed tree, rebased on origin/main 8df7885d4):
- mote: go test -count=1 -timeout 45m ./internal/provider ./internal/gui
  ./internal/cli: ok (provider 279s, gui 209s, cli 113s)
- mote: GOOS=linux and GOOS=windows go vet of the three (linux with -tags nogui): clean
- gofmt -l internal/: empty
- mica: node --test qianfan-plan, stepfun-per-provider, qianwen-plan,
  i18n-keys, i18n-en-no-cjk, old-webkit (Chromium and WebKit, en and zh;
  i18n-keys over zh, zh-TW, ja, de): 40 of 42 pass. The two reds are
  old-webkit's headerpresets.js (#6030) and app.css :has() (#5919), the
  same on origin/main 8df7885d4, run there.
- Red before: qianfan-plan.test.cjs on origin/main 8df7885d4, 4 of 4 red
  (no field). Broken by hand on mica: with a
  redirect not read as signed out and Released not skipped,
  TestReadQianfanPlan, TestSaveQianfanPaste and TestQianfanPlanCard go red.
- Not run: the whole Go suite and the whole GUI suite.
This commit is contained in:
yetone
2026-11-16 01:54:28 +08:00
parent 8df7885d48
commit 8f3f7a46af
17 changed files with 1029 additions and 23 deletions
File diff suppressed because one or more lines are too long
+2
View File
@@ -494,6 +494,8 @@ var notYet = map[string]string{
"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
"POST /api/qianfan/{id}/session": P, // providers.go
"POST /api/qianfan/{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
+17 -9
View File
@@ -10087,7 +10087,9 @@ 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
// a Baidu Qianfan Token Plan's to a console sign-in (qianfanplan.js), and
// a Qwen AI platform plan's to a sign-in there (qianwenplan.js)
if (p?.qianfanPlan) { const at = el("span"); ed.append(at); import("./qianfanplan.js").then(() => at.replaceWith(...qianfanPlanField(p)), () => {}); }
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)
@@ -12934,29 +12936,32 @@ function renderPluginAsk(sub) {
return box;
}
// renderStepPlan: StepFun's platform sign-in by bookmarklet, per provider id
function renderStepPlan(sp, id) {
// renderStepPlan: StepFun's platform sign-in by bookmarklet, per provider
// id; n names another vendor's sign-in brought the same way (Baidu Qianfan's)
function renderStepPlan(sp, id, n) {
n ||= { route: "stepfun", bm: "magpie · StepFun", state: t("Signed in · the Usage page shows the Step Plan"),
open: t("Sign in to StepFun in your browser ↗"), ok: t("Signed in to StepFun") };
const box = el("div", "stepplan");
if (sp.signedIn) {
const row = el("div", "pair");
const side = el("div", "side");
const out = el("button", "text", t("Sign out"));
out.onclick = async () => {
try { providers = await api("stepfun/" + encodeURIComponent(id) + "/signout", {}); renderProviders(); } catch (e) { statusErr(e); }
try { providers = await api(n.route + "/" + encodeURIComponent(id) + "/signout", {}); renderProviders(); } catch (e) { statusErr(e); }
};
side.append(out);
row.append(el("span", "state", t("Signed in · the Usage page shows the Step Plan")), side);
row.append(el("span", "state", n.state), side);
box.append(row);
return box;
}
const steps = el("ol", "steps");
const s1 = el("li");
const open = el("button", "link", t("Sign in to StepFun in your browser ↗"));
const open = el("button", "link", n.open);
open.onclick = () => api("open", { url: sp.url });
s1.append(open);
const s2 = el("li");
// dragged to the bookmarks bar it is a bookmark; a click here does nothing
const bm = el("a", "bookmarklet", "magpie · StepFun");
const bm = el("a", "bookmarklet", n.bm);
bm.href = sp.bookmarklet;
bm.onclick = (e) => e.preventDefault();
const cp = el("button", "link", t("copy it"));
@@ -12970,9 +12975,9 @@ function renderStepPlan(sp, id) {
if (!paste.value.trim()) return;
go.disabled = paste.disabled = true;
try {
providers = await api("stepfun/" + encodeURIComponent(id) + "/session", { text: paste.value });
providers = await api(n.route + "/" + encodeURIComponent(id) + "/session", { text: paste.value });
renderProviders();
status(t("Signed in to StepFun"), "ok");
status(n.ok, "ok");
} catch (e) {
go.disabled = paste.disabled = false;
statusErr(e);
@@ -14060,6 +14065,9 @@ function quotaError(err, q) {
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");
// a Baidu Qianfan Token Plan Personal (qianfan_plan.go)
if (/^signed out of the Baidu Cloud console/.test(err)) return t("Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings");
if (/^this Baidu Cloud account has no Token Plan Personal$/.test(err)) return t("This Baidu Cloud account has no Token Plan Personal");
// 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)
+28
View File
@@ -3945,6 +3945,13 @@ const I18N = {
"paste what it copied": "粘贴它复制的内容",
"Bookmarklet": "书签小工具",
"Signed in to StepFun": "已登录 StepFun",
"Token Plan usage": "Token Plan 用量",
"Signed in · the Usage page shows the Token Plan": "已登录 · 用量页显示 Token Plan",
"Sign in to the Baidu Cloud console in your browser ↗": "在浏览器中登录百度智能云控制台 ↗",
"Signed in to the Baidu Cloud console": "已登录百度智能云控制台",
"Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "已退出百度智能云控制台 — 在服务商设置中重新带入登录",
"This Baidu Cloud account has no Token Plan Personal": "这个百度智能云账号没有 Token Plan 个人版",
"A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "密钥不告知套餐用量。套餐本月的用量只告知百度智能云控制台的登录:在这里带入一次,magpie 会保存它,不作他用。如果 magpie 用不了书签复制的内容,请从浏览器开发者工具中复制控制台请求的 Cookie 请求头粘贴到这里。",
"saved · paste a new one to replace it": "已保存 · 粘贴新的即可替换",
"optional · the account's system access token": "可选 · 账户的系统访问令牌",
"Leave it empty to read the key's own balance: most relays tell it at the Balance URL above (a sub2api relay's …/v1/usage, a new-api relay's …/api/usage/token). Only for the whole account's balance: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.": "留空即可查这个 Key 自己的余额:大多数中转站在上面的余额查询地址里就能查到(sub2api 中转站是 …/v1/usage,new-api 中转站是 …/api/usage/token)。只有要查整个账户的余额时才填:new-api 中转站填「系统访问令牌」,sub2api 面板填登录令牌(JWT,会以 Bearer 发送);不作他用。",
@@ -9253,6 +9260,13 @@ const I18N = {
"paste what it copied": "貼上它複製的內容",
"Bookmarklet": "書籤小工具",
"Signed in to StepFun": "已登入 StepFun",
"Token Plan usage": "Token Plan 用量",
"Signed in · the Usage page shows the Token Plan": "已登入 · 用量頁顯示 Token Plan",
"Sign in to the Baidu Cloud console in your browser ↗": "在瀏覽器中登入百度智慧雲主控台 ↗",
"Signed in to the Baidu Cloud console": "已登入百度智慧雲主控台",
"Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "已登出百度智慧雲主控台 — 在供應商設定中重新帶入登入",
"This Baidu Cloud account has no Token Plan Personal": "這個百度智慧雲帳號沒有 Token Plan 個人版",
"A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "金鑰不告知方案用量。方案本月的用量只告知百度智慧雲主控台的登入:在這裡帶入一次,magpie 會保存它,不作他用。如果 magpie 用不了書籤複製的內容,請從瀏覽器開發者工具中複製主控台請求的 Cookie 標頭貼到這裡。",
"saved · paste a new one to replace it": "已儲存 · 貼上新的即可替換",
"optional · the account's system access token": "可選 · 帳戶的系統存取權杖",
"Leave it empty to read the key's own balance: most relays tell it at the Balance URL above (a sub2api relay's …/v1/usage, a new-api relay's …/api/usage/token). Only for the whole account's balance: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.": "留空即可查這個 Key 自己的餘額:大多數中轉站在上面的餘額查詢位址裡就能查到(sub2api 中轉站是 …/v1/usage,new-api 中轉站是 …/api/usage/token)。只有要查整個帳戶的餘額時才填:new-api 中轉站填「系統存取權杖」,sub2api 面板填登入令牌(JWT,會以 Bearer 傳送);不作他用。",
@@ -14569,6 +14583,13 @@ const I18N = {
"paste what it copied": "コピーされた内容を貼り付け",
"Bookmarklet": "ブックマークレット",
"Signed in to StepFun": "StepFun にサインイン済み",
"Token Plan usage": "Token Plan の使用量",
"Signed in · the Usage page shows the Token Plan": "サインイン済み · 使用量ページに Token Plan を表示",
"Sign in to the Baidu Cloud console in your browser ↗": "ブラウザで Baidu Cloud コンソールにサインイン ↗",
"Signed in to the Baidu Cloud console": "Baidu Cloud コンソールにサインイン済み",
"Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "Baidu Cloud コンソールからサインアウトしました — プロバイダの設定で新しいサインインを渡してください",
"This Baidu Cloud account has no Token Plan Personal": "この Baidu Cloud アカウントには Token Plan 個人版がありません",
"A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "キーはプランの使用量を伝えません。今月の使用量は Baidu Cloud コンソールへのサインインにのみ伝えられます。ここで一度渡せば magpie が保存し、ほかの用途には使いません。ブックマークレットのコピーが使えない場合は、ブラウザの開発者ツールからコンソールのリクエストの Cookie ヘッダーを貼り付けてください。",
"saved · paste a new one to replace it": "保存済み · 新しいものを貼り付けると置き換えます",
"optional · the account's system access token": "任意 · アカウントのシステムアクセストークン",
"Leave it empty to read the key's own balance: most relays tell it at the Balance URL above (a sub2api relay's …/v1/usage, a new-api relay's …/api/usage/token). Only for the whole account's balance: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.": "空欄のままでキー自身の残高を取得できます。多くの中継サイトは上の残高 URL で答えます(sub2api の中継サイトは …/v1/usage、new-api の中継サイトは …/api/usage/token)。アカウント全体の残高が必要な場合のみ入力します:new-api 中継サイトでは System Access Token、sub2api パネルではログイントークン(JWT、Bearer として送信)。それ以外には使いません。",
@@ -19894,6 +19915,13 @@ const I18N = {
"paste what it copied": "Kopiertes einfügen",
"Bookmarklet": "Bookmarklet",
"Signed in to StepFun": "Bei StepFun angemeldet",
"Token Plan usage": "Token-Plan-Nutzung",
"Signed in · the Usage page shows the Token Plan": "Angemeldet · die Nutzungsseite zeigt den Token Plan",
"Sign in to the Baidu Cloud console in your browser ↗": "Im Browser bei der Baidu-Cloud-Konsole anmelden ↗",
"Signed in to the Baidu Cloud console": "Bei der Baidu-Cloud-Konsole angemeldet",
"Signed out of the Baidu Cloud console — bring a new sign-in in the provider's settings": "Von der Baidu-Cloud-Konsole abgemeldet — bringen Sie in den Einstellungen des Anbieters eine neue Anmeldung mit",
"This Baidu Cloud account has no Token Plan Personal": "Dieses Baidu-Cloud-Konto hat keinen Token Plan Personal",
"A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools.": "Ein Schlüssel verrät die Nutzung des Plans nicht. Sein Monat wird nur einer Anmeldung in der Baidu-Cloud-Konsole verraten: Bringen Sie Ihre einmal hierher, magpie bewahrt sie auf und nutzt sie für nichts anderes. Kann magpie nicht verwenden, was das Bookmarklet kopiert hat, fügen Sie den Cookie-Header der Konsolenanfrage aus den Entwicklertools Ihres Browsers ein.",
"saved · paste a new one to replace it": "gespeichert · zum Ersetzen ein neues einfügen",
"optional · the account's system access token": "optional · das System-Zugriffstoken des Kontos",
"Leave it empty to read the key's own balance: most relays tell it at the Balance URL above (a sub2api relay's …/v1/usage, a new-api relay's …/api/usage/token). Only for the whole account's balance: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.": "Leer lassen, um das Guthaben des Schlüssels selbst zu lesen: Die meisten Relays nennen es unter der Guthaben-URL oben (ein sub2api-Relay unter …/v1/usage, ein new-api-Relay unter …/api/usage/token). Nur für das Guthaben des ganzen Kontos: das System Access Token eines new-api-Relays oder das Anmeldetoken eines sub2api-Panels (ein JWT, als Bearer gesendet); es wird für nichts anderes verwendet.",
+9
View File
@@ -0,0 +1,9 @@
// Baidu Qianfan's Token Plan Personal: its month is told only to a sign-in
// on Baidu Cloud's console, brought by the bookmarklet and paste StepFun's
// Step Plan uses (renderStepPlan) and kept per provider id
// (qianfan_plan.go). app.js imports this when such a provider's editor
// opens, so it weighs nothing on the core.
window.qianfanPlanField = (p) => field(t("Token Plan usage"), renderStepPlan(p.qianfanPlan, p.id, {
route: "qianfan", bm: "magpie · Qianfan", state: t("Signed in · the Usage page shows the Token Plan"),
open: t("Sign in to the Baidu Cloud console in your browser ↗"), ok: t("Signed in to the Baidu Cloud console"),
}), t("A key tells nothing of the plan's usage. Its month is told only to a sign-in on Baidu Cloud's console: bring yours here once and magpie keeps it, used for nothing else. If magpie can't use what the bookmarklet copied, paste the Cookie header of the console's request from your browser's developer tools."));
File diff suppressed because one or more lines are too long
+46
View File
@@ -322,6 +322,10 @@ type providerJSON struct {
// 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 Baidu Qianfan Token Plan Personal's month, told only to a sign-in
// on Baidu Cloud's console, brought from the user's browser as
// StepFun's is: whether one is kept, and where and how to get one
QianfanPlan *stepPlanJSON `json:"qianfanPlan,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"`
@@ -1035,6 +1039,9 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
if provider.QianwenPlan(p) {
out.QianwenPlan = &qianwenPlanJSON{provider.QianwenSignedIn(p.ID), provider.QianwenAccount(p.ID)}
}
if provider.QianfanPlan(p) {
out.QianfanPlan = &stepPlanJSON{"", provider.QianfanSignedIn(p.ID), provider.QianfanSignInURL, provider.QianfanBookmarklet()}
}
out.Key.Set = p.Key != ""
out.Key.Masked = provider.Mask(p.Key)
out.ProxyGone = provider.ProxyGone(p)
@@ -3645,6 +3652,45 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
}
writeProvidersJSON(rw, providersState())
})
// Baidu Qianfan's Token Plan Personal: the console session the user
// copied from their browser, the provider's own
qianfanOf := func(rw http.ResponseWriter, r *http.Request) (*provider.Provider, bool) {
p, err := provider.Find(r.PathValue("id"))
if err != nil || !provider.QianfanPlan(*p) {
http.NotFound(rw, r)
return nil, false
}
return p, true
}
mux.HandleFunc("POST /api/qianfan/{id}/session", func(rw http.ResponseWriter, r *http.Request) {
p, ok := qianfanOf(rw, r)
if !ok {
return
}
var in struct{ Text string }
if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&in); err != nil {
fail(rw, err)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
if err := provider.SaveQianfanPaste(p.Via(ctx), p.ID, in.Text); err != nil {
fail(rw, err)
return
}
writeProvidersJSON(rw, providersState())
})
mux.HandleFunc("POST /api/qianfan/{id}/signout", func(rw http.ResponseWriter, r *http.Request) {
p, ok := qianfanOf(rw, r)
if !ok {
return
}
if err := provider.SignOutQianfan(p.ID); err != nil {
fail(rw, err)
return
}
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) {
+97
View File
@@ -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 Baidu Qianfan Token Plan Personal provider is told where and how to
// bring its console sign-in, and whether one is kept (#5860); the
// Enterprise plan and pay as you go aren't, and no other provider can be
// posted a session or signed out here. A paste the console can't be asked
// with keeps nothing.
func TestQianfanSignInRoutes(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())
for _, p := range []provider.Provider{
{ID: "baidu-qianfan", Name: "Baidu Qianfan", Key: "bce-v3/k1", Chat: "https://qianfan.baidubce.com/v2/tokenplan/personal"},
{ID: "qianfan-team", Name: "Qianfan Team", Key: "bce-v3/k2", Chat: "https://qianfan.baidubce.com/v2/tokenplan/team"},
{ID: "relay", Name: "Relay", Key: "k3", Chat: "http://127.0.0.1:1/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
auth := filepath.Join(filepath.Dir(provider.Path()), "qianfan-auth.json")
if err := os.WriteFile(auth, []byte(`{"baidu-qianfan":{"cookie":"BDUSS=x"}}`), 0o600); err != nil {
t.Fatal(err)
}
mux := http.NewServeMux()
providerRoutes(mux, nil)
plans := func() map[string]struct {
SignedIn bool
URL, Bookmarklet string
} {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil))
var got struct {
Providers []struct {
ID string
QianfanPlan *struct {
SignedIn bool
URL, Bookmarklet string
}
}
}
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
out := map[string]struct {
SignedIn bool
URL, Bookmarklet string
}{}
for _, p := range got.Providers {
if p.QianfanPlan != nil {
out[p.ID] = *p.QianfanPlan
}
}
return out
}
got := plans()
if len(got) != 1 || !got["baidu-qianfan"].SignedIn || !strings.HasPrefix(got["baidu-qianfan"].Bookmarklet, "javascript:") ||
!strings.HasPrefix(got["baidu-qianfan"].URL, "https://console.bce.baidu.com/") {
t.Fatalf("before: %+v", got)
}
for _, id := range []string{"relay", "qianfan-team", "nobody"} {
for _, path := range []string{"session", "signout"} {
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/qianfan/"+id+"/"+path, strings.NewReader(`{"text":"BDUSS=y"}`)))
if w.Code != http.StatusNotFound {
t.Errorf("%s for %s: %d, want 404", path, id, w.Code)
}
}
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/qianfan/baidu-qianfan/session", strings.NewReader(`{"text":"hello"}`)))
if w.Code == 200 {
t.Fatalf("a paste with no cookie was taken: %s", w.Body)
}
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/qianfan/baidu-qianfan/signout", strings.NewReader("{}")))
if w.Code != 200 {
t.Fatalf("signout: %d %s", w.Code, w.Body)
}
if got := plans(); got["baidu-qianfan"].SignedIn {
t.Fatalf("after signing out: %+v", got)
}
}
+1 -1
View File
@@ -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", "qianwenplan.js", "updatetrust.js", "currencyprefs.js", "appearance.js", "mirroredit.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", "qianfanplan.js", "updatetrust.js", "currencyprefs.js", "appearance.js", "mirroredit.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
});
test("the styles hold up in Safari 15.0", async () => {
+88
View File
@@ -0,0 +1,88 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A Baidu Qianfan Token Plan Personal provider's editor takes a sign-in on
// Baidu Cloud's console the way StepFun's does (yuushabu_buyinn on X, #5860):
// the paste posts to /api/qianfan/{id}/session for that provider's id, and a
// signed-in one's Sign out posts /api/qianfan/{id}/signout. A Qianfan
// provider without the plan has no such field. In English and Chinese.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const qianfan = (id, name, plan) => ({
id, name, icon: "baiducloud-color", preset: "baidu-qianfan", chat: "https://qianfan.baidubce.com/v2/tokenplan/personal", responses: "", anthropic: "", catalog: "",
models: [{ id: "ernie-5.0", name: "ERNIE 5.0", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "…ab12" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
...(plan ? { qianfanPlan: { site: "", signedIn: plan === "in", url: "https://console.bce.baidu.com/qianfan/resource/token-plan", bookmarklet: "javascript:void 0" } } : {}),
});
function serve(lang, posts) {
const providers = { providers: [qianfan("qianfan", "Qianfan Plan", "in"), qianfan("qianfan-2", "Qianfan Work", "out"), qianfan("qianfan-api", "Qianfan API", "")], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname.startsWith("/api/qianfan/")) {
posts.push({ path: url.pathname, body: route.request().postDataJSON() });
return json(providers);
}
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const words = { en: { out: "Sign out", cancel: "Cancel" }, zh: { out: "退出登录", cancel: "取消" } };
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: a Qianfan Token Plan provider signs in and out for its own id`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 900, height: 560 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
const wait = async (n) => { for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50); };
// a Qianfan provider without the plan has no sign-in field
await page.locator(".row.provider", { hasText: "Qianfan API" }).click();
await page.locator(".editor").waitFor();
assert.equal(await page.locator(".editor .stepplan").count(), 0);
await page.locator(".editor .bar").getByRole("button", { name: words[lang].cancel, exact: true }).click();
await page.locator(".editor").waitFor({ state: "detached" });
// the one not signed in takes a paste, for its own id
await page.locator(".row.provider", { hasText: "Qianfan Work" }).click();
const paste = page.locator(".editor .stepplan input[type=password]");
await paste.fill("magpie-qianfan:{}");
await paste.press("Enter");
await wait(0);
assert.equal(posts.length, 1);
assert.equal(posts[0].path, "/api/qianfan/qianfan-2/session");
assert.equal(posts[0].body.text, "magpie-qianfan:{}");
// the one signed in signs out, for its own id
await page.locator(".editor .bar").getByRole("button", { name: words[lang].cancel, exact: true }).click();
await page.locator(".editor").waitFor({ state: "detached" });
await page.locator(".row.provider", { hasText: "Qianfan Plan" }).click();
await page.locator(".editor .stepplan").getByRole("button", { name: words[lang].out, exact: true }).click();
await wait(1);
assert.equal(posts.length, 2);
assert.equal(posts[1].path, "/api/qianfan/qianfan/signout");
assert.deepEqual(errors, []);
});
}
}
+13 -2
View File
@@ -75,8 +75,9 @@ func readsKeyWindows(p Provider) bool {
// 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 and the Qwen AI platform's
// Token Plan, read with magpie's sign-in to the platform (stepfun_plan.go,
// qianwen_plan.go). The
// Token Plan and Baidu Qianfan's Token Plan Personal, read with magpie's
// sign-in to the platform (stepfun_plan.go, qianwen_plan.go,
// qianfan_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
@@ -101,6 +102,9 @@ func accountPlanOf(p Provider) string {
if QianwenPlan(p) {
return "qianwen"
}
if QianfanPlan(p) {
return "qianfan"
}
return ""
}
@@ -133,6 +137,11 @@ func accountPlanWindows(ctx context.Context, q Provider) (keyReading, error) {
return keyReading{}, nil
}
c = qianwenPlanQuota(q.Via(ctx), q)
case "qianfan":
if !QianfanSignedIn(q.ID) {
return keyReading{}, nil
}
c = qianfanPlanQuota(q.Via(ctx), q)
}
if c.Error != "" {
return keyReading{}, errors.New(c.Error)
@@ -302,6 +311,8 @@ func keyCardTag(p Provider) string {
return keyTag("stepfun", p.ID)
case "qianwen":
return keyTag("qianwen", p.ID)
case "qianfan":
return keyTag("qianfan", p.ID)
}
}
if _, ok := planQuotaSourceOf(p); ok && !sub2APIKeyLimits(p) {
+5 -3
View File
@@ -891,6 +891,8 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
go func() { ali <- aliPlanQuotas(ctx) }()
qianwen := make(chan []SubscriptionQuota, 1)
go func() { qianwen <- qianwenPlanQuotas(ctx) }()
qianfan := make(chan []SubscriptionQuota, 1)
go func() { qianfan <- qianfanPlanQuotas(ctx) }()
wg.Wait()
out := []SubscriptionQuota{}
for i, q := range got {
@@ -900,9 +902,9 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
out = append(out, *q)
}
}
// 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} {
// StepFun's, Volcengine's, Tencent's, Alibaba's, the Qwen AI
// platform's and Baidu Qianfan's, read just now too
for _, qs := range [][]SubscriptionQuota{<-stepfun, <-volc, <-tencent, <-ali, <-qianwen, <-qianfan} {
for _, q := range qs {
out = append(out, readNow(q))
}
+6 -3
View File
@@ -1805,12 +1805,15 @@ func Delete(id string) error {
if err := store(f); err != nil {
return err
}
// its StepFun and Qwen AI platform sign-ins go with it, not to a
// provider added later under the same id
// its StepFun, Qwen AI platform and Baidu Cloud console 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)
if err := forgetQianwen(id); err != nil {
return err
}
return forgetQianfan(id)
}
// keyOptional is true for a server on this computer or on the user's own
+478
View File
@@ -0,0 +1,478 @@
package provider
// Baidu Qianfan's Token Plan Personal (qianfan.baidubce.com/v2/tokenplan/
// personal, bce-v3 keys) tells what is used of its month only to a sign-in
// on Baidu Cloud's console, never to the plan's key: the console's
//
// GET console.bce.baidu.com/api/qianfan/charge/tokenPlanPersonal/resource
//
// answers a request without the console's session with a 302 to
// login.bce.baidu.com, a Bearer key or not, and qianfan.baidubce.com has no
// usage route (#5860, yuushabu_buyinn on X). The console's own page asks it
// with the session's cookies and X-Requested-With, and reads
//
// {"success":true,"result":{"items":[{"resourceId","planType":"pro",
// "resourceStatus":"Running","billingMode":"credit"|"token",
// "usedCredits","totalCredits","usedTokens","totalTokens",
// "expiresAt","autoRenew","apiKey"},…]}}
//
// (Baidu's console bundle, useRedeemCodeActivation and caller; the same
// fields as qnnp-me/dsh-qianfan-token-plan reads). An item Released, or
// past its expiresAt, is no plan. The item's apiKey is never kept.
//
// As StepFun's sign-in (stepfun_plan.go), the user brings the session from
// their own browser: a bookmarklet run on the signed-in console copies its
// cookies, or the Cookie header of the console's request is pasted from
// the browser's developer tools, where the HttpOnly ones are too. magpie
// asks the console with it before keeping it, and keeps it in
// qianfan-auth.json beside providers.json, readable by the user alone, one
// per provider: two can be two Baidu accounts. The console doesn't renew
// it for magpie: when Baidu ends it the card says so, and the user brings
// a new one.
//
// The Enterprise plan (tokenplan/team) is read on the console from its
// seats' admin pages (tokenPlan/seat/admin/overview), not this one; it
// isn't read here.
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/filememo"
"github.com/yetone/magpie/internal/lastgood"
)
// qianfanConsole is Baidu Cloud's console, a var for tests.
var qianfanConsole = "https://console.bce.baidu.com"
const (
qianfanResourcePath = "/api/qianfan/charge/tokenPlanPersonal/resource"
qianfanPlanHost = "qianfan.baidubce.com"
// qianfanPaste starts what the bookmarklet copies, the JSON of a session
qianfanPaste = "magpie-qianfan:"
// qianfanUA is a browser's: the console is a page's API
qianfanUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"
)
// QianfanSignInURL is the console page the plan is on, where the user signs
// in and runs the bookmarklet.
const QianfanSignInURL = "https://console.bce.baidu.com/qianfan/resource/token-plan"
// QianfanPlan says p is on Baidu Qianfan's Token Plan Personal, whose usage
// magpie reads with a sign-in to Baidu Cloud's console.
func QianfanPlan(p Provider) bool {
if p.Account != nil {
return false
}
for _, base := range []string{p.Chat, p.Anthropic, p.Responses} {
if hostOf(base) == qianfanPlanHost && strings.Contains(strings.ToLower(base), "/tokenplan/personal") {
return true
}
}
return false
}
// QianfanBookmarklet is the bookmarklet the user runs on the console while
// signed in: it asks the plan's page as the console does, so a page not
// signed in says so there, and copies the page's cookies to be pasted into
// magpie.
func QianfanBookmarklet() string {
return `javascript:(async()=>{if(location.host!=="console.bce.baidu.com"){alert("Open it on console.bce.baidu.com / 请在百度智能云控制台的页面上点它");return}` +
`try{const r=await fetch("` + qianfanResourcePath + `",{credentials:"include",redirect:"manual",headers:{"x-requested-with":"XMLHttpRequest"}});` +
`const j=r.ok?await r.json():{};if(j.success!==true){alert("Sign in to the Baidu Cloud console first / 请先登录百度智能云控制台");return}` +
`const t="` + qianfanPaste + `"+JSON.stringify({cookie:document.cookie});` +
`try{await navigator.clipboard.writeText(t);alert("Copied: paste it into magpie / 已复制,回 magpie 粘贴")}` +
`catch{prompt("Copy this and paste it into magpie / 复制这段,回 magpie 粘贴",t)}` +
`}catch(e){alert(String(e))}})()`
}
// qianfanSession is a sign-in on the console: its cookies, as a request's
// Cookie header.
type qianfanSession struct {
Cookie string `json:"cookie"`
}
var qianfanMu sync.Mutex
func qianfanPath() string { return filepath.Join(filepath.Dir(Path()), "qianfan-auth.json") }
// loadQianfan is every provider's sign-in, by provider id; the caller holds
// qianfanMu. A file that doesn't parse is no sign-in, and is left as it is
// (saveQianfan keeps it aside before a sign-in writes over it).
func loadQianfan() map[string]qianfanSession {
out := map[string]qianfanSession{}
b, err := os.ReadFile(qianfanPath())
if err != nil {
return out
}
if json.Unmarshal(b, &out) != nil {
return map[string]qianfanSession{}
}
return out
}
func saveQianfan(all map[string]qianfanSession) 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(qianfanPath()), 0o700); err != nil {
return err
}
if err := lastgood.KeepUnparsed(qianfanPath(), lastgood.Into[map[string]qianfanSession]); err != nil {
return err
}
return writeFileAtomic(qianfanPath(), b)
}
// qianfanSignIn is the provider's sign-in, the file read once until it
// changes: a provider list asks it on every poll.
func qianfanSignIn(id string) (qianfanSession, bool) {
all, err := filememo.Read("qianfan-auth", qianfanPath(), func(b []byte) (map[string]qianfanSession, error) {
m := map[string]qianfanSession{}
return m, json.Unmarshal(b, &m)
})
if err != nil {
return qianfanSession{}, false
}
s, ok := all[id]
return s, ok && s.Cookie != ""
}
// QianfanSignedIn reports whether magpie has a sign-in for the provider.
func QianfanSignedIn(id string) bool {
_, ok := qianfanSignIn(id)
return ok
}
// SignOutQianfan forgets the provider's sign-in, and no other's.
func SignOutQianfan(id string) error {
qianfanMu.Lock()
all := loadQianfan()
_, had := all[id]
delete(all, id)
var err error
if had {
err = saveQianfan(all)
}
qianfanMu.Unlock()
forgetPlanQuotas()
return err
}
// forgetQianfan drops the provider's sign-in, when it is removed.
func forgetQianfan(id string) error { return SignOutQianfan(id) }
// renameQianfan moves the provider's sign-in with it to its new id.
func renameQianfan(from, to string) error {
qianfanMu.Lock()
defer qianfanMu.Unlock()
all := loadQianfan()
s, ok := all[from]
if !ok {
return nil
}
delete(all, from)
all[to] = s
return saveQianfan(all)
}
var (
// a copied cURL command's cookies: -b '…' or -H 'Cookie: …'
qianfanCurlB = regexp.MustCompile(`(?:^|\s)(?:-b|--cookie)\s+(?:'([^']*)'|"([^"]*)"|\$'([^']*)')`)
qianfanCurlHeader = regexp.MustCompile(`(?i)(?:-H|--header)\s+(?:'cookie:\s*([^']*)'|"cookie:\s*([^"]*)"|\$'cookie:\s*([^']*)')`)
)
// qianfanCookie is the Cookie header in what the user pasted: what the
// bookmarklet copied, the header as developer tools show it ("Cookie: …"
// or just its value), or a request copied as cURL. "" when it holds none.
func qianfanCookie(text string) (string, error) {
text = strings.TrimSpace(text)
if body, ok := strings.CutPrefix(text, qianfanPaste); ok {
var in struct{ Cookie string }
if json.Unmarshal([]byte(body), &in) != nil {
return "", errors.New("that isn't what the bookmarklet copied: copy it again")
}
text = in.Cookie
} else if strings.HasPrefix(text, "curl ") {
var found string
for _, re := range []*regexp.Regexp{qianfanCurlHeader, qianfanCurlB} {
if m := re.FindStringSubmatch(text); m != nil {
found = m[1] + m[2] + m[3]
break
}
}
text = found
} else if len(text) >= 7 && strings.EqualFold(text[:7], "cookie:") {
text = text[7:]
}
text = strings.TrimSpace(text)
if strings.ContainsAny(text, "\r\n") || !strings.Contains(text, "=") {
return "", errors.New("paste what the bookmarklet copied, or the Cookie header of the console's request")
}
return text, nil
}
// SaveQianfanPaste keeps the console session the user pasted for the
// provider id, once the console has taken it.
func SaveQianfanPaste(ctx context.Context, id, text string) error {
cookie, err := qianfanCookie(text)
if err != nil {
return err
}
if _, err := qianfanResource(ctx, cookie); err != nil {
if errors.Is(err, errQianfanSession) {
// the bookmarklet sees only the cookies a page may read
return errors.New("Baidu's console didn't take that sign-in: copy the Cookie header of the console's tokenPlanPersonal/resource request from your browser's developer tools (Network) and paste it here")
}
return fmt.Errorf("Baidu's console didn't take the sign-in: %w", err)
}
qianfanMu.Lock()
all := loadQianfan()
all[id] = qianfanSession{Cookie: cookie}
err = saveQianfan(all)
qianfanMu.Unlock()
forgetPlanQuotas()
return err
}
// errQianfanSession is a session the console no longer takes.
var errQianfanSession = errors.New("signed out of the Baidu Cloud console: sign in again in the provider's settings")
// qianfanClient asks the console without following its redirect to the
// sign-in page, which is how it says the session has ended.
func qianfanClient() *http.Client {
c := *http.DefaultClient
c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return &c
}
// qianfanResource asks the console for the account's Token Plan Personal
// as the session, and reads its result.
func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, qianfanConsole+qianfanResourcePath, nil)
if err != nil {
return nil, err
}
req.Header.Set("Cookie", cookie)
req.Header.Set("Accept", "application/json;charset=UTF-8")
req.Header.Set("Referer", QianfanSignInURL)
req.Header.Set("X-Requested-With", "XMLHttpRequest")
req.Header.Set("User-Agent", qianfanUA)
res, err := qianfanClient().Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
switch {
case res.StatusCode >= 300 && res.StatusCode < 400,
res.StatusCode == http.StatusUnauthorized, res.StatusCode == http.StatusForbidden:
return nil, errQianfanSession
case res.StatusCode >= 400:
return nil, fmt.Errorf("Baidu's console answered %s", res.Status)
}
var r struct {
Success any `json:"success"`
Result json.RawMessage `json:"result"`
Message any `json:"message"`
Code any `json:"code"`
}
if json.Unmarshal(b, &r) != nil {
// a sign-in page served as 200 is a session ended too
if strings.Contains(strings.ToLower(string(b[:min(len(b), 2048)])), "<html") {
return nil, errQianfanSession
}
return nil, fmt.Errorf("Baidu's console answered what isn't JSON: %s", volcHead(b))
}
if r.Success != true {
msg := strings.TrimSpace(fmt.Sprint(r.Message))
if m, ok := r.Message.(map[string]any); ok {
msg = strings.TrimSpace(fmt.Sprint(m["global"]))
}
code := strings.ToLower(fmt.Sprint(r.Code))
if strings.Contains(code, "login") || strings.Contains(code, "session") || strings.Contains(code, "unauth") {
return nil, errQianfanSession
}
if msg == "" || msg == "<nil>" {
msg = volcHead(b)
}
return nil, fmt.Errorf("Baidu's console refused: %s", msg)
}
return r.Result, nil
}
// qianfanItem is one plan the console lists, its apiKey left out.
type qianfanItem struct {
PlanType string `json:"planType"`
Status string `json:"resourceStatus"`
BillingMode string `json:"billingMode"`
UsedCredits any `json:"usedCredits"`
TotalCredits any `json:"totalCredits"`
UsedTokens any `json:"usedTokens"`
TotalTokens any `json:"totalTokens"`
ExpiresAt any `json:"expiresAt"`
AutoRenew any `json:"autoRenew"`
}
// qianfanTime reads the console's time: RFC 3339, its "2006-01-02
// 15:04:05" in Beijing time, or seconds or milliseconds.
func qianfanTime(v any) (time.Time, bool) {
if s, ok := v.(string); ok {
s = strings.TrimSpace(s)
if t, err := time.Parse(time.RFC3339, s); err == nil {
return t, true
}
for _, layout := range []string{"2006-01-02 15:04:05", "2006-01-02T15:04:05", "2006-01-02"} {
if t, err := time.ParseInLocation(layout, s, time.FixedZone("CST", 8*3600)); err == nil {
return t, true
}
}
}
return stepfunTime(v)
}
var qianfanPlanNames = map[string]string{"mini": "Mini", "lite": "Lite", "pro": "Pro", "max": "Max"}
// readQianfanPlan is the console's resource result as a card's plan, the
// time it runs until, whether it renews then, and its month's window. The
// plan is the one Running, the latest to end of several; one Released or
// past its end is none, as the console reads it. A reply with no plan, or
// none whose used and total amounts are told, is an error: unknown, never
// none left.
func readQianfanPlan(raw []byte, now time.Time) (plan string, until *time.Time, renew string, w QuotaWindow, err error) {
var r struct {
Items []qianfanItem `json:"items"`
}
if json.Unmarshal(raw, &r) != nil {
return "", nil, "", w, fmt.Errorf("Baidu's console answered a plan magpie can't read: %s", volcHead(raw))
}
type held struct {
it qianfanItem
end time.Time
}
var live []held
for _, it := range r.Items {
end, ok := qianfanTime(it.ExpiresAt)
if strings.EqualFold(it.Status, "Released") || ok && !end.After(now) {
continue
}
live = append(live, held{it, end})
}
if len(live) == 0 {
return "", nil, "", w, errors.New("this Baidu Cloud account has no Token Plan Personal")
}
slices.SortStableFunc(live, func(a, b held) int {
ra, rb := strings.EqualFold(a.it.Status, "Running"), strings.EqualFold(b.it.Status, "Running")
if ra != rb {
if ra {
return -1
}
return 1
}
return b.end.Compare(a.end)
})
it, end := live[0].it, live[0].end
used, total, unit := it.UsedTokens, it.TotalTokens, "tokens"
if strings.EqualFold(it.BillingMode, "credit") {
used, total, unit = it.UsedCredits, it.TotalCredits, "credits"
}
u, uok := number(used)
l, lok := number(total)
if !uok || !lok || l <= 0 {
return "", nil, "", w, errors.New("Baidu's console told no quota for this Token Plan")
}
w = QuotaWindow{Name: "Month", Span: 30 * 24 * time.Hour, Amount: u, Limit: l, Unit: unit,
Used: max(0, min(100, u/l*100))}
plan = "Token Plan"
if n, ok := qianfanPlanNames[strings.ToLower(it.PlanType)]; ok {
plan += " " + n
}
if !end.IsZero() {
until = &end
// a month's plan: its quota is the month's, and ends with it
if end.Sub(now) <= 32*24*time.Hour {
w.ResetsAt = &end
}
}
switch v := it.AutoRenew.(type) {
case bool:
renew = map[bool]string{true: "auto", false: "off"}[v]
case string:
switch strings.ToLower(v) {
case "true", "1":
renew = "auto"
case "false", "0":
renew = "off"
}
}
return plan, until, renew, w, nil
}
// qianfanNow is the clock readQianfanPlan is read at, a var for tests.
var qianfanNow = time.Now
// qianfanPlanQuota is the provider's Token Plan Personal as a card, read
// with its sign-in.
func qianfanPlanQuota(ctx context.Context, p Provider) SubscriptionQuota {
q := SubscriptionQuota{Provider: p.ID, Name: p.Name, Icon: p.Icon, Plan: "Token Plan", Windows: []QuotaWindow{}}
s, ok := qianfanSignIn(p.ID)
if !ok {
q.Error = errQianfanSession.Error()
return q
}
raw, err := qianfanResource(ctx, s.Cookie)
if err != nil {
q.Error = err.Error()
return q
}
plan, until, renew, w, err := readQianfanPlan(raw, qianfanNow())
if err != nil {
q.Error = err.Error()
return q
}
q.Plan, q.Until, q.Renew = plan, until, renew
q.Windows = append(q.Windows, w)
return q
}
// qianfanPlanQuotas is a card for each Token Plan Personal provider in use
// that magpie has a sign-in for: one per provider, as two can be two
// accounts.
func qianfanPlanQuotas(ctx context.Context) []SubscriptionQuota {
var jobs []Provider
for _, p := range All() {
if p.Hidden || p.Off || !QianfanPlan(p) || !wantsCard(ctx, p.ID, "") || !QianfanSignedIn(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] = qianfanPlanQuota(p.Via(ctx), p)
if out[i].Error == "" {
// what routing goes by, read just now (KeyAllowance)
noteKeyAllowance(p, out[i].Windows, time.Now())
}
out[i] = keepReading(ctx, out[i], keyTag("qianfan", p.ID))
}()
}
wg.Wait()
return out
}
+229
View File
@@ -0,0 +1,229 @@
package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
)
// qianfanResourceBody is the console's tokenPlanPersonal/resource reply in
// the shape Baidu's console page reads it (its bundle's item mapping:
// planType, resourceStatus, billingMode "credit", usedCredits and
// totalCredits as the page's Number() takes them, expiresAt, autoRenew,
// apiKey), with an item Released beside the running one.
const qianfanResourceBody = `{"success":true,"status":200,"result":{"items":[` +
`{"resourceId":"tp-old","planType":"lite","resourceStatus":"Released","billingMode":"credit","usedCredits":"6600","totalCredits":"6600","expiresAt":"2026-10-01T00:00:00Z","autoRenew":false,"apiKey":"bce-v3/ALTAK-old/secret-old"},` +
`{"resourceId":"tp-1","planType":"pro","resourceStatus":"Running","billingMode":"credit","usedCredits":"11250.5","totalCredits":45000,"usedTokens":0,"totalTokens":0,"expiresAt":"2026-12-01T00:00:00Z","autoRenew":true,"renewTimeUnit":"month","renewTime":1,"apiKey":"bce-v3/ALTAK-live/secret-live"}]}}`
// fakeQianfanConsole is Baidu Cloud's console: it answers the plan's
// resource to its one session's cookies, asked as the page asks, and sends
// anything else to the sign-in page, as the real console does.
type fakeQianfanConsole struct {
srv *httptest.Server
cookie atomic.Value // the Cookie header it takes now
body atomic.Value
asked atomic.Int32
}
func newFakeQianfanConsole(t *testing.T) *fakeQianfanConsole {
t.Helper()
f := &fakeQianfanConsole{}
f.cookie.Store("BDUSS=bd-1; bce-session=s-1; bce-user-info=u-1")
f.body.Store(qianfanResourceBody)
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.asked.Add(1)
if r.Method != http.MethodGet || r.URL.Path != qianfanResourcePath || r.Header.Get("X-Requested-With") != "XMLHttpRequest" {
http.NotFound(w, r)
return
}
if r.Header.Get("Cookie") != f.cookie.Load().(string) {
http.Redirect(w, r, "https://login.bce.baidu.com/?redirect=x", http.StatusFound)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(f.body.Load().(string)))
}))
t.Cleanup(f.srv.Close)
old := qianfanConsole
qianfanConsole = f.srv.URL
t.Cleanup(func() { qianfanConsole = old })
oldNow := qianfanNow
qianfanNow = func() time.Time { return time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) }
t.Cleanup(func() { qianfanNow = oldNow })
return f
}
func TestQianfanPlan(t *testing.T) {
for base, want := range map[string]bool{
"https://qianfan.baidubce.com/v2/tokenplan/personal": true,
"https://qianfan.baidubce.com/anthropic/tokenplan/personal": true,
"https://qianfan.baidubce.com/v2/tokenplan/team": false,
"https://qianfan.baidubce.com/v2": false,
"https://example.com/v2/tokenplan/personal": false,
} {
if got := QianfanPlan(Provider{Chat: base}); got != want {
t.Errorf("%s: %v, want %v", base, got, want)
}
}
p := Provider{ID: "baidu-qianfan", Key: "bce-v3/k", Chat: "https://qianfan.baidubce.com/v2/tokenplan/personal"}
if got := accountPlanOf(p); got != "qianfan" {
t.Errorf("accountPlanOf: %q, want qianfan", got)
}
}
// The running plan's month: what it used of its credits (or tokens, a
// token plan's), named as the console names it, to its end. A plan
// Released or past its end is none; a reply with no plan, or without the
// amounts, is an error and never a window with nothing left.
func TestReadQianfanPlan(t *testing.T) {
now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
var r struct{ Result json.RawMessage }
if err := json.Unmarshal([]byte(qianfanResourceBody), &r); err != nil {
t.Fatal(err)
}
plan, until, renew, w, err := readQianfanPlan(r.Result, now)
end := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)
if err != nil || plan != "Token Plan Pro" || renew != "auto" || until == nil || !until.Equal(end) {
t.Fatalf("%q %v %q %v", plan, until, renew, err)
}
if w.Name != "Month" || w.Unit != "credits" || w.Amount != 11250.5 || w.Limit != 45000 || w.Used < 24.99 || w.Used > 25.01 || w.ResetsAt == nil || !w.ResetsAt.Equal(end) {
t.Fatalf("window: %+v", w)
}
// a token plan, its end in the console's own "2006-01-02 15:04:05",
// Beijing time
_, until, renew, w, err = readQianfanPlan([]byte(`{"items":[{"planType":"max","resourceStatus":"Running","billingMode":"token","usedTokens":70000000,"totalTokens":700000000,"expiresAt":"2026-12-01 00:00:00","autoRenew":false}]}`), now)
if err != nil || w.Unit != "tokens" || w.Used < 9.99 || w.Used > 10.01 || renew != "off" || until == nil || !until.Equal(time.Date(2026, 11, 30, 16, 0, 0, 0, time.UTC)) {
t.Fatalf("token plan: %+v %v %q %v", w, until, renew, err)
}
for name, body := range map[string]string{
"no plan": `{"items":[]}`,
"released": `{"items":[{"planType":"pro","resourceStatus":"Released","billingMode":"credit","usedCredits":0,"totalCredits":45000,"expiresAt":"2026-12-01T00:00:00Z"}]}`,
"past its end": `{"items":[{"planType":"pro","resourceStatus":"Running","billingMode":"credit","usedCredits":0,"totalCredits":45000,"expiresAt":"2026-11-01T00:00:00Z"}]}`,
"no amounts": `{"items":[{"planType":"pro","resourceStatus":"Running","billingMode":"credit","expiresAt":"2026-12-01T00:00:00Z"}]}`,
"no total": `{"items":[{"planType":"pro","resourceStatus":"Running","billingMode":"credit","usedCredits":"5","totalCredits":"0","expiresAt":"2026-12-01T00:00:00Z"}]}`,
"not JSON": `<html>`,
} {
if _, _, _, w, err := readQianfanPlan([]byte(body), now); err == nil || w.Limit != 0 || w.Used != 0 {
t.Errorf("%s: %+v %v, want an error", name, w, err)
}
}
}
// What the user pastes: the bookmarklet's copy, the Cookie header as
// developer tools show it, or the request copied as cURL; the console is
// asked with it before it is kept, and anything else is refused with
// nothing kept.
func TestSaveQianfanPaste(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
f := newFakeQianfanConsole(t)
ctx := context.Background()
cookie := f.cookie.Load().(string)
for _, bad := range []string{
"",
"hello",
qianfanPaste + "{",
"BDUSS=other; bce-session=gone", // the console sends it to sign in
"Cookie: BDUSS=bd-1\r\nX-Evil: 1",
} {
if err := SaveQianfanPaste(ctx, "baidu-qianfan", bad); err == nil {
t.Errorf("%q was kept", bad)
}
if QianfanSignedIn("baidu-qianfan") {
t.Fatalf("%q signed in", bad)
}
}
if err := SaveQianfanPaste(ctx, "baidu-qianfan", "BDUSS=other"); err == nil || !strings.Contains(err.Error(), "developer tools") {
t.Errorf("a refused bookmarklet copy should say where the whole cookie is: %v", err)
}
copied, _ := json.Marshal(map[string]string{"cookie": cookie})
for _, good := range []string{
qianfanPaste + string(copied),
"Cookie: " + cookie,
"cookie: " + cookie + "\n",
cookie,
`curl 'https://console.bce.baidu.com/api/qianfan/charge/tokenPlanPersonal/resource' -H 'accept: application/json' -b '` + cookie + `' -H 'x-requested-with: XMLHttpRequest'`,
`curl 'https://console.bce.baidu.com/api/qianfan/charge/tokenPlanPersonal/resource' -H 'Cookie: ` + cookie + `'`,
} {
if err := SignOutQianfan("baidu-qianfan"); err != nil {
t.Fatal(err)
}
if err := SaveQianfanPaste(ctx, "baidu-qianfan", good); err != nil || !QianfanSignedIn("baidu-qianfan") {
t.Fatalf("%.40q: %v", good, err)
}
if got := loadQianfan()["baidu-qianfan"].Cookie; got != cookie {
t.Fatalf("%.40q kept %q", good, got)
}
}
if fi, err := os.Stat(qianfanPath()); err != nil || runtime.GOOS != "windows" && fi.Mode().Perm() != 0o600 {
t.Fatalf("session file: %v %v", fi, err)
}
// the plan's own key, in the console's reply, is never kept
if b, _ := os.ReadFile(qianfanPath()); strings.Contains(string(b), "bce-v3") || strings.Contains(string(b), "secret") {
t.Fatalf("the plan's key was kept: %s", b)
}
}
// The card is read with the provider's own sign-in. A session the console
// sends to sign in again is told as that, with no window: unknown, never
// nothing left.
func TestQianfanPlanCard(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
forgetPlanQuotas()
f := newFakeQianfanConsole(t)
ctx := context.Background()
p := Provider{ID: "baidu-qianfan", Name: "Baidu Qianfan", Icon: "baiducloud-color", Key: "bce-v3/k", Chat: "https://qianfan.baidubce.com/v2/tokenplan/personal"}
if q := qianfanPlanQuota(ctx, p); q.Error == "" || len(q.Windows) != 0 {
t.Fatalf("no sign-in: %+v", q)
}
if err := SaveQianfanPaste(ctx, p.ID, f.cookie.Load().(string)); err != nil {
t.Fatal(err)
}
q := qianfanPlanQuota(ctx, p)
if q.Error != "" || q.Plan != "Token Plan Pro" || q.Renew != "auto" || q.Until == nil || len(q.Windows) != 1 || q.Windows[0].Limit != 45000 {
t.Fatalf("card: %+v", q)
}
if b, _ := json.Marshal(q); strings.Contains(string(b), "bce-v3") || strings.Contains(string(b), "secret") {
t.Fatalf("the plan's key reached the card: %s", b)
}
kr, err := accountPlanWindows(ctx, p)
if err != nil || len(kr.ws) != 1 || kr.plan != "Token Plan Pro" {
t.Fatalf("routing's reading: %+v %v", kr, err)
}
// Baidu ends the session: the console answers with its sign-in page
f.cookie.Store("BDUSS=new-one")
q = qianfanPlanQuota(ctx, p)
if q.Error != errQianfanSession.Error() || len(q.Windows) != 0 {
t.Fatalf("session ended: %+v", q)
}
if _, err := accountPlanWindows(ctx, p); err == nil {
t.Fatal("routing read an ended session as a reading")
}
// the console answers, but not success
f.cookie.Store(loadQianfan()[p.ID].Cookie)
f.body.Store(`{"success":false,"message":{"global":"系统繁忙"}}`)
if q := qianfanPlanQuota(ctx, p); !strings.Contains(q.Error, "系统繁忙") || len(q.Windows) != 0 {
t.Fatalf("refused: %+v", q)
}
// the sign-in goes with the provider's id, and with the provider
if err := renameQianfan(p.ID, "qf2"); err != nil || QianfanSignedIn(p.ID) || !QianfanSignedIn("qf2") {
t.Fatalf("renamed: %v", err)
}
if err := forgetQianfan("qf2"); err != nil || QianfanSignedIn("qf2") {
t.Fatalf("forgotten: %v", err)
}
}
+5 -1
View File
@@ -101,13 +101,17 @@ func Rename(from, to string) error {
if err := store(f); err != nil {
return err
}
// so are its StepFun and Qwen AI platform sign-ins, kept by provider id
// so are its StepFun, Qwen AI platform and Baidu Cloud console
// sign-ins, kept by provider id
if err := renameStepFun(from, to); err != nil {
return err
}
if err := renameQianwen(from, to); err != nil {
return err
}
if err := renameQianfan(from, to); err != nil {
return err
}
s := settings.Load()
changed := renameModelPrefs(&s, from, to)
for a, names := range s.Visible {
+1
View File
@@ -18,6 +18,7 @@ func TestUnreadStateKeptAside(t *testing.T) {
write func()
}{
{"stepfun-auth.json", stepfunPath, func() { saveStepFun(map[string]stepfunSession{"cn": {}}) }},
{"qianfan-auth.json", qianfanPath, func() { saveQianfan(map[string]qianfanSession{"baidu-qianfan": {}}) }},
{"login-returns.json", loginReturnsPath, func() { setLoginReturn("codex", loginReturn{Back: "a", To: "b"}) }},
{"quota-history.json", quotaHistPath, func() { writeQuotaHist(quotaHist{}) }},
{"balance-history.json", balanceHistPath, func() { writeBalanceHist(balanceHist{}) }},