Commit Graph
1001 Commits
Author SHA1 Message Date
yetone 88b4c00ea1 provider: a Codex token refresh, once sent, is waited for even when its caller gives up
willz on Discord: a Codex account that isn't the current one stops showing
its quota after a day or two and asks to be signed in again, while
requests on it still work; moving it to the top "fixes" it.

codexRefresh sent the refresh on the caller's context. OpenAI rotates the
refresh token as it answers, so a refresh whose caller went away mid-flight
(an agent's cancelled request, a usage read's deadline, the keep-alive's
2-minute run) dropped the answer and left magpie holding the spent refresh
token. The next refresh (the keep-alive forces one each day) is refused as
refresh_token_reused, the account is marked lapsed and its row says to sign
in, while the access token it still holds keeps serving requests. Moving it
to the top makes it the active account, whose lapse isn't shown.

Like siwcFresh (the ChatGPT API's refresh) already does, a refresh that has
been sent now runs on context.WithoutCancel with its own 30 s; a caller
already gone sends nothing.

The cause can't be confirmed without willz's log; this is the one path
found where a working account's refresh token is lost.

Run: TestCodexRefreshOutlivesItsCaller fails without the change
("context canceled") and passes with it; -race -count=10; the whole
internal/provider package (sandbox HOME); gofmt -l; go vet darwin,
GOOS=linux -tags nogui, GOOS=windows.
Not tried: a real Codex account.
2026-10-14 14:47:35 +08:00
yetone 6e9930e374 provider: the Kiro mover asks for opencode-kiro-auth 0.1.10, which passes the caller's prompt-cache marks to Kiro (magpie-community/plugins#110)
kiro 0.1.10 (plugins 386a2ba) turns each cache_control in the Anthropic
body magpie hands the plugin (system, messages, tools) into Kiro's
cachePoint, at most 4 with the last kept; up to 0.1.9 it dropped them, so
a moved Kiro never asked Kiro to cache. This raises the mover's min, so
keepMovedCurrent updates every moved user.

Run: npm view @magpie-community/opencode-kiro-auth version on
registry.npmjs.org shows 0.1.10 (the publish run is red only for
zed-auth and zen-free-auth, refused by npm's trusted publishing); the
plugin's bun test (1191 pass) and scripts/check.mjs kiro, with its
cache-points.test.mjs failing 3 of 4 with the fix broken by hand; gofmt
-l; go vet darwin, linux -tags nogui, windows on internal/provider; go
test -count=1 ./internal/provider (ok).
Not tried: a real Kiro account.
2026-10-14 13:20:36 +08:00
yetone 33da86c71a provider: removing a plugin sets its providers' model picks in providers.json aside, and adding it again puts them back (#2057, dawn1095)
A plugin's provider leaves a record in providers.json once the user
picks its models: its id and nothing of its own (OnlyPicks). Removing
the plugin left those records behind. Nothing listed them, `magpie
provider rm` couldn't reach them, and a sync or backup asked for a
sign-in to them on every run.

RemovePlugin now finds the ids the plugin's providers are stored under
(PluginID of each provider plugin.Listed gives for its spec), and moves
the records with those ids that hold only picks into providers.json's
new pluginLeft, under the plugin's package name. Left alone:
- any record with an endpoint or a key (the user's own provider,
  whatever its id);
- a built-in's ids (accountIDs) and "magpie";
- an id another installed plugin serves too;
- everything, when the plugins' listing isn't known (no cache and no
  plugin-providers.json): unknown is not "none is the user's".
provider.AddPlugin (CLI, GUI, backup restore) puts the set-aside
records back, each one whose id has no record now; one the user has
given to a provider since stays aside. plugin.Listed is new: the cached
listing, or plugin-providers.json.

Run:
- plugin_left_test.go, four tests with user-owned records beside the
  plugin's (a user "zap" with an endpoint next to the plugin's
  zap-plugin, a hand-made "mine", a built-in's picks, another plugin's
  and a shared id). Each guarantee broken by hand turned its test red:
  no set-aside, no OnlyPicks check, no other-plugin exclusion, no
  unknown-listing guard, take-back over the user's record, no take-back.
- go test ./... in a sandbox HOME; gofmt -l; go vet darwin, linux
  (-tags nogui), windows.
Not done: records left by plugins removed before this change stay where
they are; turning a plugin off (not removing it) sets nothing aside;
`magpie provider rm` still can't name such a leftover. The move flow
(installPlugin) still adds through plugin.Add, since its own
migration owns those records. Not tried with a real plugin removal in
the GUI.
2026-10-14 13:20:13 +08:00
yetone 3a7d0314a9 usage: a window's Pace as a number on its card, and in the menu bar when asked (fflake33)
fflake33 on Discord asked for the pace as a figure, "+12%" or "−8%"
against an even pace through the window, on the Usage cards and in the
menu bar.

- provider: QuotaWindow.Pace(readAt, now) is the share used (0-100) less
  the share of the window gone by, from Bounds (reset less span; a
  month's window a calendar month); none for an unlimited window, one
  whose span or reset isn't known, or outside it. WithWindowStarts sets
  startsAt on copies of the cards for the GUI (the caches' cards are
  left alone); /api/usage/quotas and its refresh send it.
- Usage page: "Pace +20%" on the reset line after the wait (quotaPace,
  paceLine), its sign turned with the meter in Left mode, amber while
  more is used than an even pace would have, what it means in its
  tooltip. Past cycles and windows with no known start show none.
- Menu bar: Settings > Menu bar pace (settings.TrayPace, off by default;
  hidden on Windows, whose tray shows no text) puts " +12%" beside each
  figure ("42% −14%", at most 10 runes, trayRowMax) and "pace −14%" in
  the tooltip. KeepOwn keeps it device-local like the other tray
  settings; the Settings save keeps it (prefsKeep).
- Strings in en, zh, zh-TW, ja, de. gui-shell.md says it.

Run:
- go test -tags nogui ./internal/provider ./internal/gui ./internal/settings
  ./internal/usage: ok; ./internal/davsync: ok (now covers TrayPace;
  red with TrayPace taken out of KeepOwn). go test ./internal/gui -run
  Tray (darwin, with the tray image tests): ok.
- New TestWindowPace, TestWithWindowStarts (input not mutated),
  TestTrayUsagePace (off unchanged, used and left, rows, tooltip).
- quota-pace.test.cjs, chromium and webkit: 4 pass; cards in en, zh,
  zh-TW, ja, de at 1100 and 420px, used and left, amber, tooltips, no
  sideways scroll, a click moves nothing; the Settings row in all five
  at both widths, On posts trayPace, a currency save keeps it, no
  scroll; hidden with no card and on Windows, shown on Linux. Red with
  paceLine not called, with trayPace out of prefsKeep, and with the
  Left-mode sign not turned.
- gui-de, gui-ja, gui-zh-tw, i18n-keys: 12 pass; tray-bird 6, quota-holds
  2, quota-read-at 4 pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.
Not tried: the real menu bar on a Mac or Linux tray.
2026-10-14 13:02:48 +08:00
yetone 722abfbb0a usage, gui: a window whose whole can't be estimated says "not enough data", and why in its tooltip (#2045)
The Usage page's account cards told a window's whole ("Whole ≈ N tokens
· ≈ $X") only where it could be reckoned honestly, and said nothing
elsewhere, so a reader couldn't tell a window magpie can't reckon from
a fault (#2045 asked for "数据不足" there).

The server now says why on each window of an account's own card that
isn't reckoned (QuotaWindow.HoldsWhy):
- low: under 5% used (HoldsFloor);
- clock: no reset clock, so no known start;
- log: the window began before magpie's request log;
- none: magpie routed nothing the window counts in it;
- credits: a call in it may have been paid from credits or extra usage
  (#2010's dry runs).
Windows whose whole is never told (a pool, a family, money aside, an
error card, another magpie's) carry no reason and say nothing, as
before. WithWindowHolds now also fills reasons when no window at all can
be reckoned; the caller's cards are still left unwritten.

The GUI shows a muted "Whole: not enough data" on the reset's line, with
the reason in its tooltip, in all five languages. A reason it doesn't
know says nothing. History cards are unchanged.

Run:
- go test ./internal/usage ./internal/gui: pass. The window-holds tests
  check each reason, that reckoned windows carry none, and that the
  caller's cards stay unwritten. Not writing HoldsWhy turns 3 tests red.
- quota-holds.test.cjs in Chromium and WebKit, en/zh/zh-TW/ja/de, at
  360, 420, 440, 1000 and 1100: the line, its reason, muted, not cut,
  inside its card. Removing the GUI branch turns it red. Screenshots at
  420 in zh and de looked at.
- i18n-keys, quota-curve, keep-login, quota-name-translated in both
  engines: pass.
- gofmt -l clean; go vet darwin, linux (-tags nogui), windows; linux and
  windows builds.
Not tried: a real account's card in the running app.
2026-10-14 12:53:09 +08:00
yetone f074996d93 provider, gateway, gui: a model with none of its levels ticked is sent no reasoning field, on every route and in a routing group (yuexian7)
yuexian7 on Discord: models.dev lists their model as reasoning, and the
vendor answers any reasoning parameter with 422 while the same request
without it works. In a routing group they couldn't set an effort per
model, and the model editor refused to untick the last level ("Keep at
least one level"). The learned refusals (bed306ae, #1062) don't cover
this: they learn a refusal of reasoning *off* and of Gemini levels, and
optionalFields holds thinking/enable_thinking, not reasoning_effort.

- settings.ModelReasonless, set by provider.SetModelReasonless (the
  provider editor's Names & levels with every level unticked, saved as
  modelPrefs {reasonless: true}; `magpie model efforts <ref> off`).
  Ticking levels again or Restore default clears it (setModelEfforts);
  setting it drops the model's kept levels.
- entryFor and Efforts/Thinks/Levelless: the model offers no levels and
  is Quiet, so agents are given none for it.
- Gateway: the candidate loop strips the body with withoutAnyReasoning
  in the agent's protocol (Chat/Responses reasoning_effort, reasoning,
  thinking, enable_thinking, include's reasoning.encrypted_content;
  Anthropic thinking of any type and output_config.effort; Gemini
  thinkingConfig). The Anthropic relay doesn't add
  thinking:{type:disabled} for it, and forwardTranslated clears Effort,
  ThinkOff and Thinking for its other callers (continuation, search).
- A routing group with it as a member keeps the other members' levels
  (it `continue`s like a member whose levels are unknown, #597), and the
  member that reasons is still sent the effort asked.
- GUI: none ticked shows "No reasoning field sent" beside the levels, in
  zh, zh-TW, ja and de too; a model with one known level now shows its
  picker so it can be unticked. A model whose levels aren't known
  (m.given) keeps none ticked meaning no levels known.

Run (worktree on origin/main 82f3befd2, sandbox HOME, private GOCACHE):
gofmt -l clean; with set -o pipefail go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... all clean; node --check
app.js. go test -count=1 ./internal/provider ./internal/gateway
./internal/settings ./internal/cli: ok. ./internal/gui: ok except
TestMainWindowCorners/macOS_15_SDK killed at its 40s deadline under
load (AppKit window measurement, untouched here; #1936, noted there).
The run caught TestSettingsSaveKeepsWhatItDoesNotSend (ModelReasonless
added to it) and the CLI usage alignment tests (fixed).
New tests and what breaking the change does: TestReasonlessModelSentNoReasoning
(Chat, Chat+enable_thinking, Responses with include, Anthropic->Chat
translated; by name and through group/mix) and TestReasonlessAnthropicRelay
fail with gateway.go/quiet.go reverted; TestGroupReasonlessMemberKeepsLevels
fails with group.go's reasonless branch disabled; TestModelReasonless
needs the new API. model-reasonless.test.cjs in chromium and webkit, at
1100 and 420, in en, zh, zh-TW, ja, de: 20/20; on the old assets all
fail. Related GUI tests 418/418 (one model-copy-id failure on a first
run under load, passed alone; #2066).
Not tried against the reporter's real vendor: the 422 is taken from
their report.
2026-10-14 09:38:12 +08:00
yetone 54a003d48d provider tests: the device sign-ins' fakes poll every 10ms, not the 1s floor a vendor's 0 interval got (#2051)
Copilot, Factory and ZCode's device sign-ins wait at least a second
between polls, whatever interval the vendor gives. The tests' fakes give
0, so each poll in a test cost a full second, and these tests were 56.5s
of the provider package's 399s of test time.

The floor is now devicePollFloor, read through devicePoll(seconds) at the
three call sites, and the provider package's TestMain lowers it to 10ms.
Real sign-ins still wait max(vendor's interval, 1s), as before.
TestDevicePollKeepsItsFloor checks 0, -1 and 1 give 1s and 5 gives 5s.

Run:
- go test ./internal/provider (full, -count=1, load avg ~100): pass,
  403s -> 316s of package time; the Copilot/Factory/ZCode tests 56.5s
  -> 22.5s.
- A/B on -run 'Copilot|Factory|ZCode', base vs this: 45-58s vs 15-16s
  (32s once, under load).
- Removing the floor from devicePoll turns TestDevicePollKeepsItsFloor red.
- gofmt -l clean; go vet darwin, linux (-tags nogui), windows; linux and
  windows builds.

One A/B round failed on both base and this change at load over 200; the
cause wasn't captured, and the next 4 rounds passed on both.

Not done: the other slow causes in the package. The 1.2s sleeps waiting
for the callback port to be let go (signin_test.go:137,
signin_proxy_test.go:92, signin_usage_afresh_test.go:70), Cursor's
linkWait, MoveToPlugin (7-9s) and WarmAtSeveralTimes (6-10s).
2026-10-14 09:29:59 +08:00
yetone ccffdadb8a gateway: /v1/audio/transcriptions passes speech-to-text through to the provider (#2053, niyoh120)
niyoh120 asked for an OpenAI-style speech-to-text endpoint so a client's
voice input can go through magpie like its chat does. magpie had no
/v1/audio route, so the request 404ed.

What changed:
- POST /v1/audio/transcriptions and /v1/audio/translations (and the
  /audio/... spellings) route through the same core as embeddings and
  rerank. embeddings.go's routing is pulled out into serveRetrieval, so
  disabled models, key access, groups, pause rules, account holds,
  failover, redaction and usage records are shared rather than copied.
- transcribe.go reads the multipart form only to find `model` (as
  provider/model) and `prompt`. The form goes to the provider byte for
  byte; it is rebuilt part by part, under the same boundary, only when
  the model name is rewritten or the prompt was masked. The audio part
  is always copied as sent.
- Only providers with an OpenAI-style base are tried; an Anthropic-only
  provider gets a 400 saying so. A body that isn't multipart, a form with
  no model, or one that doesn't parse gets a 400 and nothing is sent.
- The vendor's answer type passes through (response_format text/srt/vtt
  stays text/plain). Usage records output tokens from usage.output_tokens.
- The 404 message, the info api list, remote magpie's suffix list, the
  CORS and LAN tests, docs/reference.md, gateway-routing.md and the
  remote docs (en, zh, ja) name the new paths.

What was run, at 9c36c3a0 (this change rebased on 10f38770):
- gofmt -l internal/gateway internal/provider: empty
- go vet (darwin); GOOS=linux and GOOS=windows go vet -tags nogui on
  ./internal/gateway ./internal/provider: clean
- go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider:
  ok (1367s, 339s); also green on two earlier bases (b4fe6663, 06fbfd95)
- Rebased again on a0ebe003 (main had moved 5 commits, none in these
  files; routing.go's Factory rest is the nearest): gofmt, vet on darwin,
  linux (nogui) and windows (nogui) clean, and
  go test -tags nogui -run 'Transcri|Embed|Rerank|CORS|LAN|Lan|Factory|
  Retriev|NotFound|Info' ./internal/gateway ok. The full packages were not
  rerun on this last base.

Break-checks, each turned red and restored:
- routes removed (the old code): all 5 new tests fail
- model never rewritten: TestTranscriptionGoesToTheModelsProvider and
  TestTranscriptionPromptRedacted fail
- answer always labelled JSON: TestTranscriptAsTextKeepsItsType fails
- rebuild truncates the audio part: Goes + PromptRedacted fail
- prompt not masked: TestTranscriptionPromptRedacted fails
- output tokens ignored: TestTranscriptionGoesToTheModelsProvider fails

Real use: through magpie's real handler against aihubmix
(https://aihubmix.com/v1) with a `say`-made m4a: whisper-1 json 200
{"text":"Hello from the Magpie Gateway."}, response_format=text 200,
srt 200 text/plain with SRT cues, translations 200.

Not tried: OpenAI direct (the key answers 429 "account is not active"),
Groq, a local vLLM/whisper server, and any real client's voice input.
2026-10-14 09:19:16 +08:00
yetone 40df6dbd38 provider: a subscription sign-in canceled while its token is fetched adds no account (#2054)
A sign-in checked canceled/finished only when its callback was claimed.
The token exchange after that went on to addLogin / addGoogleLogin /
addSideLogin and only then called finish, a no-op after CancelSignIn, so
a sign-in the user canceled while its token was in flight still added
the account, or replaced an existing account's tokens. Sibling of #1750
(mcpauth's flow.keep, 1a7aa76b4).

Every built-in sign-in's write of its account now goes through one gate:
keepLogin(ctx, store), which finds the flow s.via put on the sign-in's
context and runs store under the flow's lock only while the flow is
live (signInFlow.keep). The CLI-run sign-ins (Claude, Grok, Cursor),
whose context isn't the flow's, call s.keep directly. Cancel takes the
same lock in finish, so either it comes first and nothing is written
(the flow stays "canceled"), or the account is kept and a cancel after
that is too late (kept): the flow then goes on to "done", matching the
account list.

Routed through it: Codex and Devin callbacks (Devin's own credentials
file and its side home), Gemini/Antigravity, ChatGPT API, Claude Code,
Copilot, Command Code (callback and pasted key), Factory, Kiro, MiMo,
Qoder, WorkBuddy, Zed, ZCode, and runCLISignIn's identity (Grok's second
account). Plugin sign-ins are kept by the plugin host and aren't
covered here.

Run:
- TestCanceledSignInAddsNoAccount (Codex: browser callback and pasted
  address, the token endpoint's reply held until CancelSignIn) and
  TestCanceledDeviceSignInAddsNoAccount (Copilot device code, GitHub's
  answer held, read whole, until after the cancel). On the old code all
  three FAIL: "the canceled sign-in wrote ~/.codex/auth.json", "the
  canceled sign-in added cx@example.com", "the canceled sign-in added
  late-user". With the fix they pass, -race -count=5.
- go test -tags nogui -timeout 45m ./internal/provider/... ok (sandbox
  HOME, private GOCACHE).
- gofmt -l clean; go vet ./internal/provider (darwin), GOOS=linux and
  GOOS=windows go vet -tags nogui ./internal/provider ok.
Rerun after rebasing on origin/main f71155591 (#2052, which touches
provider/models.go): gofmt and the three vets ok; the provider suite
(-timeout 45m) ended once in a bare FAIL with no test named, then passed
3 runs in a row (one -v). Filed as #2061. Rebased again on 8da304767:
gofmt, the three vets and the provider suite ok.
Not tried against a real vendor's sign-in.
2026-10-14 08:39:37 +08:00
yetone 75cbc7e1e5 provider: a subscription switched off or removed makes no background requests, no claude auth status every minute (Riko on Discord)
Riko switched Claude off in Providers, and magpie still ran
`claude auth status --json` about every minute. Off only kept the
gateway from routing to it. Every page and request lists accounts,
which re-asked the CLI, and the background loops went on reading
allowances, renewing, switching, warming, checking in and fetching lists.
The same held for each sibling with a CLI or account check: Cursor
(`cursor-agent about`), Devin (`devin auth status`) and the rest.

What changed:
- left_alone.go: leftAlone(id), true for a provider that is Off or
  Hidden (account removed).
- account.go claudeIdentity and cli_identity.go get (Cursor, Devin): the
  CLI isn't asked; what it said last (memory or cli-identity.json) is
  served, so the account stays listed to switch on again.
- subscription_usage.go: claude, cursor and grok are checked as hidden
  before their account is looked up (the look-up ran the CLI).
- login_usage.go loginUsageAt, keepalive.go RenewLogins,
  codex_switch.go NextLogin, codex_warmup.go keepWarm: leftAlone where
  only accountRemoved (or nothing) was checked.
- models.go newDue: a provider that is off has no list fetched.
- checkin.go: each check-in account knows its card's provider; the loop
  skips one that is left alone, a press still checks it in (minimax,
  trae, qoder, workbuddy, plugin check-ins set it).
- docs/subsystems/providers-accounts.md says so.
Not covered: KeepPluginsListed lists every plugin at once in the host. A
Cursor switched off that was never asked who is signed in isn't listed
until switched on.

What was run:
- TestLeftAloneRunsNoCLI: fake claude, cursor-agent and devin on PATH log
  each run; with claude and cursor off and devin removed, All, Hidden,
  fetchSubscriptionUsage, LoginUsage, RenewLogins, SwitchWhenSpent and
  FetchNew run three times over stale caches and no CLI is run; switched
  back on, all three are asked again.
- Break check: with the source changes reverted it fails with
  "switched off or removed, the CLIs were run: [claude_auth_status_--json
  cursor-agent_about_--format_json devin_auth_status ...]"; with only the
  claude gate removed only claude is logged, with only cliIdentity's only
  cursor and devin.
- go test -tags nogui -timeout 45m ./internal/provider ./internal/gateway:
  ok (399s, 1271s).
- gofmt -l: clean. go vet (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean, under set -o pipefail.
2026-10-14 08:28:08 +08:00
yetone 8f03b78069 cli, gateway: magpie statusline prints the session's model and each account's windows for Claude Code's status line (#1997, kensenzhao)
kensenzhao asked for magpie's routing and quota in Claude Code's status
line. Claude Code runs the statusLine command on every update and cancels
the run that is still going, so the command must answer fast. It must never
make a vendor read.

- `magpie statusline [<provider|account>]` reads Claude Code's statusLine
  JSON from stdin. It prints "→ <served model>" from
  /v1/magpie/route?session=<session_id>, then each subscription account's
  windows ("claude a@x* 5h 62% 7d 41%"). `*` marks the account that served
  last. A window whose reset has passed shows 0%. With the gateway off it
  prints an empty line. Each request times out after 1s.
- /v1/magpie/quotas?kept=1 (provider.KeptQuotaReport) builds the same
  report from the kept cards (CachedCards) and never starts a vendor read.
  The plain endpoint can take up to 12s.
- magpie never writes statusLine into Claude Code's settings. The user
  adds `"statusLine": {"type": "command", "command": "magpie statusline"}`
  themselves (magpie statusline's help, docs/reference.md).

Run: go test -tags nogui ./internal/cli ./internal/provider
./internal/gateway in a sandbox HOME; gofmt -l; go vet natively and with
GOOS=linux and GOOS=windows.

Broken by hand, each went red:
- the CLI asking without kept=1 (TestStatuslineTellsRouteAndEveryAccount);
- dropping the route line (same test);
- KeptQuotaReport calling QuotaReport (TestKeptQuotaReportAsksNobody).

Real use: a built binary against a sandbox gateway on 127.0.0.1:3517.
- kept=1 answered in 0.07s and route in under 1ms.
- `magpie statusline` with Claude-style stdin printed an empty line, since
  the sandbox has no accounts.
- Its ~1.1s wall time matches `magpie version`, so that is process start.
Not tried: real accounts, or the line inside a real Claude Code statusLine.
2026-10-14 08:26:04 +08:00
yetone a5d72a095b gateway, gui, cli: a search API's keys take turns, a refused one rests, and each Tavily key shows what it has used (SlouchyQuill)
SlouchyQuill on Discord asked for a Tavily key pool after
dsh-tavily-pool: several keys, each key's quota shown, keys rotated.
Before this, the comma-separated keys (#1477) always started from the
key that last answered, so one key took every search until it was
refused, a refused key kept no rest of its own, and nothing showed what
a key had left.

What changed:
- Turns (internal/gateway/search_keys.go). Searches take turns over the
  keys by default (round robin, a counter per vendor). pick=order (CLI)
  or In order (Settings) always starts from the first key; the pick is
  saved in SearchAPI.Pick.
- Rests. A refused key rests: 401/403 for 10m ("turned away"), 402 for
  1h ("out of credit"), 429 for its Retry-After held to 30s-10m (1m
  without one). 432/433 count as out of credit from Tavily only; from
  any other vendor they rest as a rate limit. A resting key is asked
  after the others, soonest back first, so failover is kept, and it
  wakes when it answers. Rests are keyed by a hash of the key.
- Quota (internal/gateway/search_quota.go). Each Tavily key's quota is
  read from GET /usage with that key. The fixture is the documented
  reply from docs.tavily.com. The key's own limit is used when it has
  one; otherwise its plan's plan_limit/plan_usage, which the account's
  keys share. A failed read, or a reply missing those fields, says
  unknown and why, never 0. A read is kept 2m unless asked fresh. A key
  found used up with no pay-as-you-go credit rests 1h; a later read
  with credit wakes it.
- Keys never appear in full. The vendor's error has the key masked
  (tvly-…abcd), and errors name "key N (tvly-…abcd)".
- GUI. Settings › Models › Web search adds a "Keys of <API>" row under
  an API with several keys or with Tavily's: In turn / In order, each
  key masked with what it has used and why it is asked last, and Check
  again. There is an API for it (POST /api/settings/search-quota), and
  13 strings in zh, zh-TW, ja and de.
- CLI. `magpie search` lists the pick and each Tavily key's quota, read
  fresh; `magpie search add … pick=turns|order`.
- Docs. gateway-routing.md has a new section "A search API's keys";
  both READMEs have a line on web search.

What was run:
- go test -tags nogui ./internal/gateway ./internal/provider
  ./internal/cli ./internal/gui: ok. After the last rebase, provider
  and cli again, and gateway -race -run Search.
- New tests: TestReadTavilyUsage, TestSearchKeysTakeTurnsRoundRobin,
  TestSearchKeyRefusedRests, TestSearchRestFor, TestSearchQuotas and
  TestSearchKeyNeverInFull. Each guarantee was broken by hand and its
  tests went red:
  - turns pinned to the first key: RoundRobin and RefusedRests;
  - rests ignored: TestSearchAPIKeysTakeTurns, RefusedRests and
    TestSearchQuotas;
  - key masking removed: NeverInFull;
  - a failed read reported as known: TestSearchQuotas.
- gofmt -l; go vet -tags nogui for darwin, linux and windows on the
  four packages.
- GUI: search-keys.test.cjs covers en, zh, zh-TW, ja and de ×
  Chromium and WebKit × 1100 and 420px: 20/20. Without the new
  .search-keys .val wrap rule, de at 420px fails ("Erneut prüfen" went
  past the window's edge).
  - search-api, search-first, search-instead, search-mcp,
    searcher-pick, settings-search, provider-search, gui-de, gui-ja and
    i18n-keys: 56/56 in each engine.
  - Full suite in Chromium (concurrency 6, load ~40): 4498/4504. The
    files that failed (gateway-key-groups, rest-try-now,
    routing-wb-restricted, text-size, usage-sum-whole) were rerun
    alone. All pass except usage-sum-whole, which fails now and then
    on an origin/main worktree too under the same load (#1864, #2023;
    rest-try-now and routing-wb-restricted are #1905). None of them
    touch search.
- Real Tavily API with two invalid keys: /search returns 401
  {"detail":{"error":"Unauthorized: missing or invalid API key."}},
  which counts as a refusal. Both keys rest 10m as turned away, the
  error names them only masked, and both quotas read "unknown · 401".
  Checked through a test and through the nogui CLI binary in a sandbox
  HOME.

Not tried: a valid key's /usage against the real API. No Tavily key
was at hand, so the quota parsing is checked against the documented
bytes only.
2026-10-14 08:24:03 +08:00
yetone f71155591e provider: a provider at a vendor's own endpoint is priced from that endpoint's models.dev catalog (#2052, mengyianx)
A custom provider added by its address alone, with no catalog named, was
priced only by the model's maker. Qwen3.8-27B, whose maker (Alibaba) sells
no such model on any of its seven models.dev catalogs, read "no price is
known for it" even at AMD's own endpoint, where models.dev's amd lists it
at $0, a price.

- catalog: models.dev's provider "api" is read; AtEndpoint names the
  catalogs at a base URL (trailing slash and case ignored).
- provider: EndpointCatalog is the one catalog models.dev lists at one of
  a key's provider's endpoints (an Anthropic base, kept as its root, also
  with /v1), used by ListPrice when the provider has no catalog of its
  own. Never for a subscription's account, never when two catalogs share
  the address (minimax / minimax-coding-plan), never a plan's catalog
  (an id with -plan, or membershipCatalogs), whose $0 is the membership's.
  A user's price and a named catalog still come first; a relay's endpoint
  matches nothing and its model stays unpriced (no reseller guess).
- cli: `magpie model price p/m` with no price gives the two commands that
  set one (p/m and */m); a price from an endpoint's catalog names it.
- gui: the Catalog field's hint says it also sets list prices (en, zh,
  zh-TW, ja, de).
- docs: reference.md's "What a model costs", providers-accounts.md row.

What was run:
- Reporter's exact case, built binary (go build -tags nogui), sandbox
  HOME with a copy of this machine's models.dev cache (2026-10-14, same
  amd entry as the report), providers 001 (relay), 002 and amd at
  https://developer.amd.com.cn/radeon/api/v1:
    001/gpt-5.5      $5/$30, tiers, as before
    001/Qwen3.8-27B  no price, now with the two commands to set one
    002/Qwen3.8-27B  $0/$0, "what models.dev's amd lists at its endpoint"
    amd/Qwen3.8-27B  $0/$0
  The two suggested commands were run and took effect.
- TestEndpointCatalogPrices / TestEndpointCatalogOnlyItsOwn, fixture
  testdata/endpoint_catalog.json trimmed from the real models.dev cache.
  Break checks, each FAILs with the case named:
    ListPrice not using EndpointCatalog -> 002/amd/001 at AMD unpriced,
      EffectivePrice(002, Qwen3.8-27B) unpriced
    plan exclusion removed -> "a plan's endpoint: EndpointCatalog() =
      alibaba-coding-plan", qwen3.5-plus at $0 instead of $0.4/$2.4
    single-match rule removed -> "an endpoint two catalogs share:
      EndpointCatalog() = minimax"
    Account check removed -> "a subscription's account ... = amd"
    Anthropic /v1 match removed -> thinkingmachines unmatched
- GUI: internal/gui/tests/catalog-hint.test.cjs, chromium and webkit, en
  zh zh-TW ja de, widths 1100 and 420: 20/20 pass, plus i18n-keys; with
  the old app.js/i18n.js it fails "one hint names list prices".
- go test -tags nogui -timeout 45m ./internal/catalog ./internal/provider
  ./internal/cli: ok (provider 244s, cli 125s, catalog 3s). gofmt -l
  clean; go vet (darwin), GOOS=linux go vet -tags nogui and GOOS=windows
  go vet -tags nogui on those packages: clean.
2026-10-14 07:51:41 +08:00
NorethSea 56fcd1dc27 usage: each account picks a recorded allowance cycle beside its curve, meters and legend following it (#2009, NorethSea)
Let each account choose completed cycles beside its allowance curve. The
meters, sampling dates, plot and legend follow that cycle. Missing readings
stay unknown, and current account actions and whole-window estimates are
not presented as historical data. Fixed-deadline refills preserve cycle
boundaries alongside natural and early resets.

Keep the upstream whole-window estimate for the current view; no separate
price endpoint or duplicate estimation is added.

Verified on the integrated tree based on origin/main a75de4c2:
- 155 allowance, translation and scroll UI tests pass in Chromium/WebKit.
- Quota history race tests pass with count=3.
- macOS/Linux/Windows vet and builds pass.
- New Go cases fail without the unchanged-deadline refill handling; the UI
  case fails against upstream assets because the picker is absent.
- Real local allowance snapshots confirm cycle and meter switching.
- Full Go suite has one failure: TestPluginModelListThroughAccountProxy
  exceeds its context deadline. Other packages, including provider, usage
  and gui, pass. No release or complete-suite pass is claimed.

Reviewed and landed by yetone's agent from NorethSea's commit 69021d2c8,
cherry-picked onto origin/main (README conflict only: both appends kept).
Run at this head: go test -tags nogui ./internal/provider -run Quota,
-race -count=3 -run QuotaHistory, gofmt, GOOS=linux/windows go vet;
TestQuotaHistoryUnscheduledResets goes red with the refill rule removed.
GUI: quota-*, usage-*, balance-*, panel-usage, tray-*, click-scroll,
i18n-keys, gui-ja/de/zh-tw in Chromium and WebKit: 923/926; the three
reds are usage-sum-whole (also red 3 of 4 runs alone on origin/main
591ed58b5, #1864) and a usage-ledger case that passes alone.
2026-10-14 05:32:03 +08:00
yetone bf25842714 gateway: a provider's own cap on how long a key that keeps failing rests (#2008, Gaudi-XIX)
A key that keeps failing doubles its rest from a minute up to 10 minutes,
and one rate limited again as soon as its rest is over up to 30; both
caps were fixed, so a free key down for hours was asked again every 10
or 30 minutes all the while.

`magpie provider rest-cap <id> 4h` (Provider.RestCap, minutes, at most
MaxQuotaRest, 8 days) sets where both ladders stop for that provider's
keys and accounts (RestCapOr in restAfterMarked's default branch and in
rateRest); `default` gives back the gateway's own. A time the vendor names
still stands over it. Unset, nothing differs. It is kept by the editor's
save, the account copy and normalize.

Run: go test -tags nogui ./internal/provider ./internal/gateway
./internal/cli ./internal/gui (temp HOME). Broken by hand: both ladders
back on the fixed caps fail TestOwnRestCap (rate-long #6: 30m, want 32m);
the GUI keep removed fails TestSaveKeepsQuotaResetAt. Not tried against a
real vendor's outage.
2026-10-14 05:22:40 +08:00
yetone 064cffdbfd gateway: a key out of a daily allowance rests until the time of day it comes back (#2008, Gaudi-XIX)
A free tier's "You've reached today's free-model token quota" says
nothing of when it is back, so it rested 15 minutes (or the provider's
own quota-rest), and was asked again all day. A vendor Retry-After over
an hour was cut to the hour, and that hour then stood over the user's own
longer rest.

- Provider.QuotaResetAt: "08:00" on this computer's clock, or
  "00:00+08:00" on the vendor's. `magpie provider quota-rest <id> until
  08:00` sets it; a number of minutes set after it replaces it, and
  default clears both. normalize drops one that isn't a time of day.
  It is kept by the editor's save and the account copy.
- restAfterMarked's quota branch rests until its next occurrence
  (OwnQuotaRest). A time the vendor names, or a window's end, still
  stands over it; a Retry-After stands unless it was cut to longestWait
  while the user's own rest is longer.
- Defaults are unchanged: nothing set, nothing differs.

Run: go test -tags nogui ./internal/provider ./internal/gateway
./internal/cli ./internal/gui (temp HOME). Broken by hand, each fails:
OwnQuotaRest replaced by QuotaRestFor (TestQuotaRestsUntilTheTimeOfDaySet,
3 asserts), the Retry-After guard removed (the 7200 case), the GUI keep
removed (TestSaveKeepsQuotaResetAt), default not clearing it
(TestQuotaRestUntil). Not tried against a real free-tier vendor.
2026-10-14 05:22:39 +08:00
yetone 77f90fd84f gateway: a plugin whose config hook says searches: true is sent the client's web_search as sent (#2027, yudaleng)
A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api
relay whose quota the plugin reads) had no way to say its upstream runs
the hosted web search tool: searchesItself returned at once for any
signed-in account, letting only Codex and Grok through, so Claude Code's
WebSearch and Codex's web_search always went through magpie's own search.

Now a plugin's config hook can set `searches: true` on its provider, as
it sets `decide` (#1514). The host passes it through
(plugin.Provider.Searches), pluginProvider sets the provider's Searches,
and searchesItself honours it for a plugin's provider only, on Anthropic
or Responses and only where the plugin has a model on that API, the same
rule a custom provider's "Searches the web by itself" has (#359). Another
sign-in's Searches is never read; Codex and Grok are unchanged. As with a
relay, searchRank leaves it out, so magpie never picks it to search for
other models; Settings can name it by hand.

Documented in docs/subsystems/provider-plugins.md and the plugin guide
(site/public/docs plugins.html, en/zh/ja).

Verified:
- TestPluginSaidToSearch (new, gateway, through the real fake plugin on
  bun and New().Handler()): with FAKE_SEARCHES the plugin's upstream gets
  web_search_20250305; without it, it gets no search tool; Chat doesn't
  search and searchRank is -1 either way.
- Broken by hand, each red: search.go reverted, plugins.go reverted,
  host.js reverted (each "searches by itself on Anthropic: false"); with
  the searchesItself assertion disabled and search.go reverted, the wire
  check fails "said to search true, the plugin was sent []".
- TestMovedGrokSearchesItself, TestGrokPluginSearchesItself,
  TestWebSearch* pass.
- go test -tags nogui ./internal/plugin ./internal/provider ok, and
  ./internal/gateway (see the run noted on #2027) under a sandbox HOME
  with pinned caches; gofmt -l clean; GOOS=linux and GOOS=windows
  go vet -tags nogui on the three packages clean.
- Not tried with a real CPA/sub2api plugin.
2026-10-14 05:17:31 +08:00
yetone 0337ce4bc7 factory: Haiku 5.5 and Mistral Large 4, in droid 0.240.0's picker, are offered, and moved users get plugin 0.1.25 (JL on Discord)
JL (Windows, droid 0.240.0, Factory desktop 0.197.1, magpie 0.1.1226,
opencode-factory-auth 0.1.24): droid and Factory desktop offer
claude-haiku-5-5; droid through magpie couldn't pick it.

droid's models are the registry bundled in its npm binary
(@factory/cli-<platform> 0.240.0, bin/droid). Against 0.233.0's registry,
0.240.0 adds claude-haiku-5-5, mistral-large-4 and gpt-6-astra-ultrafast.
The plugin (magpie-community/plugins e4023d9, published as 0.1.25, npm view
checked) now offers Haiku 5.5 (Anthropic Messages, 872000/128000, efforts
low..max) and Mistral Large 4 (chat completions, x-api-provider mistral,
Droid Core, 524288/64000, images). GPT-6 Astra Ultra Fast stays out: droid
offers it only once the user accepts Factory's high-cost terms.

- migrate_factory.go: the mover's min is 0.1.25, so keepMovedCurrent
  updates moved users (JL is on the plugin).
- factory.go: the built-in had the same gap; its table gets the same two
  rows for users who haven't moved.
- factory_pool_rest_test.go: the plugin's Core list, copied from its
  usage, gains Mistral Large 4.
- TestFactoryDroid0240Models is new; its fixture is droid 0.240.0's
  registry bytes (the same as the plugin's models.test.mjs). It fails with
  the Haiku 5.5 row removed.

Run, under a temp HOME: go test -tags nogui ./... with the machine at load
35-190 (other sessions). Every package passed except five that hit the
10m timeout mid-test (agent, gateway, library, plugin, provider, in
tests that don't touch Factory). Rerun with -timeout 40m: provider ok;
gateway still timed out at load ~130 (TestCodexHeardWithinItsIdleTimeout
failed on its timing, unrelated); -run 'Factory|Moved' on gateway ok.
agent, library and plugin were not rerun to the end; this change
doesn't touch them. gofmt -l clean; GOOS=linux and GOOS=windows go vet
-tags nogui on internal/provider and internal/gateway ok.
Not tried against Factory itself (no Factory account here); droid was read,
not run.
2026-10-14 05:11:19 +08:00
ggbdpqandfactory-droid[bot] 509328ccb0 provider: a Codex reset spent while an allowance read is in flight is never undone by that read, even on Windows' coarse clock (#1754, ggbdpq)
Allowances took time.Now() when its background read began, and
forgetAllowance stamped the reset with time.Now(); a reading was dropped
only when the reset was After the start. On Windows two events in one
clock tick get the same time, so a read begun before a spent reset could
put the account's 100% back right after it. Reads and resets are now
ordered by a generation counter under usedCache's lock.

ggbdpq's patch (e07232ef), cherry-picked unchanged.

Run (reviewer): TestResetAllowanceKnownAtOnce, Windows test binary on
the Windows box (sandbox USERPROFILE/APPDATA), -count=10: old code FAIL
4 of 10 ("routing reads 100 used (known true), want 0"), this change
PASS 10 of 10. macOS -race -count=20 of the Allowance/Renewed tests ok.
Full provider package, gofmt, linux and windows vet: see the push.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2026-10-14 04:59:07 +08:00
yetone 591ed58b53 provider: Nous Portal is a vendor preset, Nous Research's API with a Portal key (#392, Vocllum, laojianzi)
Nous Research makes the Hermes models and serves them, with other makers'
models, through Nous Portal. #392 was wrongly answered as a relay. A new
preset, nous ("Nous Portal", KindVendor with Hosts, lobe-icons
nousresearch icon), points chat completions at
https://inference-api.nousresearch.com/v1. A Portal API key goes in as a
Bearer, the way Hermes Agent's own nous-api provider uses NOUS_API_KEY.
The model list is the Portal's /v1/models, which uses vendor/model ids.
An entry another app has at that URL, such as Hermes Agent's base_url,
now imports as the preset.

The preset sets no Anthropic endpoint. The Portal's /v1/messages serves
only its anthropic/* models (Hermes Agent's
test_nous_portal_anthropic_wire.py), so Claude Code's requests are
translated to chat completions for every model. It sets no Responses
endpoint either, because none is documented.

The preset is added to the README (en, zh), docs/reference.md, and the
site's import pages and icon.

Sources:
- hermes-agent docs: integrations/nous-portal, integrations/providers,
  features/subscription-proxy.
- hermes-agent source at 6e7b83a2: hermes_cli/auth_constants.py
  (DEFAULT_NOUS_INFERENCE_URL), plugins/model-providers/nous,
  cli-config.yaml.example ("nous-api - Nous Portal API key (requires:
  NOUS_API_KEY)"), agent/anthropic_endpoints.py, and
  tests/e2e/core/live/_helpers.py, whose live run calls the Portal with
  NOUS_API_KEY.

Probed without a key:
- /v1/models answers 200 with 423 models.
- /v1/chat/completions with a bad Bearer answers 401 "Your API key is
  invalid, blocked or out of funds".
- /v1/messages answers an Anthropic-shaped 401.

Not tried: a real Portal key or a real request, since no key was
available. Also not built: OAuth sign-in with the 1-hour token and its
refresh (Hermes Agent's ~/.hermes/auth.json).

Run:
- TestNousPortalPreset fails without the preset (no preset "nous") and
  with an Anthropic endpoint added (endpoints: … "https://inference-api.nousresearch.com").
- go test -tags nogui of internal/provider, internal/gui and
  internal/catalog passes.
- gofmt -l is clean.
- go vet, GOOS=linux go vet and GOOS=windows go vet -tags nogui on
  ./internal/provider pass.
- add-sheet and add-button GUI tests pass in Chromium and WebKit (6/6).
2026-10-14 04:40:21 +08:00
yetone 4c746ab390 gui: Azure OpenAI says its models are the deployments magpie lists with the key (#1995, parkavenue9639)
Adding Azure OpenAI asked only for the endpoint and key. Nothing said that,
once it is saved, magpie asks the resource for its deployments with that
key (Provider.azureModels), so people took the page for one where model ids
must be typed. A saved one whose list hadn't come back yet said "The
vendor's list is empty", the same as one asked and empty.

- The endpoint hint (presets.go) now says magpie asks the resource for its
  deployments with this key once added, and the deployments' names are the
  model ids.
- The add page has a Models row for Azure: nothing to type; a deployment's
  name is typed as a model id only if the list can't be fetched.
- A saved Azure provider with an empty list says it is asking the resource
  with this key while the background fetch runs (providers.fetching, not
  yet fetched, no list error), and after it that no deployments came back,
  with Fetch again or a deployment's name. Every other provider's empty
  text is unchanged.
- New strings in zh, zh-TW, ja and de.

azureModels itself is unchanged.

Run: azure-endpoint.test.cjs (24 pass, Chromium and WebKit, en and zh),
extended with the add page's Models row and four empty-list cases (asking,
asked and none, asked and failed, OpenRouter unchanged). With the old
app.js put back it fails 10 of 12 on Chromium (no .azure-models row, the
generic empty text). With the old i18n.js the zh cases fail (6 of 12).
gui-de, gui-ja, gui-zh-tw, i18n-keys, provider-fetch-again,
provider-picks-stay, add-sheet: 34 pass in each engine. go test -tags nogui
./internal/provider ./internal/gui ok under a sandbox HOME; gofmt -l clean;
GOOS=linux and GOOS=windows go vet -tags nogui on both packages clean.
Not tried against a real Azure resource (no account): only the text
changed, not the fetch.
2026-10-14 04:39:51 +08:00
yetone 80211e7075 provider: a balance field sums, maxes or counts a list's items, and one amount it can't read is "—" (#1993, RicardoWYP)
A relay's /api/subscription/self tells usage per subscription, a list.
A balance path could only name one index (subscriptions.0), so several
active subscriptions read as the first, ".0 + .1" failed whole when only
one existed, and a weekly cap of 0 ("divides by 0") hid every amount of
the field.

Now a path goes through a list's items with "*" (a.*.used), or those
that match with "[key=value]" / "[key!=value]" (a[status=active].used,
also on an object: a.*.subscription[status=active].used). Such a path is
several values, made one by sum(), max(), min() or count(); arithmetic
between two of them goes item by item, so max(a.*.used / a.*.cap) is the
fullest window. Several values left outside a function are an error
naming the functions, not a guessed sum. Within a list an item without
the path, or divided by 0, is left out; max/min of nothing is an error.

In a field of several ";" amounts, one that can't be read shows "—"
(BalancePart.Error says why, as the card's hover on the Usage page and
in the panel) and the others still show; the read fails only when none
can be read. A single amount alone still fails as before.

The GUI hint (zh, zh-TW, ja, de) and `magpie provider` help say the new
syntax.

Run:
- TestBalancePathLists, with the reporter's literal JSON: against the
  old balance.go it fails ("nothing at \"sum\" in the reply", and the
  "—" cases error); passes now. TestReadBalancePath's one case that
  expected a whole-field failure with one bad amount now expects it
  only when every amount fails.
- go test -tags nogui ./internal/provider ./internal/cli ./internal/gui
  under a temp HOME: ok.
- balance-parts, gui-de, gui-ja, gui-zh-tw, i18n-keys in Chromium and
  WebKit: 14 pass. With the title lines removed, balance-parts fails on
  the missing hover text.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on
  provider and cli.
Not tried against the reporter's real relay.
2026-10-14 04:37:43 +08:00
yetone cc43e9893c provider: a plugin subscription put first on one computer is first on the other too, once sync has named it by both ids (#1940, Sun1090)
Sun1090, on v0.1.1225 (which had 9c922b9f7): WorkBuddy and WorkBuddy AI
put first on one computer, and on the other WorkBuddy AI still came last.
Their screenshots show why. WorkBuddy AI is moved onto its plugin on one
computer (workbuddy-ai) and signed in to the plugin under its own id on
the other (workbuddy-ai-plugin). The order synced in names
workbuddy-ai-plugin first, and MirrorOrder keeps the ids this computer
names alone after the other's, so the stored order named both:
[workbuddy-ai-plugin, ..., workbuddy-ai]. 9c922b9f7 looked up the
counterpart only when the order didn't name the provider's own id, so the
own id, put last by sync, won.

- ordered(): a provider takes the earlier of its own place and its
  counterpart's, when the counterpart isn't a provider of its own here
  (both signed in on one computer still each keep their own place).
- The same pair made sync's "Not signed in on this computer" list
  workbuddy-ai-plugin (as a raw id) on the computer where WorkBuddy AI is
  signed in as workbuddy-ai, and the other way round (both screenshots).
  NotSignedIn counts a subscription signed in under its other id as
  signed in.

Run: TestSyncedOrderKeepsAPluginsPlaceNamedBoth goes through MirrorOrder
with the reporter's ids; on the old ordered() it fails ("listed:
[zhipu deepseek workbuddy-ai]"), and with the NotSignedIn change taken out
it fails ("not signed in here: [workbuddy-ai-plugin
commandcode-plan-plugin]"). go test -tags nogui ./internal/provider
./internal/davsync ./internal/backup ok under a sandbox HOME; gofmt -l
clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/provider
clean. Not tried across two real computers.
2026-10-14 04:35:55 +08:00
yetoneandggbdpq e297a8ab27 provider: a codex-autoreset.json that can't be read no longer lets a Codex account's auto-use spend a second reset the same week (#2017, ggbdpq)
What changed:
- autoResets.load read a codex-autoreset.json that didn't parse (a crash
  leaving it zeroed, as #1505's files were) as "none spent this week",
  so the next week-used-up look spent another reset, and the write after
  it took the unreadable bytes with it. Now a file that can't be read or
  parsed is unknown: the bytes are copied aside as .bad-<ts> (as
  noteResetUsed keeps codex-resets-used.json's), and what was spent is
  rebuilt from codex-resets-used.json, which records every reset used
  for a week used up. When that file can't be read either, no account
  spends one by itself for a week (the longest a lost spend could still
  count), kept past restarts under a "*" entry.
- autoResets.save writes through steady.WriteFile, as every write of
  magpie's own state does since #1505, and logs a failed write.

ggbdpq's patch kept the file aside and made the write durable, but still
read the unreadable file as none spent, so its own scenario (a crash,
then a restart) still spent a second reset. This takes their patch and
fixes the read at the cause.

Run:
- TestAutoResetUnreadableKeptAside (ggbdpq's) fails on main: "the
  unreadable file was written over with nothing kept aside".
- TestAutoResetUnreadableReadsResetsUsed and
  TestAutoResetNothingKnownSpendsNone fail on main and on ggbdpq's patch
  alone: "spent 1 resets, want 0" / "spent 1 resets with nothing known
  of the week". Cases: an auto-use an hour ago holds off; one 8 days
  ago, one by hand, or another account's doesn't.
- go test -tags nogui ./internal/provider under a temp HOME passes;
  -race -count=10 -run TestAutoReset passes; gofmt -l clean; go vet,
  GOOS=linux and GOOS=windows go vet -tags nogui ./internal/provider pass.
- Not tried: a real corrupted file from a user (none reported); a real
  Codex account (checked against the fake ChatGPT server only).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-13 23:30:32 +08:00
yetone 47ec2a969f provider: a Sub2API Claude account comes in by its email_address, with its account and organization (#1975)
KKKKKKKEM's Sub2API export of a Claude OAuth account was refused, "the
file doesn't say which Claude account this is": sub2apiEntry read only
credentials.email, and Sub2API keeps a Claude account's email under
Anthropic's own name, email_address. Its CreateAccountModal stores the
token Sub2API was given whole as credentials ({...tokenInfo}: access_token,
refresh_token, expires_at, scope, org_uuid, account_uuid, email_address)
and the uuids and email again in extra (useAccountOAuth's
buildExtraInfo); read in Wei-Shaw/sub2api's source.

The siblings in the same export now come in too:
- email_address in credentials or extra (and extra.email);
- scope, OAuth's space-separated string, as Claude Code's scopes instead
  of the four magpie assumes when a file says none (importScopes, shared
  with loginEntry's scopes);
- account_uuid and org_uuid as the oauthAccount's accountUuid and
  organizationUuid, so sameLogin tells two Team seats of one email apart
  as it does for a sign-in in magpie, and the session identity has its
  account id.
A ChatGPT Sub2API account already read email, id_token and
chatgpt_account_id, Sub2API's names for them (useOpenAIOAuth's
buildCredentials). The Google importer reads no Sub2API shape, and CC
Switch's import is of API-key providers, with no account email.
docs/subsystems/providers-accounts.md says which fields are read.

Run:
- TestImportSub2APIClaudeAccounts imports the reporter's file as filed
  (tokens put back) and a Sub2API-shaped export with two Team seats of one
  email. Old code: "got #1:failed,#2:failed,#3:failed … the file doesn't
  say which Claude account this is". With only the reporter's one-line
  fix (credentials email_address): "#3:failed", the seat whose email is
  only in extra. With org_uuid not kept: "sk-ant-ort01-a kept as
  team@example.com org \"\"". With scope not read: the seat kept the four
  default scopes.
- gofmt -l, go vet (darwin), GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on internal/provider: clean.
- go test -tags nogui ./internal/provider -count=1: ok (130s).

Not tried: a real Sub2API export or account; `magpie accounts import`
itself, which on macOS writes the active Claude sign-in to the Keychain.
It calls the same ImportLogins.
2026-10-13 18:16:03 +08:00
yetone af39ee4b5f gateway: a 402 for a usage limit rests the model out of quota, until the window renews (#1979)
Factory answers a Standard pool used up with 402 "You've reached your
weekly standard usage limit (resets in 0h 19min). Switch to Droid Core
...". failure() read every 402 as out of credit, so the whole account
rested a fixed 30 minutes: its Droid Core models (GLM-5.3, the
reporter's fallback) were skipped with it, the "resets in" was ignored,
and renewed() never lifted the rest when the window came back, since it
lifts only failQuota or By=="window" rests (Ziqi-Cui, 09:16Z).

- failure(): a 402 that matches usedUpWords and says nothing of money
  (creditWords, insufficient_quota) is failQuota. A payment 402, an
  empty one, Kiro's monthly count, Command Code's credits stay credit.
- With failQuota the pooled check applies: Factory's Standard windows
  are scoped away from Core (built-in factoryQuota matches; the
  plugin's notModels/models through quotaOfPlugin), so only the model
  rests, and only until its window's end.
- resetsAt also reads "resets in Xd Yh Zmin" (resetsAfter) when no
  windows are known, capped at longestWritten.
- FactoryAllowanceForTest / PluginAllowanceForTest let the gateway test
  build both paths' allowances from their real payloads.

Run: TestFactoryStandardOutLeavesCore (built-in and plugin:factory),
TestPaymentRequiredReadByItsWords, TestResetsInWords; full
internal/gateway (327s) and internal/provider ok; gofmt -l; go vet
darwin, windows, linux -tags nogui.
Broken by hand: the new failure() case removed -> both subtests red
(account rested for credit, GLM resting); resetsAfter returning 0 ->
TestResetsInWords red; quotaOfPlugin's notModels ignored -> plugin
subtest red.
Not tried: a live Factory account; Factory's Droid Core used-up
wording is assumed to read like Standard's.
2026-10-13 18:11:23 +08:00
yetone 12ecb6d8e9 gateway: a gateway key held to a budget, models or accounts is told none of this magpie's accounts, only its own limit and routes (#1981)
321sssrt-bit shared magpie on the LAN with a gateway key held to a budget,
and that key still read every account's quota and balance. A held key
(heldKey: a budget, models or accounts) is someone else's to use, so it
now gets 403 with code gateway_key_held (refuseHeld) on
/v1/magpie/quotas, quotas/history, quotas/cards, POST quotas/refresh and
/v1/magpie/concurrency. That holds from loopback as well as the LAN, the
same as usageSummary already did. /v1/magpie/route tells it only the
routes of its own requests. Route.callerKey is set by trace.beginFor at
all five begin sites, so a route begun without it fails closed. It still
reads its own limit at /v1/magpie/limit. Unrestricted keys and the local
owner are unchanged.

Client side (remote magpie): a 403 gateway_key_held drops the cards kept
from before and shows only the key's own card, instead of "isn't shared".
The cache is now keyed by provider and key (remoteCardsID), so a changed
key never shows what the old one was told, and keepRemoteCards keeps a
read only over one asked before it, so a slow pre-held answer can't bring
cards back.

Decided against letting an account-held key see its own accounts' cards:
that would still show the host's account email and balance to the key's
holder.

Run:
- New TestHeldKeyToldNoAccounts covers keys held by budget, models and
  accounts plus one held to nothing, from 127.0.0.1 and 192.168.1.9.
  Every route goes red with the refuseHeld calls or the route filter
  removed by hand.
- New TestRemoteMagpieHeldKeyShowsOnlyItsOwnCard goes red with the
  errKeyHeld mapping removed. TestRemoteMagpieCardsKeptByKey goes red with
  the cache keyed by p.ID alone.
- gofmt -l and go vet (darwin, linux -tags nogui, windows) are clean.
- go test -tags nogui ./internal/gateway ./internal/provider -count=1
  passes in a sandbox HOME.

Not tried: two real machines over the LAN; the tests drive the handler
with LAN remote addresses. An older client shows "isn't shared" (or its
cached cards until they expire) against an updated host until it updates
too.
2026-10-13 17:59:36 +08:00
yetone 4795f56469 provider, gui, cli: a Codex account's card says the last reset magpie used, when and why (foobra12 on Discord)
foobra12: "magpie会自动使用codex重置卡吗 我发现刚才好像不小心自动给我使用了
一张". Auto-use is off by default and spends only for accounts switched on
(the week used up with no other account to answer, or a reset ~30 min
before it expires), but a reset magpie spent was said only in the gateway's
log. A reset gone from the card read the same whether magpie used it, the
user did, or it ran out.

Each reset magpie spends is now kept in codex-resets-used.json (by account,
when, why: week / expiring / hand, windows started again; 90 days, 200 at
most, under a cross-process filelock, written with steady.WriteFile; a file
that doesn't parse is copied aside to .bad-<ts>, never read as empty). Only
a consume whose outcome is "reset" is kept. useCodexReset carries why:
AutoUseCodexReset passes week, SpendExpiringCodexResets expiring, and
UseCodexReset (Usage page, panel, CLI) hand.

loginReading, the choke point for LoginUsage and the Usage page, attaches
an account's last 5 uses to its reading (cached readings too, so a reading
kept from before a use still says it), and Quota/SubscriptionQuota carry
resetsUsed. The auto-use row on the Usage page's and the panel's card adds
a line "Last reset used: {when} · {why}" (zh 上次用卡:… · 自动,重置卡到期前),
every kept use in its title; an account in brief has it in its switch's
title. `magpie quota auto-reset <account>` lists them. en, zh, zh-TW, ja, de.

The default (off) and the expiry rule are unchanged: both are documented in
the switch's title and only reach accounts the user turned on.

Run:
- go test -tags nogui -count=10 -run TestResetUse ./internal/provider/
- break by hand: noteResetUsed call removed -> TestResetUsesKept red
  ("kept [], want [week hand expiring]"); loginReading attach removed ->
  red ("the card's reading has []")
- node --test codex-resets-used.test.cjs: chromium+webkit, 1100 and 420,
  en zh zh-TW ja de, the Usage page card, brief title, the panel card; 3
  runs green; with the say.append removed, 5/5 red
- codex-auto-reset, routing-auto-reset, quota-curve, click-scroll,
  tray-usages, i18n-keys, gui-ja, gui-de, gui-zh-tw: green.
  old-webkit is red on "Safari 15.0 styles" at app.css .prefs
  .val:has(> .side-effort), from dc2f0da82, the same on origin/main
  692a779d3; not this change's.
- gofmt -l, go vet (darwin, linux -tags nogui, windows), full tests of
  internal/provider, internal/cli, internal/gui, internal/gateway

Not tried: no real Codex account and no real reset spent (the ChatGPT
endpoints are faked); no notification when magpie spends one.
2026-10-13 17:32:39 +08:00
yetone 5b9530b567 agent: Claude Code's model notes name the Codex account magpie goes to first, not the one Codex is signed in to (#1957, parkavenue9639)
With the signed-in ChatGPT account paused for the others ("this
account off, the others on"), the gateway sends codex/<model> to the
first account still on, yet Claude Code's /model list still said
"<signed-in user> · via magpie". The note now names the account that
comes first in the gateway's order: provider.FirstLogin gives
inUseLogin without the allowance-room check (the note is written once,
not per request), so a kept "keep signed in to X" still names the
account at its place, and a paused own account is passed over.

Not changed: magpie still writes openai_base_url for Codex failover
when several accounts are on. That is the failover itself; the
"Only switch Codex's sign-in" tick (#1907, v0.1.1224) already keeps
magpie out of Codex's config for those who don't want it.

Run: TestViaMagpieNamesTheAccountFirstInOrder (new) fails with the
note reverted to a.User and passes with the fix;
TestCodexPausedOwnAccountPassedOver and TestKeptLoginStandsAtItsPlace
also check FirstLogin against the account the gateway served. Full
internal/agent tests, gateway/provider login tests, gofmt -l, go vet
for darwin/linux/windows (-tags nogui).
Not tried: a real Claude Code /model list with two real ChatGPT seats.
2026-10-13 17:02:05 +08:00
yetone 0c2dad1e12 provider: a Codex approval's auto-review is served by an account kept to some models, not refused as every account barred (#1959, parkavenue9639)
With Codex's own model calls going through magpie's account failover
(another ChatGPT account on), Codex's auto-review of an approval
(x-openai-subagent: guardian, model codex-auto-review) became
codex/codex-auto-review and went through perKey. An account with its own
list of models ("only serve these", #474) was struck from it, because
the list is picked from the provider's models and codex-auto-review is
hidden from those (#1460), so no list could hold it. With the signed-in
account paused, every approval got 403 "every account barred". Relayed
as it came (no failover) the same call was a 200.

AccountServes now lets a Codex account serve codex-auto-review whatever
its list says (codexOwnHidden), as freeOnChatGPT already passes it by the
usage windows. A gateway key's own model list (access.Key.Models) is not
changed: that is a restriction the user set on a key they hand out.

Test: TestCodexReviewPassesAnAccountsModelList reproduces the report:
me@ signed in and paused, spare@ on with a list of gpt-6.1-sol and
gpt-5.6-luna, a guardian call on codex-auto-review through Codex's
endpoint. It goes to acct-2 as codex-auto-review; a model the list leaves
out is still 403 and one it names still served. With the
codexOwnHidden check taken out it fails with the reporter's 403
("is set not to be served by any account or key of Codex").

Run: go test -tags nogui ./internal/provider ./internal/gateway (ok),
gofmt -l, go vet for darwin, linux (-tags nogui) and windows.
Not tried: a real ChatGPT account's approval through the failover.
2026-10-13 17:02:05 +08:00
yetone aef0327b61 gateway, provider: comments no longer say magpie spends Claude's usage resets (#1972)
AutoReset and ResetOutcome still named Claude's resets, which 9bf6d4352
took out on purpose (reading or spending one means magpie calling
Anthropic with the account's token). #1972 read them as a place left
for the feature. Comments only; no code changes.

Run: gofmt, go build -tags nogui ./internal/gateway ./internal/provider.
2026-10-13 17:01:26 +08:00
yetone 7d6358ff6b gateway: /v1/models can list each model by its bare id too, for apps moved from another proxy (love1sbug on X)
love1sbug moved from CLIProxyAPI: their clients ask for gpt-5.6-sol, and
magpie's /v1/models gave only codex/gpt-5.6-sol. "Provider in model names"
(36ca5432d, 6fa3109ea, 250bdd5c4) changes labels in agents' lists, never
ids, so no setting changed what the list returned. A bare request already
routed (serve: GroupFor, then Resolve); only the list didn't offer it.

What changed
- settings.BareModelIDs, off by default; Settings › Network and sharing ›
  "Model ids without the provider" (en, zh, zh-TW, ja, de), posted on its
  own to POST /api/settings/bare-ids (the general settings save keeps it).
  Drawn in gateway mode too, where such apps are.
- On, /v1/models (and ?format=text) lists every row it listed before,
  unchanged and first, then one row per bare model id
  (provider.BareEntries): the row of the entry that id reaches, its label
  that one's. GET /v1/models/{id} answers a bare id the same way.
- Which entry is decided by the gateway's own resolution (groupForIn, the
  GroupFor loop now shared; then resolveIn), so the list never offers what
  a request wouldn't reach: a model several providers serve is listed once
  and goes to its found group (found groups on) or the first provider in
  the Providers order (off), exactly as a bare request did before. An id
  already a catalog id isn't listed twice.
- The target must be in the shown list, so a gateway key held to some
  models sees only bare ids that reach them. Never listed for another
  magpie (DrawersHeader), whose remote provider would list each twice, nor
  in Claude Desktop's list.
- No agent file changes: magpie still writes provider/model ids, so the
  switch rewrites nothing and nobody who hasn't turned it on sees a change.
- docs/subsystems/gateway-routing.md: a section and verification lines.

What was run
- go test -tags nogui ./internal/gateway -run TestBareModelIDs: the
  reporter's case (a Codex provider with gpt-5.6-sol listed as
  gpt-5.6-sol, then asked for it on chat, responses and messages against a
  fake ChatGPT backend that saw gpt-5.6-sol; off, the list is byte-equal
  to before) and several providers with found groups on and off, a held
  key, another magpie. Both go red with the listing disabled by hand.
- go test -tags nogui ./internal/gui -run 'TestBareModelIDsSetting|TestSettingsSave'.
- node --test internal/gui/tests/bare-ids.test.cjs (playwright 1.62.0):
  Chromium and WebKit, 420px (gateway mode) and 900px, all five languages,
  20/20; i18n-keys.test.cjs passes.
- gofmt -l clean; go vet ./... (darwin), go vet -tags nogui ./... on
  darwin, GOOS=linux, GOOS=windows clean.
- go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui
  ./internal/settings ./internal/cli ./internal/agent -timeout 40m,
  rebased on origin/main 06ff45fed: all six ok (gateway 533s, agent 460s,
  the machine at load ~130; the default 10m ran out on wall time in an
  earlier run, the test then running 1s in, nothing failed). Before the
  rebase agent's TestFolderVarsAreListed was red on REASONIX_STATE_HOME,
  fixed upstream by 24146c031.
- After the rebase (a conflict with #1914's tiers for every client, kept;
  a bare row carries its source row's tiers): gofmt, vet on all three, and
  bare-ids, i18n-keys, plain-names, gateway-port .test.cjs, 31/31.
- Rebased again on 9b52fb504 (side efforts touched settings, api.go,
  app.js, i18n.js; a doc table conflict, upstream's rows kept): gofmt, go
  vet ./... and -tags nogui on linux and windows, go test ./internal/gui
  ./internal/settings, gateway -run 'TestBareModelIDs|TestModels|
  TestCodexTiers|TestSideEffort', and bare-ids, i18n-keys, side-effort
  .test.cjs 31/31.

Not tried: a real CLIProxyAPI client against a live gateway, or the
reporter's own setup; no CLI command for the switch (Settings only).
2026-10-13 16:55:27 +08:00
yetone 23611ca6a5 provider: a moved ZCode subscription takes plugin 0.1.17, which reads ZCode's sign-in from the folder its data was moved to
What changed: the zcode mover's min goes from 0.1.16 to 0.1.17, so
keepMovedCurrent updates every moved user's @magpie-community/opencode-zcode-auth.
41972b25f made the built-in follow ZCode 3.14's 数据存储路径 (dataBaseDir in the
home folder's .zcode/v2/setting.json); the plugin, which is what runs for a
moved ZCode subscription, still read ~/.zcode/v2/credentials.json and
runtime/provider only, so "ZCode app's sign-in" read the stale copy ZCode
left at home. plugins 65a7676 (0.1.17) reads dataBaseDir as ZCodeDataIn does
(trimmed, ignored when empty or not absolute) for credentials.json and the
zcode-builtin.json walk, and keeps reading setting.json from the home folder,
where ZCode keeps it (getSettingsFile; copyDataDirectory leaves it out).

ZCode's CLI session database (~/.zcode/cli/db/db.sqlite, internal/sessions)
does not move with dataBaseDir: the CLI (glm/zcode.cjs, 3.14.3) takes it
from storage.sessionDbPath, default "~/.zcode/cli/db/db.sqlite" expanded
with os.homedir(), and the host sets neither ZCODE_SESSION_DB_PATH nor
ZCODE_STORAGE_DIR; copyDataDirectory copies .zcode/v2 only. So the session
reader is unchanged.

What was run:
- npm view @magpie-community/opencode-zcode-auth@0.1.17: published (publish
  run 38370080577; that run is red only for zed-auth and zen-free-auth,
  E404 Trusted Publisher).
- Plugin: HOME=$(mktemp -d) bun test at the repo root, 1185 pass; its new
  moved.test.mjs fails with the old path.
- gofmt -l; go vet ./internal/provider (darwin), GOOS=linux and
  GOOS=windows go vet -tags nogui; go test -tags nogui ./internal/provider
  under a sandbox HOME: ok.
- Not run: a real ZCode with a moved folder, Windows.
2026-10-13 16:40:14 +08:00
Versun b2b015c584 provider: MLX-Serve's decision models classify routing groups through System One, separated from chat models by capabilities
MLX-Serve (github.com/ddalcu/mlx-serve) serves decision models (Clef,
Clef-Flash, Kev, Laya, D1) at POST /v1/systemone (and /v1/decisions). Its
/v1/models lists them alongside chat models, marking them with
capabilities: ["decisions"]. Setting a routing group classifier to an
mlx-serve decision model previously failed because the preset had no
decision endpoint and magpie offered it as a chat model, which MLX-Serve
rejected with 400.

- The mlx-serve preset has a decision base, http://localhost:11234/v1.
  An existing MLX-Serve provider saved without decide gets its chat base as
  one, at whatever port it was given (as oMLX does).
- mlxServeDecides joins listsDecisions. fetchDecide reads /v1/models and
  keeps models with the "decisions" capability under <id>.decisions, with
  the model's context window and input modalities.
- DecidesModel takes them out of the agents' chat lists and offers them as
  deciders. Jev() is the first of them. A server with no decision model
  lists none, and no Jev alias is made up for it.
- Provider test on a decision model asks System One rather than chat.

Run:
- TestMlxServeDecisionModels: fake MLX-Serve answers with real captured
  fields. Clef-Flash with capabilities: ["decisions"] is a decider, chat
  models reach agents, and RouteDecider plus AskSystemOne post to
  /v1/systemone. TestModels tests clef-flash-4bit via decide. Red without
  mlxServeDecides in listsDecisions.
- TestListedMLXServeDecideTable: real captured response, vision modalities,
  `models` field fallback with omitted input_modalities, chat-only server,
  empty list, and invalid JSON.
- TestMLXServeWithoutDecisionModels: no decision model means none, not Jev.
- Real MLX-Serve on localhost:11234 in sandbox HOME with isolated config:
  provider add mlx-serve, provider refresh, provider test mlx-serve
  clef-flash-4bit (543 ms, decide OK), group add with classifier.
- go test -tags nogui ./internal/provider/..., gofmt -l, GOOS=linux and
  GOOS=windows go vet, cross-OS builds.
2026-10-13 16:34:59 +08:00
wizzy-yang f9f1df2e1a provider, agent, gui: saving a routing group no longer waits on a Codex usage read, and the saved row comes back into view (#1093)
Saving a group ran agent.SyncCatalog, and Codex's Sync asked whether the
signed-in ChatGPT account is used up through LoginUsage, which reads the
vendor when its one-minute cache is stale and makes the caller wait
(922-1148ms in the reporter's 17 saves, 9-20ms on a cached read).
provider.CodexUsedUpKnown() answers from what was already read and never
asks; the sync uses it. KeepOnAnAccountWithRoom still reads it every
loginSwitchEvery and touches the catalog when the answer changes, so the
sync learns of it without asking itself.

The group editor stands in for the row, so on Save the page got shorter
and the browser clamped the view to the list's foot. routing.js now
brings the saved row back with readerScrolls + scrollIntoView, and only
when it is out of view, so a click hold isn't released for nothing.

Squashed from #1093 by wizzy-yang onto current main.
2026-10-13 16:34:23 +08:00
yetone c3dc7aefba provider, settings: an idle magpie no longer parses settings.json for every account of every model's price (xsw on Discord)
xsw reported v0.1.1222 sitting at ~15% CPU while idle, with no gateway
requests. Since 8c5b9f928 (#1535, v0.1.1176), provider.All asks
settings.AccountDiscoveryOff for each account provider, and that reads
settings.json through Load, which caches the bytes but runs json.Unmarshal
on every call. agent.magpieModels prices each model under one Hold, and
each price asks All. So one pricing pass parsed settings.json models ×
accounts times. That pass runs on the GUI's drift poll (every 15s) and on
KeepDshWired (every 30s), per agent.

Evidence: `sample` of the owner's live dev build (26% average over 11.5h,
6–10% while sampled) had its top stacks in settings.loadChecked →
encoding/json under provider.All ← EntryPriceIn ← magpieModels, reached
from the drift handler and keepDshWired. A sandbox serve with an empty
config sat at 0.0%. A throwaway bench (not committed) priced 300 models
with 2 accounts: 81ms and 639 parses before, 11.5ms and 40 parses after.

All now asks once per call, from the settings the held look has already
read (heldSettings), through the new settings.AccountDiscoveryOffIn.
settings.Parses counts parses for the test, and loadChecked's comment no
longer claims the file is "parsed once".

Test: TestAllReadsNoSettingsPerLookWhileHeld prices 200 looks under one
Hold with 2 signed-in accounts and fails at >= 200 parses. Putting back
the per-account call by hand: "settings.json parsed 840 times for 200
looks at 2 accounts". With the fix: ~40, all from the first provider
build. It also checks MAGPIE_NO_ACCOUNTS=1 still hides account providers.

Run: gofmt -l; go vet -tags nogui on darwin, GOOS=linux and GOOS=windows
for internal/settings, internal/provider, internal/agent; sandbox-HOME
go test -tags nogui of those three packages, before and after rebasing
on origin/main. Other short tickers were checked (plugin host stop,
sessions readSlot, gui glide, update/claude sign-in polls): all bounded,
none run while idle.

Not run: a reproduction on xsw's machine or OS (unknown yet), a Linux or
Windows runtime CPU check, the GUI suite (no assets touched). Accounts()
still parses settings ~40 times per provider build; that is once per held
second, left for later.
2026-10-13 16:34:15 +08:00
yetone a65f2131dd gateway: a provider's model can be marked a video or image model in its editor (#1399, shen-joe)
shen-joe's relay serves a video model (agnes-video-2.5-flash), but its
/models list doesn't say "kind": "video". magpie only took a base-URL
provider's video models from that field, and its image models from that
field or from the model's name. So the model could never be asked at
/videos. They asked to tag video models, either in Settings or when
adding the provider.

What changed:
- settings.ModelKinds holds "image" or "video" by "<provider>/<model>".
  RenamePerModel carries it along with the other Model* maps.
- provider/modelkind.go:
  - MarksKinds: only a provider with its own base URL can be marked. A
    subscription, another magpie and a decision API can't.
  - ModelKind, KindModels and SetModelKind. A model can be marked if the
    provider serves it, or if its fetched list has it (a video model is
    left out of the chat list).
  - SetModelPrefs takes a "kind" with the model's other prefs.
- gateway:
  - Drawers adds the models marked image and drops the ones marked video.
  - customVideomakers adds the models marked video and drops the ones
    marked image.
  - The 400 for a model that can't make videos now says where to mark it.
- GUI: the model chip's right-click menu gets "Makes: Auto/Image
  model/Video model…" (an app menu, not a native select). The pick is
  staged until Save, and a marked model shows a small image/video tag.
  Strings are in zh, zh-TW, ja and de.
- docs/subsystems/gateway-routing.md describes it.
- settings_keep_test sets ModelKinds, so a Settings-page save is checked
  to keep it (that guard test went red until it did).

Why per model, in the provider's editor: the kind belongs to one model
of one provider, like the per-model API pref already set there.
Settings → Image/Video only pick the default model. This also covers
their "tag it on the provider" alternative.

Not done: Agnes's own video API (polling at /agnesapi?video_id=, the
finished video in "url") isn't OpenAI's GET /videos/{id}. Marking the
model gets the request to its /videos, but the poll won't match until
there's a mode for it. I've asked the reporter for real responses.

Run:
- go test ./internal/provider ./internal/settings ./internal/gui
  ./internal/gateway: ok (gateway 1658s).
- TestCustomProviderVideoTheUserMarks, which goes red with the
  KindModels loop in video.go removed.
- GUI model-kind.test.cjs, 16/16 (en/zh/ja/de, 900/420, Chromium and
  WebKit). It goes red with the menu item removed.
- Sibling GUI tests: model-api-gemini, model-copy-id, model-api-preset,
  model-test-one/as/why, provider-detect-models, provider-typed,
  i18n-keys, gui-ja and gui-de.
- gofmt, plus linux and windows go vet -tags nogui.
- Not tried against Agnes's real API (no key).
2026-10-13 16:33:44 +08:00
yetone 9c922b9f77 provider: a subscription's place in the order holds on a computer where its plugin has the other id (#1940, Sun1090)
Sun1090 put two plugin subscriptions first on one computer; the other
computer, synced, kept them where they were. The order is synced (the
providers part of WebDAV sync carries providers.json's order) and no
sign-in reorders it. But a built-in subscription served by its plugin is
"workbuddy-plugin" where the built-in isn't moved onto it and
"workbuddy" where it is (PluginID), and whether it is moved lives in
migrations.json, which isn't synced. The order from one computer named
ids the other doesn't have, and ordered() put those providers last.

ordered() now ranks a provider whose own id the order doesn't name by
its counterpart (id <-> id-plugin), only for the built-in subscription
ids (accountIDs), so a custom provider ending in -plugin is only itself.
An id the order names itself still wins.

Run: TestOrderKeepsAPluginsPlaceByEitherID passes; with the lookup taken
out it fails ("not moved here: [zhipu deepseek workbuddy-plugin
workbuddy-ai-plugin]"). go test ./internal/provider ok; gofmt -l clean;
go vet and GOOS=linux / GOOS=windows go vet -tags nogui
./internal/provider ok. Not tried across two real computers; the
reporter's ids are asked on the issue.
2026-10-13 16:26:10 +08:00
yetone 41972b25fc zcode: magpie's provider reaches a ZCode whose data was moved to another folder in its settings (flower on Discord)
What changed: ZCode 3.14 has a 数据存储路径 (data storage path) setting.
Changing it copies ~/.zcode/v2 to <folder>/.zcode/v2, and from the next
start ZCode reads its providers (provider_config.json, config.json),
credentials.json and runtime/provider from there. The choice stays in the
home folder's .zcode/v2/setting.json as dataBaseDir, which ZCode's main
process reads first (readBootstrapDataBaseDirFromDisk, then setDataBaseDir;
getDataBaseDir is that, else ZCODE_DATA_BASE_DIR, else HOME). magpie always
wrote ~/.zcode/v2, so for such a user it said ZCode was connected while
ZCode's 模型设置 showed only BigModel and Start Plan and no magpie.
appdir.ZCodeDataIn reads dataBaseDir the way ZCode does (trimmed, ignored
when empty or relative); the ZCode agent target, the ZCode subscription's
credentials.json and its zcode-builtin.json glob use it. Skills, AGENTS.md
and the CLI's cli/config.json stay under the home folder: ZCode reads
those from HOME/USERPROFILE (getUserZcodeSkillRoot, the MCP config path),
so internal/library is unchanged. ZCode's session database
(internal/sessions) is not changed here: where ZCode's CLI keeps it under a
moved folder was not checked.

Read from ZCode 3.14.3's app.asar (copied to the scratchpad):
out/main/index.js (bootstrap, setDataBaseDir, buildHostProcessEnv passing
ZCODE_DATA_BASE_DIR), out/host/chunk-*.js (getAppConfigDir =
<base>/.zcode/v2) and out/host/index.js (provider_config.json under it).
flower hasn't said they moved the folder; this is the one way found in
ZCode's code for "magpie says connected, ZCode has no magpie" with a
provider_config.json magpie wrote. That file, and the one this build
writes, decode with ZCode's own decodeProviderConfigFile (run from a copy
of glm/zcode.cjs): providers ["magpie"].

What was run:
- TestZCodeMovedDataFolder (new): with dataBaseDir set, Set("magpie")
  writes both files under the moved folder and none in ~/.zcode/v2; an
  empty, blank or relative dataBaseDir keeps ~/.zcode. On the old
  zcode.go it fails: "no magpie in the moved folder's
  provider_config.json".
- Sandbox, built binary: HOME=<sandbox>, setting.json dataBaseDir=<sandbox>/D,
  `magpie zcode magpie` wrote D/.zcode/v2/{config,provider_config}.json
  and nothing under the home folder's .zcode/v2 but setting.json.
- go test -tags nogui ./internal/agent ./internal/appdir ./internal/provider
  under a temp HOME; gofmt -l; GOOS=linux and GOOS=windows go vet -tags
  nogui on the three packages.
- Not run: the ZCode app itself with a moved folder (not launched against
  any config), and Windows.
2026-10-13 16:21:56 +08:00
yetone 15105161e0 provider: the Claude account Claude Code is signed in to is told by its sign-in, so its /usage goes through its own proxy (#1938, kensenzhao)
kensenzhao: two Claude accounts, each with its own proxy (accountProxies,
#1807). With B signed in, `magpie quota` read B's usage through A's
proxy, while a saved account's read went through its own.

The cause: magpie named the account Claude Code is signed in to from
~/.claude.json's profile. After a switch, a Claude Code started on the
account before writes that account's profile, so the sign-in was B's
while the profile still named A. liveLogin and claudeAccount then called
A the signed-in account. Logins flagged A as active, /usage ran with
ViaLogin(A), which is A's proxy, using B's credentials, and B's
reading was shown on A's card. claudeSignInOfAnother already kept this
crossing out of the saved records (netfishx), but not out of the live
name.

Now liveLogin and claudeAccount correct the profile's name by the
sign-in (claudeSignInOwner). When the profile's account doesn't hold
Claude Code's credential and exactly one other saved account does, that
one is the account signed in. claudeSignInOfAnother and the new owner
share claudeHolders. Everything that names the live account follows:
Active, /usage and its card, settings.json's proxy env, warm-up, model
test and the bridge.

Audit of the other usage readers: every per-account read goes through
loginQuota's ViaLogin(l.User), and the saved Claude read through
ViaLogin at the run. Codex names its live account from auth.json's own
tokens, so it can't cross this way. Grok's reading and Kiro's API-key
reading still use the provider's proxy (noted in 3dc8f00f0), and a
Claude Code in WSL is handed no *_PROXY. Both are left as they are.

Run: TestClaudeUsageGoesThroughTheSignedInAccountsProxy (new) fails
with the correction reverted by hand: pro is active, /usage runs
through 127.0.0.1:7897, and the reading is on pro's card. It passes with
the correction. It clears the kept readings before and after: without that,
TestRefreshSavedClaudeUsage, which runs after it, found max's reading left
over. Both pass together at -count=3. On the rebased head (on d9a050cc1):
go test -tags nogui ./internal/provider, ./internal/gateway (1178s, under
other sessions' load; an earlier run at -timeout 20m ran out mid-suite,
with nothing hung) and ./internal/cli pass. gofmt -l is clean, and GOOS=linux
and GOOS=windows go vet -tags nogui ./internal/provider pass. Rebased again
onto dbcf791e4: ./internal/provider in full, the gateway's
Claude|AccountProxy|KeyProxy tests, gofmt and both vets pass. Before the fix, the reporter's case was reproduced
with the same test, and real Claude Code 2.1.296 was checked to take the
proxy from its env and not from settings.json under --setting-sources "".
Not tried with real accounts behind real proxies.
2026-10-13 16:11:42 +08:00
Ha1baraA11 a75fa9e54a gateway, provider: OpenRouter's image-only models draw on its /images API, not chat (#1116, fixes #1105)
OpenRouter answers a chat request for gpt-image-*, seedream, flux,
qwen-image, grok-imagine and the like with 404 "Use the /api/v1/images
endpoint instead", and viaFor sent every OpenRouter model to chat. Models
catalog.ImagesAPI names now go to OpenRouter's POST /images, with reference
images as input_references (image_url parts) and its media_type and
prompt/completion token usage read back; a 404 there is returned as is
rather than retried on chat. Gemini and gpt-5-image stay on chat. The
provider Test probe asks the same endpoint.

Run: go test -tags nogui ./internal/gateway/ ./internal/provider/
./internal/catalog/, go vet (darwin, linux nogui, windows), gofmt. With
the /images dispatch removed, both new gateway tests go red. The real case
(owner's OpenRouter key, sandbox HOME, a throwaway test not committed):
openai/gpt-image-1-mini at quality low drew one image, 200, usage 12/272,
and with that image as a reference drew again, 200, usage 1035/272. The
request shape matches OpenRouter's openapi.json ImageGenerationRequest.
2026-10-13 16:00:31 +08:00
forever dbcf791e4e providers: the Providers page keeps asking while an account's list is on its way, as a fetch started behind it is counted before it returns (#1147)
* providers: the Providers page keeps asking while an account's list is on its way, as a fetch started behind it is counted before it returns

FetchNewBehind and FetchNewSoon started FetchNew in a goroutine, and
newRunning, which FetchingNew reads, was counted only once it ran:
providersState read FetchingNew straight after, was told no fetch was on
its way, and the page stopped asking with the list still to come.

fetchNewGo counts a fetch before it returns, but only one with work: a
poll with nothing due starts and counts nothing, or each poll found the
last one's no-op still under way and the page asked for ever (#1092 at
GOMAXPROCS=1). Which accounts are due is known at once unless a CLI is
left to ask who is signed in (never answered, being asked or about to be
asked by the next look): then the fetch is counted and lists, waits on
the CLI (#1789) and fetches behind the page, which doesn't wait on a CLI
(#541). FetchNewSoon lists nothing before it returns, so /api/state?last=1
still answers at once (#1519). FetchingNew also says true while
fetchingNew is set, for a page whose FetchNewBehind found another still
picking the accounts due (tsuixl).

FetchNew keeps main's missing: an account that failed, one waiting out
newFetchRetry unless another's fetch listed it meanwhile, or a CLI that
didn't answer in time. The accounts are listed again when a CLI answered
while they were listed.

* providers: a CLI that answers while the accounts are listed has its account's list fetched in that pass, and one forgotten then sends the fetch behind the page

fetchNewHeld counts the CLIs answered before it lists the accounts and
lists them again if one answered by the time awaitIdentities returns,
in place of listForNew; TestFetchNewListsAgainForAnAnswerWhileListing
fails without it (and on main). fetchNewGo, which lists only with no CLI
left to ask, sends the fetch behind the page when one was forgotten
meanwhile (a sign-in finishing); TestFetchingNewForgottenWhileListed
fails without it. FetchNewSoon no longer counts itself before FetchNew
does: fetchingNew covers that. The CLI cases of
TestFetchingNewOnceStarted wait on a 5s look and allow 1s (yetone).
2026-10-13 15:58:31 +08:00
yetone b8e23db45a backup, davsync: an import or a sync installs the plugins and names the subscriptions to sign in to (yapechan)
yapechan on Discord (Windows, Synology WebDAV): after an import or a WebDAV
sync no providers showed on the other computer; adding the same provider by
hand made the synced settings and usage apply. No error, a restart didn't
help.

Cause. A backup and a sync carry providers.json as stored. For a
subscription that is its model picks and settings alone (no endpoint, no
key), and sign-ins are never carried by design; allProviders lists such an
entry only once an account is signed in here. plugins.json was not carried
at all, so a provider served by a plugin (every moved subscription, any
plugin provider) had nothing to come from on the other side. The import
said "N added" and "Needs a key: , " (the picks entries have no name and no
key), and the sync said nothing. API-key providers do come over: tried with
a nogui build in two sandbox HOMEs (DeepSeek, a custom relay, Kimi Code all
listed after `magpie restore`). No Windows-only path issue found.

What changed:
- provider.Carried(keys): the plugins added from npm or git, on/off and
  their options (without keys, options whose names look like a key are left
  out, as secret headers are). Folder plugins and plugin-auth.json stay.
- backup.Bundle.Plugins (nil from an older magpie). Restore installs the
  ones not here through provider.AddPlugins (plugin.Add, then Off and
  Options, then HandOver once); it never removes or changes one already
  here. A failed install is reported, not a failed restore.
- Result.SignIn / provider.NotSignedIn: the subscriptions brought with no
  account here. NeedKey no longer lists picks-only entries (provider.OnlyPicks).
- davsync: the providers part's hash covers the plugins (unchanged for a
  setup without any), take/bring carry them, bring installs (logged on
  failure), and Status().SignIn names what to sign in to.
- CLI restore and `magpie webdav`/`s3` status print both; the GUI's import
  result and the sync row show them (en, zh, zh-TW, ja, de).
- docs/reference.md says what a backup carries now.

Run:
- go test -tags nogui ./internal/provider ./internal/backup ./internal/davsync
  ./internal/cli ./internal/gui in a sandbox HOME.
- New tests fail with the change broken by hand: TestPluginsCarried
  (installed-skip and the HandOver guard), TestNotSignedIn,
  TestRestorePluginsAndSignIn ("Needs a key: [ Acme]" without OnlyPicks),
  TestSyncPluginsAndSignIn (bring not installing, Status not naming),
  sync-sign-in.test.cjs (the lines removed).
- sync-sign-in.test.cjs: Chromium and WebKit, en/zh/ja/de, 900 and 440px,
  16/16; it also caught subNames throwing while providers was still null.
  sync-*.test.cjs, s3-sync, i18n-keys, gui-ja, gui-de pass.
- gofmt -l, go vet, GOOS=linux and GOOS=windows go vet -tags nogui on the
  touched packages.
Not tried: a real plugin install from a real sync (the installs are stubbed
in tests); a real Synology server.
2026-10-13 15:52:17 +08:00
yetone 2810a7154d provider: a moved Cursor gets plugin 0.2.11, whose collected usage of earlier steps no longer inflates the step's prompt (#1053, plugins #101)
The Cursor plugin collects a tool step's late usage event with the
conversation's next step. Before 0.2.11 it added it to that step's
prompt_tokens, so pi read its context as 366,940 tokens on a 300k window
with 185,670 in use, and compacted early (geoqiao, #1053). 0.2.11 sends
the collected part as usage.magpie_deferred, which the gateway bills
with the step but never tells as its prompt (3a9d73c5c). The cursor
mover's min goes to 0.2.11 so keepMovedCurrent updates every moved user.

Run: npm view @magpie-community/opencode-cursor-auth@0.2.11 version on
registry.npmjs.org gives 0.2.11 (published by the plugins repo's
publish.yml from merge 4aae1ce7b). go test -tags nogui ./internal/provider
(whole package, sandbox HOME, TestMovedBuiltinsSayTheirPlugin among
them); gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
Not run: the update on a real moved Cursor account.
2026-10-13 15:01:32 +08:00
yetone ab1006bb80 gui: each WorkBuddy, Trae CN, MiniMax, Qoder or plugin account's daily check-in can be turned off on its own (#1902, magicLaLa)
settings.CheckinOff lists the accounts left out, by their entry in the
vendor's check-in file ("workbuddy|<uid>", "trae-cn|<uid>", a plugin's
"<provider>|<account>"). checkinNow skips them, both in the loop and on
Check in now. provider.CheckinAccounts() lists every account a check-in
reaches; /api/settings carries it as checkinAccounts, and
POST /api/settings/checkin-account {key,on} turns one off or on. A full
/api/settings save keeps the list. Settings shows an Off/On switch per
account under each vendor's Daily check-in row when it has 2 or more
accounts; the Usage card says "Auto check-in is off for this account" and
offers no Check in now for it. en, zh, zh-TW, ja, de.

Run (on 63a361b5f's tree, then targeted again on 7565d93c8):
- go test -tags nogui ./internal/provider -run 'TestCheckinAccount|TestWorkBuddyCheckin|TestTraeCheckin|TestPluginCheckin|TestQoderCheckin|TestMiniMax.*Checkin' : ok
- go test ./internal/gui -run 'TestCheckinAccountSetting|TestSettingsSaveKeeps' : ok
- broken by hand: skipping off accounts (false && off[a.key]), listing On,
  the card flag, the /api/settings carry and the dedup each turned the
  new tests red
- GUI (playwright, Chromium + WebKit, 1100 and 420, en/zh/zh-TW/ja/de):
  checkin-account 40/40, plugin-checkin, usage-checkin, i18n-keys,
  warm-at-own, warm-at-times all pass; app.js broken by hand made
  checkin-account fail 20/20 in Chromium
Then on 8e6354714 (fresh origin/main):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows for
  provider, gui and settings ok
- go test -tags nogui ./internal/provider ok (260s); ./internal/settings ok
- GUI checkin-account, plugin-checkin, usage-checkin, i18n-keys 91/91
- go test ./internal/gui: everything passed except two timing tests, both
  at load average ~180 from other sessions:
  - TestMainWindowCorners was killed at its 40s deadline. Filed as #1936.
    It passes alone on origin/main 81f587d7b and on this change (13s).
  - TestSetAnswersWhileDevinAndProvidersHang hit 14s against its 10s bound
    (#1375). Alone it passes (1.1s).
  Neither test goes near check-in or settings.CheckinOff. The whole of
  ./internal/gui passed (506s) on the tree before the rebase.
2026-10-13 14:40:11 +08:00
yetone d6fd9b3a36 provider, agent, gui, cli: Codex can switch only its own sign-in between accounts, never through the gateway (#1907, foobra)
foobra wants Codex Desktop and the CLI kept on their own ChatGPT
subscription, moved to the next saved account when the signed-in one is
used up and back when it resets, without magpie's gateway in the way.
magpie already did the switch (codex_switch.go: 98%, 100% In order, back
under 90%, unknown usage never switches), but with more than one Codex
account on it also wrote openai_base_url into config.toml so a refused
request fails over through the gateway (codexFailover). There was no way
to have the first without the second.

Now Codex's subscription has SwitchOnly (providers.json "switchOnly",
opt-in, off by default so nothing changes for anyone who doesn't tick it):
- provider.SetSwitchOnly / provider.SwitchOnly; only Codex's own
  subscription takes it. An unreadable providers.json reads as on, so
  magpie's own failover is never written on a guess.
- agent.codexFailover is false when it is on: no openai_base_url, no
  failover note, no magpie models in Codex's list. A base URL the user
  wrote stays.
- The account Save copy keeps it.
- GUI: "Only switch Codex's sign-in" tick under Providers > Codex's
  accounts (with more than one on), posting provider/switchonly; the
  Agents row's failover title points at it. zh, zh-TW, ja, de.
- CLI: magpie accounts switch-only codex [on|off].
- docs/reference.md and providers-accounts.md say what it does and that
  an open Codex app or app-server stays on its account until reopened.

Run (darwin, sandbox HOME, -tags nogui):
- go test ./internal/provider -run 'TestCodexSwitchOnly|TestCodexSwitchedWhenUsedUp|KeepLogin'
- go test ./internal/agent -run 'TestCodexSwitchOnly|TestCodexFailover|TestCodexOwnModelThroughMagpie|TestCodexHandWritten'
- Broken by hand, each red: codexFailover guard removed (agent test),
  SwitchOnly dropped from the Save copy, SwitchOnly reading false on an
  unreadable file (provider test), the tick drawn unticked (GUI, 16/16).
- GUI: switch-only (new), keep-login, agent-failover, gui-ja, gui-de,
  gui-zh-tw in Chromium and WebKit, en/zh/ja/de at 1100 and 420: 77 pass.
- The built binary's `accounts switch-only` in an empty sandbox HOME:
  reads off, refuses on with no Codex provider, refuses claude.
- gofmt -l clean; darwin go vet.

Reviewed and rerun after rebasing onto eba718736 (darwin, sandbox HOME).
The rebase met #1899's withPicks; SwitchOnly is copied there now.
- gofmt -l clean; go vet -tags nogui on darwin, GOOS=linux and
  GOOS=windows for internal/provider, agent, cli, gui.
- go test -tags nogui -timeout 40m ./internal/provider ./internal/agent
  ./internal/cli ./internal/gui: all ok. (On the base before, provider's
  TestCopilotSecretToolUsername timed out once under load: #1627,
  untouched code, 3 of 3 alone.)
- Broken by hand, each red: the codexFailover guard removed
  (TestCodexSwitchOnlyKeepsCodexOffTheGateway), SwitchOnly dropped from
  the Save copy, from withPicks, and an unreadable providers.json
  reading off (TestCodexSwitchOnlyStillSwitchesTheSignIn).
- GUI: switch-only, keep-login, agent-failover, gui-ja, gui-de, gui-zh-tw
  in Chromium and WebKit at 1100 and 420: 77 of 77 pass.

Rebased again onto 81f587d7b (clean; it touches provider, cli, gui but
not agent): vet on all three OSes again, go test -timeout 40m
./internal/provider ./internal/cli ./internal/gui all ok, -run TestCodex
./internal/agent ok, and the 77 GUI cases above pass again.

Rebased once more onto d45b20757 (clean; no lines of this change touched):
vet on all three OSes, -run 'TestCodex|KeepLogin|SwitchOnly'
./internal/provider ./internal/agent ok, switch-only and agent-failover
in Chromium and WebKit pass.

Not run: not tried with real ChatGPT accounts or the Codex app.
2026-10-13 14:35:08 +08:00
yetone b68377dae7 provider: Antigravity's retired 2.5 Flash models are named for themselves, not "Gemini 3.5 Flash Lite" (#1918, kchen0x)
What changed: Antigravity's fetchAvailableModels gives gemini-2.5-flash,
gemini-2.5-flash-lite and gemini-2.5-flash-thinking the displayName
"Gemini 3.5 Flash Lite" and the tagDescription gemini-3.5-flash-lite
(checked on the owner's account, 2026-10-13). magpie showed three
buttons of that name and the same name in /v1/models and the quota
windows. When several models share a name, one whose tagDescription
names another family is now named from the catalog, or by its id. A
model tagged with its own family (the effort levels of one model) keeps
the shared name.

Run: go test ./internal/provider/ (ok). TestAntigravityRetiredModelNamedForItself
is built from the reporter's JSON plus two effort levels of one model;
with the renaming removed it fails (both 2.5 models "Gemini 3.5 Flash
Lite", two models read the same). gofmt -l clean; go vet -tags nogui on
darwin, linux and windows.
2026-10-13 14:14:59 +08:00
yetone 8e6354714f provider: OpenCode Zen's free models answer again, with a session id OpenCode itself could have made (c9cu on Discord)
c9cu (v0.1.1222, Pi, a group routed to OpenCode Zen's
muse-spark-1.3-contributor-free on /v1/responses) got 403 FreeTierError
"OpenCode's free tier can only be used from within OpenCode" on a setup
that worked the day before. Zen now reads x-opencode-session as
OpenCode's identifier.ts lays an id out (12 hex of ~(Date.now()*0x1000 +
counter), then 14 base62) and refuses one whose counter isn't small.
magpie's built-in sent a sha256 of the conversation cut to that shape,
so its counter was anything. The zen-free plugin hit the same (#100 on
magpie-community/plugins, 0.1.5); the built-in had the same code.

Header diff against the real upstream, same request with curl:
- magpie's ses_e9283da055b15JwOAra76bwUx4 (hash): 403 on /v1/responses
  and /v1/chat/completions.
- ses_ecc5d8f28ffe9Cy14V8Em7lI2u from a real OpenCode 1.19.0 run, the
  old opencode/1.18.34 UA unchanged: 200 on /v1/responses. So it is the
  session, not the UA or the endpoint; muse-spark is still served on
  Responses (Chat answers 400 ModelProtocolUnsupported, as before).

Now (opencode_client.go):
- openCodeSession makes a real descending id from the current time and
  a per-millisecond counter, kept per conversation (the last 1000) so a
  conversation's turns share one session; one OpenCode could have made
  is passed on unchanged, a hash-shaped one is not.
- x-opencode-request is an ascending msg_ id the same way.
- the session also goes in x-opencode-session-id, x-session-affinity
  and X-Session-Id, as OpenCode's packages/core/src/session/
  model-request.ts sends it, and the User-Agent is OpenCode 1.19.0's
  (opencode/1.19.0 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14,
  the latest on npm, as the plugin captured it).
- Kilo's task/session id goes through the same openCodeSession (the
  Kilo CLI is OpenCode's fork and makes ids the same way).

Run:
- Through an in-process gateway under a sandbox HOME against the real
  opencode.ai/zen with the public key: muse-spark-1.3-contributor-free
  on /v1/responses with reasoning xhigh, streamed and not, big-pickle
  streamed on Chat, mimo-v2.6-flash-free on Chat: all 200 "pong". The
  same file on origin/main's code: all 403 FreeTierError, the
  reporter's message word for word.
- TestOpenCodeSessionIsOpenCodes, TestOpenCodeSessionsKeptBounded and
  TestOpenCodeClientHeaders (now with a real 1.19.0 session) fail with
  the hash put back by hand.
- gofmt -l, go vet (darwin, GOOS=linux, GOOS=windows -tags nogui) on
  internal/provider and internal/gateway.
- go test -tags nogui -count=1 ./... under a temp HOME on base
  eba718736 (load average ~170): every package ok but provider
  (TestPluginModelsSayExpired, TempDir cleanup race, added to #1543),
  gateway and agent (10m timeout in TestNotAnAPIReplyFailsOver and
  TestOmpLevelSuffix). Rerun with -timeout 40m: provider, gateway and
  agent ok.
- Rebased onto 488569227 (kilo.go's model paging, no overlap) and not
  rebuilt there: the disk was under 10G free.

- Kilo Gateway, anonymous, nvidia/nemotron-3.5-lightning:free through
  the same in-process gateway: 200 twice.
2026-10-13 14:03:58 +08:00
yetone 488569227e zhipu: a GLM Coding Plan key at the pay-as-you-go endpoint is asked again at the plan's, and the provider moves there
@cleverpigo on X: "glm coding plan放在codex/chatgpt里显示余额不足没法用". The editor
showed OpenAI https://open.bigmodel.cn/... red with 429 · 余额不足或无可用资源包,
请充值。 next to a green Anthropic https://open.bigmodel.cn/api/anthropic.

Root cause: the zhipu and zai presets start on their first region, Pay as
you go, whose OpenAI URL is /api/paas/v4. The Anthropic URL is the same in
both regions, and it bills the Coding Plan when the account has one. So a
Coding Plan key left at the default works in Claude Code, while Codex goes
to /api/paas/v4 and Zhipu answers 429 code 1113 (no balance). A provider
made by pasting the paas/v4 URL hits the same wall. Nothing in the key
says which kind it is. LESSONS.md's e63fbb0e entry records that last
time only the label was changed; this commit fixes the request itself.

Fix (internal/provider/zhipu_coding.go, following RetryOneAuth):
- A 429 1113 from {open.bigmodel.cn,api.z.ai}/api/paas/v4/... is sent
  once more to /api/coding/paas/v4/.... This happens both in the gateway
  (forwardOnce, Chat) and in the editor's endpoint test (probe).
- If the coding endpoint serves it, LearnZhipuCoding moves the saved
  provider to the plan's OpenAI URL, plus the preset's /api/v1 Responses
  URL if none is set. It only does this when the provider has that one
  key and is still at the paas URL. A provider with more keys, or one
  the user has changed since, is left alone.
- If the coding endpoint refuses too, the 1113 body keeps its code, so
  the error is still classed as out of credit. Its message also names
  both URLs and says what to change: set Plan to Coding Plan (with its
  URL), or top up the pay-as-you-go balance.
- A pay-as-you-go key that has a balance never gets a 1113. It stays on
  /api/paas/v4 and is never sent to the plan's endpoint.

Tests:
- TestGLMCodingPlanKeyAtPayAsYouGo (gateway; zhipu and zai) covers:
  - the Codex /v1/responses path
  - the move
  - a second request going straight to coding
  - a payg key staying put
  - the broke key's message
- TestZhipuCodingPlanKeyTested and TestZhipuCodingBase (provider) cover:
  - a draft
  - a saved preset
  - a pasted custom provider (only Chat moves)
  - a provider with several keys (not moved)
  - payg
  - broke
  - a key the user has changed
- With the two hooks reverted, both new behaviour tests fail.

Run (sandbox HOME, pinned Go caches):
- gofmt -l: clean
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...:
  clean
- GOOS=linux go build -tags nogui and GOOS=windows go build: OK
- go test -tags nogui ./internal/provider/: ok (363s)
- go test -tags nogui -timeout 40m ./internal/gateway/: ok (1922s, on a
  machine at load ~200)

Not tried: a real Zhipu or Z.ai key. None was available, so the 1113
body and the coding endpoint's answer come from the report and the
presets, not a live call.
2026-10-13 13:59:17 +08:00
yetone 26465bc017 provider, gui: oMLX's decision API moves with its Server address (#1165, #1641)
Since #1641 main fills an oMLX provider's empty Decide with its Chat URL
in Normalize, so a provider saved before #1165 has a localhost Decide.
#1165 moved Chat, Responses and Anthropic to the new Server address but
left Decide behind: System One's decisions kept going to the old
localhost port after the address changed. atAddress now moves Decide too,
in the provider package (local_address.go) and in the editor
(addressFrom/movedURLs in app.js), and the decide-url field follows the
address while the user hasn't typed their own; a Decide the user typed
is kept.

Tests: provider TestProviderAtAddress asserts Decide moves; gui
TestProviderSaveLocalPresetAtItsURLs expects oMLX's Decide moved and the
others empty; local-address.test.cjs checks the saved decide, that the
decide field moves, and that a typed https://jev.example/v1 survives a
second address change.

Run at this commit's tree on origin/main: gofmt; go vet darwin,
GOOS=linux -tags nogui, GOOS=windows; builds for all three;
go test -tags nogui -p 4 ./... green. GUI: local-address 11/11 in
chromium and in webkit; local-address, azure-endpoint, gui-zh-tw,
gui-ja, gui-de and system-one together 43/43.
Broken by hand: without Decide in local_address.go the provider test
goes red; without decide in addressFrom local-address goes 0/11.
Not tried: a real oMLX server.
2026-10-13 13:47:59 +08:00