Files
magpie/internal/provider/codex_usage_words.go
T
yetone b0174e7615 usage: a ChatGPT card says why its allowance can't be read, and a ChatGPT API account says where it shows
hmy on Discord: five ChatGPT accounts each said only "暂时无法获取额度"
(Allowance unavailable). danzi002 on Discord: accounts added through the
API never show usage, ones added as ChatGPT do.

What changed:
- Codex's usage read (codexWindows) now words its failure
  (codex_usage_words.go): a Cloudflare challenge names the proxy/VPN
  address as the usual cause; any other HTTP answer names its status and
  what ChatGPT said; a network error says chatgpt.com couldn't be
  reached; a reply magpie can't decode says so. The error still unwraps
  to accountStatusError, so expiry and passing logic is unchanged.
- A ChatGPT API account (chatgpt-api) was read as a Codex account: a
  saved one said "chatgpt-api accounts can't be used side by side", the
  one in use read Codex's own sign-in ("Codex is signed out", or another
  account's allowance under its name). OpenAI's API tells no plan usage,
  so its row now says so, names chatgpt.com/settings/usage (SeeAt) and
  says the same account added as ChatGPT shows it here.
- GUI quotaError translates each of these (en, zh, zh-TW, ja, de), and
  "not read yet" (errNotAsked) gets its own words. The generic fallback
  now reads "Allowance unavailable — hover for why"; the row's tooltip
  has always been the raw error. Comments in app.js were shortened to
  stay under TestCoreScriptBudget, which is not raised.
- docs/subsystems/providers-accounts.md describes the words.

Endpoint: the real wham/usage read of the owner's accounts in a sandbox
HOME copy (read-only, ~/.codex untouched) answered 200 and parsed, so
the endpoint itself is not broken; the "error decoding response body"
work is another session's and is not touched here.

Run (on mote; provider and gui again at the pushed head, rebased on
18c69aa46; 2251ca1ce, new under it, changed app.js and the budget):
- gofmt -l clean; GOOS=linux -tags nogui and GOOS=windows go vet of
  provider and gui clean.
- go test -timeout 45m ./...: ok except TestEveryRouteHasACommandOrIsNamed
  (#4826, red on origin/main 2251ca1ce too), TestMainWindowCorners (#3949,
  red on main too) and TestCodexPoolSaysTheClientsVersion (#4807, red in
  the full run, ok alone here and on main). At the pushed head:
  provider ok, gui ok but TestMainWindowCorners (#3949), core budget ok.
- GUI: chatgpt-usage-why.test.cjs (new; chromium and webkit, 560 and
  390, en/zh/zh-TW/ja/de, each row's words, its status code, the raw
  tooltip, no overflow) and the six tests whose generic line changed.
  The whole GUI suite was not run before this push: another session's
  full suite held mote. The change adds no API call and no layout, only
  words; the whole suite runs after the push and its reds get issues.

Broken by hand:
- codexWindows returning the bare err: TestCodexUsageSaysWhy and
  TestCodexLoginUsageSaysCloudflare red.
- the GUI ChatGPT patterns removed: chatgpt-usage-why 0/2.
- the chatgpt-api branch off: TestChatGPTAPIUsageSaysWhere red, the
  row read "Codex is signed out; run codex login".

Not tried: a real Cloudflare challenge (the fixture is the start of its
page as Cloudflare serves it, not hmy's bytes, which magpie hasn't got); a real ChatGPT API account (none signed in here); making a
ChatGPT API account's usage readable, since its token is for
api.openai.com and OpenAI shows plan usage only on chatgpt.com.
2026-11-02 20:04:32 +08:00

126 lines
4.4 KiB
Go

package provider
// Why a ChatGPT account's usage read failed, in words the account's row
// can say (hmy on Discord: five ChatGPT accounts in use, each saying only
// "Allowance unavailable"). The read's error used to be Go's: the bare
// status text ("Forbidden", "Unauthorized"), a JSON decode error, or a
// transport error naming the URL. The GUI read none of them, so the card
// said nothing it could act on, and why was in a tooltip at best.
//
// The words keep what the old ones were matched for: the status text
// (passing in quota_last.go, keeping the last reading over a 429 or a
// 5xx), a transport error's own words ("timeout", "connection refused"),
// and the vendor's answer itself (codexExpired, codexRevoked), which
// errors.As still finds through Unwrap.
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
)
// codexUsageFailed is a failed /wham/usage read: err as it was, and the
// words it is said in.
type codexUsageFailed struct {
err error
words string
}
func (e *codexUsageFailed) Error() string { return e.words }
func (e *codexUsageFailed) Unwrap() error { return e.err }
// codexUsageWords is err, a failed /wham/usage read, with words that say
// why. A read held back (allowances read only when asked) is left as it
// is: it isn't a failure, and readDeferred knows its words.
func codexUsageWords(err error) error {
if err == nil || errors.Is(err, errNotAsked) || strings.Contains(err.Error(), errNotAsked.Error()) {
return err
}
var se *accountStatusError
var ue *url.Error
var syn *json.SyntaxError
var te *json.UnmarshalTypeError
switch {
case errors.As(err, &se):
return &codexUsageFailed{err, codexStatusWords(se)}
case errors.As(err, &ue):
return &codexUsageFailed{err, "couldn't reach chatgpt.com for the usage read: " + ue.Err.Error()}
case errors.As(err, &syn), errors.As(err, &te):
return &codexUsageFailed{err, "ChatGPT's usage reply isn't one magpie reads: " + err.Error()}
}
return err
}
// codexStatusWords says what a non-2xx /wham/usage answer was: always
// with its status as "HTTP <code> <text>", and the backend's own words
// when it gave some. A 401 that says the token expired or the sign-in
// is gone is renewed or marked by codexWindowsRenewing; any other is
// unknown (TestCodexUsageOtherFailuresMarkNobody), so it is told as it
// was, never as a sign-in to make again.
func codexStatusWords(se *accountStatusError) string {
status := strings.TrimSpace(fmt.Sprintf("HTTP %d %s", se.status, http.StatusText(se.status)))
if cloudflareChallenge(se.body) {
// Cloudflare's "Just a moment..." page, sent in place of the
// backend's answer to a client it wants a browser check of
return "ChatGPT's Cloudflare check turned the usage read away (" + status + "): chatgpt.com wants a browser check from this network; a proxy or VPN address is the usual cause"
}
said := codexSaid(se.body)
if said != "" {
said = ": " + said
}
return "ChatGPT answered the usage read with " + status + said
}
// cloudflareChallenge says body is Cloudflare's challenge page rather
// than anything the backend wrote.
func cloudflareChallenge(body []byte) bool {
b := bytes.ToLower(body)
return bytes.Contains(b, []byte("<html")) && (bytes.Contains(b, []byte("just a moment")) ||
bytes.Contains(b, []byte("challenge-platform")) || bytes.Contains(b, []byte("cf_chl")) ||
bytes.Contains(b, []byte("cf-chl")) || bytes.Contains(b, []byte("attention required")))
}
// codexSaid is the backend's own words in an error body: its detail, as
// a string ({"detail":"…"}) or an object ({"detail":{"message","code"}}),
// or an OpenAI-style {"error":{"message","code"}}; "" when it said none
// magpie can find. Cut to a line's length.
func codexSaid(body []byte) string {
var v struct {
Detail json.RawMessage `json:"detail"`
Error json.RawMessage `json:"error"`
}
if json.Unmarshal(body, &v) != nil {
return ""
}
said := ""
for _, raw := range []json.RawMessage{v.Detail, v.Error} {
if len(raw) == 0 || said != "" {
continue
}
var s string
if json.Unmarshal(raw, &s) == nil {
said = s
continue
}
var o struct {
Message string `json:"message"`
Code string `json:"code"`
}
if json.Unmarshal(raw, &o) == nil {
said = o.Message
if said == "" {
said = o.Code
}
}
}
said = strings.Join(strings.Fields(said), " ")
if r := []rune(said); len(r) > 200 {
said = string(r[:199]) + "…"
}
return said
}