Commit Graph
1870 Commits
Author SHA1 Message Date
yetone f37de8cc4e provider: the saved Claude accounts' files are listed once per request
claudeCodePrice and claudeModelsOf listed claude-accounts/*/.claude.json
with filepath.Glob on every call, and each Claude model's price asks.
Building an agent's model list (the window's drift poll rebuilds it each
minute, buildClaudeVia and Pi's list) read the folder once per model. The
listing is now held while a request holds the catalog (heldOf, 1 s), so a
build lists it once; outside a hold it is listed afresh, as before.

Measured on mote, real-account copy, GUI page open in Playwright
Chromium, network blocked, 115 s CPU profile (acgui.sh), v0.1.3425-era
build vs this change:
- filepath.Glob: 50 ms -> gone; agent.buildModels 90 ms -> 50 ms
- total samples 320 ms -> 290 ms; footprint 197 MB -> 172 MB (one run each)

Test: TestClaudeCodeFilesListedOncePerHold saves a folder during a hold
and checks the hold's second listing is the first one (same array), and
that after the hold the new folder is seen. Broken by hand (the old
claudeCodeFiles): red, "listed again within one hold".

Run (mote): go test ./internal/provider ./internal/agent ok; go vet
native (provider, agent), GOOS=linux and GOOS=windows (provider) ok;
gofmt clean.
2026-11-09 23:25:19 +08:00
yetone 8f72f95304 provider: a group's lookup copies the group found, not every group
FindGroup, FindGroupAlso and GroupFinder built every routing group with
groupsIn, which copies each group and its rules, to return one. The
window's 15-second /api/drift poll asks GroupFinder for each Pi model on
a group (piModelJSON), and the gateway asks once per request on a group.
They now read the groups held (sharedGroupsIn, heldFrom while Hold is
active) and copy only the group found and each group a member comes
through (cloneGroup), so what a caller gets is still its own to change.

Measured on mote with the real-account copy, GUI page open in Playwright
Chromium, network blocked, 2 minutes (acgui.sh):
- piModelJSON allocations: 10.6 MB -> 1.5 MB (v0.1.3420 vs this change)
- process CPU 0.39 s vs 0.43 s, footprint 187 vs 197 MB: within the run
  noise of the once-a-minute catalog rebuilds; the drop is in the profile.

Test: TestGroupFoundCopiesItselfAlone changes a found group, its member's
Via and EffortMap, and checks FindGroup, GroupFinder and Groups still see
the saved ones; then 50 looks must allocate less than 50 copies of every
group (100 groups with rules).
Broken by hand, each red:
- A: sharedGroupsIn -> groupsIn: looks 5384832 B >= copies 4796000 B
- B: no cloneGroup of the found group: index out of range (shared slice)
- C: no clone of a member's sub-group: "a change to a found group
  reached the next look"

Run (mote): go test ./internal/provider ./internal/agent ok;
go test ./internal/gateway -timeout 45m ok; go vet native, GOOS=linux,
GOOS=windows ok; gofmt -l clean.
Not tried: a gateway request through a group with a real account
(the path is the same FindGroup the test covers).
2026-11-09 23:08:13 +08:00
yetone 88b541a25c images: every pointer names Settings › Models › Images, where the page is
The image models moved under Settings › Models, but the Library's Magpie
Image sheet, the MCP server's instructions to agents, the gateway's
"no image model" errors, the video tool's text and the docs still sent
users to "Settings › Images", a tab that no longer exists (the scattered
settings audit after netube99 on X). Every user-facing string now names
Settings › Models › Images in en, zh, zh-TW, ja and de, as do the site's
Qwen docs (en, zh, ja), llms-full.txt, the subsystem pages and comments.

Run in the tree with this change and the rest of the audit's fixes
(mote, base cd0ba05c2):
- go vet ./internal/gui ./internal/gateway ./internal/agent
  ./internal/provider ./internal/settingsapi: ok
- go test -run 'Image|Draw|Video|Hidden|Group|Settings' ./internal/gui
  ./internal/gateway ./internal/settingsapi: ok; ./internal/imagemcp,
  ./internal/library, ./internal/catalog: ok
- GUI: i18n-keys, i18n-en-no-cjk, image-models-hide,
  library-browser-setup: pass in Chromium and WebKit
- gofmt -l: nothing
Not tried: a real agent reading the new MCP instructions (text only).
2026-11-09 21:51:53 +08:00
yetone cdd99c5578 routing: a re: pattern with a lookahead saves and matches as its preview showed
maer8824 on Discord wrote "re:(?!.*flash).*glm.*" (glm but not flash) in
a routing group. The GUI's preview, which reads patterns with JS's
RegExp, matched the right models, but saving failed: Go's regexp has no
lookaround ("invalid or unsupported Perl syntax: (?!").

compilePattern now reads with Go's regexp first, as before, and only a
pattern Go can't read goes to regexp2 (already in go.sum; now required
directly), with a 100ms bound on one match. A pattern Go reads keeps
exactly the matches it had; one neither reads is still refused with
Go's error. Groups' patterns and providers' auto-include rules both
compile here, so both take it.

Run on mote at this head: go mod verify ok; go vet ./... ok;
GOOS=linux and GOOS=windows go vet ./internal/provider/ ok;
go test -count=1 ./internal/provider/ ok (133s).
Broken by hand: with groupmatch.go/autolist.go/go.mod reverted,
TestRegexpPatternLookahead fails 5 ways (the reporter's error among them).
Not tried: a real group saved in the GUI; the full suite follows the push.

Reported-by: maer8824 (Discord)
2026-11-09 20:06:22 +08:00
yetone 1f1d210156 quotas: a wallet's counted spend goes out on /v1/magpie/quotas too (#5770)
a06872dec gave each wallet window spent and spentSince. QuotaSpan didn't
carry them, so TestQuotaSpanCarriesEveryWindowField went red on main
(seen in the full suite run after the push). quotaReport now copies
both, so a status line or a script reading /v1/magpie/quotas sees what
magpie counted a wallet spending and since when.

Run on mote at this tree (lockf ~/suite.lock mote-run):
- go test ./internal/provider -count=1 -timeout 30m: ok (whole package)
- gofmt -l internal: clean
The rest of the full suite at a06872dec was green, except internal/gui,
which doesn't build since f8186c691/36ddd5761 (#5806, not this change).

Reported-by: 9won (Discord)
2026-11-09 19:42:51 +08:00
yetone a06872dec8 caps: a wallet window's spend is counted, so a cap holds it (#5770)
A window that tells only what is left (QuotaWindow.Balance: AStudio
0.2.0's 通用积分 and 星火积分, SuperMagic's points) read 0% used until
it was empty, so an account cap never tripped on it. 9won capped an
AStudio account at 4 and it spent over 1,000 credits past it.

magpie now counts what such a wallet spends (wallet_spend.go). Each
plugin reading's balance is set against the one before: a fall is
spent, a rise (top-up, daily grant) is not. The count runs over the
window's own period when it tells a reset, else the local day: a
wallet never renews, and a cap reached for good would switch the
account off with no time it comes back; the ask was "N a day". Spend
before a period's first reading, or across a gap between periods, is
unknown and not counted; spentSince says when counting began. The
counts are kept in wallet-spend.json beside providers.json, so a
restart doesn't lose them.

Every wallet window carries spent and spentSince. On an account with a
usage cap (WindowCaps.Holds) it also reads as amount spent of limit
(spent plus what is left), and used that share. A cap by share then
holds it in routing (allowanceOf takes the fields as they are) and on
the GUI row (capHeldOf reads used). So does 40cbdaa7e's amount cap,
which skipped a window with no total: 9won's "at most 300 a day" on a
wallet now holds (magpie provider account-cap ... --window 通用积分
--amount 300). An uncapped wallet is unchanged:
balance alone, routed by Allowance.Left. A cap just set is judged from
the next reading. holdsBounds leaves wallets out: there is no whole to
reckon "holds" from.

Tests, each red on the old code (broken by hand where they compile):
- TestPluginWalletCapHolds: real plugin host, fake plugin, wallet
  10,000 -> 9,500 on an account capped at 4. Used 5, CapHeld set, the
  uncapped account untouched. Red with the plugin_usage.go hook
  removed (Used 0, Spent nil).
- TestWalletSpendCounted: falls counted, top-ups not, a restart reads
  the count back, the next local day and a told reset start over
  (UTC+8 fixed zone), failed and share readings left alone.
- TestWalletCapHolds: account cap 4, the window's own cap 4, and an
  amount cap of 700 (not held at 650 spent, held at 750).
- TestWindowHoldsLeavesAWalletOut: red without the holdsBounds change
  (a wallet reckoned a 500-token whole).

Run on mote at this tree on f8186c691. Rebased under it after: 7000b23b8
(GUI files only) and 36ddd5761 (internal/sessions only) (lockf ~/suite.lock
mote-run):
- go test ./internal/provider -run 'Wallet|Cap|Amount' -count=1: ok
- go test ./internal/usage -run TestWindowHolds -count=1: ok
- gofmt -l .: clean
- go vet ./... for darwin and windows, and for linux with -tags nogui:
  ok
Pushed and tagged at once, per the owner's rule. The full go test ./...
-timeout 45m runs after the push and any red gets filed.

Not changed: the GUI. A wallet meter still shows "{n} left". A capped
one shows "At its cap" from used. The meter's Amount... item still
needs a total and a unit, so an uncapped wallet doesn't offer it yet
(follow-up). A Text window (a balance that isn't
a number) still can't be capped by share.

Reported-by: 9won (Discord)
2026-11-09 19:23:13 +08:00
yetone fc8e98ba47 edit: Codex's thousands of [projects] tables are left out of the reads that don't want them (#2278)
Codex writes a [projects."…"] table for every project it is trusted in;
the owner's config.toml has 10,933 of them in 1.5 MB. go-toml's decoder
checks each table against its siblings one at a time, so every decode
of the file cost ~0.3s of CPU, and six readers decoded it again each
time Codex wrote it, plus a whole-file check before each write magpie
made to it.

- edit.TOMLWithout drops [projects…] tables in a single unstable.Parser
  pass. The agent's codexTopOf, sessions' readCodexConfig, provider's
  readCodexStoreSetting, library's rtk sandbox, hooks rekey and MCP
  entries read through it. None of them reads projects. A file that
  doesn't parse is passed through unchanged, so it still fails.
- validateTOML checks definitions with the rest of the file and the
  projects decoded apart, 128 projects to a decode. A bare [projects]
  table, a dotted projects.… key outside the tables, or any error
  decodes the whole file, so the error is the one it gives.

Run on mote (M5 Pro):
- BenchmarkCodexConfigDecode (10,933 projects): 283ms -> 7.6ms a decode.
- BenchmarkValidateCodexConfig: 52ms (the whole decode was 283ms).
- Startup CPU profile, first 70s, the real-account copy (the real
  1,524,099-byte config.toml): 2.76s -> 2.26s of samples; go-toml
  0.32s -> none sampled.
- go test ./internal/edit ./internal/sessions ./internal/provider
  ./internal/library ./internal/agent: all ok.
- go vet of the same five on darwin, GOOS=linux and GOOS=windows; gofmt -l clean.

Broken by hand:
- Decoding the batches into struct{} instead of a map:
  TestValidateTOMLDefinitionsInGroups went red ("a key twice", "a
  subtable then its key"), so the check keeps maps.

Not tried:
- the whole suite. Only the five packages that read the file were run.
- Now that projects is left out, a project table defined twice no longer
  fails these readers' decode. Codex itself refuses such a file.
2026-11-09 19:07:06 +08:00
yetone c056b7c8c3 provider: a Responses provider's turns may go over the Responses WebSocket (#5781)
A provider the user added with an http(s) Responses address can now send
its Responses turns over the Responses WebSocket that magpie already
speaks to chatgpt.com (codexSocket), with `socket=auto|on|off`:

- off, or absent: today's behaviour exactly. Provider.Via hides any
  socket value an outer context carried, so such a provider never dials.
- auto: tries the socket, falls back to HTTP when the handshake is
  refused or the socket ends before the reply, and speaks HTTP to a host
  for 10 minutes once it refused the handshake (codexShun).
- on: the same fallback, but never shuns; the socket is tried each turn.

Provider.Via puts the provider's Responses host and path in the request's
context (withSocket); codexSocket's gate is provider.SocketTurn, which
takes a ChatGPT turn as before, or a POST to that host at
<Responses>/responses. The rest is the ChatGPT leg's: the kept socket and
its delta (codexKeepKey now also hashes the scheme, X-Api-Key and
Api-Key), the error frames, 1009 handling. A provider's reply with no
Content-Type is marked text/event-stream, since it is read as one.
Routing, keys, limits, usage and masking are unchanged: only the
transport under the request differs.

Set with `magpie provider set <id> socket=auto|on|off` (refused on a
provider with an account, no http(s) Responses address, or Vertex,
TakesSocket), saved in providers.json as "socket", shown by `provider
show`, and in the editor's Advanced as a WebSocket tick beside HTTP
version (ticked saves auto, keeps a CLI's on, unticked saves off; shown
only while the Responses address is http(s) and there is no account).
docs/subsystems/providers-accounts.md describes it.

app.js pays for its rows by three long comments cut to one line
(renderMove, the vendors' status pages, header rows): the core's scripts
are 478 bytes smaller than on 0eac4e6aa (1,533,069 of 1,533,802); no
budget raised.

Run on mote at this change on origin/main 0eac4e6aa (since then main
added a39b63e88 and 7cabf0da9, internal/sessions only):
- gofmt -l clean; go vet (darwin) of provider, gateway, cli, gui, clean.
- go test -tags nogui ./internal/gui ./internal/cli: ok;
  ./internal/provider -run TestSocket: ok.
- go test ./internal/gateway -run 'TestResponsesProvider|TestCodexSocket|
  TestCodexKept|TestCodexTurn|TestHTTP1|TestInsecureTLS': ok. The new
  tests use an httptest WebSocket upstream: a turn over the socket, a
  provider without the field never dialling (and one on the same host
  with it), a refused handshake shunned on auto and tried again on on, a
  socket closed before the first event going over HTTP, the kept
  socket's delta on the next turn, and the reply being a stream.
- node --test provider-socket (new; chromium and webkit, en zh zh-TW ja
  de, 1100 and 420 wide), provider-http1, provider-insecure-tls,
  i18n-en-no-cjk: pass. i18n-keys' "a plugin's words are its own" is
  red for three words in files this doesn't touch, filed as #5327/#5332,
  #5426 and #5482.
- One rebase earlier (on 2a48974e8, the same change): GOOS=linux (nogui)
  and GOOS=windows go vet of the four packages clean, and the whole of
  ./internal/provider ok.
- Broken by hand, each red then green: SocketTurn codex-only (all six
  gateway tests red); a path-suffix gate in place of the context
  (WithoutSocketNeverDials, TestSocketTurn red); the never-shun case
  removed (RefusedOnTriesAgain red); the Content-Type line removed
  (ReplyIsAStream red).

Not tried: a real Responses upstream speaking the WebSocket (no network
in tests); the keep key's X-Api-Key/Api-Key separation has no test of
its own; the editor in the Linux app's WebKitGTK; the full suite (run
after the push).

Reported-by: matrix0487 (Discord)
Reported-by: faithleysath (#5781)
2026-11-09 18:57:29 +08:00
yetone 4da0aa0272 provider: Kiro's mover min is 0.1.35, its sign-in words in magpie's languages
Kiro plugin 0.1.35 (plugins 588b3611) gives each sign-in way, its first
question, the question's choices and their hints in zh, zh-TW, ja and de,
which magpie shows since the commit before last, and the API key field a
ksk_… placeholder (mahiro233 on Discord). keepMovedCurrent brings every
moved Kiro user to it.

npm view @magpie-community/opencode-kiro-auth version --prefer-online
--registry https://registry.npmjs.org: 0.1.35 (shasum 98618eda), at
landing. The publish run 42600418987 is red for the known
middleware-system-prompt and middleware-think-tags trust errors only; kiro
itself published. A one-line min change; the Go checks of the two commits
before ran at that tree on mote (internal/provider ok).
2026-11-09 18:36:07 +08:00
yetone 40cbdaa7e8 provider: an account's window can be capped at a fixed amount of its unit
A window magpie reads with a total and a unit (a day's 1000 credits, a
plan's requests) can now be capped at an amount of that unit, not only
a share: 9won_25273 asked to stop an account at 300 of its day's credits.

- AccountWindowAmounts keeps it per account and window (capId). An
  amount and a window's own share replace each other.
- WindowCaps.limitShare turns it into a share of the total for the mark
  and NearCap. CapHeld and capReached hold the account once the window's
  count reaches the amount (past), and rest it as the percentage cap
  does: the next account takes the request. cappedError and the trace
  say "has used 300 credits ... past its cap of 300".
- A reading with no total ignores the amount; the account's share
  applies.
- GUI: the window meter's menu has one more item, Amount..., typed in
  place (provider/windowcap with amount). It shows only on a window
  with a unit and total. Strings in zh, zh-TW, ja, de.
- CLI: magpie provider account-cap <id> <account> --window <name>
  --amount <n|off>.

Usage outside magpie counts: every cap reads the vendor's own count, so
what the account spent in the vendor's app or on another machine counts
from the next reading on. magpie can only hold back its own requests.

Run, at this head on Linux (wsl-run, magpie-desktop):
- gofmt -l: clean; go vet ./... for linux (-tags nogui) and windows: ok (darwin
  vet needs cgo, so it runs with the full suite on mote afterwards)
- go test -run 'Lang|ToolLoop|LoopGuard|Cap|Amount' ./internal/gateway
  ./internal/provider ./internal/cli: ok (TestWindowAmountCapHeld,
  TestSetWindowAmount, TestWindowAmountHoldsTheAccount, the CLI cases)
- GUI window-cap, window-cap-pool, account-cap in chromium and webkit,
  420 and 1100 wide, en zh zh-TW ja de: 78 of 78 in each engine. An
  earlier webkit run lost the amount test's page once ("Target page,
  context or browser has been closed"); it passed in 2 more full-file
  runs and 60 of 60 alone
- i18n-keys: only "a plugin's words are its own" red, words that aren't
  this change's (#5332, #5426, #5482)
Broken by hand: limitShare ignoring amounts (of < 0): TestWindowAmountCapHeld
and TestWindowAmountHoldsTheAccount go red.
Not tried: the full go test ./... at this head (queued on mote, runs
after); a real account at an amount cap.
iFlytek: 9won's 讯飞 overshoot isn't covered. Loomy's daily window sends
used as a count and amount as what is left (plugins#889); AStudio's
wallets tell a balance only, which no cap can hold (#5770).

Reported-by: 9won_25273 (Discord)
2026-11-09 18:19:02 +08:00
yetone 2b8ff0fbeb routing: an account's model list older than the model is unknown, not a plan without it
wudao_85256 on Discord: two ChatGPT Plus accounts on the Codex
subscription, each serving gpt-6.1-sol alone. With both on, Routing said
of the second "its plan doesn't list gpt-6.1-sol", and once the first ran
out of its allowance nothing failed over: an unlisted account is asked
only after a listing one refuses the model as unserved, never after a 429.
Re-adding the account and refreshing changed nothing.

Cause: the second account's own list (models/codex@<user>.json) was the
evidence, and it was stale. The ChatGPT backend lists gpt-6.1-sol only to
Codex 0.161.0 and later (dd12c75bf), and a saved account's list is asked
once a day, one account a look, for whatever codexVersion() was then (the
0.159.0 fallback before a Codex client has come through). Codex's own
account is asked every hour, so it gained the model and the saved one kept
a list without it for up to a day, every day the race went that way. A
refresh asks the saved lists only when they are a day old, and removing an
account leaves its list behind, so re-adding found the same list.

Fix, for every subscription that keeps each account's own list in the
catalog (Codex, Antigravity):
- catalog: a kept list records Since, when each model was first in it
  (carried from save to save; a list saved before counts from its fetch),
  and Asked, what it was asked as (LiveSince, LiveAsked, SaveLiveAsked).
- provider.AccountsFor: an account whose list lacks the model is left out
  only when that list can know the model: fetched after, or within
  listRound (10 minutes, one look) before, another account's list first
  had it, and, for ChatGPT, asked for the Codex magpie speaks
  as now (codexListBehind; a list with no version kept is behind). Else
  it is unknown, and routed over at its own place in the order
  (Account.listLags). A Free account's list fetched after the Plus one had
  the model still leaves it out (#520).
- codexFetchSaved asks a behind list at once, as one with no list, and
  one fetched more than listRound before another account's list first
  had a model (catalog.LiveNewest); either waits an hour after a failed
  try. Both Codex lists are kept with the version asked.

Not covered: plugin accounts (pluginLists) and Claude's entitlements keep
their lists elsewhere and are unchanged; API keys' per-key lists
(KeysFor) are unchanged. After the update every Codex list saved before
counts as behind until it is asked again (within the hour), so a Free
account beside a Plus one may be asked a Plus-only model in that time
and refuse it, as an unknown list should be.

Tested: TestStaleAccountListIsNotAPlanWithoutTheModel (two Plus accounts,
the second's list asked for 0.159.0 / with no version / fetched before the
first listed the model / the first's list from before Since: both routed;
fetched since, or in the same look, for this version: left out) is red
on the old AccountsFor, 4 of 6 subtests; its same-look subtest is red
with listRound taken out. TestBehindListAskedAgain is red with the behind
branch of codexFetchSaved taken out by hand, and
TestListOlderThanAnothersModelAskedAgain with the LiveNewest rule taken
out. TestLiveSinceCarriesOver. Without listRound,
TestCodexProviderListsEveryAccountsModels and
TestAntigravityPoolRoutesDiscoveredModels went red (a Free list fetched
moments before the Pro one counted as older than the model).
gofmt -l; go vet ./internal/catalog ./internal/provider ./internal/gateway
for darwin, linux and windows; go test ./internal/catalog ./internal/provider
ok on mote; go test -run 'Unlisted|Codex|Pool|Antigravity|Account'
./internal/gateway ok on mote.
Not tried: a real pair of ChatGPT accounts against the backend; the
version gating is the one dd12c75bf read from the backend's error.

Reported-by: wudao_85256 (Discord)
2026-11-09 18:13:08 +08:00
yetone 40cfae5d3b provider: Kiro's mover needs opencode-kiro-auth 0.1.34, which gives each model Kiro's credit multiplier as its rate
01huadalang on Discord asked for Kiro's credit multiplier. 0.1.34
(plugins 1aab125b) reads each model's rateMultiplier (rateUnit
"Credit") from ListAvailableModels and carries it as the model's rate,
which magpie's plugin host reads as Model.Rate. Usage is not multiplied
again: a meteringEvent's credits already include the rate. Raising min
makes keepMovedCurrent update every moved user's plugin.

Run: npm view --prefer-online --registry https://registry.npmjs.org
@magpie-community/opencode-kiro-auth version = 0.1.34, checked again at
landing. At base c7ebb6f8d on mote (lockf ~/suite.lock mote-run):
gofmt -l on migrate_kiro.go printed nothing; go vet ./...,
GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... ok;
go test ./internal/provider/ -timeout 45m ok (138.7s); go test ./...
-timeout 45m: 88 packages ok, one red, internal/gui
TestGatewayModeStatsNameTheGatewaySessions (keys [] leave out the
gateway's session). That is #5690, which is red in the first hour of a
local day, and mote's clock was 00:57. It has a patch from skygunner and
this change doesn't touch it. A rerun of internal/gui after 01:00 was
still going when this was pushed.

The pushed head is rebased onto origin/main 4314f4b77, whose seven new
commits don't touch migrate_kiro.go. They were not run with this change
before the push; CI runs them. The plugin's own record is in its commit
(packages/kiro 170 pass). Not tried: a moved account's plugin update on
a real install.
2026-11-09 17:22:08 +08:00
yetone 2d1b7c1b6c codex: a workspace sharing Codex's sign-in reads and sends as its own workspace
JdAZzzzzz (X) has a personal Pro and a Team seat of one ChatGPT login in
magpie, and switches workspace in the Codex app. Both cards read the
same plan ("Prolite"), week, reset time, pace and two reset cards; only
the token counts (local sessions) differed.

Cause: one ChatGPT sign-in reaches every workspace of its login with
one refresh token. Codex's workspace routing (codex-rs
login/src/auth/manager/workspace_routing.rs, /wham/accounts/check)
changes which one auth.json names in tokens.account_id. rememberLogins
saved each workspace as an account (codexWho goes by account_id), both
with that refresh token. renewSaved found the account not in use "held
by Codex" (heldByCodex: same refresh token), renewed through Codex's
store as it should, and returned that store's account id too: the
workspace Codex is on. So the other account's usage, plan, resets and
the gateway's requests for it named the workspace in use, and spent it.

- renewSaved returns the saved account's own workspace for a token read
  where Codex holds the sign-in, in ~/.codex and in another Codex folder
  (codexOwnWorkspace).
- A sign-in sync put Codex's auth.json on every record sharing its
  refresh token, so the other workspace's record was carried as the one
  in use. liveCodex and applyLogins no longer match by refresh token
  when the workspaces are known apart (codexWorkspacesApart).

TestCodexAppWorkspaceSwitchReadsEachWorkspace: one sign-in (same
refresh token, the real token's claim layout), the app's switch with
only account_id rewritten or with the tokens naming the new workspace,
Codex left on either one. On the old code all 4 cases are red with the
report's picture ("jd@example.com · ws-team (ws-team) reads plan
"prolite" ... 2 resets; its workspace has "team" ... 0 resets"), the
account's requests signed for the other workspace, and CollectSignIns
carrying each record as the other workspace. Green with the change.

Run at 9a00bfed1 (origin/main) plus this change, on mote (macOS):
- gofmt -l internal/provider: nothing
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  internal/provider; go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok
- go test -count=1 ./internal/provider: ok (134s)
Not run: go test ./... (mote's suite.lock queue had five suites ahead;
shipped without holding behind it).
Not tried: a real Team seat (no such account here); that ChatGPT's
backend honours chatgpt-account-id for a token whose claim names the
other workspace is what Codex's routing does, not checked by hand.
Not changed: once Codex rotates the shared refresh token, the other
workspace's saved copy holds a spent one (#5779).
2026-11-09 17:13:17 +08:00
yetone 608c1543e8 gateway: a bare model name goes to the asking agent's own subscription first
freefcw on X: Codex, started by Mirasim, asked for gpt-6-astra by its bare
name. Its own ChatGPT subscription serves it, but magpie sent it to Devin
through the group it found (auto-gpt-6-astra, soonest renewal first).
With found groups off it still went to another vendor: Resolve takes the
first provider in the Providers order, AutoStandIn and agent.Reseat did
the same.

Now:
- A bare model id the asking agent's own subscription in magpie serves (a
  provider whose Account.Agent is the agent: Codex's ChatGPT accounts,
  Claude's for Claude Code, Copilot's) goes there, found groups on or off
  (gateway ownFirst, provider.OwnRoute). count_tokens counts it there too.
- Kept as they were: a group the user made or changed by that name; a found
  group magpie set one of the agent's fields to (agent.SetToGroup over the
  applied record, #750's bare spelling included, wired as
  gateway.SetToGroup); a gateway key held to some models; ids with a
  provider in them and group refs; clients magpie doesn't know as an agent.
- Found groups off: a bare id several providers serve, none of them the
  agent's own, is refused for an agent that has a subscription of its own
  in magpie, with a 400 naming the provider/model ids and
  "magpie group auto on" (provider.OffSpread). Off, magpie picks no vendor.
- AutoStandInFor and Reseat's sameModel prefer the agent's own
  subscription for a found group that is gone.

Docs: gateway-routing.md's Model resolution row and the bare-ids section.

Run (mote, at this tree on c7ebb6f8d):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/provider
  ./internal/agent ./internal/cli ./internal/gateway: all ok.

Broken by hand, each red:
- ownFirst off in serve (and AutoStandIn back):
  TestBareNameGoesToTheAgentsOwnSubscription went to the relay with groups
  on, and again with groups off alone (the reporter's two cases).
- OffSpread check off: TestBareNameOnSeveralVendorsRefusedWhileGroupsOff
  answered 200 from the relay.
- SetToGroup check off: TestBareNameOfAGroupSetOnTheAgentStaysTheGroups.
- The user's-group and own-entry checks off: TestOwnRoute, TestOffSpread.

Not run at this head: the full ./... suite (mote's suite.lock had five
suites queued); it runs under the lock after the push, any red filed.
Not tried: a real Codex with a real Devin plugin account; Reseat's own
preference has no test of its own (needs a fetched Codex account in the
agent package's sandbox).

Reported-by: freefcw (X)
2026-11-09 16:28:02 +08:00
yetone c81065ca72 providers: System One for a custom provider and Ark's pay as you go
A user on Discord (#feedback) found no System One endpoint under a custom
provider's More endpoints (OpenAI Responses), no System One choice in its
Model settings, and on the Volcengine Ark page neither an endpoint nor any
model a routing group could ask as its classifier.

System One is asked at POST …/systemone under a provider's Decide base;
a model is offered as a group's classifier only when its provider has
one. Two causes:

- A custom provider kept a Decide URL only when its API was "System One
  base URL". With a Responses or chat URL there was no field for it, and
  Save sent "" for one the provider didn't have yet. More endpoints now
  has "System One URL" for any API, saved as typed.
- Ark's pay as you go answers System One on the same key at
  ark.<region>.volces.com/api/v1, but a provider asked at …/api/v3 (the
  preset's or a custom one, chat completions or Responses) had no Decide
  unless the user knew to type it. normalize now sets it (arkSystemOne);
  a URL the user gave is kept. The Coding and Agent Plans answer System
  One 404, so they get none, and decideKeys leaves out a key whose plan
  has none (a Coding Plan key beside a pay-as-you-go one). Ark's one
  decision model is offered whatever chat models are picked, as
  Bailian's is (OfferedDeciders).

Run on mote at this head's tree (65aacb8f8, on e0f6eda64):
- gofmt -l clean; GOOS=windows go vet and GOOS=linux go vet -tags nogui
  of internal/provider, internal/gateway, internal/gui: ok.
- go test -timeout 45m ./internal/provider ./internal/gateway
  ./internal/gui: ok (provider 136s, gateway 849s, gui 131s).
- GUI: custom-systemone-url.test.cjs (chromium and webkit; en, zh,
  zh-TW, ja, de; 1200px and 420px), i18n-en-no-cjk, i18n-keys,
  editor-advanced-align: ok but i18n-keys' "a plugin's words are its
  own", red on main for three plugin words Go files also say (#5332,
  #5426, #5482). Earlier, at c9d253e4a, 30 GUI files a provider editor
  change reaches: the same red, and editor-advanced-align's two whole-run
  reds under load 670 (#4615), green alone and in the run above.

- Rebased onto 77076eef4 (four commits: a group editor's Advanced,
  Remote magpie cards, npm updates on Windows; none in these files' code
  paths): gofmt, both vets, go test -run 'Ark|Decide|Decider|Classif|
  SystemOne' of the three packages, custom-systemone-url and
  i18n-en-no-cjk: ok.

Broken by hand, each red:
- arkSystemOne returning "": TestArkPayAsYouGoDecides and
  TestArkDecisionSkipsPlanKeys.
- OfferedDeciders without the bailianApart exemption:
  TestArkPayAsYouGoDecides (the providers with chat models picked lose
  their classifier).
- decideKeys without the Decides filter: TestArkDecisionSkipsPlanKeys,
  "doubao-seed-2.1-lite asked with: [k-api … k-coding]".
- No System One URL under More endpoints: custom-systemone-url, every
  subtest.

Not tried: a real Ark account (the decision call is held to the
recorded reply); a provider whose main key is on the Coding Plan with a
pay-as-you-go key beside it gets no Decide, since normalize reads the
provider's own URLs.
2026-11-09 13:05:00 +08:00
yetone 77076eef47 agent: an npm update on Windows lets go of magpie's own claude and codex first
CLJY (Discord) had %APPDATA%\npm with only the 308-byte sh shim of claude:
no claude.cmd, no claude.ps1 and no codex at all, and `npm i -g
@anthropic-ai/claude-code` ended in "npm warn cleanup ... EPERM ...
unlink ...\.claude-code-<rand>\...\claude-code-win32-x64\claude.exe".
On Windows a running program's file can't be removed. npm moves the old
package aside, takes the old shims away, and stops partway when a
claude.exe of that package is still running; the sh shim is what is left.

magpie keeps such processes running itself:
- the Claude subscription bridge keeps up to 6 Claude Code runs waiting
  for their conversations' next turns, for up to an hour;
- Codex's app-server daemon has no idle exit, and magpie restarts it.
Its Update button ran npm with both still up.

- agent.UpdateCLI, on Windows through npm, bun or pnpm, first lets go of
  them: gateway.LetGoIdleClaudeCode ends every waiting run (its session
  shelved for the next turn, as a run let go past idleMost is) and returns
  once each has exited; provider.StopIdleCodexDaemon stops the daemon when
  no codex session is on it. Runs in a turn and sessions are left.
- An update on Windows that leaves the CLI's file gone fails, saying to
  quit it and reinstall, instead of "updated".
- proc's toolIn (FindTool) and codexExecutable no longer take the bare
  extensionless file on Windows, which CreateProcess can't run. Beside
  name.exe and name.cmd, the sh shim alone stands for the .exe it runs
  (Claude Code's bin\claude.exe), read from cmd-shim's exec line and kept
  inside its folder; a node shim (codex) or any other script is skipped.
  The testdata shims are cmd-shim 7's bytes, made with cmd-shim@7 on the
  Windows box.

Run at this head (rebased on origin/main; after the rebase, vet on all
three systems and the changed tests again: ok on Windows and macOS):
- gofmt -l internal/: clean. go vet of proc, agent, provider and gateway
  on macOS (mote), Windows (win-run) and Linux (wsl-run): ok.
- Windows (win-run): internal/proc ok;
  TestToolInNPMShShimAlone, TestLetGoIdleClaudeCodeFreesTheExe and the
  TestClaudeIdle* tests pass. internal/agent, internal/provider and
  internal/gateway (-run "Claude|LetGo|Codex") have Windows reds, and
  the same run at origin/main c9d253e4a has the same ones (26 in agent,
  15 in provider, 2 in gateway), except TestUsageReadAndReadAgain, a
  clock-tick flake filed as #4796.
- macOS (mote): internal/proc, internal/agent, internal/provider and
  internal/gateway (-run "Claude|LetGo|Codex") ok.
- Linux (wsl-run): internal/proc and internal/provider ok; internal/agent
  red only in TestGrokInstalled, red the same on origin/main c9d253e4a
  (3 of 3), filed as #3548.

Broken by hand:
- toolIn taking the bare name again: TestToolInNPMShShimAlone red on
  Windows (6 cases).
- letGoIdle not waiting for the trees: TestLetGoIdleClaudeCodeFreesTheExe
  red on Windows, and with that check off the removal fails with "Access
  is denied" - the user's EPERM.
- no let-go call and no gone check: TestUpdateCLIOnWindowsLetsGoFirst red;
  StopIdleCodexDaemon ignoring sessions: TestStopIdleCodexDaemon red.

Not tried: a real npm update of Claude Code or Codex on the Windows box
with magpie running; the Windows-only path is tested with
updateGOOS = "windows" on macOS, and the process lock with a copy of the
test binary.

Reported-by: CLJY (Discord)
2026-11-09 12:56:42 +08:00
yetone 08a42c40ff provider: a Remote magpie's cards are passed on down a chain of magpies
yuyong_id (Discord) chains three magpies through Remote: magpie1 has a
Codex subscription, magpie2 uses magpie1, magpie3 uses magpie2. magpie2
showed magpie1's Codex card; magpie3 showed none.

Cause: since 8c71cd27f a magpie told only its own cards
(CachedCards kept From == "") and the receiver skipped any card it was
told with a From (remoteCards). So no card from a remote, of any
provider, reached a third magpie; Codex wasn't special. Antigravity and
DeepSeek showing at magpie3 means magpie2 has those accounts itself
(not checked with the reporter).

Fix:
- CachedCards passes on the cards it already holds from each Remote
  magpie (passedOnCards, from the 30s cache: it asks no remote, and a
  held remote's cards stay home).
- Each card told carries Via, the magpies (catalog.Self) it passed
  through; a receiver leaves out a card that comes back to it or has
  passed more than MaxVia magpies (catalog.Loops, the same rule as
  magpie_via for models).
- Refresh on a passed-on card ("m1/codex" at magpie2) goes to
  RefreshUsage, which asks that remote again, instead of a 400.
- Sibling: the status line (KeptQuotaReport, /v1/magpie/quotas?kept=1)
  read CachedCards too, so a magpie's own Remote cards were missing
  from it; now there.
- A held key still sees only own cards (quotaScope unchanged).
- Codex's resets stay with the magpie next door only, as before.
- catalog.Self becomes a func with SetSelfForTest, so one test process
  can play magpie2 and then magpie3.

Run on mote at b9cdac0c6 (rebased on origin/main 8a7f77cb7):
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build ./...: ok.
- New TestRemoteChainPassesOnCards (magpie1 fake -> this gateway as
  magpie2 -> magpie3 reading it: Codex, Antigravity, GLM plan and a
  DeepSeek balance arrive, named "Codex · M1 · M2", Via [m1 m2],
  refresh reaches magpie1, a looped card is dropped),
  TestKeptReportHasRemoteCards and the updated TestRemoteMagpieCards,
  with TestRemoteMagpie*, TestRemoteSelf, Quota* and TestCachedCards:
  ok; -race -count=3 on the new and changed ones: ok.
- On origin/main with only these tests (and the Via field / Self func
  they compile against): all three FAIL. magpie3 gets just the
  "nothing read on that magpie yet" stand-in for magpie2, the kept
  report is empty, and the third magpie's card is nil.
- Full suite (-tags nogui -timeout 45m ./... under the suite lock):
  cut short when mote closed the connection, before any package
  reported. Rerunning at the pushed head.
- Rebased again onto origin/main e0f6eda64 (gateway changed): go vet
  of gateway, provider and catalog and the same targeted tests: ok on
  Linux (wsl-run magpie-desktop, -tags nogui); mote was refusing ssh.

Not tried: three real magpies on separate machines.
Not changed: a passed-on card's quota history (#5747).

Reported-by: yuyong_id (Discord)
2026-11-09 12:47:12 +08:00
yetone e0f6eda641 gateway: a probe's reply that thinks its 16 tokens and ends unsaid is answered (plugins#827)
Through a Remote magpie, the plain model test of Open Design's
glm-5.3-flash was red. The model always thinks. It spent the test's 16
tokens on that and ended after content_block_stop, with no message_delta
or message_stop. So:

- translate made it a 502 "ended before it was complete";
- the 502 is busy, so the remote retried it and waited out its 60s
  patience;
- the asking magpie had given the remote only 20s (testWait), and said
  no answer came.

Each step is now fixed for the class, not for this model:

- A reply whose request was capped at a short probe's worth
  (cutVoidTokens, 1024) and that spent some of it, then ended cleanly
  with nothing saying it ended, ended at its length (endsAtProbeCap).
  - This holds in translate, in streamTranslated and in gathered (a
    Responses plugin's stream asked whole becomes response.incomplete at
    max_output_tokens).
  - It covers Anthropic and Responses upstreams only. Gemini always
    ends with a finishReason, so a Gemini stream without one stays a cut
    (TestGeminiUpstreamEndedShort, asked for 256, caught a wider first
    draft).
  - A reply asked for more than 1024, or one that spent nothing, is
    still the 502.
- A client may say how long it waits (provider.WaitHeader,
  X-Magpie-Wait, in seconds). The gateway then takes no same-one retry
  pause and no patience round that would end within clientRoom (10s) of
  that wait (keptAlive.outlives), so the client gets the error while it
  still waits. Like every X-Magpie- header, it is not sent upstream.
- A model test through a remote magpie waits pluginTestWait (60s), as a
  plugin's test does here, and sends that wait as X-Magpie-Wait.

Not changed: a stream relayed as it came (passthrough to an agent of the
same protocol) still gets no end added. That is filed as #5736 and named
in gateway-routing.md.

Run, through mote-run:
- At the pushed tree, rebased on origin/main b68218f43 (802f03e68 after
  it changes only site/): go vet, GOOS=windows go vet and GOOS=linux go
  vet -tags nogui of internal/gateway and internal/provider are ok. go
  test of both packages with -run
  "ProbeCap|Gathered|ClientWait|RemoteMagpie|EndedShort|Gemini|SingleProvider|Responses|Enum|Group|Spent|Capped|Patience"
  is ok. That covers the base's new Responses-enum and group commits.
  At 8a7f77cb7 the same kind of run, with Compact|Signin|Carry for that
  base's commits, was ok.
- Full run at 9c34dc7cb (the same change, rebased on origin/main
  e2afbfc15): go vet
  ./internal/..., GOOS=linux go vet -tags nogui ./internal/..., and
  GOOS=windows go vet ./internal/... are ok; go test ./internal/gateway
  ./internal/provider -timeout 45m: provider is ok; gateway is ok
  except TestCodexGeneratedImagesPastOldLimit (#5281: held 31s
  without routing in a full run; at this head it passes alone, 3 of
  3, with -count=3)
- At 32a31963b, the first draft: go vet ./..., GOOS=linux go vet -tags
  nogui ./... and GOOS=windows go vet ./... were ok; gofmt -l was empty.
  The suite there:
  - TestGeminiUpstreamEndedShort was red. The rule was too wide, and it
    is scoped above.
  - TestCodexGeneratedImagesPastOldLimit was red: #5281, the
    images-body hold, not on these paths.
  - TestCodexListTagNotKeptOverAFreshFile was red: #4216, under load.

Broken by hand, then put back:
- endsAtProbeCap returning false:
  - TestProbeCapEndsAtLength goes red, both whole (502 ended before it
    was complete) and stream (no finish_reason length).
  - TestGatheredProbeCapIncomplete goes red (capped 16: 502).
- outlives returning false: TestClientWaitBoundsPatience/short_wait goes
  red (upstream asked 6 times).
- probeOnce's remote-magpie wait and header taken out:
  TestRemoteMagpieProbeWait goes red ("no answer in 1s", X-Magpie-Wait
  said "").

Not tried: a real Open Design account, and a real two-magpie Remote
setup. The fixture is the reporter's described ending (thinking block,
content_block_stop, close), not their captured bytes.

Reported-by: Gitleonan
2026-11-09 12:42:35 +08:00
yetone 44d6dd75d1 gateway: a subscription's capped or spent turn goes on to the user's group with it in
adorable_piglet on Discord (v0.1.3354): a Codex subscription with a usage
cap set in magpie, first in a routing group with two APIs after it. Past
the cap the Codex app's turns were answered 429 "usage cap reached" and
never reached the APIs; only switching the subscription off in Providers
moved them.

Cause: the Codex app signed in to ChatGPT asks Codex's own model
("gpt-5.5"), never "group/<id>". With a cap on the account,
codexAccounts routes the turn as codex/gpt-5.5, and serve plans the
codex provider and its own Fallback list only. A group that merely has
codex/gpt-5.5 in it was never planned, so with every account held the
answer was cappedError's 429. A request for the group itself was already
routed on past the cap (TestCappedSubscriptionGivesWayInGroup, green on
the old code too). The same gap was on Codex's own sign-in out of its
allowance at OpenAI: codexFallsBack counted the subscription's Fallback
only, so the backend's usage_limit_reached reached Codex.

Fix:
- provider.GroupsAfter(id): the routing groups the user built that have
  the model in them and another member to go on to, in the user's order;
  auto groups, hidden or switched-off ones are none.
- serve: when every account is held at its cap (pl.capped, no candidate
  left, CapStop off), or for a turn codexFallBack handed on, the provider
  is planned again with those groups after its own fallbacks
  (groupsAfter), each group routed as a request to it is. One place, so
  it holds on every protocol (chat, responses, messages, Codex's backend
  path), streaming or not, and for plugin-served subscriptions.
- codexFallsBack counts those groups as fallbacks too.
- Stop at the caps (CapStop) still answers 429 (planPaused returns
  before any fallback, the groups included).

Tests:
- TestCappedCodexOwnModelGoesToItsGroup: backend path with "gpt-5.5" and
  /v1/responses with "codex/gpt-5.5", stream and not; red on origin/main
  3cabaab54 (4 of 4, 429 usage cap reached).
- TestCodexOneAccountSpentGoesToItsGroup: one ChatGPT account, the
  backend's usage_limit_reached, group [codex/gpt-5.5, a/m].
- TestPluginCarefulPool: the fake plugin as Factory through a real
  plugin host, both accounts past their caps, no fallback, group
  [factory/fake-1, spare/m2]: 429 with Stop at the caps on, the API with
  it off.
- TestCappedSubscriptionGivesWayInGroup (11 routings x 4 paths) and
  TestSubscriptionCappedMidConversationGivesWay pin the group/<id> case.

Broken by hand (each through mote-run):
- the serve block off: TestCappedCodexOwnModelGoesToItsGroup 4 of 4 red
  and TestPluginCarefulPool red ("group, stop off: 429").
- GroupsAfter out of codexFallsBack: TestCodexOneAccountSpentGoesToItsGroup
  red (429 usage_limit_reached).
- the handedOnOf arm out of serve: the same test red.
- the !p.CapStop guard out: still green, since planPaused itself returns
  before fallbacks with CapStop; the guard only saves a second plan.

Run at this tree (mote-run, mote under load from other sessions):
- gofmt -l . empty; go vet (darwin, GOOS=windows, GOOS=linux) of
  internal/gateway and internal/provider ok.
- go test -timeout 45m -count=1 ./internal/gateway ./internal/provider:
  provider ok (673s); gateway FAIL (2545s) on TestBurstTellsNoSpeed/
  responses_from_chat_burst alone (5000 tokens in 1091ms read as a
  speed), a timing red under load, ttft untouched here; 3 of 3 green
  alone at this tree, noted on #2719 (the same test's chat_burst).
  That run was at base 3cabaab54.
- Rebased onto origin/main 8a7f77cb7 (9 gateway/provider files changed
  there): gofmt empty, go vet ok, and go test ./internal/gateway -run
  "Cap|Capped|Fallback|TestCodexOneAccount|TestPluginCarefulPool|
  TestSubscriptionCapped" ok (199s) at the pushed tree.

Not tried: a real Codex app and ChatGPT account past a real cap (fakes
only). Not covered: an account that crosses its cap in serve's near-cap
walk (planned with room, held at its turn) still gets the 429 for that
turn; the next turn is planned with it held and goes to the group.
Drawing (images) and embeddings keep their own planning and are
unchanged. No GUI change.
2026-11-09 12:31:00 +08:00
yetoneandggbdpq 8a7f77cb71 provider, plugin: a sign-in whose refresh token rotates is never carried (#5583)
With Sign-ins ticked in Sync, a MiniMax Code sign-in went to both of the
reporter's computers. MiniMax spends a refresh token once: each computer
renewed it as it came due, the loser got invalid_grant 400 and was
signed out for good, with no newer generation anywhere in the sync path
to come back from. Qoder spends its refresh tokens once too.

The safest rule is that such a credential has one owner: it is never
carried. The auth hook declares `rotating` beside keepAlive and
refreshLead; the host passes it in the providers' row (Provider.Rotating),
and the carry path honours it: CollectSignIns leaves such sign-ins out of
what a backup or sync carries, and records() leaves out one an older file
carried, so MergeSignIns neither takes one in nor sends one up, and
RestoreSignIns writes none. Since the plugins don't declare it yet, and
the plugin host's list may not be read when a sync runs at start, magpie
also knows MiniMax Code (minimax-code, minimax-code-global) and Qoder
(qoder, qoder-cn) as rotating (rotatesKnown, read from their sources).
Nothing is deleted: local sign-ins stay, and a copy already on the server
falls out of the carried set by the usual removal.

The tradeoff, on purpose: each computer signs in to these itself. The
reporter's "relay" (carry one generation chain, re-read the store before
declaring a sign-in dead) would keep cross-computer sync for them; it is
a design of its own, not this fix, and stays open on the issue.

Ported from ggbdpq's patch on the issue, with rotatesKnown added so the
rule holds now and before the host lists its providers.

Run:
- TestCollectSignInsLeavesARotatingSignInOut,
  TestMergeSignInsDoesNotTakeARotatingSignInIn,
  TestRestoreSignInsLeavesARotatingSignInOut and
  TestKnownRotatingSignInsStayWithNoPluginListed (new): all four red on
  the old signins_carry.go ("a rotating sign-in is carried", "put in
  here", Added:1, "minimax-code's rotating sign-in is carried"), green
  after.
- go test -tags nogui ./internal/provider/ -run 'SignIns|Rotating' on mote.
- gofmt -l on the changed files: nothing.

Not tried: the two-computer race with real MiniMax Code or Qoder accounts.

Reported-by: skalitz-wolf (yetone/magpie#5583)
Reported-by: gua2100 (Discord)
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-09 12:04:20 +08:00
yetone 64ecd0f693 provider: Qoder's mover min is 0.2.64 (plugins#880, #879)
qoder 0.2.64 answers a model the account's listing has off, while its
usage says no credits are left, with 429 "usage limit reached: the
account's credits are used up (800 / 800 credits), …" instead of the
400 "unknown or disabled model" that a routing group on
/v1/chat/completions neither failed over on nor rested the account for
(yetone/magpie#5726). An id Qoder never served keeps the 400. Its
Windows check-in also finds the runtime qodercli 1.21.2 caches as one
file, runtime-info-win32-<arch>-<hash>.exe. Raising the min lets
keepMovedCurrent update every moved Qoder and Qoder CN user.

npm checked first: `npm view --prefer-online --registry
https://registry.npmjs.org @magpie-community/opencode-qoder-auth version`
gives 0.2.64. Plugins commit e2d15ba6.
Run on mote: `go test -count=1 -timeout 45m ./internal/provider` ok
(262s). `gofmt -l internal/provider` is clean.
Not tried: a real out-of-credit Qoder account; Windows itself.

Reported-by: zane668 (#880)
Reported-by: ArmedHelicopter (#879)
2026-11-09 10:05:44 +08:00
yetone 6b0b7a96e9 claude: a Max 20x account reads Claude Ultra, apart from Max 5x
Anthropic renamed Max 20x to Claude Ultra, but Claude Code still says
subscriptionType "max" for both Max plans; only rateLimitTier
(default_claude_max_20x / _5x) tells them apart. Every account chip read
"Claude Max", so a 20x account looked like a 5x one (owner's report).

claudePlan names "max" with a max_20x tier "ultra". Every place a Claude
plan is written uses it (sign-in, Claude Code's own login, a saved
directory taken back, the live account, `claude auth status`), and
parseLogins reads an account saved as "max" before by its tier, so no one
signs in again. claudeRenewedHeld compared the raw "max" with the held
account's plan; it now compares the same name, or a renewed Ultra
account would no longer find the held one.

Run: TestClaudeMax20xIsUltra on mote at da52b8ab7 + this change: ok.
Broken by hand: without parseLogins' rename the saved-plan case is red;
with claudeRenewedHeld on the raw subscriptionType the held case is red.
At b855cfee9 + the same change: internal/provider ok, internal/gateway
ok, internal/gui red only in TestMainWindowCorners/macOS_26_SDK (#3949,
macOS 27, unrelated). The same three packages at this head were still
running when the owner asked to ship.
Not tried: the real app's account list; the owner's logins.json has six
20x and one 5x Max account, which these rules name Ultra and Max.
2026-11-09 06:48:26 +08:00
yetone aa3d11d5b7 kimi: a key's booster wallet is read, and a key spending it isn't rested to the month (#5721)
apple_test_src on X (#5721): a Kimi Code key at 98.85% of its month was
rested until the month renews, while Kimi still served it from its
booster wallet. magpie never read the wallet.

readKimiCode now reads booster_wallet (or boosterWallet). A BOOSTER wallet
with an amount over 0 adds an "Extra usage" row: amountLeft, in cents x 1e6,
in the currency of monthlyChargeLimit, else monthlyUsed, else USD. When
something is left, the plan windows are marked Credits. The gateway's full()
then doesn't count a key on its booster as full at the month's 98%. A 429
quota refusal rests it as any refusal does, not until the month renews.
A wallet that is empty, of another type or missing changes nothing.

Tests: TestReadKimiCodeBooster runs on the reporter's literal body
(testdata/kimi-booster-5721.json, where 0 is left: no Credits) and on the
same body with amountLeft injected (snake and camel case). A GIFT wallet
and amount 0 add nothing. TestKimiKeyOnItsBoosterIsNotRestedToTheMonth:
a key with booster left isn't full and its 429 rests it under 24h; a
spent key is still rested by its window.

Run on mote: gofmt -l clean; GOOS=linux and GOOS=windows go vet of
internal/provider and internal/gateway; go test ./internal/provider
./internal/gateway -count=1 -timeout 45m: both ok (154.9s, 951.7s).
Broken by hand: routing.go reverted turns the gateway test red ("a key
on its booster counts as full at the month's 98%"); dropping the Credits
marking turns the provider test red.
Not tried: a real Kimi key with booster balance left (the reporter's
body has 0 left).
2026-11-09 05:06:48 +08:00
yetone ed0ab567cb usage: a key's balance card carries its curve again
nf1qaz2w on Discord: Usage -> Overview showed the subscriptions' curves
and no "Balance over time" for any API key. f8525323d (v0.1.3281) kept
typed estimates out of the balance history by passing KeyBalances'
cards through slices.Clone before noteBalanceHistory. noteBalanceHistory
sets each card's BalanceTrend on the slice it is given, so every trend
went onto the copy and was thrown away: since v0.1.3281 no key's card
has had one. The history file kept growing, so the curves come back
with their past readings.

Now KeyBalances notes the history on its own cards, and
noteBalanceHistory itself leaves an Estimate out: no point kept and no
trend given, for KeyBalances and for noteCardHistory alike.

Run (mote):
- TestKeyBalancesCarryTheirTrend (new): a key read at $3 an hour ago and
  $2 now has a two-point trend. It is red at the old balance.go ("trend
  <nil>").
- Broken by hand: no Estimate guard in balancePointsOf makes
  TestTypedBalanceCountsDown go red (an estimate kept in the history).
- go test -run 'Balance|Typed|OwnBalance' ./internal/provider: ok.
- gofmt -l clean; go vet (darwin, GOOS=linux -tags nogui, GOOS=windows)
  of internal/provider and internal/gui; go test -tags nogui -count=1
  ./internal/provider ./internal/gui under mote's suite lock: ok.
- GUI: balance-curve, balance-*, usage-*, quota-* among the 293 files
  run for the commit before this one, same tree: no red of their own.
- Rebased onto origin/main 4436b7d98 and run again there: the provider
  balance tests ok; routing-calm-in-flight and balance-curve 14 of 14 ok;
  TestCoreScriptBudget red, the same at 4436b7d98 alone (1,534,166 bytes
  either way, these commits add none to the core), filed as #5720.

Not tried: the full go test ./... and the whole GUI suite; a real
account's curve in the built app. No GUI change: the
page draws a trend when the card has one.

Reported-by: nf1qaz2w (Discord)
2026-11-09 04:06:39 +08:00
yetone b684308c61 provider: an allowance or usage read a test leaves running ends with it (#3174)
TestClaudeAccountServesModelsListedSinceItsFetch went red in full
internal/provider runs under load (macOS CI at 5849b47ca, run
42448627522; mote; WSL): find(All(), "claude") came back empty right
after claudeSignIn.

Cause: the test before it in file order, TestClaudeAllSignedOutStaysListed,
ends with InUseLogin("claude"), whose loginRoom asks Allowances. Allowances
starts its read in a goroutine and waits for it only firstWait (3s); under
load the read runs on past the test. It reads the logins (Logins ->
liveLogin -> claudeCredential) with whatever HOME is set by then: the next
test's, after claudeHome forgot the credential cache and before
claudeSignIn wrote the sign-in. It caches "no credential" in the one
global slot for 10s, and the next test's All() is served that miss, so
there is no Claude row. skygunner's -race run on #3174 named the same
path (isolate's write against an Allowances read from that test).
SubscriptionUsage (with a stale copy to serve) and KeyAllowance leave
their reads running the same way; an instrumented full run saw all three
store into the credential cache from goroutines no test waited for.

Fix: those three reads start through goRead, which counts them
(readsOut). isolate, which every account test goes through, waits for
them before it resets anything and again as the test's last cleanup,
and fails the test if one still runs a minute later (a read gives up
after 30s). TestReadLeftOutEndsWithItsTest leaves an Allowances read
out past firstWait and checks it ended with its subtest.

Not taken: the patches offered on #3174 (ggbdpq, skygunner) forget the
credential cache after claudeSignIn's write. That hides this one victim's
symptom while the read keeps running into the next test's home and its
other caches (usedCache, logins), so the cause is left.

Run on mote (darwin arm64, go1.26.8):
- pinned repro (throwaway test, deleted): an Allowances read left out
  past a 10ms firstWait reading claudeCredential in a loop, then the
  victim; on 691a10446 the victim was red 3 of 5 with the issue's
  output (claude_models_test.go:52 ... Account:<nil>} false).
- with the fix: the repro, TestReadLeftOutEndsWithItsTest and the victim
  -count=10 -race ok.
- broken by hand (goRead as a bare go f()): TestReadLeftOutEndsWithItsTest
  red 5 of 5 ("ran on after its test"), the victim red 4 of 5.
- go test ./internal/provider -count=3 -shuffle=on (seed
  1794116678624149000): one red, TestCodexSubagentModelsKept's
  allocation ratio (filed as #5435, output added there); all else ok.
- go vet ./internal/provider on darwin, GOOS=linux -tags nogui and
  GOOS=windows: clean. gofmt -l clean.
- full suite: `lockf /Users/yetone/suite.lock go test -timeout 45m ./...` on mote at this tree (base 691a10446): every package ok, no reds (internal/provider 201s, internal/gateway 978s, internal/agent 379s). A first attempt was cut off when mote rebooted.
- after rebasing onto origin/main a5c97cd83 (which changed internal/provider): `go test ./internal/provider -count=2 -shuffle=on` on mote, seed 1794163393889037000: only TestCodexSubagentModelsKept red, the allocation count already filed as #5435.

Not tried: the loaded CI schedule itself (the repro stands in for it);
Windows and Linux test runs of the package.

Fixes #3174
2026-11-09 02:47:26 +08:00
yetone c6bdc172a0 netguard: a fake-IP resolver's own AAAA beside its fake A is left out, not refused
jiezhengj (Discord, 11-08): under Clash Verge Rev's TUN (mihomo
1.19.33, enhanced-mode fake-ip, fake-ip-range 198.18.0.1/16) every
web_fetch of `magpie mcp search` answered "it is at a private address".
#2593 already lets a name whose every answer is in 198.18.0.0/15 through,
so that wasn't it. Clash Verge Rev writes dns.ipv6: true and
fake-ip-range6: fdfe:dcba:9876::1/64 into its default config (and fills
in 2001:2::/64 when IPv6 is on without one), and mihomo then answers
AAAA from that pool too (dns/middleware.go withFakeIP, read at
v1.19.33). The resolver's answer was 198.18.x.y beside fdfe:dcba:9876::z,
the ULA is private, a fake answer beside a private one is refused, so
every name failed.

netguard.FakePaired names that AAAA: an IPv6 address in fc00::/7 or
2001:2::/48 while the same answer holds an IPv4 one in 198.18.0.0/15.
It is dropped where Loon's paired AAAA is dropped (dropLoon in the
gateway's publicTransport, iconIPs for a provider's icon, the two
places that share netguard), and the fake A is judged and pinned in its
place. 2001:2::/48 (RFC 5180 benchmarking) joins Public's special ranges;
it wasn't covered by 2001::/32 and passed as public.

Why this opens nothing new: the AAAA is never dialled. What is dialled
is the fake A, exactly as when the resolver answered the A alone, which
#2593 already allows: an address in 198.18.0.0/15, which no host on a
normal network uses, so without a TUN it goes to the default route and
reaches the internet or nothing. A hostile DNS that pairs 198.18.0.9
with fd00::<a LAN host> gets the 198.18 address dialled, never the LAN
one. Through a proxy on this computer the proxy gets the name, as for a
pure fake answer; a hostile resolver could already give a proxy another
answer for that name than it gave magpie, so the pairing adds no route.
What stays refused (tests below): a ULA or 2001:2:: alone or beside a
real A, a fake pair beside 10.0.0.1 or ::1, a fake A beside a public
address, and ULA / 2001:2:: / 198.18 address literals.

Ran (on mote; whole packages at base f1a4b5751, the -run set, vet and
gofmt again after the rebase onto the next main):
- go test ./internal/netguard ./internal/provider ./internal/gateway
  -run 'FakePaired|FakeIP|Loon|Icon|Public|Fetch|Guard|Private': ok
- go test -timeout 45m ./internal/netguard ./internal/provider
  ./internal/gateway (whole packages): ok (netguard 0.2s, provider
  130s, gateway 838s)
- go vet for darwin, GOOS=linux and GOOS=windows on those packages,
  gofmt -l internal cmd: clean

Broken by hand: with netguard.go, image_fetch_guard.go and icon.go back
at origin/main, TestFakeIPWithItsIPv6Answer fails with the reporter's
own message ("couldn't fetch http://example.com/: it is at a private
address ..."), TestFakeIPRefusesTheRest lets http://[2001:2::7]/
through, and TestIconIPsLoon refuses fdfe:dcba:9876::5 + 198.18.0.5 and
keeps 2001:2::5. Green with the fix.

Not tried: a real Clash Verge Rev / mihomo TUN on mote or the Mac (the
answers are a fake resolver in the tests, nothing reaches the network);
sing-box's inet6_range is covered only as far as it is a ULA. Not run:
the full ./... suite (mote's suite.lock had five full runs queued).

Reported-by: jiezhengj (Discord)
2026-11-08 22:55:09 +08:00
yetone 2c31815c59 provider: Kiro's mover needs opencode-kiro-auth 0.1.33, which asks an account in the IDE's CreateResponse experiment at /v1/responses
ThirdTimes (plugins#842, plugins#848): on one Builder ID account the
plugin's generateAssistantResponse got 429 USER_REQUEST_RATE_EXCEEDED,
and Kiro IDE 1.4.121 was answered 11s later on CreateResponse ("api=
CreateResponse armSource=experiment"). 0.1.33 (plugins 9b41df15) reads
Kiro's feature configuration as the IDE does. An account in the
create_response_api arm is asked at /v1/responses with the IDE's body and
headers, and any other account is unchanged. Raising min makes
keepMovedCurrent update every moved user's plugin.

Run: npm view --prefer-online --registry https://registry.npmjs.org
@magpie-community/opencode-kiro-auth version = 0.1.33 at landing.
mote-run go test -run 'Kiro|Mover|Moved' ./internal/provider/ ok. gofmt -l
clean. The plugin's own record is in its commit (package 168 pass, plugins
root 6892 pass 0 fail). Not tried: a real Kiro account in the arm.
2026-11-08 20:38:55 +08:00
yetone 0f04dca6e3 provider: WorkBuddy's plugin is at least 0.2.26, where deepseek-v4.1-flash replies 128000
sayagoodbyeplz on Discord: WorkBuddy's deepseek-v4.1-flash was told to
agents as replying 384000 tokens (models.dev's), but WorkBuddy serves
128000. Plugin 0.2.26 (magpie-community/plugins 7e01fa81) gives each
model it declares before the account's list is read its reply limit,
with the China build's deepseek-v4.1-flash at 128000. keepMovedCurrent
now brings every moved user's plugin up to it.

npm view --prefer-online --registry https://registry.npmjs.org
@magpie-community/opencode-workbuddy-auth version: 0.2.26, at landing.
Run (WSL magpie-desktop, Go 1.26.8, at this tree, since mote is down):
go test -tags nogui -run 'Mover|Moved|Migrat|ModelOutput|Output'
./internal/provider/: ok
Not tried: a real moved WorkBuddy account updating to 0.2.26.
Full suite not run at push.

Reported-by: sayagoodbyeplz (Discord)
2026-11-08 19:05:37 +08:00
yetone b0926e81a2 import: a link can say where its key's balance is read (balance=, balance_path=, balance_method=)
A relay's "Add to magpie" link can now name the URL that tells a key its
balance, where the amount sits in the reply, and GET or POST. magpie
takes it only on the host of one of the link's own base URLs, over
https, with no userinfo or fragment, so a link can't send the key
anywhere its requests don't already go; anything else refuses the whole
link. balance_path or balance_method without balance is an error. No
header or token is taken from a link: an account-wide token is worth
more than a key, and a URL stays in browser history.

- provider.ParseImport: linkBalance checks and sets BalanceURL,
  BalancePath and BalanceMethod.
- CLI: the import preview shows the balance URL and doesn't ask it
  before yes (showProviderAsking).
- GUI: the import dialog shows method, URL and field (.imp-bal).
- Docs: docs/import in en, zh and ja (table rows, a note on headers,
  the builder's three fields with the same host check, a security
  bullet); docs/reference.md's parameter table.

Run on mote at this tree (rebased on 8fa3c60f8):
- go test -count=1 ./internal/provider ./internal/gui: ok
  (TestParseImportBalance, TestCoreScriptBudget in it).
- go test ./internal/cli: ok but TestEveryRouteHasACommandOrIsNamed,
  red on main since f418edffc (GET /api/context/session); fixed in the
  next commit, and ok there with -run 'TestEveryRoute…|Import'
  (TestImportPreviewAsksNoBalance).
- GUI import-link-balance, import-link-gemini, i18n-keys: 43/44. The
  red is i18n-keys "a plugin's words are its own", the same three
  strings on an origin/main 8fa3c60f8 copy (#5327, #5426, #5482).
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of provider,
  cli, gui: ok. gofmt -l: clean.

Not tried: a real link with balance= imported into the app and read
against a real relay's balance endpoint.
2026-11-08 18:37:41 +08:00
yetone 1aabc66fd1 gateway: /v1/models answers its ETag, and 304 to a client that has the list already
clyzhicore (Discord) runs a server magpie as the gateway and a local magpie
that takes its /v1/models and writes the models into dsh. They asked for
an ETag or a list you can wait on, so the local side knows a change at
once and a dead connection costs little. The wait is there since
06c4582cc (v0.1.3172: X-Magpie-List-Wait with If-None-Match, and the
Remote magpie follower). What was missing, and is added here:

- A plain GET /v1/models (no wait header) is answered with the same ETag
  a wait answers (listTag of the bytes this caller gets), Cache-Control
  private, no-cache, and 304 with no body, at once, when If-None-Match
  names it (strong or W/, in a comma list, or *). A tag it doesn't name,
  or none, is answered the list as before, same bytes. A refused list
  (400) stays untagged. Any client (a script, curl, another tool) can
  now poll cheaply.
- A wait's answer, 200 or 304, says in X-Magpie-List-Wait how many
  seconds it held. A plain answer doesn't.
- The follower (waitRemoteList) takes a 304 that comes sooner than
  followQuick (5s) without that header as a magpie that doesn't wait.
  This guards the change above: a proxy that drops X-Magpie-List-Wait
  would now get a tagged plain list and an instant 304, and the follower
  would ask every followGap (1s). It now leaves such a magpie to its
  schedule and asks again after followOldAgain (1h), as for one from
  before the wait. Servers from 06c4582cc on hold each wait to its end
  (50s), so their 304s pass.

Compatibility: an old server (no ETag) is still left to the schedule,
as TestRemoteMagpieOldListNotFollowed checks. An old client never sends
If-None-Match without the wait header and gets the same bytes plus an
ETag. The GUI doesn't read the gateway's /v1/models through Wails (whose
304 on WebView2 is a 505, gui/api.go writeJSONSame), so that doesn't
apply.

Hidden models (their second ask) already exist and are not changed: a
provider's "Only through routing groups" (Provider.Unlisted, `magpie
provider listed <id> no`) and a group's listed=no (Group.Unlists, `magpie
group set ... listed=no`, CLI only) keep models out of /v1/models while
groups still route to them.

docs/subsystems/gateway-routing.md says the above.

Run (on mote, through mote-run, first at 04ed05733):
- gofmt -l on the changed packages: clean.
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet
  ./...; go build ., GOOS=linux -tags nogui, GOOS=windows: all ok.
- go test -tags nogui -race -count=1 -timeout 90m ./internal/gateway:
  ok 2145s, no DATA RACE (mote at load ~100-130).
- go test -tags nogui -count=1 -timeout 45m ./internal/provider: ok 126s.
- After rebasing onto origin/main (5 commits, none in these files):
  gofmt -l clean; go vet (darwin, linux nogui, windows) of both
  packages ok; -race -run "ModelsWait|ModelsList|RemoteMagpie": gateway
  ok 12.5s, provider ok 4.8s.

Broken by hand, each red:
- models() back to listModels (no tag on the plain list):
  TestModelsListConditional ("ETag \"\"") and TestModelsWaitTagged ("a
  plain list: 200, ETag \"\"").
- tagNamed never matching: TestModelsListConditional (200 with the body
  for each of the tag, W/, a list and *).
- No X-Magpie-List-Wait on a wait's answers: TestModelsWaitTagged ("a
  wait's list says it held \"\"", same for its 304).
- The followQuick check off: TestRemoteMagpieStrippedWaitNotAskedOver
  ("asked 28 times in 300ms, want 2").

Not tried: two real magpies, or a real reverse proxy that drops the
header (the stripped case is a fake in the test). Not run on Windows or
Linux. The full suite (go test ./...) and the GUI suite: not run at push.
Following a provider added as a plain OpenAI-compatible endpoint (not the
Remote magpie type) is not done: its list URL comes from fetchOne's
several bases, and it still goes by its #2135 schedule.

Reported-by: clyzhicore (Discord)
2026-11-08 15:45:57 +08:00
yetone 15918265e3 zcode mover: min 0.1.57, the busy hold's answer arms no quota rest
plugins#859 (zxy20250120) merged as 93dacd738: an in-flight Start Plan
request answered by the busy hold's own 429 was counted as a spent gift,
so a -Trial model (or free first) rested in `blocked` for a minute with
quota left. 0.1.57 marks that answer and both gift paths skip it.

npm view --prefer-online --registry https://registry.npmjs.org
@magpie-community/opencode-zcode-auth version: 0.1.57 at landing.

Run on mote: go test -run 'Mover|Moved|Migrat|ZCode|Zcode'
./internal/provider ok; gofmt -l clean. Full suite: not run at push.
The plugin change itself was run in the PR review (bun test packages/zcode
236/0, red on main's index.mjs).
2026-11-08 15:37:01 +08:00
yetone 37df73b1bb balance: a key holds several credits that expire, each added and removed on its own
tenacious_eagle_96548 (Discord, 11-08) has two promotional credits on one
key, one ending tomorrow and one the day after. v0.1.3305 kept one grant
per key, and its form showed the date only after Enter or a blur, with no
button to confirm.

- OwnBalance.Expiring is now a list (`expirings`, up to 20). Spending
  goes to the grant that ends soonest first (ties by when it was typed),
  and each grant drops out at its day. A write prunes ended grants.
- The pill and the menu say "Expires in N days" per grant, amber from 7
  days. The menu has a Remove item per grant, "Add credit that
  expires…" and "No credit that expires" to clear them all.
- The form shows the amount and the last day together, the day filled in
  30 days ahead, with an Add button; Enter adds, Escape cancels, a bad
  amount or a past day is refused in place. The app's own menu, no
  native select, no stripes. A pill with two or more grants wraps at a
  grant on a narrow row (a class, not :has(), for Safari before 15.4).
- CLI: `--expiring amount@day` can be given several times, `--expiring
  off` clears all, `--expiring-remove [amount@]day` removes one. --help
  prints usage; a day that isn't a date, or is past, is refused.
- /api/provider/keyexpiring adds `{expiring:{amount,until}}`, removes
  `{expiring:{at,until},remove:true}`, clears `{expiring:null}`.

Old data: a v0.1.3305 single `expiring` grant is read as the first grant
and saved as `expirings` on the next write, for every user. An older
magpie reading the new file sees no grants (the balance itself stays).

Run on mote at 1d5b5dc2d plus this change:
- go test -run 'Budget|Balance|Expir|KeyOwn' ./internal/gui
  ./internal/provider ./internal/cli: ok (TestCoreScriptBudget passes,
  not raised). gofmt -l clean. GOOS=linux go vet -tags nogui and
  GOOS=windows go vet on provider, cli, gui: ok.
- GUI (Chromium + WebKit, 900/400px, en zh zh-TW ja de):
  key-balance-expiring, key-own-balance, key-balance-card,
  key-row-steady, key-row-chips-fit, account-rows-fit, old-webkit,
  i18n-en-no-cjk, balance-parts, balance-quota-left: 203/203. A broader
  run (key-*, balance-*, i18n-keys, panel-balance-order) had reds that
  are red on origin/main 04ed05733 too: i18n-keys "a plugin's words are
  its own" (#5332, #5482, #5426) and key-replace WebKit 420px (#4126).
- Real app on mote, sandbox HOME, `serve --web`: the CLI set ¥40 plus
  ¥5 to tomorrow and ¥8 to the day after and printed about ¥53.00 left;
  providers.json has `expirings`. --help, `5@yesterday` and removing a
  credit the key doesn't have each answered as above. In Chromium (en)
  and WebKit (zh) at 900 and 400px: the pill, the menu, the form (day
  2026-12-07), Add ¥3 by Enter, then Remove ¥3 from the menu, each
  checked by text and screenshot.

After a rebase on 437580535, on mote: the same go test
-run (TestCoreScriptBudget included): ok; key-balance-expiring,
old-webkit, key-own-balance: 46/46. Rebased again on 8f6298fb5 (Go
only, no asset changed): the go test -run plus Signin: ok.

Broken by hand, each went red: sorting grants by when typed
(TestTypedBalanceGrantsSoonestFirst); no migration in UnmarshalJSON
(TestTypedBalanceOneGrantMigrated); no Enter handler (GUI en 900); no
wrap rule (GUI en 400, row past the window's edge); Remove sending the
first grant (GUI, at/until mismatch).

Not tried: Full suite: not run at push. No real vendor account (the
grants are typed by the user). The Linux and Windows desktop apps.

Reported-by: tenacious_eagle_96548 (Discord)
2026-11-08 15:27:14 +08:00
yetone 8f6298fb5e providers: a notification when an account in use has to be signed in again, and before a Claude sign-in ends
steven_4422 asked on Discord whether magpie warns when a Claude Code
login is close to expiring or has expired. It didn't, outside the app:
a sign-in that Anthropic, OpenAI, GitHub or a plugin's vendor refused
showed only on the account's row (Sign-in required, Sign in again) and
on the provider row's Signed out pill, and nothing warned before a
Claude sign-in ended. The system notifications covered only usage,
balance, reset, masking and task-done alerts.

What Claude's tokens carry (read from Claude Code 2.1.316): the access
token refreshes itself, but claudeAiOauth.refreshTokenExpiresAt ends the
sign-in. Claude Code sets it from refresh_token_expires_in, or to 30 days
from the sign-in, keeps it over a refresh that sends none, says "Your
login expires in N days · run /login to renew" from 3 days before, and
treats a sign-in past it as none. It skips the warning when the access
token outlasts that end by more than the 3 days.

- provider.WatchSignIns looks a minute after start and then every two
  minutes. It reads only magpie's own files and asks no vendor. It
  covers every account in use of every subscription that is on.
- An account is told of when its row says Sign in again, by the
  Providers page's own test (needsSignIn mirrors renderAccounts): any
  mark on a Claude, Copilot or plugin account, and on another built-in
  (Codex revoked, a refresh that failed, ChatGPT API) a mark that
  signInGone matches.
- A Claude account is also told of 3 days before refreshTokenExpiresAt,
  by Claude Code's rule (claudeSignInEnds).
- Each alert goes out once: a lapse until the account is usable again,
  an end until it moves. The marks are kept in signin-alerts.json, so a
  restart doesn't repeat them, and an unreadable file tells nothing.
- The GUI sends the alert as "<Name> · <user>" with "Signed out — click
  to sign in again" or "Sign-in ends in N days — click to sign in
  again", in en, zh, zh-TW, ja and de. A click opens that provider's
  editor (?view=providers&edit=<id>), where the account's Sign in again
  is. A Linux dismissal still opens nothing (#2513).

Run on mote in a sandbox HOME, on this change over 04ed05733. It was rebased
onto 437580535 after the run, which changes only a gateway test:
- gofmt -l: clean.
- go vet ./...: ok.
- GOOS=linux go vet -tags nogui ./...: ok.
- GOOS=windows go vet ./...: ok.
- go build .: ok.
- go test -count=1 -timeout 45m ./internal/provider ./internal/gui:
  ok internal/provider 163.7s, ok internal/gui 162.2s.

Broken by hand, each red and then restored:
- Gone left false, which is the old code where nothing was told:
  TestSignInAlertClaudeSignedOut is red ("alerts …: []").
- The refreshTokenExpiresAt read turned off:
  TestSignInAlertClaudeEnding is red.
- The once-only mark dropped: TestSignInAlertClaudeSignedOut and
  TestDueSignIns are red ("told again").
- A click on a sign-in alert opening Usage:
  TestSignInAlertOpensItsProvider is red on darwin, windows and linux.

Not tried:
- A real notification on any OS.
- A real Claude account near its refreshTokenExpiresAt.
- A real revoked Codex, Copilot or plugin sign-in end to end.
- The GUI page is unchanged, so no Playwright run.
- Full suite: not run at push.

Reported-by: steven_4422 (Discord)
2026-11-08 15:19:03 +08:00
yetone 04ed05733e codex: a refresh of Codex's sign-in never writes its account back over a switch
darwish4021 on Discord (macOS, Codex app, 11-08): after 56f095604 the
Codex app "quit abnormally and switched my account".

codexTokenRenewing read auth.json, sent the refresh (a network round
trip, up to 30s), and then wrote the refreshed sign-in back
unconditionally. If Codex was signed in to another account in between,
the write switched Codex back to the account it had been switched off.
Two things could do that:
- magpie's own switch (switchSavedLogin: the auto-switch off a spent
  account, or the user's own). It took savedTokenMu but not codexMu,
  and only renewSaved holds savedTokenMu. The usage reads, warm-up,
  resets and acct.sign refresh under codexMu alone. The switch also
  saved the replaced account into logins.json with the refresh token
  that refresh was spending, so it was signed out on its next use.
- the Codex app's own sign-in, or a sign-out.

The fix:
- codexTokenRenewing reads the store again before writing. It writes
  only while the store still holds the refresh token that refresh
  started from. Otherwise it logs "the sign-in in <dir> changed while
  <account> was being refreshed" and leaves the store alone. The fresh
  access token still serves the request in hand.
- switchSavedLogin takes codexMu for Codex, after savedTokenMu and
  before loginsMu, the order renewSaved already uses. A switch then
  waits for a refresh in progress, and saves the replaced account with
  the refresh token that refresh got.

Test: TestCodexRefreshNeverUndoesASwitch has two subtests. In one,
the Codex app signs in to another account mid-refresh. In the other,
magpie switches mid-refresh.

Run at this head on mote:
- the new test with TestCodexLogins and TestCodexSignInGone, -count=3:
  ok;
- go test -timeout 45m ./internal/provider ./internal/agent: ok;
- go vet for darwin, linux and windows: ok;
- gofmt -l: clean.

Broken by hand, on mote:
- Both halves reverted: both subtests red ("Codex is signed in to
  r-work-2 after the refresh").
- Only the codexMu in switchSavedLogin reverted: the magpie subtest is
  red, because the replaced account was saved with the spent refresh
  token.

Full suite: not run at push.

Not tried:
- the reporter's own machine, version and accounts;
- the real Codex app going through a switch with this build.

The reporter's "projects cleared" is not explained by this change. The
app's projects live in state_5.sqlite (the projects and project_roots
tables), and their SQL is not scoped by account. magpie writes only
threads.model_provider there.
2026-11-08 14:37:31 +08:00
yetone c736906b17 providers: part of a key's typed balance may expire on a day
tenacious_eagle_96548 (Discord, #general): some vendors split a balance
into money that stays and credit good until a date. A key's balance typed
by hand can now carry that part (`expiring`: {amount, until, at}, in the
balance's currency, until = the last day it counts).

- Spending order: the expiring part is spent first, as DeepSeek spends
  its granted balance before money topped up. It takes the spend from its
  `at` up to its end (midnight after `until`, local time) or now; only
  what it took after `From` comes off the rest, so a refill or typing the
  balance again doesn't count it twice.
- Left is the whole balance. From its end the remainder counts no more,
  and unspent credit is gone.
- Typing the balance again keeps the part in the same currency and drops
  it in the other, where its amount would mean another sum.
- A balance saved before has no part and reads exactly as it did
  (TestTypedBalanceSavedBeforeExpiring).
- Set from the pill's menu: "Credit that expires…" asks the amount, then
  the last day (a day gone by, or the other currency's sign, refused);
  "No credit that expires" takes it off. GUI route provider/keyexpiring;
  CLI `magpie provider key-balance <id> <key> --expiring amount@yyyy-mm-dd|off`.
- Shown: the pill "≈$100.00 left · $30.00 expires in 30 days", the Usage
  page and panel line "Expires in 30 days ≈$30.00", amber from 7 days;
  TUI and `magpie quota` "($30.00 until Dec 7)". New strings in zh,
  zh-TW, ja and de.

Run (mote):
- go test of internal/provider, internal/gui, internal/cli (with
  TestCoreScriptBudget: the days' lines in app.js are paid for by five
  balance comments cut there, no raise; core 1,533,559 of 1,533,802); the new tests
  again with TZ=UTC and TZ=Pacific/Kiritimati (every clock held);
  gofmt -l clean; GOOS=linux and GOOS=windows go vet of those packages.
- GUI: key-balance-expiring.test.cjs 20/20 (chromium and webkit, 400px,
  en/zh/zh-TW/ja/de), with every balance-*, key-*, i18n-* file: 768
  pass, 6 red, each red the same alone on origin/main 691a10446:
  i18n-keys "a plugin's words are its own" (#5327) and key-replace's
  five webkit 420px cases (#4126, numbers added there).
- A real sandbox (own HOME, -tags nogui binary, ports 3591/3592): set
  $70 + $30 until +30d and ¥40 + ¥5 for +3d through the CLI, then
  through the pill's menu in the real page (¥8 for +6d, then removed);
  a past date shows the part no longer counting; retyping in USD dropped
  the CNY part; `magpie quota` shows the split. No page errors.

Broken by hand, each red:
- Go (TestTypedBalanceExpires): part not spent first; end taken in UTC
  (red under Kiritimati); part kept after its end; part kept across a
  currency change.
- GUI (key-balance-expiring): no soon class; soon only from 2 days; a
  past day accepted; the other currency's sign accepted.

Not tried: a real vendor's spend priced against the part; the GUI on
Windows or Linux. The full Go and GUI suites were queued on mote's
suite lock behind other sessions' and had not run when this was pushed.

Reported-by: tenacious_eagle_96548
2026-11-08 13:39:32 +08:00
yetone 5849b47ca0 provider: Grok's mover min is 0.2.6 (plugins#852)
opencode-grok-auth 0.2.6 (plugins ae5188363, lxyer) asks Grok again
when a Responses stream is cut before its first byte. It tries up to
three times, before the answer is returned, so a 429 or 401 on a retry
comes back as itself. Once a byte has arrived, the stream goes on as it
comes, reasoning included. A later cut just ends the stream, and magpie
closes it as a whole response.failed (29bfd5dc8, v0.1.3298). The
plugin no longer writes a response.created or response.failed of its
own: those frames had no sequence_number, and Grok Build failed the
turn on them. An upstream response.failed or error goes on as it came.

npm has 0.2.6: `npm view --prefer-online
@magpie-community/opencode-grok-auth time` gives
2026-11-08T04:50:00Z. The publish run's npm job is red only for
middleware-think-tags 0.1.2 (E404, plugins#180). grok 0.2.6 was
published in that run.

Run on mote at this tree: gofmt -l is clean; go vet
./internal/provider on darwin, linux nogui and windows; go test
./internal/provider: ok (119s).

The plugin's side was run at 463afb79 on mote. Its package tests: 107
pass. The repo-root bun test: 6878 pass, 0 fail. check.mjs grok: ok.
Breaking the retry by hand turned the tests red. The real chain was
Grok Build 1.0.67 and 1.0.77, then magpie eef99e4bb, then the plugin,
then a fake upstream that cuts before the first byte, after
response.created and after text. Every cut was read and retried, with
no "missing field". A retry's 429 reached magpie as a 429, and a vendor
response.failed showed its own message. The plugins merge body has the
details.

Not tried: a live Grok stream cut by the real vendor.
2026-11-08 12:53:45 +08:00
yetone 7880a00ac6 models: a model of a key's provider can be asked on System One
axelburks on Discord: a relay serves its decision model under a name of
its own (an Ark endpoint id). A key's provider with a System One URL
beside a conversation URL can set a model's API to decide (System One
in Model settings' API row, its chip's right-click, or `magpie model
api <pid/model> decide`). The model is then a decision model there:
asked on System One by its own name, offered to routing groups, kept
out of the conversation models, and a turn for it is refused with 400
before the vendor is asked. Auto gives it back. A provider with no
System One URL, with that URL alone, an account, a remote magpie and
Vertex refuse it, saying why. Chat routing (apisAmong) ignores decide.

Broken by hand: removing the decideSet check in DecidesModel turns
TestModelSetToSystemOneIsADecisionModel and
TestModelSetToSystemOneAskedThere red.

Run, on this stack over origin/main 0fc3455e2 (mote's suite lock had
hours of queue, so the suites ran on WSL magpie-desktop under flock):
- go test -timeout 45m ./internal/{provider,gateway,gui,cli,settings,fx}
  on WSL, ok; ./internal/codexcat on mote, ok; gofmt -l clean;
  go vet on mac, GOOS=linux -tags nogui and GOOS=windows on mote, ok;
  TestCoreScriptBudget ok (paid by cutting comments, no raise).
- GUI, both engines, every language, on WSL at the pushed head and at
  0fc3455e2: every touched test file plus the provider-editor files a
  first run found red. No red at head that isn't red at 0fc3455e2. The
  shared reds have issues: i18n-keys #5332, model-chip-steady #4388,
  model-copy-id #4621, models-works-only #4391, plugin-move-unserved
  #4392, provider-fetch-again #5232, provider-levels-save #4394,
  provider-levels-scroll #4395, provider-models-rest #4396,
  provider-picks-stay #4397, provider-typed #4673, remote-magpie #4398,
  zero-priced-free #5262, model-reasonless (webkit de) #4100,
  name-suffix-no-names #1937.
- Rebased on origin/main 4ab1191bc (gateway.go moved under it) and run
  again at the pushed head: gateway and provider ok on WSL, gofmt,
  vet (mac, linux nogui, windows) and the budget ok, i18n-keys,
  model-headers and routing-groups-back with only #5332's red.
Not run at push: the whole GUI suite (1277 files).

Not tried: a real relay's System One endpoint; fake vendors only.

Reported-by: axelburks (Discord)
2026-11-08 11:28:54 +08:00
yetone 7a6211d047 providers: a model's own headers, in Model settings
axelburks on Discord: a vendor routes one model by a header of its own.
A key's provider (built-in or custom) can give each model headers
(settings.ModelHeaders["pid/model"]). They go on that provider's
requests for that model alone, after the provider's headers and after
auth: a name both have is sent once, as the model's, so a user's value
is never overridden by the provider's or magpie's key header. The
gateway names the model (provider.WithModel) on every route that asks
one: chat on each API, translated and streamed, count_tokens, System
One's decision, embeddings, images, videos and the model test. A
fallback provider serving the same model id gets its own headers only.
Accounts and plugins carry their sign-in's headers and take none.

The editor's "Name, price and reasoning level" panel is now "Model
settings" (every language), with + Add header per model, staged and
made with the Save; Restore default takes them away.
The rows being typed are kept out of the draft's
compare, so an untouched editor still closes without asking.

Broken by hand: dropping WithModel from gateway.go turns
TestModelHeadersReachTheirModelOnEveryRoute red; dropping the provider
id check in modelOf turns TestModelHeadersStayWithTheirProvider red.

Run, on this stack over origin/main 0fc3455e2 (mote's suite lock had
hours of queue, so the suites ran on WSL magpie-desktop under flock):
- go test -timeout 45m ./internal/{provider,gateway,gui,cli,settings,fx}
  on WSL, ok; ./internal/codexcat on mote, ok; gofmt -l clean;
  go vet on mac, GOOS=linux -tags nogui and GOOS=windows on mote, ok;
  TestCoreScriptBudget ok (paid by cutting comments, no raise).
- GUI, both engines, every language, on WSL at the pushed head and at
  0fc3455e2: every touched test file plus the provider-editor files a
  first run found red. No red at head that isn't red at 0fc3455e2. The
  shared reds have issues: i18n-keys #5332, model-chip-steady #4388,
  model-copy-id #4621, models-works-only #4391, plugin-move-unserved
  #4392, provider-fetch-again #5232, provider-levels-save #4394,
  provider-levels-scroll #4395, provider-models-rest #4396,
  provider-picks-stay #4397, provider-typed #4673, remote-magpie #4398,
  zero-priced-free #5262, model-reasonless (webkit de) #4100,
  name-suffix-no-names #1937.
- Rebased on origin/main 4ab1191bc (gateway.go moved under it) and run
  again at the pushed head: gateway and provider ok on WSL, gofmt,
  vet (mac, linux nogui, windows) and the budget ok, i18n-keys,
  model-headers and routing-groups-back with only #5332's red.
Not run at push: the whole GUI suite (1277 files).

Not tried: a real vendor that routes by header (Ark); fake vendors only.

Reported-by: axelburks (Discord)
2026-11-08 11:28:54 +08:00
yetone ae58ec9b44 providers: a key's provider can have its model list off
axelburks on Discord: Ark's pay-as-you-go list names models that can't
be asked for, and each one is asked by an endpoint id the user made. A
key's provider can now have its list off (Provider.ListOff): nothing
asks its vendor for a list (Fetch, Refetch, List, RefreshLists, a test,
a new key's prefill, a resting key's probe), a list fetched before and
models.dev's are not read, and only the ids added by hand are served.
The editor shows it as "Fetch the model list", ticked by default;
unticked, Fetch models and Forget go. A save that doesn't name listOff
keeps it. CLI: `magpie provider set <id> list=off`. Accounts and plugins
list as their sign-in does, so they don't take it.

Broken by hand: ListAsks returning false for a list-off provider turns
TestListOffAsksNoListAndServesTheIDsAdded red; dropping the keep in the
save turns TestProviderSaveListOff red.

Run, on this stack over origin/main 0fc3455e2 (mote's suite lock had
hours of queue, so the suites ran on WSL magpie-desktop under flock):
- go test -timeout 45m ./internal/{provider,gateway,gui,cli,settings,fx}
  on WSL, ok; ./internal/codexcat on mote, ok; gofmt -l clean;
  go vet on mac, GOOS=linux -tags nogui and GOOS=windows on mote, ok;
  TestCoreScriptBudget ok (paid by cutting comments, no raise).
- GUI, both engines, every language, on WSL at the pushed head and at
  0fc3455e2: every touched test file plus the provider-editor files a
  first run found red. No red at head that isn't red at 0fc3455e2. The
  shared reds have issues: i18n-keys #5332, model-chip-steady #4388,
  model-copy-id #4621, models-works-only #4391, plugin-move-unserved
  #4392, provider-fetch-again #5232, provider-levels-save #4394,
  provider-levels-scroll #4395, provider-models-rest #4396,
  provider-picks-stay #4397, provider-typed #4673, remote-magpie #4398,
  zero-priced-free #5262, model-reasonless (webkit de) #4100,
  name-suffix-no-names #1937.
- Rebased on origin/main 4ab1191bc (gateway.go moved under it) and run
  again at the pushed head: gateway and provider ok on WSL, gofmt,
  vet (mac, linux nogui, windows) and the budget ok, i18n-keys,
  model-headers and routing-groups-back with only #5332's red.
Not run at push: the whole GUI suite (1277 files).

Not tried: a real Ark account; the switch was checked against fake
vendors only.

Reported-by: axelburks (Discord)
2026-11-08 11:28:54 +08:00
yetone 0fc3455e2a providers: a key's typed balance may be in yuan and refill each month or week
tenacious_eagle_96548 asked, after v0.1.3281's typed balance, to type it
in RMB and to have it refill (e.g. $10 a month, on the 1st).

- A balance may be typed in yuan ("¥100", "100元", or a bare number while
  Settings shows costs in CNY). What magpie counts spent stays in USD and
  is turned into yuan at fx.Known(): the rate internal/fx last fetched
  (cached 12h, fetched again in the background, never on a request).
  fx.Known never returns fx.Fallback, so with no rate fetched and
  something spent, what is left is unknown (left null; the card says
  why), not a guess.
- An optional refill: monthly on day 1-31 (past a month's end, its last
  day) or weekly on a weekday, at midnight in the user's local time.
  Nothing is stored on a refill: the spend counts from the last boundary
  after the balance was typed. Typing the amount again keeps the refill.
- GUI: the pill's menu gains Refills each month… (a day, in place),
  Refills each week… (the app's menu of weekdays) and Never refills;
  provider/keybalancerefill; keyownbalance takes currency cny. CLI:
  magpie provider key-balance <id> <key> [usd|¥cny|off]
  [--refill monthly[:day]|weekly[:mon…sun]|off]. Strings in zh, zh-TW,
  ja, de. docs/subsystems/providers-accounts.md updated.

Run on mote at this tree (base origin/main 350599a0f):
- go test -tags nogui -count=1 -timeout 45m ./internal/fx ./internal/provider
  ./internal/cli ./internal/gui ./internal/usage: all ok (suite lock).
- GOOS=linux go vet -tags nogui ./... ok; GOOS=windows go vet ./... ok;
  gofmt -l clean.
- key-own-balance.test.cjs 20/20 (chromium + webkit, en zh zh-TW ja de,
  900 and 400px): yuan typed posts currency cny, monthly day (40
  refused), weekly Friday, never. i18n-keys, i18n-en-no-cjk, old-webkit ok.
- Broken by hand, each red: Known returning Fallback
  (TestKnownIsNeverAGuess); refill days taken in UTC
  (TestTypedBalanceRefills, TestRefillDays); refill dropped on retype
  (TestTypedBalanceRefills).
- Full GUI suite still running at push: 3502 ok, 6 red so far, none in a
  file this touches: webkit By weight; webkit de 1100/420 Codex resets
  used by themselves; chromium en named caller keys; chromium zh-TW 420
  a key's several limits; webkit en gateway key held to its models.
  They are run on origin/main next and filed if red there.

Not tried: a live rate fetch (tests stay offline), the real app window,
WebKitGTK.

Reported-by: tenacious_eagle_96548 (Discord)
2026-11-08 09:03:00 +08:00
yetone 778b8e0753 provider: Kiro's mover needs opencode-kiro-auth 0.1.32, which waits out a 429 throttle as the Kiro IDE does
onemezao on Discord: a "hi" answered, and the next message straight
after was Kiro's 429 USER_REQUEST_RATE_EXCEEDED, while the Kiro IDE on
the same account took two in a row (plugins#842, plugins#848). The IDE
gets the same throttles but tries again, 3 tries after 1s and 2s or
Kiro's retryAfterMilliseconds; the plugin sent the first 429 straight
back with Retry-After 30s. 0.1.32 (plugins 966cf717) retries the way
the IDE does. Raising min makes keepMovedCurrent update every moved
user's plugin.

Run: npm view --prefer-online --registry https://registry.npmjs.org
@magpie-community/opencode-kiro-auth version = 0.1.32 at landing;
mote-run go test -run 'Kiro|Mover|Moved' ./internal/provider/ ok;
gofmt -l clean. The plugin's own record is in its commit (package 157
pass, plugins root 6867 pass 0 fail).

Broken by hand: in the plugin (5 tests red with the retry off); nothing
here beyond the version string.

Not tried: a real throttled Kiro account; none was at hand.

Reported-by: onemezao (Discord)
2026-11-08 04:59:59 +08:00
yetone d32a7a70cb remote magpie: once magpie updates, the Remote magpies it uses update too
nnlrl_75403 on Discord: a magpie used as another's Remote magpie stayed on
its old version after the local one updated, and had to be updated by
hand on the other computer. Now nothing needs setting up:

- provider.KeepRemotesUpdated (started by the app's updater and by
  magpie serve) runs UpdateRemotes 30 s after start and hourly. A
  released build with automatic updates on reads each Remote magpie's
  version (GET /v1) and, when it is older, asks it through
  POST /v1/magpie/update?version=<v> with the provider's key, at most
  once in six hours per version. Off here, or a dev build: nothing asked.
- The remote updates as its own automatic update would: the app
  downloads and restarts once idle (updater.updateAsked → download,
  waitIdle); magpie serve puts the latest in where it runs from, one at
  a time, never elevated, and serveFollow restarts into it. Automatic
  updates or downloads off there: it answers "off" and stays.
- A copy that can't replace itself says why: a container (docker pull
  ghcr.io/yetone/magpie:latest), a package manager's (its command), a
  folder it can't write, a build from source. A magpie from before the
  route answers 404 ("too old"), a read-only or held key is "refused".
  The provider's row on the Providers page adds a short status to its
  line ("updating to v…" for 30 min, or "can't update itself" etc.),
  with the reason and the command in its tooltip. en/zh/zh-TW/ja/de.
- The route replaces the program, so it takes the Codex reset's
  admission: another machine only while shared, never a browser page,
  an enabled key with full access from loopback too (401 without one),
  read-only 403 gateway_key_read_only, held 403 gateway_key_held. It is
  in readOnlyRefused and the CORS route list.

App.js stays under TestCoreScriptBudget by cutting two comments; the
budget is not raised.

Run (on mote, at the tree committed here):
- gofmt -l internal/: clean. go vet of gateway, gui, cli, provider for
  darwin, GOOS=linux and GOOS=windows: ok.
- go test -count=1 ./internal/gui ./internal/cli ./internal/provider
  ./internal/gateway: gui and cli ok but for #5644's two settings tests
  (red on main since 6b7ee4a98, owned); provider and gateway were
  still running at the push, and go in the full run after it.
- Rebased on origin/main c7c05dcf2, again: gofmt, vet, the new tests,
  ReadOnlyKeyEveryRoute, CORS, TestCoreScriptBudget (not raised) and
  both GUI files 32 of 32: ok.
- New: TestRemoteUpdateNeedsAFullKey (no key from loopback, Origin null,
  an app scheme, *.localhost, a rebound Host, a foreign page with and
  without the full key, another machine with none or a wrong key,
  read-only and held keys, then not shared; the updater is never
  called until a full key asks, from LAN and loopback),
  TestRemoteMagpieAskedToFollow (UpdateRemotes against a real gateway:
  dev build, same and newer remote, NoAutoUpdate here, asked once per
  version, container answer kept, read-only key refused, a 404 magpie
  "old"), TestUpdateAskedByAnotherMagpie, TestRemoteUpdateNote,
  TestServeUpdateAsked.
- GUI: remote-update.test.cjs (new) and remote-self.test.cjs, Chromium
  and WebKit, 1100 and 420 wide, en/zh/ja/de: 32 of 32 ok, with every
  key checked in zh, zh-TW, ja and de. i18n-en-no-cjk ok. i18n-keys'
  "a plugin's words are its own" is red, the same on origin/main
  f8525323d (#5327/#5332, #5426, #5482); its other cases ok.

Broken by hand, each red, then put back: the handler's key check
(loopback without a key got 200 updating), its held-key check, the
route itself (404 = the old code), asking a remote that is current,
ignoring NoAutoUpdate here, asking again for the same version, the
app ignoring automatic updates off, the app never waiting to restart,
serve's single flight (2 downloads), serve's container answer.
The handler's own Origin and not-shared checks stay green when removed:
corsGuard and lanGuard refuse those first; they are kept as the Codex
reset keeps them.

Not tried: a real update of a real remote (a Docker magpie and an app
on another Mac) end to end; Windows and Linux runs of the new tests
(vet only); the full suite (run after the push).

Reported-by: nnlrl_75403
2026-11-08 03:13:15 +08:00
yetone f8525323dd providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL,
no relay query found), so their keys showed none. Now the user types what
the vendor's page says is left, on the key's row in the provider editor
(Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`.
The key's card shows that less what magpie's usage priced the calls it
sent on the key since it was typed (usage.KeySpent, the spend caps'
count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its
title saying what was typed, when, and what was counted since. Typing it
again counts from then; No balance takes it off.

A balance the vendor tells always wins: a provider with a Balance URL, a
plan source, Cline's or OpenCode Zen's card takes none typed, and a relay
whose query is found shows its own; when the probe finds none
(errNoBalance) the typed one is shown. A typed balance stays saved as the
user left it: the editor's save keeps it, a key's replaced value carries
it. An estimate is never kept in the balance history and tells routing
nothing (the routing allowances cache is left alone).

keybalance.js is loaded by keyspend.js (itself loaded when the editor
draws a key) for a provider that takes one, so app.js and the core's
script budget are unchanged. Words in zh, zh-TW, ja and de.

Run at this tree (mote):
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of
  gui, provider, cli and usage;
- go test -tags nogui -count=1 ./internal/gui ./internal/provider
  ./internal/cli ./internal/usage: provider and usage ok; gui and cli
  red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main)
- the provider tests under -race -count=3;
- GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de,
  900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de,
  gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk:
  104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the
  same on origin/main 7a2946caf (#5327, #5332, #5482, #5426).

Broken by hand, each went red:
- estimates kept in the balance history: TestTypedBalanceCountsDown;
- no fallback to the typed balance on errNoBalance:
  TestToldBalanceWinsOverTyped;
- the editor's save dropping KeyOwnBalances: TestKeyOwnBalanceRoutes.

Red on main, not this change: TestSettingsSaveKeepsWhatItDoesNotSend
and TestSettingsCLISetsWhatTheWindowSaves (groupSink, groupFirstToken,
groupPatience from 6b7ee4a98), filed as #5644.

Not tried: a real relay account with no balance URL (the cost counted is
magpie's own estimate, so a vendor pricing differently drifts until the
balance is typed again); the full Go and GUI suites before the push (run
after it, under the suite lock); the GUI in the real Windows and Linux
apps; routing does not use the estimate.

Reported-by: tenacious_eagle (Discord)
2026-11-08 02:54:25 +08:00
yetone 30b7a17326 codex: a relay's dated or renamed GPT id keeps its xhigh, max and Ultra levels
Found while looking into maomao_00001's report on Discord: the Windows
Codex app offered no xhigh or Ultra for a relay's model. Their relay
(vip.aipro.love, ids from its public /api/pricing) names its 31 models
plainly, and every one already got its full levels in
magpie-models.json before this change and gets the same after it, so
this is not their fix. Exact ids (gpt-6.1-sol, openai/gpt-6.1-sol)
were fine; two spellings other relays use were not:

- OpenAI's dated snapshot id (gpt-6.1-sol-2026-09-29) was unknown to
  the catalog, so it got the low/medium/high fallback. borrowedEfforts
  now drops a dated suffix and takes the base model's levels.
- A relay's rename (codex-gpt-6.1-sol, "[A] gpt-6.1-sol", an id the
  user marked the same as gpt-6.1-sol) got the levels up to max but no
  Ultra, because OffersUltra matched exact ids only. It now matches
  through catalog.IsOneOf, the lookup ContextOf and EffortsOf use.

Only known models change: a dated id whose base is unknown
(model-x-2026-01-01) keeps low/medium/high, a dated Luna gets its own
levels without Ultra, and glm-5.3-flash keeps [low high max].

Not changed: a dashed-date id's window and price are still unknown,
because catalog.SameModel doesn't strip that date form (#5643).

Run:
- TestCodexCatalogRelaysKnownModelsLevels red on the old code (the
  dated Sol and Luna at [low medium high], three renames without
  ultra), green with the fix.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... and builds on mote.
- go test -tags nogui ./internal/catalog ./internal/provider
  ./internal/agent ./internal/codexcat on mote: all ok.
- The relay's 31 ids put through codex's Set with the real
  models.dev file (a probe, not committed): the same levels on
  origin/main and with this change.
- Full suite: not finished. My probe runs reused the suite's copy
  on mote, so it was stopped; it runs again after the push.

Refs: maomao_00001 (Discord)
2026-11-08 02:37:42 +08:00
yetone 6b7ee4a984 routing: every group follows a default for rate limits, slow starts and busy members unless it sets its own
jiezhengj on Discord asked to set the per-group policies once instead of
in each group. The Routing groups page's Settings card, under the list,
now has three rows: Rate limited (keeps its place / goes to the back),
Slow to start (wait / 30 s ... 4 min) and Every member busy (off / 1 min
... 4 min). They are saved in settings.json as groupSink, groupFirstToken
and groupPatience (settings.SetGroupDefaults, POST /api/groups/defaults).

A group follows the default for each value it leaves unset, and its own
value always wins:
- Sinks() is the group's Sink, or else the default unless NoSink, a new
  field for an explicit "Keeps its place".
- FirstTokenOr() is the group's own FirstToken (-1, FirstTokenWait, is an
  explicit Wait), or else the default. The gateway reads it where it
  reads a group's first-token time.
- Waits() reads the default when Patience is 0. 60 is an explicit 1 min.
Groups saved before have 0 and no NoSink, so they follow the default,
which starts at magpie's own (keep its place, wait, 60s). Nothing a user
set changes. The group editor's three rows gain a Default option, on for
a group that sets none, and its hint names the value it follows. Segments
only, with no native select.

Run on mote, at 06b2daeff rebased on origin/main 2dac9b84e:
- go test on the new tests TestGroupDefaultsUnlessItsOwn,
  TestGroupFirstTokenFollowsTheDefault, TestGroupSinkFollowsTheDefault
  and TestGroupDefaultsSaved, plus TestKeysAreWhatTheSaveWrites and the
  existing first-token and sink tests: ok.
- Broken by hand (Waits, FirstTokenOr and Sinks ignoring settings): the
  three provider/gateway tests went red.
- GUI: group-defaults (new), group-patience, group-first-token,
  group-found-off and rate-limited-sink, in Chromium and WebKit, in en,
  zh, zh-TW, ja and de, at 1100 and 420: 56/56 pass. With the old
  client.js and routing.css, group-defaults, group-patience and
  group-first-token fail 44 of 44.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...:
  clean. gofmt -l: clean.

Still running when this was pushed (owner: never hold a verified commit
behind the suite): go test -timeout 45m on internal/provider,
internal/gateway, internal/gui, internal/settings and
internal/settingsapi, then the whole GUI suite under suite.lock. Any red
they show gets its own issue.

Not tried: the real app with real groups under real rate limits. Only
the gateway tests' fakes exercise the default sink and first-token paths.

Reported-by: jiezhengj on Discord
2026-11-08 02:08:30 +08:00
yetone 3b541a7f36 routing: Smart ranks an account by its week once its month can't be used up before it renews (#5639)
Smart ranked a Volcengine Agent Plan (5 hours 2,000, week 7,000, month
20,000) by its month, the biggest window, so it always stood behind
accounts renewing weekly, and its month could reach a point where it
could no longer be used up before it renewed.

The rule keeps #1778's reasoning: a month holding less than its weeks add
up to is the real cap while the weeks can still carry it. Once what the
biggest window has left is more than the next window (a day or longer,
same unit, counts known) can let through between its own reset and the
biggest one's (Of x time between / Span), what the week leaves at its
reset is lost, and the week ranks the account.

- provider: Allowance.Unreached counts the biggest windows to pass over.
  Renewal and Seat.Soon are unchanged for other strategies and plugins.
- routes: Seat.Unreached; Smart compares Soon past it.
- gateway: weighRouted fills it; the trace's Weighed carries `unreached`.
- GUI Routing: renewsBy skips those windows, and a new story line says the
  shorter window decides. The Smart header and the group hint say so in
  en, zh, zh-TW, ja and de.
- docs: reference.md (How magpie picks an account) and
  subsystems/gateway-routing.md.

With the issue's numbers as reported (month 696 h away, 18,372 left),
four weeks carry 28,017, so the order is unchanged. Two weeks before the
month renews, 14,017 < 18,372, and the plan goes first, ahead of the
point where a week's leftover is lost.

Run on mote at this tree (base 2dac9b84e; origin/main bb33142ea touches
none of these files):
- go test -tags nogui ./internal/provider ./internal/routes: ok
- go test of TestMonthOutOfReachRanksByWeek,
  TestSmartSpendsAWeekTheMonthCantWait, TestSmartPassesAnUnreachedWindow
  and the Smart/Renewal/Weighed tests in provider, routes, gateway: ok
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok
- gofmt -l internal/: clean
- node --test routing-key-windows.test.cjs: 52/52 in Chromium and WebKit,
  en/zh/ja/de, the new #5639 scene included

Broken by hand:
- Unreached returning 0: TestMonthOutOfReachRanksByWeek ("two weeks to
  go", "the last week") and TestSmartSpendsAWeekTheMonthCantWait went red.
- Smart comparing a.Soon, b.Soon whole: TestSmartPassesAnUnreachedWindow
  and TestSmartSpendsAWeekTheMonthCantWait went red.
- client.js without the slice and the story line: the #5639 GUI case went
  red (Chromium en).

Still running when pushed (the owner's rule not to hold a verified commit
behind the suite): the full internal/gateway package; all routing-*,
panel-routing*, gui-zh-tw/ja/de and i18n GUI files in both engines; and
the full go test ./... -timeout 45m. Any red they show gets its own issue.

Not tried: a real Volcengine Agent Plan account. Ark replies that send
only Percent carry no counts, so the rule can't apply to them. Not
changed: Use before expiry (Pace) still ranks this plan by its month;
filed as #5641.

Reported-by: louisgreen0726
Refs #5639
2026-11-08 02:08:08 +08:00
yetone cde3bc9fad provider: WorkBuddy's mover min is 0.2.25, which leaves "DSH" in a user's path alone (liby233)
liby233 on Discord: on every WorkBuddy model, from DeepSeek Harness, a
path the user asked to have repeated word for word,
"/root/DSH/Work/OC-182.92.66.95/", came back as
"/root/the agent harness/Work/OC-182.92.66.95/". The plugin's "Hide
DeepSeek Harness's name" (0.2.23, on by default) replaced every bare
DSH in user and assistant text. Plugin 0.2.25 (magpie-community/plugins
49d4042e) takes the bare name out of the system prompt and tools'
descriptions only, never out of a path or file name, and lets the
user's and assistant's words go as written; dsh's own runtime lines are
still reworded. keepMovedCurrent updates every moved user to it.

Run on mote at this tree (mote-run, base 578053d6a): go test -count=1
./internal/provider ok (160s); gofmt -l clean. Plugin side:
HOME=$(mktemp -d) bun test packages/workbuddy 334 pass at 49d4042e;
npm view --prefer-online --registry https://registry.npmjs.org
@magpie-community/opencode-workbuddy-auth version shows 0.2.25.
Broken by hand (plugin): replacing in user text again, and replacing in
a path in the system prompt, each turned the literal-path test red.
Not tried: a real WorkBuddy account through a moved install.

Reported-by: liby233
2026-11-07 23:27:15 +08:00
yetone 578053d6aa gui: the menu bar's picker leaves out a card of text alone (Google AI Studio)
LuckymanJC on Discord ticked Google AI Studio in Settings › Allowances
in the menu bar, and the macOS menu bar never showed it. The card comes
from the magpie-gemini-web plugin's ai-studio provider (AIStudio2API).
Its usage reports no allowance: Google AI Studio gives none to read,
and the plugin only knows which models its accounts are cooling down on.
With nothing cooling, the card holds just two text lines (代理出口,
管理页). quotaOfPlugin marks those Text and Aside, trayWindows has no
window left, and trayCardText gives no label, so the menu bar draws
nothing. The picker still offered the card because it asked only
q.windows?.length.

The picker now offers a card with a window that isn't text, or with a
balance. That is what trayCardText can draw (withTrayKinds gives the
same set its trayKind). While an account is cooling, the card has a
used-100 window and is offered and drawn as before. A card ticked
earlier stays in the list, under its card's name instead of its
provider id, so it can be unticked. Comments in renderTrayUsage were
cut to pay for this: app.js is 1,311,353 bytes against 1,311,462 at
origin/main, and no budget was raised.

Run on mote at this tree (970a86ff3 + this change):
- go test ./internal/gui -run 'TestTray|TestCoreScriptBudget': ok
  (new TestTrayTextOnlyCardShowsNothing)
- go test ./internal/provider -run
  'TestPluginTextRowIsText|TestAIStudioServiceLinesAreText': ok
- node --test tray-text-only (new), tray-inuse, tray-totals,
  tray-windows, tray-usage-redraw: ok, Chromium and WebKit, en/zh
  (tray-totals in five languages)
- i18n-keys: "a plugin's words are its own" red, and red the same on
  origin/main 970a86ff3 in a clean worktree. It is already filed as
  #5332, #5327, #5482 and #5426. Nothing in this change touches it.
- gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet
  of internal/gui and internal/provider: ok
Broken by hand: putting back q.windows?.length makes tray-text-only red
("nothing cooling: its card is text alone, not offered").
Not tried: the real app with the real plugin and a Google account. The
plugin's card shape was read from magpie-gemini-web 0.10.0's
lib/studio.mjs (usage, poolUsage, accountUsage, serviceWindows) from npm.

Reported-by: LuckymanJC
2026-11-07 22:36:03 +08:00
yetoneandggbdpq 31ece9761c provider: a Codex reset spent by itself is the very one its checks passed (#5555)
stillExpiring said only whether the account still had one due to be
spent; the spend then read the cards afresh and took the one that runs
out first. If the card the checks had passed expired and went in
between, that was another card entirely, one never checked for being
due. The check now says which card it passed (Each[0], the soonest,
from the same read as Until), and the spend is of that one through the
named-credit path: gone from the spend's own read, held() fails and
nothing is spent, no card picked in its place; the next look decides
afresh. When the list read isn't the count (Each empty), the credit is
"" and the spend picks as before.

Run (wsl-run, magpie-desktop, Go 1.26.8):
- go vet ./internal/provider; gofmt -l: clean
- go test -count=1 -run 'Reset|Expiring|CapNeverSpends' ./internal/provider: ok
- go test -race -count=5 -run 'TestResetUse|TestExpiringSpend|TestSpendExpiringCodexResets': ok
Broken by hand: the spend unbound again (spendCodexReset(ctx, who, "",
...)): TestExpiringSpendKeptToTheCreditChecked red, `spent 1 ("later"):
the card that ran out was replaced by one the checks never passed`.
Not tried: a real reset credit expiring between the reads (the fake
server stands in for the vendor's list losing it).

Reported-by: cgsme
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-07 21:59:07 +08:00
yetoneandggbdpq 96f99b7609 provider: a Codex reset's lost use record is named, not silent (#5556)
noteResetUsed dropped the errors of keeping codex-resets-used.json: a
full disk or a denied path left the spend a success with no record and
no word of it. It says so now, and spendCodexReset names the loss in
the log. The spend stays a success either way: the reset is spent on
the server, so a lost record must never read as one to spend again.

Run (wsl-run, magpie-desktop, Go 1.26.8), with #5555 on top:
- go vet ./internal/provider; gofmt -l internal/provider: clean
- go test -count=1 -run 'Reset|Expiring|CapNeverSpends' ./internal/provider: ok
- go test -race -count=5 -run 'TestResetUse|TestExpiringSpend|TestSpendExpiringCodexResets': ok
Broken by hand: the write's error dropped again (`_ = steady.WriteFile`):
TestResetUseWriteFailureSeen red, "the record's loss went unnamed".

Not changed (pre-existing, its own issue): when readResetsUsed fails
for a reason other than a parse (a denied read), no copy is put aside
and the history is written over, and the `.bad-` copy's own write
error is dropped.
Not tried: a real full disk or denied path on a real account.

Reported-by: cgsme
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-07 21:59:07 +08:00