plan: a Mistral Studio key shows the organization's API month, not the Vibe month (dhanyqaz on Discord)

8216592a8 (v0.1.3109) read vibe_budget from api.mistral.ai/v1/billing/budget
for every key on api.mistral.ai. That budget is the organization's, not the
key's: a Vibe key and a Studio key made in the console of one organization
are told the same body, so dhanyqaz's Studio key (Student plan) showed the
Vibe month, 149.36 / 150, and "All 2 accounts" added the two into 298.72 /
300.

Which budget a key spends is its kind. Mistral's Vibe CLI asks
console.mistral.ai/api/vibe/whoami (plan_type CHAT, API or MISTRAL_CODE,
vibe/setup/auth/whoami.py at mistralai/mistral-vibe c96a6db) and reads the
Vibe budget of a CHAT key only (_account.py). magpie now asks whoami once a
key (kept by the key's hash): a Vibe key keeps vibe_budget as "Month"; a
Studio key gets the same body's api_budget (Vibe's own fixture in
tests/app_server/test_billing.py, "Producer: dashboard billing_api_public")
as "API · Month", Aside while the subscription's payg_enabled is on (Vibe's
uses vibe_payg_enabled). The names differ, so the accounts' strip never adds
a Studio month to a Vibe month. A key whoami can't place (a failed read, no
plan_type, Mistral Code) has no card read: the org's budget alone doesn't
say which of its two it spends. The unit stays the currency billing names
(dhanyqaz's USD came from the reply, as nothing in magpie writes USD for
Mistral); none when it names none. Only api.mistral.ai keys are touched;
every other plan source takes the same path as before.

Run (mote): go test ./internal/provider (whole package, ok);
go vet ./internal/provider ./internal/gui, GOOS=linux -tags nogui and
GOOS=windows vet; gofmt -l clean; usage-merge, i18n-keys, i18n-en-no-cjk,
gui-de, gui-ja, gui-zh-tw in Chromium and WebKit, all ok but
i18n-keys' "a plugin's words are its own", red the same on origin/main
0f07fbd0c (#5327, #5332, #5426; this change adds no plugin words).
Broken by hand: with readMistralBudget reading vibe_budget whatever the
kind, TestMistralStudioBudget goes red (the Studio window is 0.65 / 150
USD, Aside from the wrong flag, the same name as the Vibe month).
Not tried: a real Studio or Vibe key; none at hand. whoami's and
api_budget's shapes are Vibe's own code and fixtures, not a reply seen;
console.mistral.ai answers 401 to a bad key on any /api path, so the probe
doesn't prove the route. Two Vibe keys of one organization would still
each show the org's month and add up on the strip.

Reported-by: dhanyqaz
This commit is contained in:
yetone
2026-11-06 13:52:28 +08:00
parent 0f07fbd0c6
commit 1c45645b59
5 changed files with 252 additions and 31 deletions
File diff suppressed because one or more lines are too long
+4
View File
@@ -4376,6 +4376,7 @@ const I18N = {
"questions": "次提问",
"videos": "个视频",
"Video · 24 hours": "视频 · 24 小时",
"API · Month": "API · 本月",
"Video · 7 days": "视频 · 7 天",
// agents' advice after a change (NOTICES)
"Ante reads its catalog at start-up — restart open ante sessions to use this.": "Ante 启动时读取模型目录,需重启已打开的 ante 会话才会生效。",
@@ -8998,6 +8999,7 @@ const I18N = {
"A new provider with {name}'s project, credentials, headers and models, to change before adding": "新建供應商,沿用 {name} 的專案、憑據、請求頭和模型,新增前可修改",
"videos": "個影片",
"Video · 24 hours": "影片 · 24 小時",
"API · Month": "API · 本月",
"Video · 7 days": "影片 · 7 天",
// agents' advice after a change (NOTICES)
"Ante reads its catalog at start-up — restart open ante sessions to use this.": "Ante 啟動時讀取模型目錄,需重啟已打開的 ante 會話才會生效。",
@@ -13601,6 +13603,7 @@ const I18N = {
"questions": "件の質問",
"videos": "本",
"Video · 24 hours": "動画 · 24 時間",
"API · Month": "API · 今月",
"Video · 7 days": "動画 · 7 日",
"Menu bar magpie icon": "メニューバーの magpie アイコン",
"Pace {n}": "ペース {n}",
@@ -18238,6 +18241,7 @@ const I18N = {
"questions": "Fragen",
"videos": "Videos",
"Video · 24 hours": "Video · 24 Stunden",
"API · Month": "API · Monat",
"Video · 7 days": "Video · 7 Tage",
"Discard unsaved changes? Your changes will be lost.": "Nicht gespeicherte Änderungen verwerfen? Ihre Änderungen gehen verloren.",
"This removes the selected item. Continue?": "Das ausgewählte Element wird entfernt. Fortfahren?",
+16
View File
@@ -142,3 +142,19 @@ test("a window held by a longer one used up counts as nothing left", () => {
], now);
assert.deepEqual(by(c, "Credits").map((w) => [w.amount, w.limit, w.held]), [[600, 1000, 1]]);
});
test("a Mistral Studio month never adds up with a Vibe month (dhanyqaz on Discord)", () => {
// the two keys of one Student organization, as magpie reads them: the
// Vibe key's vibe_budget and the Studio key's api_budget, both in USD
const mistral = (user, w) => ({ provider: "mistral", name: "Mistral", user, plan: "Student", windows: [w] });
const r = merge([
mistral("Vibe", { name: "Month", amount: 0.64, limit: 150, unit: "USD", used: 0.43 }),
mistral("Studio", { name: "API · Month", amount: 3, limit: 15, unit: "USD", used: 20 }),
], now);
assert.deepEqual(r.windows, [], "no 'All 2 accounts' figure of 165 USD");
const two = merge([
mistral("Vibe", { name: "Month", amount: 0.64, limit: 150, unit: "USD", used: 0.43 }),
mistral("Vibe 2", { name: "Month", amount: 15, limit: 150, unit: "USD", used: 10 }),
], now);
assert.equal(by(two, "Month")[0].limit, 300, "two Vibe months still add up");
});
+96 -23
View File
@@ -2,8 +2,11 @@ package provider
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"strings"
"sync"
"time"
)
@@ -14,9 +17,19 @@ import (
// _account.py): GET /v1/billing/budget for the month's budget, and
// GET /v1/billing/subscription for the plan it is on (dhanyqaz on Discord,
// a Student plan). Le Chat's own message limits are told nowhere.
//
// The budget is the organization's, not the key's: every key of one
// organization is told the same vibe_budget and api_budget. Which of them a
// key spends is the key's kind, which console.mistral.ai's /api/vibe/whoami
// tells (plan_type "chat" for a Vibe key, "api" for a Studio key made in the
// console, "mistral_code"), as Vibe reads it (vibe/setup/auth/whoami.py) and
// reads the budget only of a chat key (_account.py). Reading vibe_budget for
// every key showed a Studio key the Vibe month (dhanyqaz on Discord: 149.36
// of 150 on both cards, and 298.72 of 300 for the two together).
const (
mistralBudgetURL = "https://api.mistral.ai/v1/billing/budget"
mistralSubscriptionURL = "https://api.mistral.ai/v1/billing/subscription"
mistralWhoamiURL = "https://console.mistral.ai/api/vibe/whoami"
)
// mistralPlanTitles are the plans billing names, as Vibe titles them.
@@ -29,41 +42,86 @@ var mistralPlanTitles = map[string]string{
// mistralBudget: {"vibe_budget":{"usage_percentage":42.5,
// "initial_budget":300.0,"currency":"EUR","reset_at":"2026-11-01T00:00:00Z",
// "payg_enabled":false},"api_budget":{…}}
// "payg_enabled":false},"api_budget":{"usage_percentage":3.0,
// "initial_budget":50.0,"currency":"EUR","reset_at":"2026-11-01T00:00:00Z"}}
type mistralBudget struct {
Vibe *struct {
UsagePercentage float64 `json:"usage_percentage"`
InitialBudget float64 `json:"initial_budget"`
Currency string `json:"currency"`
ResetAt string `json:"reset_at"`
PaygEnabled *bool `json:"payg_enabled"`
} `json:"vibe_budget"`
Vibe *mistralBudgetDetail `json:"vibe_budget"`
API *mistralBudgetDetail `json:"api_budget"`
}
type mistralBudgetDetail struct {
UsagePercentage float64 `json:"usage_percentage"`
InitialBudget float64 `json:"initial_budget"`
Currency string `json:"currency"`
ResetAt string `json:"reset_at"`
PaygEnabled *bool `json:"payg_enabled"`
}
// mistralSubscription: {"plan_name":"INDIVIDUAL","payg_enabled":true,
// "vibe_payg_enabled":true,"enterprise":false}
type mistralSubscription struct {
PlanName string `json:"plan_name"`
PaygEnabled *bool `json:"payg_enabled"`
VibePaygEnabled *bool `json:"vibe_payg_enabled"`
}
// readMistralBudget is a Mistral key's Vibe month: what share of the
// budget is used, in the budget's currency, and when it resets. A key with
// no Vibe budget (a la Plateforme key, or none in its plan) has no
// windows, and no card. With pay-as-you-go on (the budget's own, else
// payg, the subscription's), what goes past the budget is billed rather
// than stopped, so the window doesn't stop the models.
func readMistralBudget(b []byte, payg *bool) ([]QuotaWindow, error) {
// The kinds of key whoami tells, lower-cased as Vibe reads them.
const (
mistralChatKey = "chat"
mistralAPIKey = "api"
)
// mistralKeyKinds: what whoami said of a key, by its hash; a key's kind
// doesn't change, so it is asked once.
var mistralKeyKinds sync.Map
// mistralKeyKind is the key's plan_type, asked of whoami; a reply that
// can't be read is an error, never a kind.
func mistralKeyKind(ctx context.Context, key string) (string, error) {
h := sha256.Sum256([]byte(key))
if k, ok := mistralKeyKinds.Load(h); ok {
return k.(string), nil
}
b, err := planBody(ctx, planQuotaSource{url: mistralWhoamiURL, bearer: true}, key)
if err != nil {
return "", err
}
var r struct {
PlanType *string `json:"plan_type"`
}
if err := json.Unmarshal(b, &r); err != nil || r.PlanType == nil {
return "", fmt.Errorf("mistral whoami: no plan_type in its reply")
}
k := strings.ToLower(strings.TrimSpace(*r.PlanType))
mistralKeyKinds.Store(h, k)
return k, nil
}
// readMistralBudget is a Mistral key's month: what share of the budget
// its kind spends is used (vibe_budget for a Vibe key, api_budget for a
// Studio key), in the currency billing names, and when it resets. A
// budget billing doesn't name, or of 0, has no windows, and no card; a
// currency it doesn't name is left unsaid rather than guessed. With
// pay-as-you-go on (the budget's own, else payg, the subscription's),
// what goes past the budget is billed rather than stopped, so the window
// doesn't stop the models. The Studio month is "API · Month", so the
// accounts' strip never adds it to a Vibe month.
func readMistralBudget(b []byte, kind string, payg *bool) ([]QuotaWindow, error) {
var r mistralBudget
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
v := r.Vibe
v, name := r.Vibe, "Month"
if kind == mistralAPIKey {
v, name = r.API, "API · Month"
} else if kind != mistralChatKey {
v = nil
}
if v == nil || v.InitialBudget <= 0 {
return []QuotaWindow{}, nil
}
used := max(0, v.UsagePercentage)
w := QuotaWindow{Name: "Month", Used: min(100, used), Limit: v.InitialBudget,
w := QuotaWindow{Name: name, Used: min(100, used), Limit: v.InitialBudget,
Amount: v.InitialBudget * used / 100, Unit: strings.ToUpper(strings.TrimSpace(v.Currency))}
if t, err := time.Parse(time.RFC3339, v.ResetAt); err == nil {
w.ResetsAt = &t
@@ -76,26 +134,41 @@ func readMistralBudget(b []byte, payg *bool) ([]QuotaWindow, error) {
return []QuotaWindow{w}, nil
}
// readMistralPlan is the source's reader without a key to ask whoami
// with: it tells no window, since which budget a key spends is the key's.
func readMistralPlan(b []byte) (string, []QuotaWindow, error) {
ws, err := readMistralBudget(b, nil)
ws, err := readMistralBudget(b, "", nil)
return "", ws, err
}
// mistralKeyWindows is readMistralBudget's window with the plan it is on,
// asked only of a key that has a budget; the card stands without its
// name when billing/subscription can't be read.
// mistralKeyWindows is readMistralBudget's window for the key's kind, with
// the plan it is on, asked only of a key that has a budget; the card
// stands without its name when billing/subscription can't be read. A key
// whose kind whoami doesn't tell has no card read: the organization's
// budget alone doesn't say which of its two it spends.
func mistralKeyWindows(ctx context.Context, src planQuotaSource, key string) (string, []QuotaWindow, error) {
kind, err := mistralKeyKind(ctx, key)
if err != nil {
return "", nil, err
}
if kind != mistralChatKey && kind != mistralAPIKey {
return "", []QuotaWindow{}, nil
}
b, err := planBody(ctx, src, key)
if err != nil {
return "", nil, err
}
ws, err := readMistralBudget(b, nil)
ws, err := readMistralBudget(b, kind, nil)
if err != nil || len(ws) == 0 {
return "", ws, err
}
var sub mistralSubscription
if sb, err := planBody(ctx, planQuotaSource{url: mistralSubscriptionURL, bearer: true}, key); err == nil && json.Unmarshal(sb, &sub) == nil {
ws, _ = readMistralBudget(b, sub.VibePaygEnabled)
payg := sub.VibePaygEnabled
if kind == mistralAPIKey {
payg = sub.PaygEnabled
}
ws, _ = readMistralBudget(b, kind, payg)
}
name := strings.ToUpper(strings.TrimSpace(sub.PlanName))
plan := mistralPlanTitles[name]
+135 -7
View File
@@ -2,6 +2,7 @@ package provider
import (
"context"
"crypto/sha256"
"crypto/tls"
"net"
"net/http"
@@ -22,11 +23,14 @@ func TestMistralVibeBudget(t *testing.T) {
body string
}
var budget, sub reply
who := reply{200, `{"plan_type":"CHAT","plan_name":"EDU","prompt_switching_to_pro_plan":false}`}
var auths []string
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auths = append(auths, r.Host+" "+r.Header.Get("Authorization"))
var rep reply
switch r.URL.Path {
case "/api/vibe/whoami":
rep = who
case "/v1/billing/budget":
rep = budget
case "/v1/billing/subscription":
@@ -60,6 +64,8 @@ func TestMistralVibeBudget(t *testing.T) {
plan, ws, _, err := planKeyWindows(context.Background(), p, src, p.Key)
return plan, ws, err
}
mistralKeyKinds.Clear()
t.Cleanup(mistralKeyKinds.Clear)
const vibe = `{"vibe_budget":{"usage_percentage":42.5,"initial_budget":300.0,"currency":"EUR","reset_at":"2026-11-01T00:00:00Z","payg_enabled":false},"api_budget":{"usage_percentage":3.0,"initial_budget":50.0,"currency":"EUR","reset_at":"2026-11-01T00:00:00Z"}}`
budget = reply{200, vibe}
@@ -76,13 +82,9 @@ func TestMistralVibeBudget(t *testing.T) {
if w.Aside {
t.Error("the budget's own payg_enabled false is the window's, over the subscription's")
}
for _, a := range auths {
if a != "api.mistral.ai Bearer vibe-key" {
t.Errorf("asked %q, want api.mistral.ai with the key as a Bearer", a)
}
}
if len(auths) != 2 {
t.Errorf("asked %d times, want the budget and the subscription", len(auths))
want := []string{"console.mistral.ai Bearer vibe-key", "api.mistral.ai Bearer vibe-key", "api.mistral.ai Bearer vibe-key"}
if strings.Join(auths, "|") != strings.Join(want, "|") {
t.Errorf("asked %q, want whoami at the console, then the budget and the subscription, the key as a Bearer", auths)
}
// pay-as-you-go the subscription's alone: billed past the budget
@@ -101,6 +103,7 @@ func TestMistralVibeBudget(t *testing.T) {
// a key with no Vibe budget: no windows, so no card, and nothing more asked
for _, body := range []string{`{"vibe_budget":null,"api_budget":{"usage_percentage":3,"initial_budget":50}}`, `{"vibe_budget":{"usage_percentage":0,"initial_budget":0}}`, `{}`} {
budget = reply{200, body}
// whoami is asked once a key
if _, ws, err := read(); err != nil || len(ws) != 0 || len(auths) != 1 {
t.Errorf("%s: %+v %v, asked %d", body, ws, err, len(auths))
}
@@ -116,3 +119,128 @@ func TestMistralVibeBudget(t *testing.T) {
t.Errorf("a member without the permission: %+v %v, want an error, and no card from it unless one was read", ws, err)
}
}
// A Studio key (made in console.mistral.ai, whoami's plan_type "API") of
// the same organization is told the same budget body as its Vibe key, and
// spends the api_budget, not the Vibe month (dhanyqaz on Discord: the
// Studio card showed 149.36 / 150 USD, the Vibe key's, on a Student plan
// whose Studio month is 15). Its window is "API · Month", in the
// currency billing names, and never adds up with a Vibe month; a key
// whoami can't place has no card read, and Mistral Code's key none.
func TestMistralStudioBudget(t *testing.T) {
type reply struct {
status int
body string
}
// one organization's budget, as dhanyqaz's two keys are told it
const budget = `{"vibe_budget":{"usage_percentage":0.43,"initial_budget":150.0,"currency":"USD","reset_at":"2026-12-01T00:00:00Z","payg_enabled":false},"api_budget":{"usage_percentage":20.0,"initial_budget":15.0,"currency":"USD","reset_at":"2026-12-01T00:00:00Z"}}`
whos := map[string]reply{
"Bearer vibe-key": {200, `{"plan_type":"CHAT","plan_name":"EDU"}`},
"Bearer studio-key": {200, `{"plan_type":"API","plan_name":"FREE","primitive_access_scope":"personal_and_shared"}`},
"Bearer code-key": {200, `{"plan_type":"MISTRAL_CODE","plan_name":"E"}`},
"Bearer odd-key": {200, `{"plan_name":"EDU"}`},
"Bearer down-key": {502, `{"message":"Bad Gateway"}`},
}
sub := reply{200, `{"plan_name":"EDU","payg_enabled":true,"vibe_payg_enabled":false,"enterprise":false}`}
var asked []string
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asked = append(asked, r.URL.Path)
var rep reply
switch r.URL.Path {
case "/api/vibe/whoami":
rep = whos[r.Header.Get("Authorization")]
case "/v1/billing/budget":
rep = reply{200, budget}
case "/v1/billing/subscription":
rep = sub
default:
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(rep.status)
w.Write([]byte(rep.body))
}))
t.Cleanup(srv.Close)
addr := srv.Listener.Addr().String()
old := http.DefaultClient.Transport
http.DefaultClient.Transport = &http.Transport{
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, network, addr)
},
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
t.Cleanup(func() { http.DefaultClient.Transport = old })
mistralKeyKinds.Clear()
t.Cleanup(mistralKeyKinds.Clear)
read := func(key string) (string, []QuotaWindow, error) {
asked = nil
p := Provider{ID: "mistral", Chat: "https://api.mistral.ai/v1", Key: key}
src, _ := planQuotaSourceOf(p)
plan, ws, _, err := planKeyWindows(context.Background(), p, src, key)
return plan, ws, err
}
plan, vibe, err := read("vibe-key")
if err != nil || plan != "Student" || len(vibe) != 1 {
t.Fatalf("vibe key: %q %+v %v", plan, vibe, err)
}
if w := vibe[0]; w.Name != "Month" || w.Limit != 150 || w.Unit != "USD" || w.Aside {
t.Errorf("vibe key's window: %+v", w)
}
plan, studio, err := read("studio-key")
if err != nil || plan != "Student" || len(studio) != 1 {
t.Fatalf("studio key: %q %+v %v", plan, studio, err)
}
w := studio[0]
if w.Name != "API · Month" || w.Limit != 15 || w.Used != 20 || w.Amount != 3 || w.Unit != "USD" || w.Count(false) != "3 / 15 USD" {
t.Errorf("studio key's window: %+v (%s), want the api_budget, 3 / 15 USD", w, w.Count(false))
}
if !w.Aside {
t.Error("the organization's payg_enabled is the Studio month's, not vibe_payg_enabled")
}
if w.Name == vibe[0].Name {
t.Error("a Studio month named as the Vibe month adds up with it on the accounts' strip")
}
// whoami asked once a key
if _, _, _ = read("studio-key"); strings.Join(asked, " ") != "/v1/billing/budget /v1/billing/subscription" {
t.Errorf("read again, asked %q, want no second whoami", asked)
}
// the currency billing names, else none: never one magpie picked
for _, c := range []struct{ body, unit string }{
{`"currency":"EUR"`, "EUR"}, {`"currency":" eur "`, "EUR"}, {`"currency":""`, ""}, {`"x":1`, ""},
} {
b := `{"api_budget":{"usage_percentage":10,"initial_budget":15,` + c.body + `}}`
ws, err := readMistralBudget([]byte(b), mistralAPIKey, nil)
if err != nil || len(ws) != 1 || ws[0].Unit != c.unit {
t.Errorf("%s: %+v %v, want unit %q", b, ws, err, c.unit)
}
}
// no api_budget, or none of it: no card, as a Vibe key with none
for _, b := range []string{`{"vibe_budget":{"usage_percentage":1,"initial_budget":150}}`, `{"vibe_budget":{"usage_percentage":1,"initial_budget":150},"api_budget":{"usage_percentage":0,"initial_budget":0}}`} {
if ws, err := readMistralBudget([]byte(b), mistralAPIKey, nil); err != nil || len(ws) != 0 {
t.Errorf("%s: %+v %v, want no windows", b, ws, err)
}
}
// Mistral Code's key, and a reply with no plan_type: no card
for _, key := range []string{"code-key", "odd-key"} {
if _, ws, _ := read(key); len(ws) != 0 {
t.Errorf("%s: %+v, want no windows", key, ws)
}
}
if _, _, err := read("odd-key"); err == nil {
t.Error("whoami with no plan_type: want an error, not a kind")
}
// whoami down: unknown, so an error and no budget asked
if _, ws, err := read("down-key"); err == nil || len(ws) != 0 || strings.Join(asked, " ") != "/api/vibe/whoami" {
t.Errorf("whoami down: %+v %v, asked %q", ws, err, asked)
}
if _, ok := mistralKeyKinds.Load(sha256.Sum256([]byte("down-key"))); ok {
t.Error("a failed whoami was kept as the key's kind")
}
}