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.
241 lines
8.7 KiB
Go
241 lines
8.7 KiB
Go
package provider
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
// expiredBody is the backend's 401 for an access token it calls expired
|
|
// while the token's own exp is an hour ahead (willz on Discord, #2973).
|
|
const expiredBody = `{"error":{"message":"Provided authentication token is expired. Please try refreshing it.","type":null,"code":"token_expired","param":null},"status":401}`
|
|
|
|
// codexExpiredFakes signs in me@ (saved) and work@ (Codex's own), both
|
|
// with an hour left, and points usage and the token refresh at fakes.
|
|
// usage answers each token as refused says; refresh answers each
|
|
// refresh token with access token "fresh-<refresh token>", or as
|
|
// refuseRefresh says. It returns the refresh tokens sent and the usage
|
|
// reads made, by account and token.
|
|
func codexExpiredFakes(t *testing.T, refused func(tok string) (int, string), refuseRefresh bool) (home string, refreshes func() []string, reads func() map[string]int) {
|
|
t.Helper()
|
|
home = signIn(t)
|
|
resetRevoked() // marks are read from this HOME's logins.json
|
|
t.Cleanup(resetRevoked)
|
|
rememberLogins(true)
|
|
codexSignIn(t, home, "work@example.com", "r-work")
|
|
rememberLogins(true)
|
|
loginUsageCache.Lock()
|
|
loginUsageCache.m = nil
|
|
loginUsageCache.Unlock()
|
|
|
|
var mu sync.Mutex
|
|
var sent []string
|
|
seen := map[string]int{}
|
|
usage := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/backend-api/wham/usage" {
|
|
w.WriteHeader(404)
|
|
return
|
|
}
|
|
tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
mu.Lock()
|
|
seen[r.Header.Get("chatgpt-account-id")+" "+tok]++
|
|
mu.Unlock()
|
|
if code, body := refused(tok); code != 0 {
|
|
w.WriteHeader(code)
|
|
w.Write([]byte(body))
|
|
return
|
|
}
|
|
json.NewEncoder(w).Encode(map[string]any{"plan_type": "team", "rate_limit": map[string]any{
|
|
"primary_window": map[string]any{"used_percent": 12, "limit_window_seconds": 18000}}})
|
|
}))
|
|
t.Cleanup(usage.Close)
|
|
refresh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var body map[string]string
|
|
json.NewDecoder(r.Body).Decode(&body)
|
|
mu.Lock()
|
|
sent = append(sent, body["refresh_token"])
|
|
mu.Unlock()
|
|
if refuseRefresh {
|
|
w.WriteHeader(400)
|
|
w.Write([]byte(`{"error":"invalid_grant"}`))
|
|
return
|
|
}
|
|
json.NewEncoder(w).Encode(map[string]any{"access_token": "fresh-" + body["refresh_token"], "refresh_token": body["refresh_token"] + "-2"})
|
|
}))
|
|
t.Cleanup(refresh.Close)
|
|
oldBase, oldURL := CodexBase, codexTokenURL
|
|
CodexBase, codexTokenURL = usage.URL+"/backend-api/codex", refresh.URL
|
|
t.Cleanup(func() { CodexBase, codexTokenURL = oldBase, oldURL })
|
|
refreshes = func() []string {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
return append([]string(nil), sent...)
|
|
}
|
|
reads = func() map[string]int {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
out := map[string]int{}
|
|
for k, v := range seen {
|
|
out[k] = v
|
|
}
|
|
return out
|
|
}
|
|
return home, refreshes, reads
|
|
}
|
|
|
|
// staleExpired answers every token magpie didn't refresh as expired.
|
|
func staleExpired(tok string) (int, string) {
|
|
if strings.HasPrefix(tok, "fresh-") {
|
|
return 0, ""
|
|
}
|
|
return http.StatusUnauthorized, expiredBody
|
|
}
|
|
|
|
func TestCodexUsageRenewsTokenCalledExpired(t *testing.T) {
|
|
home, refreshes, reads := codexExpiredFakes(t, staleExpired, false)
|
|
|
|
u := LoginUsage(context.Background(), "codex")
|
|
for _, user := range []string{"me@example.com", "work@example.com"} {
|
|
q := u[user]
|
|
if q.Error != "" || len(q.Windows) != 1 || q.Windows[0].Used != 12 {
|
|
t.Fatalf("%s: %+v", user, q)
|
|
}
|
|
}
|
|
got := refreshes()
|
|
if len(got) != 2 || !(got[0] == "r" && got[1] == "r-work" || got[0] == "r-work" && got[1] == "r") {
|
|
t.Fatalf("refreshed with %q, want r and r-work once each", got)
|
|
}
|
|
if n := reads(); n["acct-1 fresh-r"] != 1 || n["acct-work@example.com fresh-r-work"] != 1 {
|
|
t.Fatalf("reads %v", n)
|
|
}
|
|
// each renewed where it is kept: the saved one in logins.json, Codex's
|
|
// own in its auth.json, every other field as it was
|
|
var live codexAuth
|
|
readJSON(filepath.Join(home, ".codex", "auth.json"), &live)
|
|
if live.Tokens.AccessToken != "fresh-r-work" || live.Tokens.RefreshToken != "r-work-2" || live.Tokens.AccountID != "acct-work@example.com" {
|
|
t.Fatalf("Codex's own sign-in: %+v", live.Tokens)
|
|
}
|
|
for _, l := range readLogins() {
|
|
if l.User == "me@example.com" && !strings.Contains(string(l.Auth), `"fresh-r"`) {
|
|
t.Fatalf("the saved account's refresh wasn't kept: %s", l.Auth)
|
|
}
|
|
}
|
|
|
|
// read again: the new tokens go out, with no refresh
|
|
loginUsageCache.Lock()
|
|
loginUsageCache.m = nil
|
|
loginUsageCache.Unlock()
|
|
u = LoginUsage(context.Background(), "codex")
|
|
if u["me@example.com"].Error != "" || u["work@example.com"].Error != "" || len(refreshes()) != 2 {
|
|
t.Fatalf("again: %+v, refreshes %q", u, refreshes())
|
|
}
|
|
}
|
|
|
|
// A refresh refused says to sign in again, once; a token still called
|
|
// expired after its refresh is read no third time.
|
|
func TestCodexUsageExpiredOnce(t *testing.T) {
|
|
t.Run("refresh refused", func(t *testing.T) {
|
|
_, refreshes, reads := codexExpiredFakes(t, staleExpired, true)
|
|
u := LoginUsage(context.Background(), "codex")
|
|
if e := u["me@example.com"].Error; !strings.Contains(e, "add the account again") {
|
|
t.Fatalf("saved account: %q", e)
|
|
}
|
|
// signed in again in magpie, not with codex login (charliepu)
|
|
if e := u["work@example.com"].Error; e != revokedText("work@example.com") {
|
|
t.Fatalf("Codex's own account: %q", e)
|
|
}
|
|
if n := len(refreshes()); n != 2 {
|
|
t.Fatalf("%d refreshes, want one each", n)
|
|
}
|
|
for k, n := range reads() {
|
|
if n != 1 {
|
|
t.Fatalf("%s read %d times", k, n)
|
|
}
|
|
}
|
|
})
|
|
t.Run("still expired", func(t *testing.T) {
|
|
always := func(string) (int, string) { return http.StatusUnauthorized, expiredBody }
|
|
_, refreshes, reads := codexExpiredFakes(t, always, false)
|
|
u := LoginUsage(context.Background(), "codex")
|
|
for _, user := range []string{"me@example.com", "work@example.com"} {
|
|
// signed out for the refreshed token too (charliepu)
|
|
if e := u[user].Error; e != revokedText(user) {
|
|
t.Fatalf("%s: %q", user, e)
|
|
}
|
|
}
|
|
if n := len(refreshes()); n != 2 {
|
|
t.Fatalf("%d refreshes, want one each", n)
|
|
}
|
|
if n := reads(); n["acct-1 fresh-r"] != 1 || n["acct-work@example.com fresh-r-work"] != 1 {
|
|
t.Fatalf("reads %v", n)
|
|
}
|
|
})
|
|
}
|
|
|
|
// Any other 401 isn't the token's age: nothing is refreshed for it.
|
|
func TestCodexUsageOther401NotRenewed(t *testing.T) {
|
|
other := func(string) (int, string) {
|
|
return http.StatusUnauthorized, `{"error":{"message":"Unauthorized","code":"unauthorized"}}`
|
|
}
|
|
_, refreshes, _ := codexExpiredFakes(t, other, false)
|
|
u := LoginUsage(context.Background(), "codex")
|
|
if u["me@example.com"].Error != "ChatGPT answered the usage read with HTTP 401 Unauthorized: Unauthorized" || len(refreshes()) != 0 {
|
|
t.Fatalf("%+v, refreshes %q", u, refreshes())
|
|
}
|
|
}
|
|
|
|
func TestSignInExpiredWords(t *testing.T) {
|
|
for body, want := range map[string]bool{
|
|
expiredBody: true,
|
|
`{"detail":"Your authentication token has expired. Please try signing in again."}`: true,
|
|
`{"error":{"code":"refresh_token_expired"}}`: false,
|
|
`{"error":{"code":"token_revoked"}}`: false,
|
|
`Unauthorized`: false,
|
|
} {
|
|
if got := SignInExpired(http.StatusUnauthorized, []byte(body)); got != want {
|
|
t.Errorf("%s: %v", body, got)
|
|
}
|
|
}
|
|
if SignInExpired(http.StatusForbidden, []byte(expiredBody)) {
|
|
t.Error("a 403")
|
|
}
|
|
}
|
|
|
|
// The gateway's 401 token expired renews the account the request went
|
|
// with: the saved one in logins.json, and only while the token sent is
|
|
// the one still saved.
|
|
func TestNoteExpiredSignIn(t *testing.T) {
|
|
_, refreshes, _ := codexExpiredFakes(t, staleExpired, false)
|
|
if err := SetLoginOn("codex", "me@example.com", true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
p, err := Find("codex")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
also := p.AlsoOn()
|
|
if len(also) != 1 || also[0].Account.User != "me@example.com" {
|
|
t.Fatalf("also on: %+v", also)
|
|
}
|
|
a := also[0].Account
|
|
req, _ := http.NewRequest("POST", "http://x", nil)
|
|
if err := a.sign(context.Background(), req, nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
stale := req.Header.Get("Authorization")
|
|
NoteExpiredSignIn(context.Background(), a, req)
|
|
NoteExpiredSignIn(context.Background(), a, req) // a second reply for the same token
|
|
if got := refreshes(); len(got) != 1 || got[0] != "r" {
|
|
t.Fatalf("refreshed with %q", got)
|
|
}
|
|
req, _ = http.NewRequest("POST", "http://x", nil)
|
|
if err := a.sign(context.Background(), req, nil); err != nil || req.Header.Get("Authorization") != "Bearer fresh-r" || stale == "Bearer fresh-r" {
|
|
t.Fatalf("next request signed %q (was %q), %v", req.Header.Get("Authorization"), stale, err)
|
|
}
|
|
}
|