quotas: a remote magpie's Codex reset is used from its card here (#3850)

prgrmrwy runs magpie on a home server and uses it from work through a
remote magpie (and DSH). The remote Codex card said "1 reset", but the
reset could only be used from the GUI of the computer that holds the
sign-in.

What changed:
- Gateway: POST /v1/magpie/quotas/codex-reset?user=<email>[&credit=<id>]
  (Server.codexReset) spends one of that account's resets with
  provider.SpendCodexReset. That is the Usage page's own code
  (UseCodexResetCard, then AwaitAllowance), moved out of
  internal/gui/usage.go so both use it. A reset can't be undone, so the
  route needs an enabled gateway key with full access, from loopback too.
  No key gets 401, and that covers every corsGuard exemption that has no
  key: Origin null, app schemes, *.localhost and a missing Origin. A
  read-only key gets 403 gateway_key_read_only (readOnlyGuard, which
  readOnlyRefused now lists, and again in the handler). A held key gets
  403 gateway_key_held, even one told quotas. The account must be named
  (400 otherwise). One ask runs per account at a time (409). When the
  reset is used, that card is read again.
- Remote client: UseRemoteCodexReset (remote_quotas.go) asks the remote
  with the provider's key. remoteJSON's status mapping is shared through
  remoteBody. A read-only key there is told as such, and a 404 as a
  remote too old. With no answer in time it says the reset may have been
  used, and it never asks again by itself. A remote Codex card now keeps
  its Resets; a GLM team's (byWindow) and every check-in are still
  dropped.
- GUI: "Use a reset" / "Use one..." show on a remote Codex card
  (codexResetCard). They open the same in-app confirmation sheet, with a
  line saying which computer's magpie uses it, and send the card's
  provider to /api/usage/codex-reset. The remote's errors are put in the
  user's words. New strings are in all 5 languages.
- DSH: no code here. Its provider plugin reads /v1/magpie/quotas/cards
  and can call the new route with a full key.
- resetOutcome (a reset's result in words) moved from app.js into
  resetask.js, the only place that says it, so the core's scripts stay
  in TestCoreScriptBudget's 1,533,802 with no raise (1,533,003 after;
  origin/main b967b1620 is 1,533,756).
- Docs: reference.md (remote quotas, gateway keys), gateway-routing.md
  (read-only list, the route's admission), providers-accounts.md.

What was run (rebased on origin/main b967b1620, then on 2e4735f8f):
- mote, at the head before the rebase and the resetOutcome move:
  go test -count=1 -timeout 45m ./internal/provider ./internal/gateway
  ./internal/gui at load ~300-450. provider ok. gateway: only
  TestCompactionOverByteCapEveryTime (#4862). gui: TestCoreScriptBudget
  (this change, 158 bytes over; fixed by the move), TestMainWindowCorners
  (#3949) and TestGatewaySkewOfAnotherIsSaidNotQuit/own_build (#5053,
  passes alone here and at b967b1620).
- mote, same run: 155 GUI files (reset|quota|usage-|panel-|i18n|budget|
  remote|gui-|old-webkit|core-script|script-size), 1856 of 1904 pass.
- WSL (magpie-desktop), the 9 red files alone, at this change and at
  origin/main b967b1620: this change 147 pass / 43 fail, main 146 / 44;
  every test red here is red on main too: codex-auto-reset webkit de
  (#4790), remote-magpie (#4398), usage-agents-hide (#3414), usage-fold
  (#3415, #4790), usage-heatmap (#4718), usage-ledger (#5048).
  codex-reset-lead (#5054) and panel-routing-providers (#5055) were red
  only under mote's load and pass alone on both.
- mote, at this head: TestCoreScriptBudget and
  TestGatewaySkewOfAnotherIsSaidNotQuit ok.
- WSL, at this head: account-every-reset, codex-resets-used, i18n-keys,
  providers-reset-use, remote-codex-reset, reset-each-title,
  reset-pick-card, reset-providers, quota-used-no-reset: 99 of 102 pass.
  The 3 reds are providers-reset-use's 420px Windows cases ("a click
  moved the page", #4873); that file alone is red on origin/main
  b967b1620 too (3 of 40 there, 2 of 40 here).
- WSL, rebased on 2e4735f8f (main had changed internal/gateway): the new
  tests and the read-only, CORS, LAN-guard, held-key, remote-magpie and
  UseCodexResetCard tests in ./internal/gateway ./internal/provider ok;
  core scripts 1,532,960 under 1,533,802; gofmt clean.
- Earlier on mote: TestCodexResetNeedsAFullKey,
  TestRemoteCodexResetThroughTheGateway, TestRemoteCodexResetAnswers, the
  read-only, CORS, LAN-guard, held-key and remote-magpie tests ok;
  remote-codex-reset and reset-pick-card 20 of 20 (chromium and webkit,
  5 languages, 900/390/440px). gofmt clean; go vet darwin, windows ok,
  linux for provider and gateway.

Broken by hand:
- With the handler's key check turned off, TestCodexResetNeedsAFullKey
  went red: "this computer, no key: 200 {code: reset}" and a reset was
  spent.
- With codexResetCard put back to provider === "codex",
  remote-codex-reset.test.cjs went red ("one Use, on the remote Codex
  card"). On the old code the route doesn't exist, so the full-key case
  gets 404.

Not tried:
- A real Codex reset spent between two real magpies: none was spent, to
  keep the owner's resets. The ChatGPT backend is the fake from
  codex_autoreset_test.
- DSH's plugin calling the route.
- GOOS=linux vet of internal/gui: it needs gtk4/webkitgtk, which neither
  mote nor magpie-desktop has. Its change is usage.go only, and that was
  vetted on darwin and windows.

Thanks to prgrmrwy for the report and the proposal.
This commit is contained in:
yetone
2026-11-03 17:12:25 +08:00
parent 2e4735f8f8
commit 5ee5274bd9
17 changed files with 728 additions and 81 deletions
+23 -1
View File
@@ -552,7 +552,12 @@ vendors, and it answers from what it has kept (`GET /v1/magpie/quotas/cards`).
A card's refresh here has it read that card once more
(`POST /v1/magpie/quotas/refresh`, at most once in 30 seconds a card); until it
has read anything, the remote's one card says so. Their history is shown with
its own. A Codex reset or a check-in is pressed on that computer, not here.
its own. A check-in is pressed on that computer, not here. A Codex card's
reset can be used from here (#3850): **Use one…** asks first, as for this
computer's accounts, and that magpie spends it on its account
(`POST /v1/magpie/quotas/codex-reset`, below). It takes the provider's key
with full access there; a read-only or held key is told so. A GLM team's
resets are still used on bigmodel.cn.
Codex's native image tool first asks the provider that served its conversation
turn for the requested image model. If that provider does not list the model,
@@ -2385,6 +2390,23 @@ told none of the cards is answered `/v1/magpie/quotas/cards` 403
that nothing was read. `/v1/magpie/concurrency` and `/v1/magpie/usage`
still refuse it.
A Codex account's rate-limit reset can be used through the gateway as
the Usage page's **Use a reset** does (#3850, the same code):
`POST /v1/magpie/quotas/codex-reset?user=<email>` spends one of that
account's resets (`&credit=<id>` one of its `resets.each`, else the one
that runs out first) and answers `{"code": "reset", "windows": 2}`, or
`no_credit` or `nothing_to_reset` with nothing spent. It can't be
undone, so it takes an enabled gateway key with full access, from this
computer too: a request without a key is refused 401 even on loopback, a
browser page or app the gateway otherwise lets in there (Origin `null`, an
app's scheme, a `*.localhost` page) included; a read-only key 403
`gateway_key_read_only`; a key held to a budget, models or accounts 403
`gateway_key_held`, whether or not it is told quotas. The account is
always named (400 without `user`). A second ask for the same account
while one is out is answered 409. Another magpie's Codex card uses this,
and so can an app reading `/v1/magpie/quotas/cards`, such as a DSH
provider plugin, with a key of full access.
An app of your own can read the Usage page's numbers too.
`GET /v1/magpie/usage?period=<today|week|month|all>` is the page's summary,
the same JSON as the window's `/api/usage` (`path` is left out for another
+20 -1
View File
@@ -535,7 +535,7 @@ page and its data, the concurrency, and the route events' snapshot and
stream) and refuses every other with 403 `gateway_key_read_only`:
every model route, `count_tokens`, the Responses WebSocket's upgrade, every
MCP server, Codex's and Gemini's backends, the catch-all and every write
(`POST /v1/magpie/usage/requests`, the quotas' refresh). A route added later
(`POST /v1/magpie/usage/requests`, the quotas' refresh, a Codex reset). A route added later
is refused it until it is put in that list. A read-only key is held to
nothing else, so `heldKey` leaves it alone and it reads the usage summary
and every account's quotas as a key held to nothing does; none of those
@@ -547,6 +547,25 @@ route the router has is in neither `readOnlyRoutes` nor its refused list,
and sends each refused pattern, by each method it takes, from loopback and
from the network.
`POST /v1/magpie/quotas/codex-reset` (`Server.codexReset` in
[`gateway.go`](../../internal/gateway/gateway.go), #3850) spends one of a
Codex account's resets, which can't be undone, so its admission is
stricter than the quotas': a key is required from loopback too. Every
origin exemption `corsGuard` makes without a key (app schemes, `null`,
loopback page names, a request with no Origin) reaches the handler with
an empty `access.Caller(ctx).KeyID`, and is refused 401 there. A
read-only key is refused by `readOnlyGuard` (and again in the handler),
and a held key (`heldKey`) 403 `gateway_key_held` even when it is told
quotas. The account is named in `?user=`, and `codexResetsAsked` lets one
ask per account run at a time (409). It calls `provider.SpendCodexReset`,
the Usage page's own code, then `RefreshUsage` of that card.
`TestCodexResetNeedsAFullKey` in
[`codex_reset_api_test.go`](../../internal/gateway/codex_reset_api_test.go)
sends it without a key from loopback, `Origin: null`, an app scheme, a
`*.localhost` page, a rebound Host and a foreign page, then with a wrong,
read-only and held key, and expects nothing spent until the full key
asks.
A remote provider serves the conversation, token-counting, System One,
embeddings, rerank, speech-to-text, image generation/edit and video
creation/status/content APIs. Gemini clients enter through the local Gemini adapter and follow the
File diff suppressed because one or more lines are too long
+173
View File
@@ -0,0 +1,173 @@
package gateway
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
// #3850 (prgrmrwy): magpie runs on a home server, and the office's remote
// magpie card (or DSH's, reading the cards) said "1 reset" with no way to
// use it but walking to the server. POST /v1/magpie/quotas/codex-reset
// spends it there, through the Usage page's own code. A reset can't be
// undone, so only a gateway key with full access spends one: never a
// request with no key, from this computer or a page or app the gateway
// lets in on loopback without one, nor a read-only key or a held one.
func TestCodexResetNeedsAFullKey(t *testing.T) {
codexSignedIn(t)
t.Setenv("MAGPIE_ADDR", "")
b := newResetBackend(t, "acct-1")
keys, secrets := newCaller(t, "Full", "Read only", "Held")
if _, err := access.Update("access-key", access.Change{Key: keys[1].ID, ReadOnly: true}); err != nil {
t.Fatal(err)
}
if _, err := access.Update("limit-key", access.Change{Key: keys[2].ID, Limit: &access.Limit{Period: "day", Tokens: 1_000_000}}); err != nil {
t.Fatal(err)
}
h := lanGuard(New().Handler())
path := provider.RemoteCodexResetPath + "?user=" + url.QueryEscape("me@example.com")
do := func(path, from, host, origin, secret string) (int, string) {
t.Helper()
r := httptest.NewRequest("POST", path, nil)
r.RemoteAddr = from
r.Host = host
if origin != "" {
r.Header.Set("Origin", origin)
r.Header.Set("Sec-Fetch-Site", "cross-site")
r.Header.Set("Sec-Fetch-Mode", "cors")
r.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Safari/605.1.15")
}
if secret != "" {
r.Header.Set("Authorization", "Bearer "+secret)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code, w.Body.String()
}
const loop, lan, gw = "127.0.0.1:50123", "192.168.1.9:5000", "127.0.0.1:3425"
refused := []struct {
why string
from, host, origin, secret string
}{
{"this computer, no key", loop, gw, "", ""},
{"a sandboxed frame (Origin null), no key", loop, gw, "null", ""},
{"an app's scheme, no key", loop, gw, "tauri://localhost", ""},
{"a *.localhost page, no key", loop, gw, "http://evil.localhost:8080", ""},
{"a rebound page (its own Host), no key", loop, "evil.example:3425", "", ""},
{"a foreign page, no key", loop, gw, "https://evil.example", ""},
{"a foreign page with the full key", loop, gw, "https://evil.example", secrets[0]},
{"another machine, no key", lan, gw, "", ""},
{"another machine, a wrong key", lan, gw, "", "sk-magpie-wrong"},
{"a read-only key", lan, gw, "", secrets[1]},
{"a read-only key, this computer", loop, gw, "", secrets[1]},
{"a held key", lan, gw, "", secrets[2]},
}
for _, c := range refused {
if code, body := do(path, c.from, c.host, c.origin, c.secret); code < 400 || code == http.StatusNotFound || strings.Contains(body, `"code":"reset"`) {
t.Errorf("%s: %d %s", c.why, code, body)
}
if _, spent := b.seen(); spent != "" {
t.Fatalf("%s spent a reset of %s", c.why, spent)
}
}
if code, body := do(provider.RemoteCodexResetPath, lan, gw, "", secrets[0]); code != http.StatusBadRequest || !strings.Contains(body, "name the Codex account") {
t.Fatalf("no account named: %d %s", code, body)
}
if code, body := do(path, lan, gw, "", secrets[1]); code != http.StatusForbidden || !strings.Contains(body, ReadOnlyCode) {
t.Fatalf("read-only key: %d %s", code, body)
}
if code, body := do(path, lan, gw, "", secrets[2]); code != http.StatusForbidden || !strings.Contains(body, provider.KeyHeldCode) {
t.Fatalf("held key: %d %s", code, body)
}
if _, spent := b.seen(); spent != "" {
t.Fatalf("spent before the full key asked: %s", spent)
}
// the full key, from another machine: one reset, of the account named
code, body := do(path, lan, gw, "", secrets[0])
var out provider.ResetOutcome
if code != 200 || json.Unmarshal([]byte(body), &out) != nil || out.Code != "reset" || out.Windows != 2 {
t.Fatalf("full key: %d %s", code, body)
}
if _, spent := b.seen(); spent != "acct-1" {
t.Fatalf("spent %q, want acct-1 once", spent)
}
// none left: said so, nothing more spent
code, body = do(path, loop, gw, "", secrets[0])
if code != 200 || json.Unmarshal([]byte(body), &out) != nil || out.Code != "no_credit" {
t.Fatalf("none left: %d %s", code, body)
}
if _, spent := b.seen(); spent != "acct-1" {
t.Fatalf("spent %q after none was left", spent)
}
}
// The office's magpie spends the home server's reset through its remote
// magpie provider (#3850): the card here keeps the remote's resets, and
// using one asks the remote with the provider's key. A read-only key there
// says so in words the card can show.
func TestRemoteCodexResetThroughTheGateway(t *testing.T) {
codexSignedIn(t)
t.Setenv("MAGPIE_ADDR", "")
provider.ForgetRemoteCardsForTest()
t.Cleanup(provider.ForgetRemoteCardsForTest)
b := newResetBackend(t, "acct-1")
keys, secrets := newCaller(t, "Office", "Viewer")
if _, err := access.Update("access-key", access.Change{Key: keys[1].ID, ReadOnly: true}); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(lanGuard(New().Handler()))
defer srv.Close()
ctx := context.Background()
save := func(secret string) {
t.Helper()
if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: secret, Chat: srv.URL}); err != nil {
t.Fatal(err)
}
provider.ForgetRemoteCardsForTest()
}
save(secrets[1])
if _, err := provider.UseRemoteCodexReset(ctx, "office/codex", "me@example.com", ""); err == nil || !strings.Contains(err.Error(), "read-only") {
t.Fatalf("read-only key: %v", err)
}
if _, err := provider.UseRemoteCodexReset(ctx, "office/codex", "", ""); err == nil {
t.Fatal("no account named was asked")
}
if _, err := provider.UseRemoteCodexReset(ctx, "office/bal", "me@example.com", ""); err == nil {
t.Fatal("a card not Codex's was asked")
}
if _, spent := b.seen(); spent != "" {
t.Fatalf("spent %q before a full key asked", spent)
}
save(secrets[0])
// the remote's card, read there, carries its reset here
provider.RefreshUsage(ctx, "office", "")
var card *provider.SubscriptionQuota
for _, q := range provider.RemoteCards(ctx) {
if q.Provider == "office/codex" {
card = &q
}
}
if card == nil || card.Resets == nil || card.Resets.Count != 1 || card.User != "me@example.com" || card.Checkins {
t.Fatalf("office/codex: %+v", card)
}
out, err := provider.UseRemoteCodexReset(ctx, "office/codex", card.User, "")
if err != nil || out.Code != "reset" {
t.Fatalf("full key: %+v %v", out, err)
}
if _, spent := b.seen(); spent != "acct-1" {
t.Fatalf("spent %q, want acct-1 once", spent)
}
// read again after: the card shows none left
for _, q := range provider.RemoteCards(ctx) {
if q.Provider == "office/codex" && q.Resets != nil && q.Resets.Count != 0 {
t.Fatalf("after the reset: %+v", q.Resets)
}
}
}
+1
View File
@@ -246,6 +246,7 @@ func TestForeignPagesRefused(t *testing.T) {
{"POST", "/mcp/notes", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`},
{"POST", "/_magpie/claude-mcp/tok", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`},
{"POST", provider.RemoteRefreshPath, ""},
{"POST", provider.RemoteCodexResetPath + "?user=me@example.com", ""},
{"GET", "/v1/magpie/quotas", ""},
{"GET", "/v1/models", ""},
{"OPTIONS", "/v1/chat/completions", ""},
+74
View File
@@ -935,6 +935,7 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("GET /v1/magpie/quotas/history", s.quotasHistory)
mux.HandleFunc("GET "+provider.RemoteCardsPath, s.quotaCards)
mux.HandleFunc("POST "+provider.RemoteRefreshPath, s.quotaCardsRefresh)
mux.HandleFunc("POST "+provider.RemoteCodexResetPath, s.codexReset)
mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute)
mux.HandleFunc("GET /v1/magpie/trace", s.gatewayTrace)
mux.HandleFunc("GET "+routeSnapshotPath, s.routeSnapshot)
@@ -1178,6 +1179,79 @@ func (s *Server) quotaCardsRefresh(w http.ResponseWriter, r *http.Request) {
writeCards(w, r, scope)
}
// codexResetsAsked are the Codex accounts a reset is being spent on now
// (codexReset): a second ask while the first is out is refused, not
// spent as well.
var codexResetsAsked = struct {
sync.Mutex
m map[string]bool
}{m: map[string]bool{}}
// codexReset spends one of a Codex account's rate-limit resets, as the
// Usage page's "Use a reset" does (provider.SpendCodexReset, the same
// code), asked by another magpie's card or an app holding a gateway key
// (#3850, prgrmrwy). A reset can't be undone, so beyond what
// quotaCardsRefresh asks it takes a gateway key, from this computer too,
// never one that is read-only (readOnlyGuard refuses that before here)
// nor one held to a budget, models or accounts: a browser page or an app the gateway lets in on loopback
// without a key (Origin null, an app's scheme, a *.localhost page) is
// refused, as is a request with no key at all. The account is named
// (?user=), never "whichever is signed in", which a caller elsewhere
// can't see; ?credit= picks one of its resets.each.
func (s *Server) codexReset(w http.ResponseWriter, r *http.Request) {
if !local(r) && !sharedWith(r) {
writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Network and sharing → Share on local network) and the request carries its API key (Authorization: Bearer <key> or x-api-key: <key>)")
return
}
who := access.Caller(r.Context())
if who.KeyID == "" || who.ReadOnly {
writeError(w, provider.Chat, http.StatusUnauthorized, "using a Codex reset can't be undone, so it takes an enabled magpie gateway key with full access (Gateway → Gateway keys), sent as Authorization: Bearer <key> or x-api-key, from this computer too; or use it on this computer's Usage page")
return
}
// a key held to a budget, models or accounts is someone else's to
// use: told some cards (#2216) or none, it spends no reset of the
// owner's
if refuseHeld(w, r, "this gateway key is held to a budget, models or accounts, so it uses none of this magpie's Codex resets: use a key with full access") {
return
}
q := r.URL.Query()
user, credit := strings.TrimSpace(q.Get("user")), q.Get("credit")
if user == "" {
writeError(w, provider.Chat, http.StatusBadRequest, "name the Codex account whose reset is used: ?user=<its email>")
return
}
key := strings.ToLower(user)
codexResetsAsked.Lock()
busy := codexResetsAsked.m[key]
codexResetsAsked.m[key] = true
codexResetsAsked.Unlock()
if busy {
writeError(w, provider.Chat, http.StatusConflict, "a reset of "+user+" is being used already; read its card to see what it did")
return
}
defer func() {
codexResetsAsked.Lock()
delete(codexResetsAsked.m, key)
codexResetsAsked.Unlock()
}()
log.Printf("Codex reset of %s asked by gateway key %q", user, who.KeyName)
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
out, err := provider.SpendCodexReset(ctx, user, credit)
cancel()
if err != nil {
writeError(w, provider.Chat, http.StatusBadGateway, err.Error())
return
}
// the card read again, so the cards answered next show its windows
// started again and a reset fewer
if out.Code == "reset" {
read, done := context.WithTimeout(context.WithoutCancel(r.Context()), 15*time.Second)
provider.RefreshUsage(read, "codex", user)
done()
}
writeJSON(w, 200, out)
}
func modelObject(e provider.Entry) map[string]any {
type reasoningLevel struct {
Effort string `json:"effort"`
+1
View File
@@ -335,6 +335,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) {
{"GET", "/api/version"}, {"GET", "/api/tags"}, {"POST", "/api/show"},
{"GET", "/v1/magpie/quotas"}, {"GET", "/v1/magpie/quotas/history"},
{"GET", provider.RemoteCardsPath}, {"POST", provider.RemoteRefreshPath},
{"POST", provider.RemoteCodexResetPath + "?user=me@example.com"},
{"GET", "/v1/magpie/route?session=s"}, {"GET", "/v1/magpie/concurrency"}, {"GET", "/v1/magpie/limit"},
{"POST", "/v1/chat/completions"}, {"POST", "/chat/completions"},
{"POST", "/v1/responses"}, {"POST", "/responses"}, {"GET", "/v1/responses"}, {"GET", "/responses"},
+1 -1
View File
@@ -44,7 +44,7 @@ var readOnlyRoutes = map[string]bool{
}
// ReadOnlyCode is the error code a read-only key is refused a route with.
const ReadOnlyCode = "gateway_key_read_only"
const ReadOnlyCode = provider.KeyReadOnlyCode
// routeMux is a ServeMux that keeps the patterns it was given.
type routeMux struct {
+2
View File
@@ -25,6 +25,8 @@ var readOnlyRefused = []string{
"POST /api/show", "POST /api/chat", "POST /api/generate",
// writes, another key's routes, the whole trace, debugging
"POST /v1/magpie/usage/requests", "POST " + provider.RemoteRefreshPath,
// a Codex reset, which can't be undone (#3850)
"POST " + provider.RemoteCodexResetPath,
"GET /v1/magpie/route", "GET /v1/magpie/trace",
"GET " + ClaudeRunsPath, "GET " + HeapPath, "GET " + CPUPath, "GET " + GoroutinesPath,
"POST " + RestartPath,
+8 -17
View File
@@ -15876,7 +15876,7 @@ function renderQuotas(lazy) {
r.append(resetsWords(sub.resets, sub));
// only Codex's are spent from here: a GLM team's are spent on
// bigmodel.cn, a plugin's wherever its vendor spends them
if (!sub.resets.byWindow && sub.provider === "codex") {
if (codexResetCard(sub)) {
const use = el("button", "text", t("Use a reset"));
use.title = resetUseTitle(sub);
use.onclick = () => askReset(sub);
@@ -17535,7 +17535,7 @@ function panelQuotaCard(q) {
if (q.resets?.count) {
const r = el("div", "pq-resets");
r.append(resetsWords(q.resets, q));
if (!q.resets.byWindow && q.provider === "codex") { // as on the Usage page
if (codexResetCard(q)) { // as on the Usage page
const use = el("button", "pq-use", t("Use one…"));
use.title = resetUseTitle(q);
use.onclick = () => askReset(q);
@@ -17635,6 +17635,12 @@ function resetsEach(r) {
}).join("\n");
}
// codexResetCard: this computer's Codex card, or a remote magpie's (#3850)
function codexResetCard(q) {
if (!q.resets || q.resets.byWindow) return false;
return q.provider === "codex" || !!(q.from && q.user && /^[^/]+\/codex$/.test(q.provider || ""));
}
// resetUseTitle: a use spends the one that runs out first
function resetUseTitle(q) {
const r = q.resets;
@@ -18097,21 +18103,6 @@ document.addEventListener("keydown", (e) => {
// an open menu in it (the reset to use) closes first, on its own
if (!confirmationPending && confirmAsk && !protoMenu && e.key === "Escape") { e.preventDefault(); e.stopImmediatePropagation(); closeConfirmAsk(); }
}, true);
function resetOutcome(out) {
switch (out.code) {
case "reset": return t(out.windows === 1 ? "1 window started again" : "{n} windows started again", { n: out.windows });
case "nothing_to_reset": return t("nothing to start again — no window has been used, and the reset is kept");
case "no_credit": return t("no reset left on the account");
case "already_redeemed":
case "already_used": return t("that reset was already used");
// Anthropic's
case "not_limited": return t("nothing to reset — no window is used up yet, and the reset is kept");
case "cooldown": return t("a reset was used a short while ago — try again later");
case "ineligible": return t("the account can't use a reset");
case "unavailable": return t("resets can't be used right now — try again later");
}
return out.code;
}
// panelAge: on the Usage tab, the footer says how old what it shows is.
function panelAge() {
+20
View File
@@ -3262,6 +3262,11 @@ const I18N = {
"That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there": "那台电脑的 magpie 没有共享 — 请在那台电脑上打开 设置 → 网络与共享 → 局域网共享",
"That computer's magpie didn't take this key — use one of its gateway keys in this provider": "那台电脑的 magpie 不认这个密钥 — 请在这个服务商里填它的一个网关密钥",
"Couldn't reach that computer's magpie — check that it is running and its address": "连不上那台电脑的 magpie — 请确认它在运行、地址正确",
"The magpie on {computer}, where this account is signed in, uses it.": "由 {computer} 上的 magpie 使用,这个账号登录在那里。",
"This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here": "这个密钥在那台电脑的 magpie 上是只读的 — 想在这里使用重置,请给这个服务商填一个完全权限的密钥",
"That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again": "那台电脑没有及时回复重置是否已使用 — 可能已经用掉了。再次尝试前请先刷新这张卡片",
"That computer's magpie can't use a reset from here yet — update magpie there": "那台电脑的 magpie 还不能从这里使用重置 — 请在那台电脑上更新 magpie",
"That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access": "那台电脑的 magpie 给这个密钥设了预算、模型或账号限制,所以不会用它的重置 — 请给这个服务商填一个完全权限的密钥",
"That computer's magpie is too old to tell this key's limit — update magpie there": "那台电脑的 magpie 版本太旧,无法告知这个密钥的限额 — 请在那边更新 magpie",
"That computer answered this key's limit in a form magpie doesn't read — hover for more": "那台电脑返回的密钥限额格式 magpie 读不懂 — 悬停查看详情",
"Gateway keys · {name}": "网关密钥 · {name}",
@@ -7776,6 +7781,11 @@ const I18N = {
"That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there": "那臺電腦的 magpie 沒有共享 — 請在那臺電腦上開啟 設定 → 網路與共享 → 區域網共享",
"That computer's magpie didn't take this key — use one of its gateway keys in this provider": "那臺電腦的 magpie 不認這個金鑰 — 請在這個服務商裡填它的一個閘道金鑰",
"Couldn't reach that computer's magpie — check that it is running and its address": "連不上那臺電腦的 magpie — 請確認它在執行、位址正確",
"The magpie on {computer}, where this account is signed in, uses it.": "由 {computer} 上的 magpie 使用,這個帳號登入在那裡。",
"This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here": "這個密鑰在那臺電腦的 magpie 上是唯讀的 — 想在這裡使用重置,請給這個供應商填一個完整權限的密鑰",
"That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again": "那臺電腦沒有及時回覆重置是否已使用 — 可能已經用掉了。再次嘗試前請先重新整理這張卡片",
"That computer's magpie can't use a reset from here yet — update magpie there": "那臺電腦的 magpie 還不能從這裡使用重置 — 請在那臺電腦上更新 magpie",
"That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access": "那臺電腦的 magpie 給這個密鑰設了預算、模型或帳號限制,所以不會用它的重置 — 請給這個供應商填一個完整權限的密鑰",
"That computer's magpie is too old to tell this key's limit — update magpie there": "那臺電腦的 magpie 版本太舊,無法告知這個金鑰的限額 — 請在那邊更新 magpie",
"That computer answered this key's limit in a form magpie doesn't read — hover for more": "那臺電腦回傳的金鑰限額格式 magpie 讀不懂 — 懸停查看詳情",
"Gateway keys · {name}": "閘道金鑰 · {name}",
@@ -12294,6 +12304,11 @@ const I18N = {
"That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there": "そのコンピューターの magpie は共有されていません — そちらで 設定 → ネットワークと共有 → ローカルネットワークで共有 をオンにしてください",
"That computer's magpie didn't take this key — use one of its gateway keys in this provider": "そのコンピューターの magpie はこのキーを受け付けませんでした — このプロバイダーにそちらのゲートウェイキーを入れてください",
"Couldn't reach that computer's magpie — check that it is running and its address": "そのコンピューターの magpie に接続できません — 起動しているか、アドレスが正しいか確認してください",
"The magpie on {computer}, where this account is signed in, uses it.": "このアカウントがサインインしている {computer} の magpie が使います。",
"This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here": "このキーはそのコンピューターの magpie では読み取り専用です — ここからリセットを使うには、このプロバイダーにフルアクセスのキーを設定してください",
"That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again": "そのコンピューターからリセットが使われたかどうかの返事が時間内にありませんでした — 使われた可能性があります。もう一度試す前にカードを更新してください",
"That computer's magpie can't use a reset from here yet — update magpie there": "そのコンピューターの magpie はまだここからリセットを使えません — そちらで magpie を更新してください",
"That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access": "そのコンピューターの magpie はこのキーを予算・モデル・アカウントで制限しているため、リセットを使いません — このプロバイダーにフルアクセスのキーを設定してください",
"That computer's magpie is too old to tell this key's limit — update magpie there": "そのコンピューターの magpie は古く、このキーの上限を伝えられません — そちらで magpie を更新してください",
"That computer answered this key's limit in a form magpie doesn't read — hover for more": "そのコンピューターが返したキーの上限は magpie が読めない形式です — ホバーで詳細",
"Gateway keys · {name}": "ゲートウェイキー · {name}",
@@ -16823,6 +16838,11 @@ const I18N = {
"That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there": "Das magpie dieses Computers ist nicht freigegeben — schalte dort Einstellungen → Netzwerk und Freigabe → Im lokalen Netzwerk freigeben ein",
"That computer's magpie didn't take this key — use one of its gateway keys in this provider": "Das magpie dieses Computers hat diesen Schlüssel nicht angenommen — trage bei diesem Anbieter einen seiner Zugangsschlüssel ein",
"Couldn't reach that computer's magpie — check that it is running and its address": "Das magpie dieses Computers ist nicht erreichbar — prüfe, ob es läuft und die Adresse stimmt",
"The magpie on {computer}, where this account is signed in, uses it.": "Das magpie auf {computer}, wo dieses Konto angemeldet ist, verwendet ihn.",
"This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here": "Dieser Schlüssel ist im magpie dieses Computers schreibgeschützt — gib diesem Anbieter einen Schlüssel mit vollem Zugriff, um von hier einen Reset zu verwenden",
"That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again": "Dieser Computer hat nicht rechtzeitig gesagt, ob der Reset verwendet wurde — vielleicht wurde er es. Aktualisiere die Karte, bevor du es erneut versuchst",
"That computer's magpie can't use a reset from here yet — update magpie there": "Das magpie dieses Computers kann noch keinen Reset von hier verwenden — aktualisiere magpie dort",
"That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access": "Das magpie dieses Computers begrenzt diesen Schlüssel auf ein Budget, Modelle oder Konten und verwendet daher keinen seiner Resets — gib diesem Anbieter einen Schlüssel mit vollem Zugriff",
"That computer's magpie is too old to tell this key's limit — update magpie there": "Das magpie auf diesem Computer ist zu alt, um das Limit dieses Schlüssels zu nennen — aktualisiere magpie dort",
"That computer answered this key's limit in a form magpie doesn't read — hover for more": "Dieser Computer hat das Limit des Schlüssels in einer Form gesendet, die magpie nicht liest — für mehr darüberfahren",
"Gateway keys · {name}": "Zugangsschlüssel · {name}",
+38 -2
View File
@@ -12,6 +12,10 @@ window.askResetSheet = function (q) {
ed.append(el("p", "lib-confirm", t(q.resets.count === 1
? "{who} has 1 reset. Using it starts its windows again at once, as if none of them had been used. It can't be undone."
: "{who} has {n} resets. Using one starts its windows again at once, as if none of them had been used. It can't be undone.", { who, n: q.resets.count })));
// a remote magpie's card (office/codex, #3850): that magpie spends it,
// on the account signed in there
const remote = q.provider !== "codex" && q.from;
if (remote) ed.append(el("p", "lib-confirm reset-remote", t("The magpie on {computer}, where this account is signed in, uses it.", { computer: q.from })));
// which of them is used: the one that runs out first unless the user
// picks another of those listed one by one (01huadalang on Discord),
// and the dialog names the one it spends
@@ -72,7 +76,10 @@ window.askResetSheet = function (q) {
go.disabled = true;
go.classList.add("busy");
try {
const out = await api("usage/codex-reset", chosen ? { user: q.user || "", credit: cards[chosen].id } : { user: q.user || "" });
const ask = { user: q.user || "" };
if (remote) ask.provider = q.provider;
if (chosen) ask.credit = cards[chosen].id;
const out = await api("usage/codex-reset", ask);
// the providers' editor and Settings read the account's windows
// and resets on their own, kept a minute: read again, as Usage is
// (#1491); asked from the editor, closing goes back to it
@@ -85,7 +92,7 @@ window.askResetSheet = function (q) {
} catch (err) {
go.disabled = false;
go.classList.remove("busy");
statusErr(err);
status(remote ? remoteResetError(err.message) : err.message, "err");
}
};
const cancel = el("button", "text", t("Cancel"));
@@ -99,3 +106,32 @@ window.askResetSheet = function (q) {
$("#modal").classList.add("lib");
go.focus();
};
// remoteResetError says why a remote magpie used no reset (remote_quotas.go)
function remoteResetError(err) {
if (/^this key is read-only on the remote magpie/.test(err)) return t("This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here");
if (/didn't say in time whether the reset was used/.test(err)) return t("That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again");
if (/^remote magpie doesn't share its quotas/.test(err)) return t("That computer's magpie can't use a reset from here yet — update magpie there");
if (/^remote magpie holds this key/.test(err)) return t("That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access");
if (/^remote magpie isn't shared/.test(err)) return t("That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there");
if (/^remote magpie didn't take this key/.test(err)) return t("That computer's magpie didn't take this key — use one of its gateway keys in this provider");
if (/^couldn't reach the remote magpie/.test(err)) return t("Couldn't reach that computer's magpie — check that it is running and its address");
return err;
}
// what a reset came to, in words (moved here from app.js; only this sheet says it)
function resetOutcome(out) {
switch (out.code) {
case "reset": return t(out.windows === 1 ? "1 window started again" : "{n} windows started again", { n: out.windows });
case "nothing_to_reset": return t("nothing to start again — no window has been used, and the reset is kept");
case "no_credit": return t("no reset left on the account");
case "already_redeemed":
case "already_used": return t("that reset was already used");
// Anthropic's
case "not_limited": return t("nothing to reset — no window is used up yet, and the reset is kept");
case "cooldown": return t("a reset was used a short while ago — try again later");
case "ineligible": return t("the account can't use a reset");
case "unavailable": return t("resets can't be used right now — try again later");
}
return out.code;
}
@@ -0,0 +1,132 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// #3850 (prgrmrwy): magpie on a home server, and the office's remote magpie
// card said "1 reset" with no way to use it there. A remote magpie's Codex
// card now offers the reset as this computer's does: the same in-app
// confirmation (no confirm()), which says the magpie on that computer uses
// it, and nothing is spent before the user says so. The use names the
// card's remote provider and the account. A GLM team's resets (byWindow),
// spent on the vendor's page, and a remote's other cards offer none. What
// the remote answered goes in the user's words (a read-only key, no answer
// in time). The Usage page at 900px and 390px and the menu bar panel at
// 440px; English, Chinese (both), Japanese and German; Chromium and WebKit.
// No backend, the API is faked.
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(process.env.ASSET_DIR || path.resolve(__dirname, "../assets"));
const day = 864e5, base = Date.now();
const soon = new Date(base + 2 * day).toISOString();
const windows = [{ name: "5 hours", used: 100, resetsAt: new Date(base + 3600e3).toISOString() }, { name: "7 days", used: 60, resetsAt: new Date(base + 3 * day).toISOString() }];
const quotas = [
{ provider: "office/codex", name: "Codex · Office", icon: "codex-color", from: "Office", user: "me@example.com", plan: "Plus", kind: "subscription", windows,
resets: { count: 1, until: soon } },
// a GLM team's, read on the remote: spent on bigmodel.cn, not from here
{ provider: "office/zhipu-team", name: "GLM Team · Office", icon: "zhipu", from: "Office", user: "team@example.com", kind: "subscription", windows,
resets: { count: 2, byWindow: true } },
];
const READ_ONLY = "this key is read-only on the remote magpie; give the provider a key with full access to use a reset from here";
const LATE = "Office didn't say in time whether the reset was used; it may have been. Refresh the card to see before asking again";
function serve(lang, posted, answer) {
const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", trayUsages: ["office/codex", "office/zhipu-team"], trayUsageEvery: 3 };
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data, status = 200) => route.fulfill({ status, json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/usage/quotas") return json(quotas);
if (url.pathname === "/api/usage/codex-reset") {
posted.push(JSON.parse(req.postData() || "{}"));
return answer.error ? json({ error: answer.error }, 400) : json({ code: "reset", windows: 2 });
}
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
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)];
await route.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType });
};
}
const KEYS = ["The magpie on {computer}, where this account is signed in, uses it.",
"This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here",
"That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again",
"That computer's magpie can't use a reset from here yet — update magpie there",
"That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access"];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: a remote magpie's Codex reset is used from here, asked first`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const errors = [];
const say = (page, key, vars) => page.evaluate(([lang, key, vars]) => {
if (lang !== "en" && !I18N[lang]?.[key]) return "untranslated: " + key;
return t(key, vars);
}, [lang, key, vars]);
const run = async (url, viewport, useSel, cardSel) => {
const posted = [], answer = {};
const page = await (await browser.newContext({ viewport, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); });
await page.route("**/*", serve(lang, posted, answer));
await page.goto(url);
if (url.includes("panel")) await page.locator('#ptabs [data-ptab="usage"]').click();
for (const k of KEYS) assert.notEqual(await say(page, k, { computer: "x" }), "untranslated: " + k);
// the remote's Codex card offers its reset; the GLM team's doesn't
await page.locator(cardSel).first().waitFor();
assert.equal(await page.locator(useSel).count(), 1, "one Use, on the remote Codex card");
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "nothing wider than the page");
const ask = page.locator(".reset-ask");
await page.locator(useSel).click();
await ask.waitFor();
assert.equal((await ask.locator(".reset-remote").textContent()).trim(), await say(page, "The magpie on {computer}, where this account is signed in, uses it.", { computer: "Office" }));
assert.equal(await page.evaluate(() => { const e = document.querySelector(".reset-ask").getBoundingClientRect(); return e.right <= innerWidth && e.left >= 0; }), true, "the confirmation fits");
// Cancel spends nothing
await page.keyboard.press("Escape");
await ask.waitFor({ state: "detached" });
assert.equal(posted.length, 0, "nothing spent before the user says so");
// a read-only key there: said in the user's words, the sheet stays
answer.error = READ_ONLY;
await page.locator(useSel).click();
await ask.locator("button.primary").click();
await page.locator("#status.err").waitFor();
assert.equal((await page.locator("#status").textContent()).trim(), await say(page, KEYS[1]));
assert.equal(await ask.isVisible(), true, "the confirmation stays to try again");
// no answer in time: it may have been used
answer.error = LATE;
await ask.locator("button.primary").click();
await page.waitForFunction((want) => document.querySelector("#status")?.textContent.trim() === want, await say(page, KEYS[2]));
await page.keyboard.press("Escape");
await ask.waitFor({ state: "detached" });
// used: the remote card's provider and account are named
delete answer.error;
await page.locator(useSel).click();
await ask.locator("button.primary").click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(posted, [
{ user: "me@example.com", provider: "office/codex" },
{ user: "me@example.com", provider: "office/codex" },
{ user: "me@example.com", provider: "office/codex" },
]);
await page.context().close();
};
for (const width of [900, 390]) await run("http://magpie.test/?view=usage", { width, height: 800 }, ".quota-resets button", ".quota-resets");
await run("http://magpie.test/?mode=panel", { width: 440, height: 700 }, ".pq-use", ".pq-use");
assert.deepEqual(errors, []);
});
}
}
+15 -15
View File
@@ -399,32 +399,32 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
// spends one of a Codex account's rate-limit resets, which the page
// has asked the user about first: the one they chose (Credit, an id
// of its resets.each), else the one that runs out first; what it did
// comes back
// comes back. A card from a remote magpie (Provider "office/codex")
// has that magpie spend it, on its account (#3850)
mux.HandleFunc("POST /api/usage/codex-reset", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ User, Credit string }
var in struct{ Provider, User, Credit string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if in.Provider != "" && in.Provider != "codex" {
ctx, cancel := context.WithTimeout(r.Context(), provider.RemoteResetWait+10*time.Second)
defer cancel()
out, err := provider.UseRemoteCodexReset(ctx, in.Provider, in.User, in.Credit)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, out)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
out, err := provider.UseCodexResetCard(ctx, in.User, in.Credit)
out, err := provider.SpendCodexReset(ctx, in.User, in.Credit)
if err != nil {
fail(rw, err)
return
}
if out.Code == "reset" {
// routing and the Providers page know the windows started
// again by the time the page hears so, not at a later
// request's reading (#1491)
who := in.User
if who == "" {
who, _ = provider.CodexSignedIn()
}
wait, done := context.WithTimeout(ctx, 10*time.Second)
provider.AwaitAllowance(wait, "codex", who)
done()
}
writeJSON(rw, out)
})
}
+20
View File
@@ -249,6 +249,26 @@ func UseCodexResetCard(ctx context.Context, user, credit string) (ResetOutcome,
return spendCodexReset(ctx, user, credit, ResetUsedByHand)
}
// SpendCodexReset is a reset used by hand wherever it is asked: the Usage
// page's "Use a reset" and the gateway's RemoteCodexResetPath, for another
// magpie's card or an app holding a gateway key (#3850, prgrmrwy). It is
// UseCodexResetCard, then, when the windows started again, a wait of up
// to 10s for routing and the Providers page to know so (#1491).
func SpendCodexReset(ctx context.Context, user, credit string) (ResetOutcome, error) {
out, err := UseCodexResetCard(ctx, user, credit)
if err != nil || out.Code != "reset" {
return out, err
}
who := user
if who == "" {
who, _ = CodexSignedIn()
}
wait, done := context.WithTimeout(ctx, 10*time.Second)
AwaitAllowance(wait, "codex", who)
done()
return out, nil
}
// useCodexReset is UseCodexReset, the use kept as made for why.
func useCodexReset(ctx context.Context, user, why string) (ResetOutcome, error) {
return spendCodexReset(ctx, user, "", why)
+123 -39
View File
@@ -37,6 +37,19 @@ const RemoteCardsPath = "/v1/magpie/quotas/cards"
// RemoteCardsPath.
const RemoteRefreshPath = "/v1/magpie/quotas/refresh"
// RemoteCodexResetPath has the gateway spend one of its Codex account's
// rate-limit resets (?user=, the account always named; &credit=, one of
// its resets.each, else the one that runs out first), as its Usage page's
// "Use a reset" does (#3850, prgrmrwy): a reset shown on another magpie's
// card, or in an app reading the cards, can be used from there too. It
// can't be undone, so the gateway takes it only with a gateway key of full
// access, never from a page or app it lets in without one.
const RemoteCodexResetPath = "/v1/magpie/quotas/codex-reset"
// RemoteResetWait is how long a remote magpie is waited for to spend a
// reset: its use (20s at most) and its wait for routing to know (10s).
const RemoteResetWait = 35 * time.Second
// remoteCardsFor is how long another magpie's cards are kept here before
// they are asked for again: reading its cache costs it nothing from the
// vendors, but the menu bar and alerts ask often.
@@ -59,6 +72,14 @@ const errRemoteNotShared = "remote magpie isn't shared; turn on Share on local n
// errRemoteKey is a remote magpie that didn't take this provider's key (401).
const errRemoteKey = "remote magpie didn't take this key; use one of its enabled gateway keys"
// KeyReadOnlyCode is the error code a gateway answers a read-only key
// with on a route that uses or changes anything.
const KeyReadOnlyCode = "gateway_key_read_only"
// errRemoteReadOnly is a remote magpie whose key here is read-only: it
// shows the cards, and spends nothing.
const errRemoteReadOnly = "this key is read-only on the remote magpie; give the provider a key with full access to use a reset from here"
// KeyHeldCode is the error code a gateway answers a key held to a budget,
// models or accounts with, where its own accounts would be told (#1981):
// the key is someone else's to use, and is told its own limit alone.
@@ -238,8 +259,13 @@ func remoteCards(ctx context.Context, p Provider, fresh bool) []SubscriptionQuot
q.Name += " · " + name
q.From = name
// what is pressed on a card acts on this computer's accounts:
// a Codex reset or a check-in is the other magpie's to do
q.Resets, q.Checkins, q.CheckinBy, q.Checkin, q.CheckinOff = nil, false, "", nil, false
// a check-in is the other magpie's to do. A Codex reset is
// spent there when pressed here (UseRemoteCodexReset, #3850);
// a GLM team's (byWindow) is spent on the vendor's page
if q.Provider != p.ID+"/codex" || q.Resets != nil && q.Resets.ByWindow {
q.Resets = nil
}
q.Checkins, q.CheckinBy, q.Checkin, q.CheckinOff = false, "", nil, false
if q.Windows == nil {
q.Windows = []QuotaWindow{}
}
@@ -393,46 +419,10 @@ func remoteKey(h http.Header, key string) {
// remoteJSON asks p's gateway, with its key, for a {"data": …} list.
func remoteJSON(ctx context.Context, p Provider, method, path string, dst any) error {
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, method, p.Anthropic+path, nil)
b, err := remoteBody(ctx, p, method, path, 8*time.Second)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
p.signRemote(req, p.Key)
res, err := p.Do(http.DefaultClient, req)
if err != nil {
return fmt.Errorf("%s %s: %w", errRemoteUnreachable, remoteName(p), err)
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 8<<20))
switch {
case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed:
return fmt.Errorf("%s", errRemoteNoShare)
case res.StatusCode == http.StatusForbidden:
var e struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if json.Unmarshal(b, &e) == nil && e.Error.Code == KeyHeldCode {
return errKeyHeld
}
return fmt.Errorf("%s", errRemoteNotShared)
case res.StatusCode == http.StatusUnauthorized:
return fmt.Errorf("%s", errRemoteKey)
case res.StatusCode < 200 || res.StatusCode >= 300:
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
if json.Unmarshal(b, &e) == nil && e.Error.Message != "" {
return fmt.Errorf("%s: %s", remoteName(p), e.Error.Message)
}
return fmt.Errorf("%s answered %s", remoteName(p), res.Status)
}
var list struct {
Data json.RawMessage `json:"data"`
}
@@ -444,3 +434,97 @@ func remoteJSON(ctx context.Context, p Provider, method, path string, dst any) e
}
return json.Unmarshal(list.Data, dst)
}
// remoteBody asks p's gateway, with its key, waiting wait at most, and
// gives back the body of a 2xx answer; any other is an error that says
// what to do about it.
func remoteBody(ctx context.Context, p Provider, method, path string, wait time.Duration) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, wait)
defer cancel()
req, err := http.NewRequestWithContext(ctx, method, p.Anthropic+path, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
p.signRemote(req, p.Key)
res, err := p.Do(http.DefaultClient, req)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", errRemoteUnreachable, remoteName(p), err)
}
defer res.Body.Close()
b, err := io.ReadAll(io.LimitReader(res.Body, 8<<20))
if err != nil && ctx.Err() != nil {
return nil, fmt.Errorf("%s %s: %w", errRemoteUnreachable, remoteName(p), ctx.Err())
}
var e struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
switch {
case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed:
return nil, fmt.Errorf("%s", errRemoteNoShare)
case res.StatusCode == http.StatusForbidden:
json.Unmarshal(b, &e)
switch e.Error.Code {
case KeyHeldCode:
return nil, errKeyHeld
case KeyReadOnlyCode:
return nil, fmt.Errorf("%s", errRemoteReadOnly)
}
return nil, fmt.Errorf("%s", errRemoteNotShared)
case res.StatusCode == http.StatusUnauthorized:
return nil, fmt.Errorf("%s", errRemoteKey)
case res.StatusCode < 200 || res.StatusCode >= 300:
if json.Unmarshal(b, &e) == nil && e.Error.Message != "" {
return nil, fmt.Errorf("%s: %s", remoteName(p), e.Error.Message)
}
return nil, fmt.Errorf("%s answered %s", remoteName(p), res.Status)
}
return b, nil
}
// errRemoteResetUnknown is a reset asked of a remote magpie that didn't
// answer in time: it may have been spent there, so it isn't asked again.
const errRemoteResetUnknown = "%s didn't say in time whether the reset was used; it may have been. Refresh the card to see before asking again"
// UseRemoteCodexReset has the remote magpie whose card id is (its Codex
// card, "office/codex") spend one of user's resets there, as its own
// Usage page would (#3850, prgrmrwy: the card here said "1 reset", and
// using it took a walk to the other computer). credit is one of the
// card's resets.each, "" for the one that runs out first. The account is
// always named: which one the remote is signed in to isn't known here,
// and a reset can't be undone. The remote's cards are read afresh after,
// so the card shows its windows started again.
func UseRemoteCodexReset(ctx context.Context, id, user, credit string) (ResetOutcome, error) {
p, card, ok := remoteOf(id)
if !ok || card != "codex" {
return ResetOutcome{}, fmt.Errorf("%s is no remote magpie's Codex card", id)
}
if user == "" {
return ResetOutcome{}, errors.New("name the Codex account whose reset is used")
}
q := url.Values{"user": {user}}
if credit != "" {
q.Set("credit", credit)
}
b, err := remoteBody(ctx, p, http.MethodPost, RemoteCodexResetPath+"?"+q.Encode(), RemoteResetWait)
if err != nil {
// no answer: the remote may have spent it all the same
if errors.Is(err, context.DeadlineExceeded) {
return ResetOutcome{}, fmt.Errorf(errRemoteResetUnknown, remoteName(p))
}
return ResetOutcome{}, err
}
var out ResetOutcome
if err := json.Unmarshal(b, &out); err != nil || out.Code == "" {
return ResetOutcome{}, fmt.Errorf(errRemoteResetUnknown, remoteName(p))
}
// the remote read the card again after the reset; what it has now
read, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
remoteCards(read, p, true)
cancel()
toldUsage()
return out, nil
}
+76 -4
View File
@@ -7,6 +7,7 @@ import (
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
@@ -106,7 +107,8 @@ func TestRemoteMagpieCards(t *testing.T) {
peer := &fakePeer{cards: []SubscriptionQuota{
{Provider: "codex", Name: "Codex", Icon: "codex", User: "a@x.com", Kind: "subscription", Windows: []QuotaWindow{{Name: "5h", Used: 40}},
Resets: &ResetCredits{Count: 1}, Checkins: true},
{Provider: "zhipu", Name: "GLM Coding", Kind: "plan", Windows: []QuotaWindow{{Name: "5h", Used: 10}}},
{Provider: "zhipu", Name: "GLM Coding", Kind: "plan", Windows: []QuotaWindow{{Name: "5h", Used: 10}},
Resets: &ResetCredits{Count: 2, ByWindow: true}},
{Provider: "deepseek", Name: "DeepSeek", Kind: "balance", Balance: "¥12.00"},
{Provider: "home/codex", Name: "Codex · Home", Kind: "subscription", From: "Home"},
}}
@@ -125,10 +127,12 @@ func TestRemoteMagpieCards(t *testing.T) {
if c == nil || c.Name != "Codex · Office" || c.From != "Office" || c.User != "a@x.com" || c.Icon != "codex" || len(c.Windows) != 1 || c.Windows[0].Used != 40 {
t.Fatalf("subscription card: %+v", c)
}
if c.Resets != nil || c.Checkins {
t.Errorf("a remote card's buttons are kept: %+v", c)
// a Codex reset is used there when pressed here (#3850); a check-in
// isn't asked of another computer
if c.Checkins || c.Resets == nil || c.Resets.Count != 1 {
t.Errorf("a remote Codex card's buttons: %+v", c)
}
if p := find(plans, "office/zhipu"); p == nil || p.Name != "GLM Coding · Office" {
if p := find(plans, "office/zhipu"); p == nil || p.Name != "GLM Coding · Office" || p.Resets != nil {
t.Errorf("plan: %+v", plans)
}
if b := find(balances, "office/deepseek"); b == nil || b.Balance != "¥12.00" {
@@ -474,3 +478,71 @@ func TestRemoteMagpieCardsKeptByKey(t *testing.T) {
}
}
}
// #3850: a reset asked of a remote magpie that is too old to spend one,
// or that doesn't answer in time, says what it means for the card: update
// magpie there, or the reset may have been used there, so read the card
// before asking again (never asked again by itself).
func TestRemoteCodexResetAnswers(t *testing.T) {
var asks atomic.Int32
stall := make(chan struct{})
t.Cleanup(func() { close(stall) })
var mode atomic.Value
mode.Store("old")
remoteQuotaHome(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != RemoteCodexResetPath {
w.Write([]byte(`{"data":[]}`))
return
}
asks.Add(1)
if r.Method != http.MethodPost || r.URL.Query().Get("user") != "a@x.com" || r.URL.Query().Get("credit") != "c-2" || r.Header.Get("Authorization") != "Bearer sk-magpie-office" {
w.WriteHeader(http.StatusBadRequest)
return
}
switch mode.Load() {
case "old":
w.WriteHeader(http.StatusNotFound)
case "stall":
select {
case <-stall:
case <-r.Context().Done():
}
case "readonly":
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"error":{"message":"read-only","code":"` + KeyReadOnlyCode + `"}}`))
case "ok":
w.Write([]byte(`{"code":"reset","windows":2}`))
}
}))
ctx := context.Background()
if _, err := UseRemoteCodexReset(ctx, "office/codex", "a@x.com", "c-2"); err == nil || !strings.HasPrefix(err.Error(), "remote magpie doesn't share its quotas") {
t.Fatalf("an old remote: %v", err)
}
mode.Store("readonly")
if _, err := UseRemoteCodexReset(ctx, "office/codex", "a@x.com", "c-2"); err == nil || !strings.HasPrefix(err.Error(), "this key is read-only on the remote magpie") {
t.Fatalf("a read-only key: %v", err)
}
mode.Store("stall")
short, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
_, err := UseRemoteCodexReset(short, "office/codex", "a@x.com", "c-2")
cancel()
if err == nil || !strings.Contains(err.Error(), "may have been") {
t.Fatalf("no answer in time: %v", err)
}
mode.Store("ok")
out, err := UseRemoteCodexReset(ctx, "office/codex", "a@x.com", "c-2")
if err != nil || out.Code != "reset" || out.Windows != 2 {
t.Fatalf("spent: %+v %v", out, err)
}
if n := asks.Load(); n != 4 {
t.Fatalf("asked %d times, want once each", n)
}
for _, id := range []string{"office/zhipu", "office", "codex", "nowhere/codex"} {
if _, err := UseRemoteCodexReset(ctx, id, "a@x.com", ""); err == nil {
t.Errorf("%s was asked", id)
}
}
if n := asks.Load(); n != 4 {
t.Fatalf("a card not a remote's Codex card asked the remote (%d)", n)
}
}