Commit Graph
200 Commits
Author SHA1 Message Date
yetone eb3f174289 agent: Claude Code's auto mode classifier model is set on its Agents row (Linka on Discord)
Claude Code 2.1.302 reads CLAUDE_CODE_AUTO_MODE_MODEL for the model its
client-side auto mode classifier checks each action with. It doesn't
change server-side auto mode, and a classifier model Anthropic sets for
the account comes first. The installed 2.1.303 binary has the variable:
unset, Claude Code picks the sonnet tier's model, else Sonnet. It refuses
claude-sonnet-5-5, claude-opus-5-5 and claude-opus-5 with a warning and
uses its own pick instead.

- Claude Code gets an "auto mode" field (key auto_mode, Quiet, follows
  nothing). It can be set only while Claude Code is routed through
  magpie, only to one of magpie's models, and is written dashed like the
  other model keys. Its options leave out the three models Claude Code
  refuses, and Set refuses them too.
- A value the user had before magpie routed Claude Code is stashed with
  their tiers (claudeOwnEnv). It is taken out while wired in and comes
  back on Disconnect or Claude Code's own model, unless they have set one
  again since. The restore loop now skips any claudeOwnEnv key the user
  wrote again.
- magpie's own value goes when magpie steps out. A value the user sets
  while wired in is never touched.
- GUI: an "Auto mode" line in the opened row's Tiers, after Subagents,
  using the app's model picker. Default is noted as Claude Code's own
  pick. Strings are translated for zh, zh-TW, ja and de.
- Docs: agent-wiring.md and reference.md.

Run, in a worktree at origin/main 33dbdcc52, sandbox HOME, load ~110-135:
- gofmt -l: clean.
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean.
- set -o pipefail; go test -timeout 45m ./...: every package ok.
- Breaking by hand turned the new tests red: dropping the stash-time
  removal, the "set again since" check, the no-classifier refusal and the
  removal on step-out made TestClaudeAutoModeModel, TestClaudeAutoModeUserValue
  and TestClaudeDisconnect fail.
- GUI, playwright 1.62.0, Chromium and WebKit: 84 files the change reaches
  (agent*, claude*, tier/subagent effort, codex subagent/memories,
  gui-de, gui-ja, gui-zh-tw, i18n-keys, header-relang, and every file
  with a Claude row or the model picker), concurrency 4: 1305 of 1306
  pass.
  - The one red is agent-expand-steady "webkit 980px ... slides" ("slid
    open: 208"). Its fixture has no auto mode field. Alone it passed 3
    of 3. Filed as #2935.
- claude-auto-mode.test.cjs (new; en and zh, 1100px and 560px, both
  engines): 8 of 8 pass, and 4 of 4 fail in Chromium on the old app.js.
- Not tried against a real Claude Code session.
- After rebasing on origin/main ab7ec8c65 (three commits, none touching
  these files):
  - go vet ./internal/agent and TestClaudeAutoMode*/TestClaudeDisconnect:
    ok.
  - claude-auto-mode, tier-effort, i18n-keys and agent-layout, both
    engines: 23 of 23 pass serially, and 19 of 19 in parallel.
  - A first parallel try at load ~127 had 16 reds in claude-auto-mode
    and tier-effort, and its output wasn't kept. It didn't come back in
    the next three runs.
2026-10-19 18:12:45 +08:00
bbornandClaude Opus 5.5 ae7dc10ae2 docker: the image is Debian 12 slim, so the Cursor and Devin CLIs magpie installs at sign-in run in it (#2834, bborn2)
magpie installs a subscription's CLI at sign-in with its vendor's
`curl … | bash` (internal/provider/install.go: Cursor, Devin, Grok
Build). The distroless image had no curl and no /usr/bin/env (the
installers' shebang), so that install couldn't run there, and only
Grok Build had a native fallback. bborn2 reported that a Cursor CLI
installed by hand failed with "cannot execute: required file not
found". The image is now debian:12-slim with ca-certificates and
curl. It keeps the nonroot user at uid/gid 65532, HOME and XDG under
/config, the healthcheck, and magpie on PATH. Size: 157MB against
82MB for origin/main's image, both built here on arm64. Running a
feature magpie offers is worth the 75MB.

Changed in review: dropped the branch's GOPROXY build arg, a separate
goal. The comments in install.go and install_test.go that said the
image has no curl now say "had". docs/reference.md and the site's
Docker page (en, zh, ja) say Debian with bash and curl instead of
distroless with busybox.

Run, with OrbStack's docker:
- docker build of this tree and of d783df46c's Dockerfile: 157MB vs
  82MB.
- docker run of the new image: health "healthy", user nonroot (id
  65532). `curl https://cursor.com/install -fsS | bash` exit 0, then
  `~/.local/bin/cursor-agent --version` printed 2026.10.16-e3cb207.
  Devin's install.sh installed devin v3000.11.92 (its trailing
  `devin setup` said "Login canceled" with no terminal, as on any
  host). `devin --version` printed 3000.11.92. bash and `magpie
  version` run.
- Old image: `which curl` finds none, and /usr/bin/env doesn't exist.
- A volume written by the old image (file owned 65532) was read and
  written by the new image.
- gofmt -l clean; go vet darwin, linux (nogui) and windows clean.
- Full `go test -tags nogui -timeout 45m ./...`: every package ok
  except internal/agent and internal/gateway, which timed out at 45m
  mid-test (TestConnectSaysHow, TestLargeRequestEndpoints) under a
  load average of about 200 from parallel suites. This commit changes
  no code those packages build, only comments in internal/provider,
  which passed (992s), so they weren't rerun.
Not tried: a Grok Build install inside the image, and a full
in-magpie Cursor/Devin sign-in with a real account in the container.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 00:19:53 +08:00
yetone e44b9aef33 middleware: onProvider changes what one provider a request is tried on is sent
A JS gateway middleware can export onProvider(body, ctx). The gateway
calls it on each try, just before the body goes to that provider, with
ctx.provider = {id, name, account, model}: account is the subscription's
kind (claude, antigravity, …), absent for a key. Every try starts again
from the body onRequest left, so a change for one provider never reaches
another in a routing group. null and ctx.reject turn nothing away there.
A hook that throws or runs past 250ms leaves the try's body as it was.

A plugin could act only before routing until now, by the model name the
agent asked for. Claude Desktop asks for opaque aliases, so a plugin
couldn't tell which vendor a request was going to. The first user is
@magpie-community/middleware-antigravity-cloak: it changes only what an
Antigravity account is sent, so that Antigravity stops refusing Claude
Code's system prompt (xzplzpl on X). magpie itself still sends every
prompt as the agent wrote it.

- gwmw.To and gwmw.Tried; middleware.Run.Tried runs the hooks.
- serveAgent puts the runs on the request's context, and serve's
  candidate loop calls triedOn before the Antigravity foresight, so it
  judges the body that will be sent.
- Docs: gateway-middleware.md, reference.md, integrating.md, and the
  hooks table and community list in site docs plugins.html (en, zh, ja).

Run:
- go test ./... -timeout 45m in a sandbox HOME (macOS, at de671719a):
  every package ok but two. internal/middleware's TestPointsLoadErrors
  pinned the old list of exports; it now says onProvider too, and the
  package is green. internal/gateway's
  TestTranslatedStreamKeepsClientAlive/chat_to_responses went red under
  the full run's load (#2737, numbers added there); -count=10 alone is
  10/10 green, and with no middleware triedOn returns the body as is.
- TestMiddlewareOnProviderPerTry (gateway): a group a/m1 (500) then b/m1;
  a got "asked for a/A/m1/key", b got "asked". With the triedOn call
  replaced by `_ = triedOn` it is red (sent a:"asked" b:"asked").
- TestOnProvider (middleware): per-try bodies, throw and null fail open
  and are counted, a reject is a no-op, a nil Run passes through.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  on the changed packages.
- node --test internal/gui/tests/plugin-middleware.test.cjs: 24 pass.
- Real use: a sandbox magpie built from this tree, a real Antigravity
  account, the plugin installed from its folder. Real Claude Code 2.1.302
  (`claude -p` with a sandbox CLAUDE_CONFIG_DIR, model
  antigravity/gemini-3-flash) got its answer. With the plugin's
  {"off": true} the same run got the 400 "Resource has been exhausted".
  Direct /v1/messages with the billing line, the Agent SDK line, and
  Claude Code's three blocks: 200 each with the plugin on, 400 each with
  it off.
2026-10-18 00:50:14 +08:00
yetone 89521b03d6 cli, gateway: magpie cpu records the running magpie's CPU profile for 30s, for a report of high CPU (@LeiCheng42 on X)
@LeiCheng42 on X reports magpie using the most CPU while Codex runs. As
with magpie heap (e085d6e92), Activity Monitor and `sample` show Go's
frames as ???, so `magpie cpu [<file>] [--seconds N]` asks the magpie
serving the gateway for GET /v1/magpie/cpu?seconds=N: runtime/pprof's CPU
profile over 30s (5..120; else 400), gzipped protobuf, with the pid,
version, uptime, CPU time used over the window (getrusage / GetProcessTimes)
and since start, cores, GOMAXPROCS and goroutines in X-Magpie-CPU-Stats. It
tells the user to use magpie as when busy (run Codex) while it records,
writes <file> else magpie-cpu-<date>-<time>.pb.gz (0600), refuses a file
that is there before recording, and says "is magpie running?" at once when
nothing answers. --help writes nothing; an unknown flag, "-", a second file
or --seconds out of range are refused before anything is asked.

Only the profiling request waits: the gateway serves everything else
meanwhile. pprof keeps one CPU profile at a time, so a second ask gets 409
(cpuRecording), and a caller that hangs up stops the recording. The route
takes heap's guard: heapRefused's checks move into profileRefused, shared
by cpuRefused, so only a loopback, unproxied, browserless call to a
loopback Host gets it, with or without a gateway key or lanGuard.

Run at bad4508c4 + this: gofmt -l (nothing); go vet ./..., GOOS=linux go
vet -tags nogui ./..., GOOS=windows go vet ./... (clean); go test -tags
nogui -timeout 45m ./... under a sandbox HOME: every package ok except
internal/agent (45m timeout, #2544; again alone, in TestPortMovesEveryAgent)
and internal/gateway (TestTranslatedStreamKeepsClientAlive/chat_to_responses,
sibling of #2169/#2711, filed as #2737; alone with -timeout 45m only
/chat_to_anthropic, #2169; the test passes 5/5 alone). TestCPU* -race
-count=3 ok. Broken by hand: cpuRefused returning "" (19 failures in
TestCPUProfileOnlyToThisComputer); no one-at-a-time guard and no hang-up
stop (TestCPUProfileOneAtATime red each); no seconds bounds, no pre-check
of the file, no is-it-running check, no help case (each CLI test red).
Rebased on 2042123f4: go build ./..., gofmt -l, GOOS=windows and
GOOS=linux vet of internal/gateway and internal/cli clean; go test -run
'CPU|Cpu|Heap|Help' ./internal/cli ./internal/gateway ok.

Real use: the built binary's `magpie serve` under a sandbox HOME on
127.0.0.1:3493; `magpie cpu --seconds 5` saved a 0600 profile that go tool
pprof -top reads and printed the numbers; a concurrent second one got the
409 while GET / answered in ms; Origin: null and a rebound Host got 403;
--help wrote nothing; an existing file was refused. Not tried: the GUI
app's process, or the Windows box.
2026-10-17 20:52:13 +08:00
yetoneandggbdpq b566745b8a gateway: the model list says each model's reasoning levels as plain names too, for Catwalk clients (#2576)
Clients of the Catwalk schema (Crush and kin) read reasoning_levels, a
flat array of names, to know which reasoning efforts a model takes, and
drop reasoning_effort from requests to a model that names none. magpie's
/v1/models said the levels only as objects (supported_reasoning_levels,
[{"effort":"low"},...]), which such a client reads as none (cyancity).
modelObject now also says reasoning_levels: the same e.Efforts in the same
order, [] when there are none, never null. The objects stay as they were.

Every row built by modelObject carries it: the provider/model rows,
routing groups, bare ids, /v1/models/{id}, deciders, and Claude Desktop's
and Claude Science's lists. Muse's list has its own shape and the
image/video rows say no levels, so neither changes. No gateway default
for thinking, no thinking/enable_thinking aliases and no
default_reasoning_effort, as decided on the issue. Docs: reference.md,
integrating.md and the site's integrate page (en, zh) name the field.

ggbdpq's patch (base a69cd070); the review folded its test into
TestModelsListReasoning, which now checks reasoning_levels on every row it
already checks (groups included, and [] on a/plain and b/mixed) and on
GET /v1/models/b/sol.

Run (macOS arm64, sandbox HOME, pinned GOMODCACHE/GOCACHE):
- broken by hand two ways: the key renamed, TestModelsListReasoning red
  ("b/sol: reasoning_levels <nil>; want [medium,high]", and the single
  model); slices.Clone(e.Efforts) (null when empty), red ("a/plain:
  reasoning_levels <nil>; want []"). Green restored.
- this tree, as 1160f2e7d before the bodies were reworded (with the
  #2578 commit, on origin/main ebf3f48f7):
  gofmt -l clean; GOOS=darwin, linux and windows go vet -tags nogui
  ./... clean; go test -tags nogui -timeout 45m ./... under pipefail,
  exit 0, 66 packages ok. The same was green at 18828ea1a (on
  6f950653f) and d6881341d (on ed0335f75).
- rebased onto e085d6e92 (six commits, gateway.go and i18n.js among
  them, no conflict) after that run: gofmt and vet of internal/gateway and
  internal/gui clean, and their Models, Desktop, Science and
  ProviderModelsSayDesktopNumber tests ok; the full suite was not rerun
  there.
Not tried: a real Crush or Catwalk client.

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
2026-10-17 13:11:41 +08:00
yetone e085d6e926 cli, gateway: magpie heap writes the running magpie's Go heap profile, with its memory numbers
A user on X (FatimaHill74421) reports the macOS app at 3.95 GB physical
footprint after ~12h (v0.1.1273, after 8a1b5916f's #2278 fix), and a macOS
`sample` shows Go's frames as ???. `magpie heap [<file>]` asks the magpie
that serves the gateway for GET /v1/magpie/heap: runtime/pprof's heap
profile after a GC (gzipped protobuf, go tool pprof reads it), with
HeapAlloc, live heap, HeapInuse, HeapSys, StackSys, Sys, NumGC and the
goroutine count in X-Magpie-Heap-Stats. It writes <file>, else
magpie-heap-<date>-<time>.pb.gz here (0600, never over a file), and prints
the path, the pid and the numbers. --help writes nothing; an unknown flag,
"-" or a second file is refused before anything is asked.

The route answers only a loopback, unproxied caller with no browser marks
calling localhost or a loopback IP. heapRefused checks this in the handler
itself, so a gateway key never lets in another machine, a listed page,
Origin null, a localhost page or a rebound Host, and it holds where Handler
is served without lanGuard.

Run at dccfefdf7: gofmt -l (nothing); go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... (clean); go build for darwin,
linux (nogui) and windows; go test -tags nogui -timeout 45m ./... under a
sandbox HOME: every package ok (gateway 1218s, cli 613s). Broken by hand:
heapRefused returning "" turns TestHeapProfileOnlyToThisComputer red
(19 failures).

Real use: the built binary's `magpie serve` under a sandbox HOME on
127.0.0.1:3481; `magpie heap` saved a 10 KB profile (0600) and printed the
numbers, go tool pprof -top read it, --help wrote nothing, and a curl with
Origin: null got 403. Not tried: the GUI app's own process, or the
Windows box.
2026-10-17 12:04:53 +08:00
yetone ebf3f48f7f usage: a reported call takes first_text_ms and flow_ms, so a reasoning reply tells its speed and a burst is held (#2637)
POST /v1/magpie/usage/requests turned away first_text_ms and flow_ms as
"not a field a reported record takes", so a reported reasoning reply was
timed from its first reasoning token and a burst-at-the-end reply was
never held. The ingest now takes both, validated like ttft_ms (whole
milliseconds, 0..ingestMaxMillis, null = unset), and checks:
- first_text_ms <= ms, and first_text_ms >= ttft_ms when both are set
  (the first text is content too);
- flow_ms <= ms*10/8+1, since the gateway's flow is the tenth-to-nine-
  tenths span scaled by 10/8 and can exceed ms.
The fields reach usage.jsonl through the Record, so DecodeOf, Row.Decode
(ThinkPace, HeldShare) and the Reported totals read them as they do the
gateway's own rows. docs/reference.md and gateway-sessions.md say so.

Tests: TestUsageIngestTellsSpeed posts the reporter's literal repro
(grok-4.7, out 307, reasoning 129, ms 5035, ttft 4632, first_text 4700:
178 tokens over 335ms), a burst held by flow_ms, an even reply told, and
a ThinkPace hold, and checks the totals. TestUsageIngestTimesChecked
covers each bound, its edge, null and absent fields.

Broken by hand: old code fails both tests (field refused); dropping
FirstText tells repro-1 0; dropping Flow tells the burst 601/4035;
removing the ttft check accepts first_text 299 < ttft 300; bounding flow
by ms rejects the valid 1501.

Run at 8bb9375e7 + this diff: gofmt -l clean; go vet ./... on darwin,
GOOS=linux and GOOS=windows -tags nogui clean; set -o pipefail; go test
-timeout 45m ./... exit 0 (66 ok, gateway 1192s) under a sandbox HOME and
private GOCACHE (an earlier run against the shared cache had build
errors from cache files removed mid-run, not code). Machine load ~250.
Not tried with a real reporting client.
2026-10-17 10:14:03 +08:00
yetone 2c72563dd1 usage: Requests splits and filters by gateway key, with "No gateway key" for the calls none made (#2521)
MauriceCarlo asked for two things on Usage → Requests.

1. The gateway-key filter should show even when one key has calls. The
   picker hides itself under two options, and with one key it had one,
   so calls made with that key couldn't be told from calls made with no
   key. A "No gateway key" choice (callerKey=none) now sits beside the
   keys whenever the period has calls with no key, or it is the current
   pick. A single key's picker therefore shows and separates the two.
   The hidden condition itself is left to #2499, which another session
   has.
2. The trend chart and the ranking can split by gateway key. LED_SPLITS
   gains "Gateway key". It's offered only while the period has a key's
   calls, and it falls back to Model otherwise. A click on a rank row
   picks that key, or none, and a second click lets go, as the other
   splits do.

Server:
- usage.Dimensions gains "callerKey". A row's key is its CallerKeyID, or
  NoCallerKey ("none") when it has none, and the filter takes "none" as
  calls without a key.
- Filter.Without(d) is the one place that clears a dimension's own pick,
  so the by-split lists every value. RequestPage's fast and slow paths
  both use it now; they each had their own switch.
- usageapi names the split's shares from the key labels: "No gateway key"
  for none, the ID if a key was deleted.
- OwnPage keeps a held key's view to its own share in by and in the
  chart's split, so one key never learns another's name or numbers. The
  series was already only its own rows.
- docs/reference.md documents callerKey=none and by.callerKey.

"No gateway key" goes into the core i18n.js. The gateway keys page says
"No gateway keys yet", and i18n-keys' "a plugin's words are its own"
matches on substrings.

Tests:
- TestCallerKeySplitAndNone runs the fast and the slow path over {},
  one key, none, and none+an agent, and checks by.callerKey. Broken by
  hand, it goes red: once with the none clause in the filter removed, and
  once with Without's callerKey case removed.
- TestUsageOverGateway: on loopback the split names both keys. A held
  key's by.callerKey is only its own. With the OwnPage scrub skipped, it
  goes red (another key's name leaked).
- usage-ledger-key-split is new, in both engines, all five languages, and
  1400 and 760 px. It checks:
  - the picker's options with the none choice;
  - filtering on none;
  - the split's rows, and a click picking and letting go;
  - no sideways scroll;
  - that a period with no key's calls shows neither the picker nor the
    pill.
  32/32 pass. With the none option removed by hand, 11 go red.

Run on origin/main d9b943555 (head 663db0ecf), with the #2517,
#2521 and #2522 changes, load ~240:
- gofmt -l clean; go vet -tags nogui for darwin, linux and windows: ok.
- go test -timeout 120m -count=1 ./... (pipefail): exit 0, every package
  ok (gateway 1416.8s, agent 1535.5s). Before the rebase, on 63be47717:
  - The 45m run had agent and gateway past 45m (#2544, #2108).
  - TestMainWindowCorners was killed at its deadline (#1936).
  - TestSkillRelinkKeepsUnreadableCopy failed (#2555; it passes alone).
  - gateway alone with 120m was ok.
- GUI, the 41 Requests/Usage files in serial, both engines, before the
  rebase: 493 pass, 3 fail. The 3 were usage-refresh "not yet 2 !== 1",
  the same on 63be47717 alone (1 of 3); seen again on #2184.
- Rebased, these all pass, 102/102: i18n-keys, usage-ledger-ttft,
  usage-ledger-key-split, usage-ledger, usage-speed, usage-ledger-detail,
  gui-ja, gui-de and gui-zh-tw.
- Rebased again onto 9b04c4e20, which touches ledger.go, request_page.go
  and gateway.go:
  - vet ×3: ok.
  - internal/usage, internal/usageapi and internal/cli: ok.
  - internal/gateway -run 'NativeCompaction|UsageOverGateway|Capped|Cap':
    ok.
  - usage-ledger-ttft, usage-ledger-key-split, usage-ledger and
    usage-speed: 86 pass. i18n-keys was red from main's own words (#2586,
    fixed in the next commit).
2026-10-16 21:59:33 +08:00
yetone c5f15cae7c provider: Amazon Bedrock's Mantle endpoint (@marktoown on X)
"添加 AmazonBedrock 的时候,API 还是旧的 Bedrock-runtime 节点,不支持最新的
Bedrock-mantle 节点". The reporter wanted to add Amazon Bedrock at its
Mantle endpoint, but magpie only offered bedrock-runtime.

What it does:
- A new vendor preset, bedrock-mantle ("Amazon Bedrock (Mantle)"), takes
  the same Bedrock API key as the runtime.
  - It has 17 regions of its own (mantleRegions): the
    bedrock-mantle.{region}.api.aws hosts that answered on 2026-10-16.
    The runtime's eu-west-3 has no Mantle host.
  - Chat completions and Responses go to /v1, and Messages to
    /anthropic.
  - Unlike the runtime, its models are listed from GET /v1/models.
    NoList stays on the runtime preset only.
- Mantle serves each OpenAI-style model under one prefix.
  - OpenAI's closed GPTs and xAI's Grok are under /openai/v1. Every
    other model is under /v1. Asking at the wrong prefix gets "model `x`
    isn't supported on this route".
  - provider.MantleBase picks the prefix from the model id. The
    gateway's forwardOnce and the provider test's tinyBody both use it.
  - For a model whose maker the rule doesn't know, the gateway asks
    again once at the other prefix when Mantle refuses it for its route
    (internal/gateway/mantle.go).
  - When the second prefix takes it, the gateway remembers that prefix
    in unfit. When both refuse, the client gets the first refusal and
    nothing is remembered.
- IsBedrockMantle is true for the preset and for any provider added at a
  Mantle host. IsBedrock includes it, so the shared Bedrock rules apply
  to Mantle too:
  - Claude goes on Messages only.
  - The key is sent as x-api-key alone, which is what Mantle's own
    examples send.
  - max_completion_tokens is used, and metadata is stripped.
  - Beta renames and refusals apply.
  - There is no Priority.
  - GPTs go to Responses first.
- I checked every other IsBedrock caller. None is runtime-only except
  the legacy /openai/v1 -> Responses migration in normalize, which is
  harmless for Mantle.
- A provider added by its Mantle address gets the APIs it wasn't given
  (mantleEndpoints, in normalize). A chat or Responses URL given at
  /openai/v1 is moved to /v1, because /openai/v1/models is a 404 and the
  list lives at /v1/models.
- GUI: the editor's Key header row is hidden for a Mantle Anthropic
  address, as it already was for the runtime's.
- Docs: README (en, zh) preset lists, docs/reference.md,
  providers-accounts.md (a new row) and gateway-routing.md (a new row,
  plus a test command).

What was run, in the worktree at e72b6a332 (origin/main):
- New tests: TestBedrockMantlePreset, TestBedrockMantleByAddress,
  TestMantleBase (internal/provider) and TestBedrockMantleRoutes
  (internal/gateway, against a fake Mantle that serves each model at
  one prefix only and refuses the other with Mantle's words). All pass.
- Each was broken by hand and went red:
  - The reroute call removed: newmaker got a 400.
  - The prefix pick turned off: gpt-5.5 got a 400.
  - mantleEndpoints made a no-op: the endpoints were not filled in.
  - mantleHost made false: the provider was not taken for Mantle.
  - On the old source, the gateway test fails with 'no preset
    "bedrock-mantle"' and the provider tests don't compile.
- GUI: I added a Mantle case to provider-auth-header.test.cjs.
  - It passes 20/20 in chromium and webkit, en and zh.
  - Against the old app.js, chromium fails 2 of 10 on the new
    assertion.
  - add-sheet 6/6, tencent-cloud 12/12, strip-scrollbar 2/2,
    zhipu-team 12/12 and volc-access-key 12/12 pass in both engines.
- gofmt -l prints nothing.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  -tags nogui ./... and GOOS=windows go vet ./... all exit 0.
- go build, GOOS=linux go build -tags nogui and GOOS=windows go build
  all exit 0.
- Full suite: go test -p 2 -tags nogui -count=1 -timeout 45m ./...
  (sandbox HOME).
  - 64 packages ok.
  - internal/agent and internal/gateway hit the 45m timeout with no
    test failing. Load average was 260-380 from other sessions, with
    about 68 other test binaries running.
  - A second 45m run of those two timed out the same way, again with no
    test failing, and different tests were running at the timeout each
    time.
  - The two were run again with -timeout 150m (-p 2, the same load):
    internal/agent ok in 2988.8s and internal/gateway ok in 2972.4s,
    both just past 45 minutes.

What was not tried:
- The real Mantle API. The owner has no Bedrock key (no Bedrock
  provider in providers.json, and AWS_BEARER_TOKEN_BEDROCK is unset).
  The only real-API evidence is unauthenticated probes of the hosts and
  the routes they answer on.
- The per-model prefix rule, /v1/models, Messages with x-api-key, and
  the "isn't supported on this route" refusal come from AWS's docs and
  model cards, not from a signed request.
- The Mantle Anthropic base's own model list (/anthropic/v1/models) was
  not checked. The list is taken from /v1/models.
- The GUI was not tried in the real desktop app.
- The gui-zh-tw, gui-ja and gui-de suites were not run, since no string
  was added.

Rebased onto origin/main e243937ca (no conflicts). At the rebased head:
go test -run 'Mantle|Bedrock' ./internal/provider ./internal/gateway ok,
gofmt -l of the changed files empty, GOOS=linux and GOOS=windows go vet
-tags nogui of both packages exit 0. The full suite above ran at
e72b6a332, not again at the rebased head.
2026-10-16 19:30:42 +08:00
yetone e243937ca3 gateway: a fast pick can be sent as Ultrafast where the account offers it (#1954)
zhenghaowen0967 asked for an agent's fast pick of a ChatGPT model to go as
Codex's Ultrafast without the client asking for it. settings.UltraPicks
holds the agent's fast picks that are set to Ultrafast; each one is in
FastPicks too.

- The gateway marks those candidates `ultra` in fastPick.
  - On Chat and Responses, a try sends service_tier "ultrafast".
  - From Messages, a try carries withUltra to forwardTranslated, which
    sets Request.Ultrafast for the ChatGPT backend.
  - In every case, the #1784 check decides the account. One whose list
    doesn't offer Ultrafast goes after a mate that does (tierMate). With
    no mate left, it is sent priority.
  - That check now covers Chat as well as Responses.
- Sibling fix: chat.go dropped a Chat client's own service_tier
  "ultrafast" (Fast was false, Ultrafast unset). It now parses as
  Responses does.
- provider: SetFastTier (""/priority/ultrafast) behind SetFastPick.
  CanUltra and UltraModels say whether one of Codex's accounts lists
  Ultrafast on the model. UltraPicks follow a provider rename
  (renameModelPrefs) and survive a GUI settings save.
- GUI: an option gets ultraOk/ultra. Where ultraOk is set, the bolt in
  the picker steps usual -> Fast -> Ultrafast -> usual, as a camera's
  flash button steps its modes. Ultrafast shows two overlapped bolts, in
  the row and after the field's model. Tooltips and the status line are
  in en, zh, zh-TW, ja and de. POST /api/agent-fast takes `ultra`.
- No `:ultrafast` suffix for routing groups yet.

Tests, each broken by hand and seen red:
- TestUltraPickSentUltrafast covers omp/Responses with no tier asked
  (acct-pro:ultrafast), the Pro account out (then acct-plus:priority),
  another agent unchanged, opencode/Chat and claude/Messages picks, a
  Chat client's own ultrafast, and switching back to Fast or off.
  - Red with ultra forced false (4 cases).
  - Red without withUltra (claude went priority).
  - Red without the chat.go parse (2 cases).
- TestSetFastPick: red without UltraPicks in renameModelPrefs.
- TestSettingsSaveKeepsWhatItDoesNotSend: red without the api.go carry.
- fast-ultra.test.cjs (en zh ja de, window and 440px panel): red (9/9)
  without the Ultrafast step.

Run (vet, gofmt, GUI and full suite at base 8b84dc902; the reruns
below at a rebase onto 6b3ee5a03 and then onto 63be47717 origin/main):
- gofmt -l: clean.
- go vet -tags nogui ./... for darwin, linux and windows: clean.
- GUI, chromium + webkit: fast-ultra, fast-pick, group-member-fast,
  i18n-keys, model-pick and 14 other agent-model/picker files. 197/197
  pass.
- Full suite: set -o pipefail; go test -timeout 45m ./... (sandbox
  HOME, macOS, 3 other sessions' suites running at the same time):
  every package ok except two.
  - internal/gateway: TestMaxRPMGroupPrefersMemberWithRoom hit its fixed
    1s bar (1.126s) under load. It passes 5/5 alone (-count=5). Filed
    as #2520.
  - internal/gui: TestPanelJoinsFullScreenSpaces, red on macOS 26.2 on
    main already, filed as #2450.
- Rerun of internal/gateway and internal/library after the rebase onto
  6b3ee5a03 (both packages changed upstream), -timeout 60m, load
  average ~290: library ok. gateway hit the 60m timeout (the test
  running, TestPauseByFolder, was 13s in) and
  TestQueueRefusalIsInTheUsageLedger saw b's 1s queue timeout as a
  second 429. Filed as #2541. TestQueueRefusalIsInTheUsageLedger,
  TestPauseByFolder and TestUltraPickSentUltrafast, -count=5 at this
  head: ok.
- At the 63be47717 rebase: gofmt clean; vet darwin/linux/windows clean.
  internal/provider ok, internal/settings ok. internal/agent hit the
  45m timeout under load ~295 (in TestCursorLocalEffort, at 0s), so
  this is not a green for that package. Its -run
  "Fast|Option|Models|Picker|Cursor|Codex" subset, run through the
  shared 3-slot queue, was ok in 794s. The whole package is left to
  CI's Test run.

Not tried: a real Pro account's Ultrafast. The fake ChatGPT backend's
model lists offer it on one account only.
2026-10-16 19:14:52 +08:00
yetone a15e576564 agent: OpenPencil uses magpie's models (@JC_be_better on X)
OpenPencil (ZSeven-W/openpencil, the openpencil-desktop app) keeps the
builtin agents its chat runs on in settings.json under Rust's
dirs::config_dir()/openpencil (read from its settings_io.rs and
settings_payload.rs). magpie adds one builtin_agents entry, id "magpie",
kind openai-compat at the gateway's /v1 with the magpie-openpencil key,
preset custom, the picked models as OpenPencil writes a list: the first
as `model`, `models` only for two or more, at most 64. The user's other
entries and settings stay, and so do the display_name and enabled they
give magpie's entry; a sync with nothing to change doesn't write. A file
magpie makes gets "version": 1 (OpenPencil sets a file without it aside
as corrupt); a file with another version, or none, is left alone.
Disconnect takes the entry out, and the file when nothing else is left.
OpenPencil reads the file once at start and writes it all back when it
quits, so a change is refused while openpencil-desktop runs (Windows
can't be asked, so the notice says to quit it first). Notice translated
in zh-CN, zh-TW, ja and de. README (en, zh-CN), docs/reference.md and
docs/subsystems/agent-wiring.md list it.

open-pencil/open-pencil, the other app of the name, keeps its providers
in its webview's localStorage, so it gets no row.

Run, under a scratchpad HOME with GOCACHE/GOMODCACHE pinned:
- go test -p 2 -tags nogui -count=1 -timeout 45m ./...: ok, 66 packages
  ok, 18 with no test files
- gofmt -l: clean; GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean
- go test ./internal/agent -run '^TestOpenPencil': ok
- node --test agent-notice-lang, i18n-keys, header-relang (Chromium and
  WebKit, every language, wide and narrow): 37/37 pass
Broken by hand, each went red: the running check, the 64 cap, the
version check, keeping the user's display_name, the no-op sync, and
writing the version into a new file.

Real use: OpenPencil v0.8.4 (latest release, arm64, sha256 checked against
its SHA256SUMS) under a sandbox HOME, started on a settings.json magpie
wrote with the user's own Anthropic entry beside it. It started and ran
15s with the file intact and no .corrupt copy. v0.8.4 has no `models`
field, so it lists only the first magpie model; main lists them all.

Not tried: a chat request through OpenPencil's UI; its exit save (it
didn't quit on an AppleEvent and was stopped with TERM, so the write-back
wasn't seen); Linux and Windows; a build of OpenPencil's main.
2026-10-16 11:43:51 +08:00
yetone 486ea82378 agents: cursor-agent's row is Cursor CLI (@G_Z_Y on X)
@G_Z_Y looked for Cursor CLI on the Agents page and took the "Cursor" row
for the editor. The row is cursor-agent, so it is named Cursor CLI. What
it keeps in ~/.cursor is the Cursor editor's too (MCP servers, skills,
chats), so the Library and Sessions name it Cursor there (SharedName).

Run at this head before the rebase onto 0f391a7a7: go test -tags nogui -count=1 -timeout 45m ./... under a sandbox HOME, every package ok; gofmt -l clean; go vet clean for darwin, linux (nogui) and windows; GUI files agent*, i18n*, gui-*, getting-started, library*, sess* and import-row in both engines: 1638/1638.
2026-10-16 05:10:43 +08:00
yetone 5c0049a38c agent: MothX is an Agents-page row, wired into ~/.mothx/settings.json, and Disconnect puts it back (#2353, zhenruyan)
MothX (oschina/mothx, formerly vibecoding; npm mothx-installer) reads its
providers and start-up model from one settings.json: $MOTHX_DIR, else
%APPDATA%\mothx on Windows, else ~/.mothx. This follows zhenruyan's fork
(#2353) and the jcode/Prime Agent pattern.

What changed
- internal/agent/mothx.go: the agent. Connect writes provider "magpie"
  (openai-chat at the gateway's /v1, key magpie-mothx, one entry per magpie
  model with reasoning, input, contextWindow, maxTokens, cost) beside the
  user's own providers, and sets defaultProvider/defaultModel; "thinking"
  is defaultThinkingLevel, narrowed to the levels magpie knows for the
  model (none → off). thinkingFormat "openai" makes MothX send
  reasoning_effort for every model; without it MothX guesses Qwen's
  enable_thinking/thinking_budget or DeepSeek's thinking from the model id.
  A thinkingFormat or headers the user put in magpie's block are kept.
  Model options: the user's own providers' models, the current built-in
  pick (deepseek-openai/…), then magpie's.
- Disconnect: settings.json is copied aside before magpie's first write
  (beforeMagpie) and put back byte for byte when nothing else changed; a
  file that wasn't there goes again. When MothX rewrote it meanwhile
  (/model, /statusline … global: SaveGlobalSettings marshals the whole
  struct), only magpie's provider, the pick and a providers object left
  empty go; the user's changes stay.
- Detection, the restart notice (mothx or vibecoding running; translated in
  zh-CN, zh-TW, ja, de), WSL distros (~/.mothx), MOTHX_DIR in agentenv and
  the WSL dir moves, CLI updates through npm mothx-installer.
- usage names its requests: the User-Agent is "Vibecoding Client/<ver>",
  matched by the alias vibecoding (usage.AgentOf takes the first word).
- GUI: the icon (upstream docs/assets/mothx-small.png, MIT).
- Docs: README en/zh lists, docs/reference.md (table row, provider-scoped
  list, notes), docs/subsystems/agent-wiring.md.
- Not in this commit: MothX as a Library skills target (its own goal).

Run
- go test -p 1 -tags nogui: TestMothX* (real first-run settings.json as
  the fixture; user keys, headers and thinkingFormat kept; no-op Sync and
  same-value Set leave bytes and mtime alone; Disconnect byte-identical;
  no-file round trip x2; changes while connected kept; MOTHX_DIR/Windows/
  WSL dirs; thinking levels), TestAgentOf, TestEveryNoticeIsTranslated,
  TestEveryAgentNamedByItsKey, TestWSLMore*; then ./internal/agent
  (1120s at load ~100; an earlier run hit the default 10m timeout inside TestReasonixConcurrentEditsAndSync at load ~50, not a failure), ./internal/agentenv, ./internal/usage: ok.
- Broken by hand, each red then restored: no take() (TestMothX and
  RoundTripNoFile red), user thinkingFormat not kept, thinkingFormat
  "openai" dropped, the vibecoding alias dropped (TestAgentOf: got
  "Vibecoding"), the empty-providers cleanup (KeepsWhatChanged red).
- gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui ./... clean.
- GUI (playwright 1.62.0, chromium and webkit): agent-notice-lang,
  models-add-and-icons, pi-default-note 30/30; a scratch check of the
  MothX row (icon loads, connect, notice in the window's language, fits)
  in en/zh/zh-TW/ja/de at 1100 and 420: 22/22.
- Real binary, MothX 1.3.104 (npm mothx-installer) in a sandbox HOME
  against a sandbox `magpie serve` and a fake OpenAI upstream:
  - `magpie mothx magpie/fake/echo-1` wrote the block; `mothx doctor`
    showed provider magpie, model fake/echo-1.
  - `mothx -P "Say PONG"` answered from the fake; usage.jsonl recorded
    agent mothx, provider fake.
  - Adding qwen3.7-plus to the provider live-synced the block (context,
    maxTokens, cost, reasoning). With thinking high, MothX sent
    reasoning_effort "high"; with thinkingFormat removed by hand it sent
    enable_thinking/thinking_budget instead, and `magpie provider refresh`
    put "openai" back.
  - The interactive TUI (tmux) started on "magpie | Qwen3.7 Plus · fake"
    and got the fake's reply; `magpie mothx effort medium` while it ran
    printed the restart notice.
  - `/statusline refresh 5 global` in the TUI rewrote the whole file
    (dropped reasoning:false, added responses:{…} to magpie's block);
    `magpie mothx` still read connected. `magpie mothx default` then left
    the original plus the user's refreshInterval, and (after the cleanup
    above) no empty providers.
- Not tried: Windows and WSL with the real binary; a real vendor key.

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 357ffac7be usage: a model's Same as prices its calls when no list does (#2344, liuweifeng)
A model a provider serves under its own id (a WorkBuddy kimi-k3-1, a
relay's renamed gpt) had no price unless the user typed one, even when the
user had already told magpie in the editor's "Same as" box which model it
is. Its calls showed no API-price cost in Usage, window holds had no price
to weigh, and `magpie model price` said unpriced.

Now, when neither the user's prices, the provider's list nor models.dev's
maker price covers a model, provider.SamePriceIn takes the maker's list
price of the model it is the same as (settings.ModelSameAs), and the
provider's price rate still applies. A price the user set, or a list that
prices the model, always wins; nothing is inferred without a Same as.
The same fallback is used by priceOf (Usage costs, re-priced when the
ledger is read, so past calls pick it up), usage's apiPricer (window
holds), the model editor's greyed list price, and `magpie model price`,
which names where the price came from. The "Same as" tooltip says so in
en, zh, zh-TW, ja and de.

Run:
- go test -p 1 -tags nogui ./internal/provider ./internal/usage
  ./internal/cli ./internal/gui (focused: TestSameAsPricesAnUnlistedModel,
  TestHoldsPriceTheModelItIsTheSameAs, TestModelEditorShowsTheSameAsPrice,
  TestModelPriceCmdSaysWhereThePriceCameFrom, plus the packages): ok
- GUI (chromium + webkit): provider-same-as, i18n-keys, model-price-edit,
  11/11 pass
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows: clean

Broken by hand, each went red:
- SamePriceIn dropped from priceOf: "kimi-k3-1 ... false; want $0.3"
- usage's apiPricer fallback removed: "wasn't its API price: <nil>"
- the GUI editor branch removed: "list <nil>"
- the CLI source line disabled: TestModelPriceCmd... FAIL
- the zh tooltip left untranslated: provider-same-as.test.cjs 0/2
A prefix-stripping branch passed when removed (MakerPrice already resolves
vendor-prefixed ids like moonshotai/kimi-k3), so it was dropped.

Not tried: a real WorkBuddy account's usage after the change.

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 0c0665126b quota: magpie quota --json and /v1/magpie/quotas tell each window's whole (holds / holdsWhy) as the Usage page does (#2333, zhenghaowen0967)
usage.WithWindowHolds reckoned a subscription window's whole (tokens, and
cost at API list prices) from magpie's own calls, or why it can't, but
only GET /api/usage/quotas and its refresh called it. magpie quota --json,
GET /v1/magpie/quotas and its ?kept=1 list showed name, used, remaining
and resetsAt only, so a script comparing plans had to rebuild the estimate
from the log without its guards.

Package provider can't import usage, so usage sets provider.ReckonHolds in
an init (like the other provider hooks). quotaReport, which QuotaReport,
KeptQuotaReport and RefreshReport share, runs it once over every card and
QuotaSpan carries Holds and HoldsWhy. The log is read through usage's
cached snapshot, so ?kept=1 (magpie statusline, every message) adds no full
read after the first. A key held to a budget, models or accounts and told
cards (#2216) is not told holds: they are reckoned from every call routed
through the account, other keys' too, so quotaScope.quotas drops them;
this machine and unheld keys get them.

The Balance guard in holdsBounds (a Codex account holding credits gets no
whole and no reason) is unchanged; it is answered on the issue.

Docs: reference.md's /v1/magpie/quotas section names holds/holdsWhy and
each reason; providers-accounts.md's Allowance row names the hook.

Run (sandbox HOME, -tags nogui, -p 1):
- New TestQuotaReportTellsWindowHolds (provider), TestQuotaReportsReckonByTheLog
  (usage, against a real usage.jsonl in the sandbox) and
  TestHeldKeyToldNoWindowHolds (gateway) pass.
- Broken by hand: the ReckonHolds call in quotaReport skipped → provider
  test FAIL "reckoned 0 times over 0 cards"; Holds/HoldsWhy not copied into
  QuotaSpan → FAIL "5 hours told no whole"; usage's init removed → usage
  test FAIL "provider.ReckonHolds isn't set"; quotaScope not clearing them
  → gateway test FAIL "a held key was told 5 hours's whole".
- go test ./internal/provider ./internal/usage ./internal/cli
  ./internal/gateway: ok.
- gofmt -l clean; go vet -tags nogui darwin, GOOS=linux, GOOS=windows on
  provider, usage, gateway: ok.
- Not run: the GUI suite (no GUI file changed), and against the owner's
  real accounts.

Full suite: SUITE_LINE
2026-10-15 23:08:02 +08:00
yetone d8d52c6e97 agent: Raycast is an agent magpie connects: a magpie entry in its Custom Providers' providers.yaml, magpie's models in Raycast AI's picker (lx_78654 on Discord)
lx_78654 asked on Discord: "agents能否加一个raycast".

Raycast AI takes models of the user's own as Custom Providers (Raycast
Pro, "Available on: Mac, Windows"), from ~/.config/raycast/ai/
providers.yaml in the user's folder on both systems
(https://manual.raycast.com/ai/custom-providers). Raycast watches the file,
so no restart notice.

What changed:
- internal/agent/raycast.go: a new agent, "raycast". One field, provider:
  connecting adds an entry, id magpie, to the providers list: the gateway's
  /v1 (OpenAI compatible, no /chat/completions), an api_keys alias holding
  magpie-raycast (Raycast's User-Agent isn't known, so its key tells it
  apart), and one model per magpie model with name, context and all five
  abilities said (Raycast assumes tools and vision off when left out):
  tools and system_message on, vision for a model taking images,
  temperature off for one that refuses it, reasoning_effort for one with
  effort levels. ListsModels: the model is picked in Raycast.
  - The list is edited as a yaml node, so the user's other providers, the
    top-level tools block (anchors too) and comments stay.
  - A key the user adds to magpie's entry or to one of its models
    (include_user_email, a description) is kept on a sync; a model gone
    from the catalog leaves the list. A sync with nothing to change
    doesn't write.
  - Disconnect takes the entry out, the list when it was the only one, and
    a file left with nothing in it (Raycast's providers.template.yaml is
    never touched). A providers key that isn't a list is refused and the
    file left as it is.
  - Detected by Raycast.app (com.raycast.macos) or the ~/.config/raycast
    folder.
- agents.go: registers it.
- icons/raycast.svg: Raycast's mark from Simple Icons (CC0), currentColor.
- docs/reference.md, docs/subsystems/agent-wiring.md, README.md,
  README.zh-CN.md: Raycast's row and its place in the agent list.

What was run:
- go test -p 1 -tags nogui ./internal/agent -run '^TestRaycast' in a
  sandbox HOME: ok. The fixture is the manual's LM Studio and tools
  examples, with comments and an anchor; the result is decoded strictly
  (KnownFields) into the manual's schema. Red by hand when I:
  - turned off the no-op check ("a sync with nothing to change wrote");
  - replaced the merge with magpie's entry alone (the user's
    include_user_email and a model's description gone).
- go test -p 1 -tags nogui ./internal/agentenv: ok.
- The whole ./internal/agent package didn't finish here: the first run hit
  the 10m default timeout at TestInstalledVersion with the machine at load
  ~110 (other sessions' suites), the second (-timeout 40m) ran 20 minutes
  with no FAIL and then stopped on "no space left on device" when the disk
  filled (0 GB free, not this run's files). It needs a run on CI.
- gofmt -l; GOOS={darwin,linux,windows} go vet -tags nogui ./internal/agent: ok.

Not tried with a real Raycast. On Windows it is found by the
~/.config/raycast folder only (its install path isn't verified). WSL isn't
covered.

Full suite: SUITE_LINE
2026-10-15 23:08:02 +08:00
Leon Zhao c6bd4e9707 agent: let Lody confirm local provider imports
Offer Lody a versioned import link for Claude, Codex, Pi, DSH,
Kimi Code, Grok and Bub. Export only loopback endpoints and the public
magpie-lody token. Leave Lody data untouched and show a confirmation hint
when the app exposes no public import-status reader.

Verified: go test -tags nogui ./... in a temporary HOME with pinned Go
caches; native, Linux nogui and Windows vet/build; gofmt and diff checks;
17 Chromium/WebKit import-row and locale checks. The actual Lody parser
accepted all seven targets with IPv4, localhost, IPv6 and canonical ports.

Negative controls: removing registration fails
TestLodyDetectionAndRegistration with "Lody missing from Agents";
removing URL handoff fails TestLodyImportHandoff with
"Lody import was not handed to the desktop". Restored tests pass.

Desktop launch and Linux/Windows runtime behavior were not exercised.

Cherry-picked onto main (4a6bf80f4) from Leeeon233/magpie
feat/lody-integration (ab6c6dd27): README lists resolved with Lody after
Cindy beside main's new agents; /api/open keeps main's OpenURL error path
(#2043) and takes lody:// beside cindy://; the test's fake Windows
returns OpenURL's error as main's interface now does.
2026-10-15 21:18:41 +08:00
yetone 37fec12409 import: OpenCode's keys come in from its auth.json, Go's on OpenCode Go (@hu_xiaomi on X)
@hu_xiaomi on X asked whether magpie could pick up OpenCode Go's API key
by itself. OpenCode keeps what `opencode auth login` signs in to in
auth.json, in $XDG_DATA_HOME/opencode (~/.local/share/opencode when that
is unset, on Windows too). Its format and path were checked against
anomalyco/opencode v1.19.0, packages/opencode/src/auth/index.ts.

- OpenCode is now a source in the import picker (appReaders,
  import_opencode.go). An "api" key comes in on the magpie preset with
  the same id: opencode-go on OpenCode Go, opencode (Zen) on OpenCode
  Zen, and a vendor's key (openai, anthropic, deepseek, openrouter, ...)
  on that vendor's preset, the same way Alma's almaPresets work.
- auth.json keeps no address beside a key, so a key for a provider with
  no preset is listed and skipped ("it has no base URL"). Sign-ins
  (oauth: Claude Pro/Max, Copilot; wellknown: an enterprise server's
  token) are listed and skipped with the reason the picker already
  translates. No new GUI strings.
- OpenCode is read only when the user opens the picker. The Providers
  page's automatic discovery leaves it out (DiscoverSources, the `asked`
  flag), because the file holds every sign-in OpenCode has. magpie never
  writes to it. OPENCODE_AUTH_CONTENT is not read.
- presetAt: the first preset at a host won even when a later one matched
  the URL exactly. OpenCode Zen and Go share opencode.ai, so a Zen key
  would have landed on Go. An exact match now wins.
- importSources: a source whose stat fails with anything but not-exist
  (a folder magpie can't search) is found with an error, which means
  unknown. Before, it read as "Not found".
- The picker's tab shows OpenCode's own mark (icons/opencode.svg).
- docs/reference.md describes the source.

Not added: an "use the key OpenCode has" offer in the OpenCode Go add
sheet, because no other app has one there (no sibling to follow).

Run (macOS, go1.26.8, worktree at dd25997a4 before the rebase):
- go test -tags nogui -timeout 40m ./...: every package ok
  (63 ok, none failed; gateway 1806s, agent 1769s at load ~160-230)
- gofmt -l internal/provider internal/gui: clean
- go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...: clean
- GUI, playwright 1.62.0: import-opencode.test.cjs in chromium and webkit,
  en/zh/zh-TW/ja/de, at 900 and 390px: 20/20. import-collision,
  import-row, provider-discovery and key-import pass. login-import fails
  in chromium (fill/click timeouts) at load ~230. It fails the same way
  with HEAD's app.js (dd25997a4 = origin/main, just fetched), and #1307
  already tracks it.
- Broken by hand, each went red and was then put back:
  1. presetAt's old first-hit rule: TestImportOpenCodeAuth, Zen came in
     as opencode-go-2.
  2. no sign-in skip: TestImportOpenCodeAuth, anthropic's oauth entry.
  3. stat errors read as not found: TestImportOpenCodeAuthUnknown,
     unreadable folder.
  4. discovery reads OpenCode: TestImportOpenCodeAuth and
     TestOpenCodeWaitsForThePicker.
  5. XDG_DATA_HOME ignored: TestImportOpenCodeAuth, TestImportOpenCodeAuthUnknown
     and TestOpenCodeWaitsForThePicker.
  6. tab icon left at app-opencode.png: import-opencode.test.cjs.

Fixtures are auth.json as OpenCode v1.19.0 writes it
(JSON.stringify(data, null, 2), 0600), under a sandbox HOME and
XDG_DATA_HOME. Not tried: a real OpenCode install with a real key, and
the Windows box (the path logic is the same there; GOOS=windows vet only).
2026-10-15 19:20:09 +08:00
yetone 4ac4d9ba99 plugins: the gateway's middleware point; JS middleware and privacy masking are built-in plugins, masking fails closed (P3)
P3's third point (docs/subsystems/plugin-runtime.md). internal/gwmw has two
places, each with its own failure policy:

- Agent: a middleware on an agent's request in its own API and on its reply.
  serveAgent runs each registered one. The JS gateway middleware is the one
  there (middleware.Chain), registered by the new built-in plugin
  `middleware`. Its place, API, limits and fail-open are unchanged. InUse is
  middleware.On(). Off, no middleware runs.
- Masker: what goes to a vendor, masked, and the values back in what comes
  back. The new built-in plugin `redact` serves masking.Masker (in
  internal/masking, since settings imports redact). InUse is masking.Wanted.
  It fails closed: masking asked for with no masker serving, or a masker that
  panics, is a 503 "nothing was sent" at every call site that masked before
  (serve, count_tokens, embeddings and audio, transcriptions, images, video,
  search stand-ins and their queries, the Codex backend).

With no masker, or with no agent middleware while plugins.json has one on,
the gateway asks pluginrt.Refresh, at most once a second. A setting or
middleware added a moment ago serves the request that needs it.
pluginrt.KeepFresh also watches plugins.json now.

Run (on origin/main 95e7c6bcc + this change, with the next commit's two
test waits):
- go test -count=1 -timeout 60m ./...: all ok (gateway 682s, agent 617s)
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, Chromium and WebKit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw. builtins reaches the Usage row by wheel now, since the
  page puts back a scroll that isn't the reader's.

Broken by hand, each went red:
- masking fails open with no masker (TestMaskingOnAndOff)
- a panic isn't recovered (TestSafelyTurnsAPanicIntoAnError, TestMaskingOnAndOff)
- no refresh asked (TestServedRefreshesOnce, TestMaskingOnAndOff)
- the plugins don't register (plugins/redact, plugins/middleware
  TestOnServesOffDoesNot)
- InUse misses redactWords (plugins/redact TestInUse)
- maskedQuery fails open (TestMaskedQueryFailsClosed)
- middleware runs with the plugin off (TestMiddlewareOnAndOff/off)
- no refresh on a middleware miss (TestMiddlewareOnAndOff), want ignored
  (TestAgentsWantedRefreshesWhenWanted)

Real use, sandbox HOME, magpie serve and a fake vendor that echoes:
- redact off with nothing asked: sent as written
- redactWords written, request at once: the vendor got {{TERM_…}} and the
  agent got the word back; `plugin builtin off redact` refused while in use
- `magpie plugin add ./alias.middleware.js`: the next request is rewritten
  (200, was 404). Removed: 404 again.
  The first build left that request at 404 until a restart, since plugins.json
  wasn't watched. That's fixed here.

Not tried: a real vendor account; the Windows box.
2026-10-15 13:40:20 +08:00
yetone b1d02fa612 groups: the user's own routing groups are the groups plugin's, served only while it is on (P3 router strategy)
The groups plugin now owns the user's own routing groups at the router
strategy point. The groups magpie finds (auto-<model>, one model several
providers serve) stay core, as Smart does: a new install has groups off
under Essentials, and taking those would silently drop cross-provider
failover. planGroup and the walk over a group's members stay core too.

- provider.GateGroups / ServeGroups (group_serve.go): the gateway holds
  the gate while it serves; the plugin holds ServeGroups while on. Gated
  with none served, groupsIn drops every group not Auto, so FindGroup,
  GroupFor, the catalog and /v1/models go without them. The CLI and TUI
  are never gated. Nothing derived from groups is cached past a call, so
  a flip is seen by the next lookup.
- Gated and off, a lookup that finds a user group asks the gate's refresh
  (pluginrt.Refresh in the gateway) at most once a second, never
  re-entrantly, then looks again. Without this, `magpie group add` was
  404 for up to 2s until KeepFresh turned the plugin on (seen in the
  sandbox).
- plugins/groups and plugins/routing: InUse is provider.NamedGroups, the
  file's non-Auto, non-hidden groups read past the gate; an unreadable
  providers.json is an error, so the plugin stays on.

Run before rebasing onto 707fbb249:
- go test -count=1 -timeout 40m ./... : all ok (59 packages)
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean
- sandbox, real nogui binary + `magpie serve` + two fake upstreams:
  before add: group/auto-m listed, group/mine 404; right after
  `magpie group add Mine models=pa/x,pb/m`: group/mine listed and 200;
  after `group rm`: 404, auto-m still served.

After the rebase onto 707fbb249: vets (3 OSes) and go test of
internal/provider, internal/gateway, internal/pluginrt and plugins/...
all ok.

Broken by hand, each went red:
- groupsIn filter removed: TestOwnGroupsWaitOnThePlugin,
  TestGroupsOnAndOff/off
- NamedGroups swallowing the read error: TestNamedGroupsUnreadable,
  plugins/groups TestInUse
- Apply not serving: TestOnServesOffDoesNot
- refresh not called / not throttled / asked for Auto groups too:
  TestOwnGroupRefreshesTheGate
2026-10-15 10:42:23 +08:00
yetone af9bd6c3e2 gateway, routes, plugins: the routings besides Smart are the rotation plugin's, on the gateway's router strategy point (P3)
The second P3 extension point (docs/subsystems/plugin-runtime.md). A
router strategy orders one pool of routes: a provider's accounts or keys,
or the heads of a group's members. The gateway still lists the pool and
keeps rests, affinity, rules, pins and failover; a strategy only orders.

- internal/routes: Seat, Strategy{Order, Exact, ByUse}, Register (stacks,
  the last serves), Find, Served, and Apply, which fails open: a strategy
  that panics or answers what isn't a permutation leaves the pool in its
  listed order, logged. Smart is the core's; Ordered, Rotate, LeastUsed,
  Pace and Weighted are routes.Builtin, moved out of the gateway with the
  rotate turns and the smooth weighted round (Round, MoveRound, Forget).
- plugins/rotation (Essential): registers routes.Builtin. InUse counts the
  providers and groups providers.json routes by one of them
  (provider.Routings), an unreadable file is an error, so it stays on. The
  gateway's KeepFresh watches providers.json too.
- Off, a routing no strategy serves is its listed order, and routingOf
  reads it as "order" wherever the core asks (a turn's mark, sinks, a
  rotate group's sessions, a group's heads, weightedKept).
- GUI: the routing pickers (provider editor, Routing page pools and group
  editor) mark the five as data-feature="rotation" (routingSegs), so off
  they offer Smart alone. i18n zh, zh-TW, ja, de.
- Docs: plugin-runtime.md router strategy section, gateway-routing.md
  (also drops a duplicated sentence about a lone key), reference.md.

Run in the worktree at this change (on origin/main fbfb76149):
- go test -count=1 ./... : 57 packages ok (gateway 587s)
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows
- GUI: full suite, chromium and webkit, every language: 9805 tests, 29
  red in 6 files. Each red alone the same way on origin/main bc470c6b6
  (just fetched): quota-count-wrap, quota-name-translated (#2228),
  refusal-retries-setting (#2258), routing-held-member (#2252), usage-fold
  (#2163), usage-agents-hide (#2276, from cf455ebd5). routing-save, builtins and
  rate-limited-sink pass in both engines.
- internal/gateway TestMain registers the strategies, so every routing test
  is the parity run with the plugin on; TestRotationOnAndOff turns it off
  (three Rotate sessions start k1,k2,k3 on, k1,k1,k1 off, no turn mark;
  Smart still served).

Rebased on origin/main 2b0037f41: go test ./... again, 56 packages ok at the
default timeout; internal/agent and internal/gateway passed with
-timeout 40m (1093s, 1039s: the machine at load ~17 with other sessions'
suites; the 10m panics stood in TestCodexAPIDisconnectStays and
TestCodexHeardWithinItsIdleTimeout, 1-2s in, no stack waiting on them).
Vets and gofmt clean again; routing-save, builtins, rate-limited-sink,
i18n-keys and the GUI files upstream changed pass.

Broken by hand, each test went red then restored:
- Apply's permutation check off: TestApplyFailsOpen
- Register's remove a no-op: TestRegisterStacks
- the plugin's Apply registers nothing: TestOnServesOffDoesNot
- InUse swallows providers.json's error: TestInUse
- routingOf passes an unserved routing through: TestRotationOnAndOff
- routingSegs not marking data-feature: routing-save.test.cjs "Smart alone"
2026-10-15 09:09:15 +08:00
yetoneandggbdpq c3bef99efd provider: magpie://import links take gemini=, and its host is named before adding (#2251, ggbdpq)
An import link could set chat=, responses= and anthropic= but not
gemini=, though the editor and the TUI take a Gemini base URL; a link
with only gemini= failed with "it needs chat=, responses= or anthropic=".
ParseImport now reads gemini= under the same base-URL rules, and the
error names it (ggbdpq's patch, with docs/reference.md and the en/zh
docs rows).

Its siblings that listed the three base URLs:
- the GUI's import dialog warned "Your prompts and this key will go to ;"
  with no host for a gemini-only link: it names the Gemini host now;
- the site's handoff page (site/public/import.html) left it out of
  "Sends to";
- the docs' link builder (en, zh, ja) had no Gemini field and didn't
  count it as a base URL; the ja docs lacked the table row, and all
  three said one of chat/responses/anthropic is required.

Run:
- TestParseImportGemini fails on the old importurl.go ("the link gives
  no base URL: it needs chat=, responses= or anthropic="), passes now;
  go test -run Import ./internal/provider/ ./internal/gui/: ok.
- import-link-gemini.test.cjs: 20/20 (chromium+webkit, en/zh/zh-TW/ja/de,
  1100 and 420 px); against the old app.js the warning reads "will go to
  ;" and it fails.
- docs builder (en/zh/ja) and handoff page in Chromium from file://: a
  gemini-only builder gives magpie://import?name=…&gemini=…, no errors;
  the handoff page lists gem.example under Sends to.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
Not tried: a real magpie://import click through the OS handler.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 06:07:43 +08:00
yetone 9916a94608 gateway, usage, plugins: OTel export is the first plugin on the gateway's observer point (P3)
P3 of docs/subsystems/plugin-runtime.md opens the gateway to plugins. The
observer point is first: it only reads, so it carries the least risk.
With plugins/otel off, the gateway exports nothing and does no observing
work. It keeps no reply whole and adds no request context.

- usage.Observer:
  - Methods: Serve, Bodies, Begin(Request) Watch and Ledger(Record). Watch
    has Attempt and End.
  - Observe(o) registers an observer until its remove is called.
  - ServeObservers is counted, and only Server.ListenAndServe calls it.
  - ObservedBodies takes the most any observer wants.
  - Record.SkipOTel becomes Watched, set by appendUsage for a request an
    observer watched.
- The gateway's otel.go becomes observe.go:
  - observeRequest asks each observer through Begin.
  - attempt and end call each Watch. Bodies are added only when an
    observer asks for them, and the whole reply only for WholeBodies.
- internal/otlp: the exporter (otel*.go) moves out of internal/usage, and
  the gateway's per-request span state moves into request.go. otlp.New()
  is an Exporter, a usage.Observer. What it sends is unchanged.
- plugins/otel:
  - Apply registers otlp.New() and disposes of it when turned off.
  - InUse is 1 while settings.OTelExport says to send. A user who exports
    only through MAGPIE_OTEL_* keeps the plugin on under Essentials.
- pluginrt.KeepFresh: the process serving the gateway refreshes every 2s
  when plugins.yml or settings.json changes. A switch made in the window or
  the CLI reaches a running gateway, or a headless serve, without a restart.
- docs: plugin-runtime.md gets a P3 section, a gateway runtime path and an
  updated failure section; reference.md says the export is the otel plugin.

Run at this tree on origin/main 82f48f093 (rebased onto 52ee84761 after,
which touches only the Linux tray icon):
- gofmt -l is clean. go vet passes on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -count=1 -timeout 25m ./...: ok, 55 packages, none failed.
- New tests:
  - usage: TestObserverServesWithTheGateway and TestObserverLedgerAndBodies.
  - gateway: TestObserverPoint, covering unwatched, no bodies, captured,
    whole and whole streamed.
  - plugins/otel: TestOnExportsOffSendsNothing (on, off, on, with a real
    collector) and TestInUseByEnvironment.
  - pluginrt: TestKeepFreshFollowsPluginsYml.
  - The OTel tests moved with their code to internal/otlp.

Broken by hand, each red, then restored:
- Apply without Observe, and without its dispose.
- KeepFresh refreshing only once.
- InUse reading settings.json only.
- Ledger keeping Watched rows: 3 gateway OTel tests red.
- ObservedBodies taking the last observer's answer.
- Observe not serving a late registration.
- appendUsage not setting Watched.
- Whole bodies never kept.
- Bodies always on with no observer asking.
2026-10-15 05:39:01 +08:00
Haogao Gu b476dc5a93 agent, gateway, gui: Claude Desktop's subagents can have a reasoning effort of their own
After #2081 gave Desktop a subagent model, its effort still came from the
request. Add subagent_effort beside that model, using the existing effort
slider. The live setting DesktopSubagentEffort belongs to magpie; no
Claude client file or binary is changed.

Empty preserves the request's effort, including disabled thinking. A pick
applies only to Desktop requests with an agent id and tools, independently
of model replacement: unset, equal and unavailable model picks all work.
Reuse the attempt-level fitting; fixed group-member efforts and reasonless
models keep their existing precedence. count_tokens applies the pick after
unmasked-body restoration. A Codex SubagentPick is not evidence of a
Desktop tool turn.

Route.Effort keeps the incoming level, SubagentEffort records the configured
pick, and tries/usage keep the actual level. Routing explains the pick
even without a model replacement. Options follow the target model; a
saved level survives a model change. POST /api/settings preserves it.
Disconnected preferences, Disconnect/reconnect and restored settings work;
a Live pick gives restart advice only when it actually connects the agent.
Codex's own settings and default-effort explanation are unchanged.

Verification on b9c589eb plus this change, with temp HOME and pinned Go
caches:
- go test -tags nogui ./...: 53 packages pass.
- Gateway effort tests under -race -count=20: pass.
- gofmt -l: empty; darwin, linux nogui and windows vet/build: exit 0.
- 23 intentional Go behavior breaks produce real FAILs, then pass
  restored: application, scope, model independence, Default/none,
  disabled thinking, fitting/member priority, counts, next request,
  trace, saving/validation, Live notices and model-dependent options.
- Three UI breaks fail in both engines at 1100/420: default explanation,
  missing effort story and missing translation. Restored: Desktop's new
  controls/story matrix passes 20/20 across five languages. Desktop,
  Codex, tier/effort and translation regressions pass 97/97.
- Desktop-bundled Claude Code 2.1.295 runs real Agent calls through the
  built gateway, temporary HOME and loopback-only sandbox, all replies
  local fixtures. Low/high/Default sends its child low/high/xhigh on m2;
  its lead remains xhigh on m1. All three runs exit 0.

The expanded Routing run is not green: Chromium 510/525, WebKit 485/525.
These failures reproduce on untouched b9c589eb, including targeted reruns.
The day/row anchor assertions conflict with #2134's at-top rule: undoing
that one guard makes all 12 tests pass. A narrow request lies below the
viewport; user wheel input makes the failed click pass. WorkBuddy's wheel
pointer/hidden-button failures overlap #2115; moving the wheel to the
view gutter fixes 3/4 selected cases, one WebKit 420 case remains.
The held-member clipping assertion also reproduces on base; its timing
cause is not established. This baseline evidence is reported separately
in the follow-up feature issue, not counted as passed or fixed here.

Not run: the complete GUI suite, the Electron window/Cowork, native
Linux/Windows or WebKitGTK. Cross-builds are not runtime checks.

Reported-by: Koohoko
2026-10-15 03:34:59 +08:00
JasonBuildAI 7c5bfd7a1d gateway: auto affinity keeps a conversation where a vendor's cache is kept without saying so (#2230, JasonBuildAI)
A vendor that keeps the prompt cached by itself and reports nothing of it —
OpenAI's automatic prefix cache, Gemini — says neither a read nor a write of
the turn that built the cache. affine judged that turn's stick by what the
reply read and wrote (0 + 0), found it under cacheWorth and moved the
conversation's second turn as "no-cache": the whole prompt went afresh to
another key or account and was paid for in full, on every turn after the
first, for anyone with more than one key or account and Affinity auto (the
default).

7f968b95b named this as not covered: "a vendor that caches without reporting
a write (OpenAI's automatic prefix cache, Gemini) still reports CacheWrite 0
on a first turn, so its second turn may still move".

What such a vendor holds of the conversation after a turn is the prompt that
turn was sent, which is what its cache now has. answered takes the reply's
usage rather than its two cache counts, and where the reply reports neither
a read nor a write, the prompt it was sent (Input) stands for the write: the
second turn stays to read it, as it does for a turn that wrote its cache. A
reply that reports no usage at all (Input 0) counts as no cache, as before,
and a prompt under cacheWorth (1024) still moves. A read or a write the
vendor does report is used as it was, and resting, spent, cold, strict, turn
and rotate are judged before this, so nothing else changes.

The observable change: with Affinity auto, a conversation whose last reply
reported neither a cache read nor a cache write, and was sent at least 1024
tokens, is kept where it was (Why "cache", Kept true) rather than moved
(Why "no-cache"). Its stick, affinity.json and the trace's
Affinity.CacheWrite carry the prompt sent, and Affinity.CacheRead stays 0,
which is what the Routing page shows as read and written; the page itself is
unchanged.

Tests:
- affinity_silent_cache_test.go (new): TestAffinityKeepsACacheTheVendorKept
  Silently. Two keys, least-used routing, and a Chat vendor reporting
  prompt_tokens 3000 with cached_tokens 0 — what OpenAI and Gemini send of a
  first turn — keeps the second turn on k1 as "cache", with the trace
  telling CacheRead 0 and CacheWrite 3000; a vendor reporting no usage at
  all still moves to k2 as "no-cache".
- TestAffinityKeepsACacheJustWritten, its "too little either way" (300/300,
  no-cache) case included, passes as it did.

Run:
- go test -tags nogui -count=1 -run TestAffinity ./internal/gateway: ok,
  80.982s (TestAffinity 39.36s, TestAffinityKeepsACacheJustWritten 26.54s,
  TestAffinityKeepsACacheTheVendorKeptSilently 9.68s).
- go test -tags nogui -count=1 -timeout 45m ./...: every package passes
  except 21 tests red on this Windows machine — agent 4
  (TestInstallWithoutNodeParses, TestWSLClaudeFollowerOnTheMainModelIsNoDrift,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI), gui 4
  (TestGatewayHeldByAContainer, TestGatewayFixQuitsOnlyAMagpie,
  TestFXStateDoesNotWait, TestUpdateThatWontStart), library 3
  (TestAgentsSkillsFolders, TestRemoveFoundSkill,
  TestHooksCodexTrustMovesWithTheGroups), gateway 2 (TestClaudeAsRootEnv,
  TestSweepBridgeProjectsTakesOnlyTheBridgesFolders) and one each in backup,
  davsync, pluginrt, provider, sessions, update and usage. A fresh worktree
  at the base e98440ae, without this change, fails the same 20 of them. The
  21st, gui's TestPurposeAssetMatchesUsage, fails only in this checkout,
  whose internal/gui/assets/purposes.js is CRLF (git says i/lf w/crlf) and so
  keeps the "\r" its TrimSuffix(";\n") doesn't cut; the file is not in this
  diff and the test passes in the base worktree.
- gofmt -l on the changed files: nothing. go vet ./..., GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./...: nothing. go build,
  GOOS=linux go build -tags nogui, GOOS=windows go build: ok.
- Broken by hand: with the substitution removed the new test fails —
  "silent cache: affinity &{... CacheRead:0 CacheWrite:0 ... Why:no-cache},
  want cache". At the base commit the case fails the same way, the second
  turn going to k2.

Not tried: the Playwright suite (no GUI asset changed; the Routing page
reads the same JSON) and a live OpenAI or Gemini key.
2026-10-15 03:34:58 +08:00
yetone 3d3a834d62 gateway: a held key its owner lets see quotas is told those of the providers and accounts it may use, not none (#2216, Kenoia)
#1981 refused every quota route to a gateway key held to a budget, models
or accounts, so a Remote magpie set up with such a key showed none of the
providers it may use. A key's owner can now let it be told them:
access.Key.Quotas, set from the key's new "Quotas" badge on the Gateway
page or `magpie gateway-key quotas <id> on|off`. Off stays the default,
so #1981's answer is unchanged for every key until its owner says so.

With it on, /v1/magpie/quotas (and ?kept=1), /quotas/history,
/quotas/cards and POST /quotas/refresh go through scopeQuotas
(internal/gateway/quotas_scope.go):
- a provider is told only when the key may use every model the catalog
  lists of it: a key with some of a provider's models is told nothing of
  it, since the models it may not use spend the same quota;
- of those, only cards of accounts and keys AllowsAccount lets it use,
  matched by the card's User against AccountIDs (a name two accounts
  share needs both; a card no account is known by only where the key's
  list names none of that provider's); a provider's only key's card,
  named by no one, is that key's;
- cards read from another magpie (From) are never told;
- a refresh of a card outside the scope is 403 gateway_key_held, one
  naming no card reads again only the scope's cards, not ReadAllCards;
- a scope with no card answers the cards routes 403 gateway_key_held, so
  the remote shows the key's own card rather than "nothing read".
/v1/magpie/concurrency and /v1/magpie/usage still refuse a held key.

Run at the reviewed head:
- gofmt -l: clean; go vet ./... (darwin), GOOS=linux -tags nogui,
  GOOS=windows: clean.
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, after the
  rebase onto 7be68467f (#2227's several limits; conflicts in access,
  the CLI usage and test, keys.js and providers-accounts.md resolved by
  keeping both): every package ok but internal/gateway, whose
  TestTranslatedSilenceStillTimesOut went red once at load ~95 (its
  400ms deadline also covers the response headers; filed #2248) and
  passed 5 of 5 alone. Before the rebase the whole suite was ok, with
  agent and gateway rerun at -timeout 40m after the 10m timeout under
  load.
- TestHeldKeyToldItsOwnQuotas (new): a provider-wide key sees A only,
  a key with A/m1 sees nothing of A, an account-held key sees only its
  key's card, a provider's only key, a key told nothing gets 403 from
  the cards route, Quotas-off still 403 everywhere, refreshes outside
  the scope 403. Broken by hand, each red: scope returned nil (every
  card told), every[id] forced true (partial models), the account check
  skipped, the refresh check removed, the only-key rule removed, and the
  told-none 403 removed. TestHeldKeyToldNoAccounts (#1981) still green.
- TestRemoteMagpieShowsHeldKeyItsQuotas (new): a magpie with this one as
  its Remote magpie provider, through a key held to alpha's Two, shows
  office/alpha's Two card beside the key's own; a key told none shows its
  own card alone. Red with the told-none 403 removed ("nothing read on
  that magpie yet").
- TestGatewayKeyQuotasCLI (new): show, on, off, bad values refused.
- GUI: gateway-key-quotas.test.cjs (new) in chromium and webkit, at 1100
  and 420, in en, zh, zh-TW, ja, de: 20/20; red when the badge sends the
  value it already has.
- The badge is a gateway key row's: off, it folds to no width until the
  row is hovered (the row had no room left at 390px: gateway-connect-keys
  went red in en until it did), and on a phone it is shown like the
  row's other controls (phone-rows went red until its rule won).
- GUI, 119 files matching gateway|key|usage|quota|remote|i18n|caller|
  web-|phone|narrow, both engines, concurrency 2: 1349/1385. The reds
  besides phone-rows (since fixed, above): quota-count-wrap and
  quota-name-translated webkit (#2228), usage-agents-hide (#2211) and
  usage-fold chromium en/zh (#2163), each red alike on a fresh
  origin/main. gateway-key-quotas, gateway-connect-keys, phone-rows and
  gateway-key-groups rerun: 38/38; after the rebase every gateway-*,
  phone-rows and key-limit file, both engines: 210/210.

Not tried: a real Remote magpie against a second machine with a held key;
the GUI badge in the Linux and Windows apps.
2026-10-15 02:29:11 +08:00
yetone f299faef48 gateway keys: a key holds several limits at once, every one must pass, and the 429 names the one that resets last (#2227, oxsean)
A key may now hold up to five limits, each in its own window (5 hours
and a week, say). A request needs every one: budget.Reserve checks
each, holds one reservation per window and settles each, and when some
are spent refuses with the spent limit that resets last, so
X-Magpie-Limit-Reset and Retry-After say when the key is really back.
Two limits in one window are refused (change that one instead).

Saved format: the first limit stays in "limit", which older magpie
reads, the rest go in "moreLimits". A file without moreLimits reads as
before.

- access: Change.Index adds (index = len), replaces (keeps its Since)
  or removes (nil) one limit; reset-limit-key with an index resets one,
  without resets all; the plain limit-key replaces all, as before.
- /v1/magpie/limit: "limit" is the binding one (what older clients
  read), "limits" is each. A remote key card shows a window per cap of
  each limit and falls back to "limit" from an older remote.
- CLI: magpie gateway-key limit <id> list | add <period> ... |
  remove <n> | reset [<n>]; the single-limit form still replaces all.
- GUI: the key's badge names the limit holding it most and "+N limit(s)",
  a line per limit under the row, and the editor has a tab per limit
  with Add a limit / Remove this limit. Strings in en, zh, zh-TW, ja, de.
- docs/reference.md and docs/subsystems/gateway-routing.md say so.

Run (worktree on e98440ae6, sandbox HOME):
- go test ./internal/access/ ./internal/budget/ ./internal/gateway/
  ./internal/cli/ ./internal/provider/ ./internal/gui/: all ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags=nogui, GOOS=windows
  on those packages: clean.
- GUI (Playwright 1.62.0) chromium and webkit: the new
  gateway-key-limits test (5 languages x 1100/420), gateway-key*,
  gateway-caller-keys, gateway-keys-off, gateway-own-key,
  gateway-connect-keys: 94/94; i18n-keys ok. quota-name-translated
  webkit en is red with HEAD's assets too, filed as #2228.
- Broken by hand, each went red: Reserve checking the first limit only;
  the refusal naming the first spent limit, not the latest reset; the
  endpoint without "limits"; every limit saved in moreLimits; duplicate
  windows allowed; the remote card ignoring "limits"; the CLI plain form
  adding instead of replacing; the GUI save without its index; the GUI
  badge taking the first limit.

Not tried: against a real remote magpie or real accounts. Known gaps:
two N-day cycle limits are both named "this cycle" on a remote card;
an older magpie that rewrites the keys file keeps only the first limit.
2026-10-15 01:54:28 +08:00
yetone 27a0458de1 gateway: /v1/magpie/concurrency lists each request in flight, its agent, model, start and phase, for a status bar's hover (#2132, bigbitbox)
The concurrency read now carries `active` beside requests/waiting/tools:
one entry per agent request counted for Busy, oldest first, [] when idle:
id, agent, model and provider (once routed, from the routing trace),
session when the agent sends one, started and ms, route (the trace id),
and phase only where the gateway knows it: "slot" waiting in a key's or
account's queue, "rpm" waiting for room in the minute, "upstream" while a
try is out at the vendor. No prompt, reply or key. The entry lives on the
request's context from `counted` (so a GET, this poll included, is never
listed), routing ties it to its first route in trace.beginFor, and
lanes.take / rpms.wait / the try loop note the phase, putting the one
before back when they return. Access is the endpoint's: this machine,
another with a gateway key, never a held key (TestHeldKeyToldNoAccounts).
Nothing in routing or limits reads it.

Run (worktree on e98440ae6, sandbox HOME, GOCACHE pinned):
- TestConcurrencyListsEachRequest (new): one request out and one of the
  same agent waiting for a one-slot provider; checks agent, model,
  provider, session, phase upstream/slot, no prompt or key, [] idle and
  after. Broken by hand, each goes red: active left out ("active left
  out or null"), the slot phase removed ("never one out and one
  waiting"), noteRoute removed (model/provider empty), the upstream
  phase removed (phase "").
- go test -race -count=5 -run 'TestConcurrency|TestBusy|TestMaxConcurrency|TestMaxRPM|TestHeldKey' ./internal/gateway: ok
- go test -tags nogui ./internal/gateway (-timeout 28m; 1394s on a loaded
  machine, the default 10m timeout cut the first run short), ./internal/proc,
  ./internal/usageapi: ok
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  on ./internal/gateway: clean
Not run: the full `go test ./...` (disk tight), a real SketchyBar hover;
no GUI change.
2026-10-15 01:13:18 +08:00
yetone 7f968b95dd gateway: auto affinity keeps a conversation on the cache its last reply wrote, not only one it read (vilicvane on Discord)
Affinity's auto mode kept a conversation on its last answerer across turns
only while that reply had read at least cacheWorth (1024) tokens from the
vendor's cache. A first turn reads nothing and writes the whole prompt
(Anthropic's cache_creation_input_tokens), so the second turn was moved as
"no-cache" and the cache just built was thrown away (vilicvane on Discord,
「会话保持 → 自动」: 「新的 cache 都建好了,再切走不可惜吗?」).

answered() is now given the usage's CacheWrite beside CacheRead (both
already parsed at that call site for every route: Anthropic, Chat's
cache_write_tokens / cache_creation_input_tokens, Cursor, Command Code,
plugins), and affine counts read + written against cacheWorth. The stick
keeps cacheWrite in memory and in affinity.json (`cacheWrite`, omitempty);
a file from before has no such field and reads as 0, so an old stick is
judged by its read alone, as before. The trace's Affinity carries
CacheWrite, and the Routing page's "cache" and "no-cache" explanations say
what was read and what was written (en, zh, zh-TW, ja, de).

Not covered: a vendor that caches without reporting a write (OpenAI's
automatic prefix cache, Gemini) still reports CacheWrite 0 on a first turn,
so its second turn may still move. Noted in gateway-routing.md.

Docs: docs/subsystems/gateway-routing.md (affinity bullet), docs/reference.md
(step 6 of how magpie picks an account).

Run:
- TestAffinityKeepsACacheJustWritten (new): an Anthropic Messages upstream
  streaming cache_creation_input_tokens 3000 / read 0; the second turn is
  kept as "cache", also across a restart (affinity.json reloaded); 600+600
  is kept, 300+300 moves as "no-cache". Broken by hand twice and watched
  red: the old `st.cacheRead < cacheWorth` (written: why no-cache), and
  stickOf not reading CacheWrite from the file (restarted: no-cache).
- routing-affinity-cache-write.test.cjs (new): chromium and webkit, 1100
  and 420 wide, en/zh/zh-TW/ja/de, 20/20 pass; red on the old routing.js
  and i18n.js. i18n-keys.test.cjs and routing-account-identity.test.cjs
  pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows for
  internal/gateway.
- go test ./internal/gateway/...: all pass except
  TestAgentGoneInTheRetryPause/group_replan, which failed in two full runs
  at load average 150-380 and passes alone (-count=3); its fixed 100ms
  sleep before cancelling assumes the pause has begun. Filed as #2175; it
  never reaches the affinity path this changes (a first request).
- go test -timeout 40m ./... at load ~300-377: 50 packages ok; agent and
  gateway hit the 40m package timeout (no test failed before it); gui's
  TestSetAnswersWhileDevinAndProvidersHang (#1375) and
  TestMainWindowCorners (#1936) failed, both filed load reds.
  internal/agent rerun alone: ok (1008s at load ~200).
- Not tried against a real Anthropic account.
2026-10-14 21:05:26 +08:00
yetone 22512cde53 provider, gateway: rest-cap off never rests a provider's keys after an unknown failure (Kismet Alan on Discord)
A relay or account pool fails now and then with errors that say nothing
of why (a 5xx, a dropped connection), and the next request often goes
through. Every such failure rested the key or account a minute, doubling
up to 10, and `rest-cap` could only move that cap (1 minute at least;
`off` read as `default`).

`magpie provider rest-cap <id> off` (provider.RestCapOff, restCap: -1 in
providers.json) now has a failure that says nothing of why (failOther)
rest nobody and not count toward the backoff: restAfterMarked returns a
Rest by "off" with no time left. What says why still rests as before: a
401 or 403, a model not served (restID), an account's window full, a
rate limit (magpie's own 30-minute cap; RestCapOr treats off as unset),
quota, credit, a restriction. `rest-cap <id> 30s` is turned away and names
1m and off (the first rest is a minute already). The Routing page tells a
try rested by "off" as not resting (one new string, zh/zh-TW/ja/de).
No "fail N times before switching" counter: a failed try already moves
the same request on to the next key or member, so a count would only
keep requests on a failing upstream longer.

Run:
- TestRestCapOff (gateway), TestRestCapCmd (cli), TestOwnRestCap: pass;
  each goes red with the change taken out by hand (the early return
  disabled: "#1 500: rests 59.99s by backoff"; restMinutes in place of
  restCapMinutes: "off: <nil> 0").
- routing-rest-off.test.cjs: 20/20 (chromium, webkit; 1100, 420; en zh
  zh-TW ja de); red 10/10 with the "off" case renamed.
  routing-wb-restricted 20/20. rest-try-now and routing-model-rest fail
  a varying few under load average 200-420 here, and fail more on
  origin/main 331c27703 run at the same time; neither reads "off".
- gofmt -l clean; go vet darwin (provider, gateway, cli, gui), GOOS=linux
  -tags nogui and GOOS=windows (provider, gateway, cli).
- go test ./... with pipefail, sandbox HOME: every package ok except
  agent, gateway and library, which hit the 10m timeout under load
  average ~200 (no test hung: each stack shows a different test seconds
  in). Rerun with a longer -timeout: library ok (603s), gateway ok
  (1572s) and agent ok (1457s).
Not tried: a real relay; the change is in the rest bookkeeping only.
2026-10-14 20:49:20 +08:00
yetone 8c5190a203 provider: a routing group keeps its thinking members' levels beside a member known not to think, so Codex shows its effort control (#2127, cnlove7777777-art)
#2127: with a routing group as its model, Codex showed an effort but no
control to change it, and new sessions and subagents ran at medium. A
group offers agents the levels its members have in common
(groupEntries), and a member magpie knows doesn't think (Entry.Quiet: its
vendor's list says no reasoning) counted as having none, so the
intersection came out empty. The group still reasons when one member
does, so Codex got its entry with reasoning but no
supported_reasoning_levels and no default_reasoning_level: no slider,
and Codex's own medium.

Since #950 the gateway sends such a member no reasoning ask at all
(withoutReasoningAsk, quiet.go), as it does a reasonless one (f074996d9)
and as it handles a member whose levels nothing knows (#597), so its
having no levels is no reason to take the others' away. groupEntries now
skips it like those two. The group's levels are those of its members
that think; Group.Levels and fixed-effort members are unchanged.

Tests: TestGroupQuietMemberKeepsCodexEffortControl builds the Codex
catalog (codexcat.Catalog(CodexListed())) for a group of a models.dev
reasoning:false model and one with levels, and wants the levels and
default (high, and max when config.toml asks max); TestGroupReasoningLevels
gains "quiet between". Both fail on the old group.go (levels [], default
""). TestGroupLevelsWithUnknownMember's "plain" group and
TestModelsListReasoning's group/auto-mixed encoded the old rule and now
want the thinking member's levels. docs/reference.md and
gateway-routing.md say the new rule.

Run (worktree on origin/main bda271999, private GOCACHE): gofmt -l clean;
go vet (darwin), GOOS=linux -tags nogui and GOOS=windows go vet of
internal/provider clean; go test -count=1 ./internal/provider
./internal/gateway ./internal/agent ./internal/codexcat ok.
Not tried: a real Codex session against the reporter's groups (their
config isn't known; a group with a non-thinking member is the case that
produces exactly what they describe).
2026-10-14 18:14:17 +08:00
yetone 4faa931325 provider: Vertex AI's preset offers Gemini 4 Argon at global, and its test asks it at low (#2155, TomXPRIME)
Gemini 4 Argon went live on Vertex AI's global location on 2026-10-13
(gemini-4-argon), and the preset's fixed list (Vertex has no list to ask)
didn't have it, so a fetch never showed it. It is added to the preset's
models, which are global's; us, eu and the regions are left as they
answered on 2026-10-06, since nothing says Argon is served there (typed
in by hand it still goes).

Its metadata (1,048,576 context, 65,536 output, low/medium/high, $2/$10)
comes from models.dev's google-vertex entry, which lists it as of today,
so nothing is hard-coded here. The gateway already tells Gemini 4 a
thinking level at the level asked (52be997b3, #2083), medium as medium.

The model test (vertexTest) only told gemini-3* a thinking level; Argon
got none, so it would think at its default medium against a 16-token
budget. It is now told low like every Gemini 3 and later
(vertexGeneration), and an id naming no generation (gemini-flash-latest)
still gets none.

Run: go test -tags nogui ./internal/provider/ (full package, ok);
TestVertexTestRequest goes red on the old gemini-3 prefix check with the
new argon row; gofmt; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
Not tried: a real Vertex AI project (no Google Cloud credentials here).
2026-10-14 17:44:03 +08:00
yetone 7d4ad7c628 gui: the menu bar's total is every token, cache too, marked Σ, as the Requests tab sums it (NextCommit)
NextCommit on Discord: the menu bar's usage showed only input tokens, and
more input than the Usage page. It showed input + output, unlabelled, so
it read as the input and came out above the page's input. And it was summed
as the Overview sums (usage.SummarizeTop: the gateway's calls only, cache
aside), while a click opens the panel's Usage tab, which sums the ledger
(the agents' own session-file calls too) and counts the cache's tokens
in its Tokens. Two numbers under one name.

- trayTotalSum is the ledger's cached sum, usage.QueryPage(p, {}, 0, 1).Sum,
  the one the panel's Usage tab and the window's Requests tab show.
- The cell's top row is every token (in + out + cache read + write, as
  allTokens) prefixed Σ; the cost stays under it. The tooltip spells out
  "N tokens (a in · b out · c cached)".
- With the window as the tray's, a click opens the Requests tab at the
  period (quotaView), not the Overview, which sums differently.
- docs/reference.md and gui-shell.md say so.

Run:
- TestTrayTotalIsTheLedgers (new): a Codex session-file call of 1000 in,
  200 out, 8000 cache read; the menu bar's sum equals ledgerPage's and the
  cell reads Σ9.2K. With trayTotalSum put back to SummarizeTop it fails
  (menu bar all zeros, ledger 1 call).
- TestTrayTotals/BesideCards updated for Σ, the cache and tab=requests.
- go test -tags nogui ./internal/gui (sandbox HOME via the package): ok.
- tray-totals, tray-usages, tray-cell-click .test.cjs, chromium and
  webkit, five languages, 1100 and 420: 70 pass.
- The Mac cell rendered with trayImagePNG and looked at: "Σ6.3M" over
  "$3.40", "Σ47M" alone, both inside the row width.
- gofmt -l, go vet darwin, GOOS=linux -tags nogui, GOOS=windows; builds.
Not tried: the real menu bar on the reporter's data.
2026-10-14 17:29:43 +08:00
yetone 1a5128747b cli: magpie provider refresh-every and auto-include set a list's schedule and rules (#2135)
`magpie provider refresh-every <id> 6h|1d|off` and
`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'|none` set the
fields the previous commit added; `magpie provider <id>` shows them, and
`magpie provider refresh` prints the models its rules took.

TestRefreshEveryAndAutoIncludeCmds: a too-short or unreadable time and
a plain id as a rule are refused, the rule takes the current matches,
and none/off clear both while keeping the picks. Run with the go test
in the previous commit's body.
2026-10-14 16:40:24 +08:00
yetone 3b6ca05571 gateway: /v1/magpie/concurrency tells the whole gateway's requests in flight, waiting and tool turns, 0 when idle, with or without a limit (#2132, bigbitbox)
A status bar (SketchyBar) polling /v1/magpie/concurrency got
{"data":{},"object":"concurrency"} with no limit set: the lanes hold only
keys and accounts with a limit, so an idle gateway and a busy one with no
limits read the same. The answer now carries, beside data:
- requests: Busy().Requests, every agent request in flight, those waiting
  for a slot among them; a GET (this poll included) is never counted;
- waiting: how many of those wait for a slot, summed over the lanes;
- tools: Claude subscription turns waiting on their caller's tool results.
Each is 0 when idle. Access is unchanged: this machine, another only with a
gateway key, a held key refused (refuseHeld). docs/reference.md says so
beside the usage API.

Run: TestConcurrencyTellsTheWholeGateway (new) fails without the change
("idle: tools = <nil>, want 0 (map[data:map[] object:concurrency])") and
passes with it, -count=5; it covers no limit anywhere (the reporter's
case), and three in flight on a one-slot provider with one waiting.
gofmt -l (nothing); go vet, GOOS=linux go vet -tags nogui, GOOS=windows go
vet on internal/gateway (ok). go test -tags nogui -count=1 ./internal/gateway
in a sandbox HOME: ok in 835s with -timeout 40m (on 0ad9661b6; the default
10m ran out while three other gateway suites ran on this machine), then
the concurrency, busy, held-key and LAN tests -count=3 after rebasing on
63ad2b7c7 (ok).
Not tried: SketchyBar itself.
2026-10-14 16:05:13 +08:00
Haogao Gu 20350dafaf gateway, agent, gui: Claude Desktop's subagents can be held to one model, set in its row on the Agents page
Claude Code in a terminal holds every subagent to one model through
CLAUDE_CODE_SUBAGENT_MODEL (its "subagents" field), and Codex through
magpie's own setting (settings.CodexSubagentModel). Claude Desktop runs
its Code tab's Claude Code with CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1,
and Claude Code 2.1.295 then ignores CLAUDE_CODE_SUBAGENT_MODEL,
CLAUDE_CODE_SUBAGENT_MODEL_FORCE and the tier variables in its settings
files ("Ignoring … this session's provider routing is managed by the
host"). The env Desktop 2.31226 builds for the Code tab has no key for it
either. So Desktop's subagents ran on the lead's model or on a tier's, and
only the tiers could be picked.

Claude Desktop's row now has a "subagent model" square, the same square
and strings as Codex's. It is magpie's setting
(settings.DesktopSubagentModel), which the gateway applies
(desktopSubagentPick):

- Only a claude-desktop request with x-claude-code-agent-id and tools is
  moved: a subagent's turn. The lead's turns, the tool-less helper calls
  Claude Code makes inside a subagent (on the haiku tier's model),
  terminal Claude Code and every other agent stay as asked.
- It is applied after desktopTurn, the tiers and the groups. A turn
  already on the model set isn't marked as moved. Route.Subagent,
  Route.Model and the ledger's Requested keep the model asked for; Kind
  stays empty.
- The model set must be served by its exact id (Resolve takes any model
  name under a provider that is on), enabled, and allowed to a gateway key
  held to some models (groupAllowed for a group). Otherwise the subagent
  stays on the model asked for and the trace says why, in the reasons
  Codex's subagent model already has.
- count_tokens counts on the same model.
- It is read on each request, so Desktop needn't restart. The field is
  Live (a new Field flag): /api/set and `magpie <agent> <field> <value>`
  leave Desktop's restart notice out after it, unless the pick connected
  Desktop. Codex's subagent model is unchanged.
- The getter follows a provider renamed since it was set (RenamedRef).
  The setter takes any provider/model or group/<id>, also one not served
  now (a restored profile), refuses a bare name, and keeps a Desktop
  alias by its catalog id. Options are shown while Desktop is on magpie.
- POST /api/settings keeps it; a stopped WSL distro's field copy keeps
  Live.
- The Routing page says why a Desktop subagent was moved or kept
  (subagentWhy, for a route with a subagent pick and no kind). "it is
  disabled in magpie" gets its zh, zh-TW, ja and de, which Codex's kept
  reason lacked as well.
- Unset, the pick costs one held settings read (no body decode, no
  catalog build).

Not changed: a Desktop on another computer that reaches magpie with a
named gateway key is read as Claude Code (agentOf), so none of Desktop's
routing applies to it, this included. There is no fallback when the model
set has a smaller window than the lead's.

Verified at this head, on 20769439, under a temporary HOME with Go's
caches pinned:
- Each new test fails with the guarantee it names broken by hand (a real
  FAIL, not a compile error), then passes restored. 48 Go breaks were
  first run on 8f34bbcd: settings trim and bare-name refusal; setter
  validation and clear; RenamedRef in the getter and in Unserved; the
  exact served check and served groups; the serve pick, each guard
  (agent id, tools, claude-desktop only, unset, same and resolved model);
  the named id kept in Route.Model, Kind and the ledger's Requested; each
  kept reason (unserved, disabled, held model, held group); groupAllowed;
  the next request reading a change; the session pick kept; count_tokens;
  the unset pick allocating; Live on the field, not on the tiers or on
  Codex's, copied by WSL; options while unwired and wired; alias
  conversion; the settings keep line; the GUI and CLI notice rules.
  Re-run at this head:
  - no tools guard: TestDesktopSubagentLeavesOtherRequests/helper,
    `sent "m2", want m1`
  - no agent-id guard: TestDesktopSubagentLeavesOtherRequests/lead,
    `sent "m2", want m1`
  - no count_tokens pick: TestDesktopSubagentCountTokens,
    `count sent "m1" to "/v1/messages/count_tokens", want m2`
  - Resolve instead of the exact served check: TestDesktopSubagentUnserved,
    `fake/missing: "", want "magpie doesn't serve it now"`
  - no Live rule in /api/set: TestDesktopSubagentModelNotice (gui),
    `wired Live pick notice "Claude Desktop reads this at start-up …"`
  - no keep line in POST /api/settings: TestSettingsSaveKeepsWhatItDoesNotSend,
    `DesktopSubagentModel:  after a save of the Settings page, was fake/m2`
  GUI breaks (0 pass / 2 fail in each engine): renderSteps' new aside
  removed (Desktop's moved story missing); the four "it is disabled in
  magpie" translations removed (the kept story keeps the English reason);
  the Default note's translation removed.
- go test -tags nogui ./...: 52 packages ok, no failure.
- go test -race -count=20 -run '^TestDesktopSubagent' ./internal/gateway: ok.
- gofmt -l on the changed files: nothing. go vet ./...,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...,
  go build, GOOS=linux go build -tags nogui, GOOS=windows go build: exit 0.
- Playwright 1.62.1: desktop-subagent-model.test.cjs (en, zh, zh-TW, ja,
  de; 1100 and 560 wide) with codex-subagent-model, codex-subagents-lead,
  codex-start-model-field, desktop-tiers, desktop-model-menu,
  subagent-effort and every routing-*.test.cjs: 472/472 in Chromium and
  in WebKit. The whole suite: Chromium 4580/4580; WebKit 4570/4572. The
  two are red on 20769439 untouched as well: group-fold.test.cjs 3 of 3
  alone (195a1009b, fixed upstream since by a125d5c9), usage-fold.test.cjs
  4 of 9 alone there and 4 of 9 here ("as many accounts on the first
  screen as before the curves: 12 of 29").
- The built binary in a temporary HOME, `magpie serve` on a free port, a
  fake Anthropic upstream, requests shaped like Desktop's Claude Code:
  `magpie claude-desktop subagent_model fake/m2` printed no restart
  advice; a subagent's turn and its count went to m2; the lead's turn,
  a subagent's tool-less call, terminal Claude Code's and a subagent turn
  after `… subagent_model default` went to m1; claude-desktop.model stayed
  fake/m1; the ledger kept requested fake/m1.
- Not tried: a real Claude Desktop or Cowork (that needs the live
  gateway), Linux and Windows machines (GOOS vet and build only),
  WebKitGTK.

Maintainer's review on origin/main c4c3cafa2 (#2081), under a scratchpad
HOME with Go's caches pinned, machine load 120-330:
- Claude Code 2.1.299's bundled source has the "Ignoring … this
  session's provider routing is managed by the host" path, with
  CLAUDE_CODE_SUBAGENT_MODEL_FORCE in the set it ignores.
- Breaks re-run: no tools guard -> TestDesktopSubagentLeavesOtherRequests/
  helper `sent "m2", want m1` and TestDesktopSubagentCountTokens helper
  count; no count_tokens pick -> TestDesktopSubagentCountTokens `count
  sent "m1" … want m2`; the Routing page's subagentWhy aside removed ->
  desktop-subagent-model 0 pass / 2 fail (webkit, zh).
- go test -tags nogui ./internal/{gateway,agent,settings,gui,cli,provider}:
  ok on 2fbbd1694 (agent with -timeout 40m: 1857s under the load; the
  default 10m timed out mid TestClaudeNewSessionEffortLastsModelSwitch, a
  test this change doesn't touch). After rebasing onto c4c3cafa2, the
  Desktop/Subagent/SettingsSave/Live/Notice tests of those six packages: ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok.
- desktop-subagent-model.test.cjs now runs at 1100 and 420 (was 560):
  20/20, chromium and webkit, en zh zh-TW ja de. codex-subagent-model,
  desktop-tiers, routing-purpose-state, routing-request-model,
  routing-sealed-task: all pass in both engines.
- usage-fold's "29 accounts" case passed 4 of 4 alone in WebKit here.
- Not repeated: the author's built-binary run; a real Claude Desktop or
  Cowork; Linux and Windows machines.

Decisions on the author's questions: Live is kept as named, and Codex's
subagent model is left as it is; a subagent's tool-less helper calls stay
on the model they asked for, being Claude Code's own housekeeping rather
than the subagent's work.

Reported-by: Koohoko (#2081)
2026-10-14 15:48:19 +08:00
yetone f70c0525aa access, gui, cli: a gateway key's limit can run every N hours, a 5-hour cycle among them (#2102)
A key's limit window was a calendar day, week or month, or every N days
(#1509). #2102 asks for a shorter cycle, every 5 hours, like a vendor's
own 5-hour window. Limit gains period "hours" with Hours (1..8760),
counted in absolute time from Since, as the N-day cycle is; a change to
N or from days restarts the cycle, a cap change keeps it, Reset starts
a new one. Budget status, the 429's wording ("this 5-hour cycle"),
X-Magpie-Limit-Reset, /v1/magpie/limit and a remote magpie's key card
carry Hours. The GUI's window menu has "Every N hours" with an Hours
field beside it (no native select); the CLI takes `<N>h`
(magpie gateway-key limit <id> 5h --tokens 200k). Docs: reference.md
and docker.html (en, zh, ja). Strings in zh, zh-TW, ja, de.

Run:
- go test ./internal/access (TestLimitHoursCycle across NY DST, UTC,
  UTC+8; TestLimitHoursSetAndReset), -tags nogui ./internal/cli
  (5h, rejects 0h/8761h/xh/1.5h/hours), ./internal/gateway
  (TestKeyLimitHoursCycle: 429 and reset header, /v1/magpie/limit,
  Reserve at the boundary, Reset; remote key card 5h), plus the full
  access, budget, cli, gateway, provider and gui packages. The gateway
  package hit go test's 10-minute default once with the load average
  near 270; rerun with -timeout 40m it passed in 1536s.
- Broke cycle() for hours by hand: TestLimitHoursSetAndReset and
  TestKeyLimitHoursCycle went red; restored.
- GUI: gateway-key-cycle (extended with the hours case: menu, field,
  validation, Save body, badge, Reset confirm, one-column at 500px)
  in chromium and webkit x en/zh/zh-TW/ja/de, 10/10; i18n-keys,
  gateway-key-limit, gateway-caller-keys, phone-rows, gateway-keys-off,
  gateway-own-key, api-key-theme 63/63; an ad-hoc check of the hours
  editor at 1100 and 420 in both engines and 5 languages (no overflow,
  screenshots looked at).
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: a real gateway under load across a 5-hour boundary; the
Windows box.
2026-10-14 15:34:31 +08:00
yetoneandfchengyan 62378c5f84 cli, usage: magpie usage takes --last <dur> and --days <n>, a window ending now, with or without --csv and --account (#2075, tinysnake, fcy222fcy)
today, 7d and 30d begin at a local midnight, so a caller wanting "the
last few hours" just after midnight had to take 7d's CSV, seven days of
rows for one. `magpie usage [--csv [--account <name>]] --last 24h` (any
Go duration, 90m) or `--days 1.5` now reads a window that began that
long ago; the presets are unchanged.

From fcy222fcy's branch (usage-rolling-window, 60472c661): a rolling
window is a period "last:<dur>" (usage.LastOf / Period.Last) that Since,
Known, shown and the chart's timeline answer for, so the ledger, Direct
and the summary read the same window.

Review fixes on top:
- a summary of a rolling window is worked out each time, like a picked
  range: kept, its start didn't move with the clock while the log
  stayed the same (reachable through the web API's ?period=last:24h);
- the CSV export's file name has no colon from "last:24h0m0s", which
  Windows refuses;
- `--last 24h 7d` is refused rather than silently taking --last;
- --days refuses NaN, Inf and over a century;
- the help line and docs/reference.md name the flags.

Run: new TestRollingWindowIsNotKeptStale fails with the cache fix taken
out ("an hour later: 1 calls, want 0"); TestCSVStamp fails without the
colon fix ("magpie-requests-last:24h0m0s-2026-09-30");
TestUsageRollingWindowRejectsJunk fails without the preset/--days
checks; TestUsageRollingWindow and the new ...WithAccount fail (3 rows,
want 2) with Since moved back. go test -tags nogui ./internal/usage/...
./internal/cli/... ./internal/usageapi/... ./internal/gui/... in a
sandbox HOME: ok. gofmt -l clean; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows; go build darwin, linux nogui, windows.
Real use: the built binary on a sandbox HOME with a generated 50,000-call
7-day usage.jsonl: --csv 7d 47,233 rows / 6.97 MB; today 4,376; --last
24h 7,140 / 1.05 MB; --last 90m 444; --days 1.5 10,712; --account me@x
--last 24h 3,570 (that account's half); oldest row of each at the
window's start.
Not tried: the full go test ./... suite; the process still parses the
whole usage.jsonl into its in-memory index on each run (as every period
does), so the cut is in rows decoded and written, not bytes read.

Co-authored-by: fchengyan <3181088318@qq.com>
2026-10-14 15:26:28 +08:00
yetone 11b1fb1db7 cli: magpie quota refresh <provider> [<account>] reads that card again, as its refresh button does (#2104)
magpie quota refresh <provider> [<account>] [--json] runs the Usage card's
refresh (RefreshUsage's path) from a terminal and prints that card alone;
no other vendor is asked. provider.RefreshReport returns the read's own
cards (refreshCards, shared with RefreshUsage), since a fresh process's
caches don't hold a partial read's subscription and plan cards. A second
refresh of the same card within 30s asks nobody and prints the kept
reading, saying so on stderr; the times live in the cache dir's
quota-refresh.json, so the gap holds across processes. --json prints
magpie quota --json's shape, with readAt and error. The account may be a
login, an alias or <provider>/<account>.

Run:
- go test -tags nogui ./internal/cli ./internal/provider ./internal/tui:
  ok (provider 591s under load ~200; an earlier run hit the 600s default
  timeout, the rerun with -timeout 25m passed)
- TestQuotaRefreshReadsOneCard / TestQuotaRefreshGapPerCard; with the gap
  check disabled by hand the first goes red ("asked a 2 times")
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on the
  three packages
- the built binary in a sandbox HOME (MAGPIE_ADDR=127.0.0.1:47614) against
  a local fake balance endpoint: refresh free-relay showed 12.50; a second
  run at once didn't hit the endpoint and said so; after 31s it read 11.00;
  "Free Relay" resolved by name; --json carried readAt, and a 404 gave
  "error": "404 Not Found"; an unknown provider exits 1.

Not tried: a real subscription (Codex, Claude) or a remote magpie's cards.
Reading from the caches instead of RefreshReport doesn't turn the test red
for a key balance (its cache holds the read in-process); the subscription
path that needs it is covered by reading only, not by a test.
2026-10-14 15:02:15 +08:00
yetone d9ca84a2f4 gateway: built-in TLS, magpie serve/web/daemon install --tls-cert --tls-key, reloaded on renewal (RoderickZH)
magpie serve, magpie web and magpie daemon install take --tls-cert <file>
--tls-key <file> (or MAGPIE_TLS_CERT / MAGPIE_TLS_KEY). The gateway and the
web UI on its listener then serve HTTPS to other computers. Without them
nothing changes.

- Half a pair, a file that doesn't parse, or a flag with no value is
  refused at start with a message naming the missing flag.
- The pair is re-read when either file's mtime or size changes (certbot
  renewal), with no restart. A renewal that doesn't parse keeps the
  certificate already served and is logged once.
- Other computers get HTTPS only. Plain HTTP from them gets net/http's
  400 "Client sent an HTTP request to an HTTPS server".
- This computer (loopback, or a peer address equal to the local one) may
  still use plain http on the same port. Its connections are sniffed on
  their own goroutine (a first byte of 0x16 is TLS) for up to 10s, so a
  silent client holds nobody else up. gateway.URL() stays
  http://127.0.0.1:<port>, which agents, MCP servers, ServedBy, the
  healthcheck and daemon status all use, and no certificate covers
  loopback.
- WSL NAT and containers count as other computers.
- ALPN is http/1.1 only (hijacked connections and websockets need it), with
  TLS 1.2 as the minimum.
- Printed links, LAN addresses, publicURL, the serve/web banners and
  daemon install show https:// for other computers' addresses.
- The DNS-rebinding Host checks (foreignPage, rebound, the MCP
  loopbackHost) don't depend on the scheme and are unchanged.
- daemon install carries MAGPIE_TLS_* into the unit or plist. A reinstall
  or `daemon web on` that names no certificate keeps the installed pair,
  and --no-tls removes it.
- Docs: reference.md gets an HTTPS section that names Caddy as the
  alternative, gateway-routing.md gets a TLS row, and docker.html (en,
  zh, ja) gets the env rows.

What was run:
- New tests: internal/gateway/tls_test.go (others HTTPS-only, this
  computer both, a silent local client holds no other, renewed
  certificate served, CheckTLS, addresses, Relisten keeps TLS),
  internal/cli/tls_cli_test.go and daemon TestInstallCarriesTLS (linux
  and darwin, paths with space, %, & and ").
- Each was broken by hand and went red: no wrap in listen, no reload, a
  synchronous sniff, a bad renewal dropping the certificate, http in
  publicURL or the pinned LANURLs, the carried entries removed, and
  keepTLS as a no-op.
- Real use under a sandbox HOME, with a self-signed pair, on
  0.0.0.0:3461:
  - Half a pair, a garbage certificate, a flag with no value, and the
    env set to half a pair each exit 1 with the message.
  - curl -k https://127.0.0.1 and https://<LAN IP>/v1/models with a key:
    200. Plain http on loopback: 200.
  - The cert files were swapped for a second pair while it ran.
    openssl s_client then showed the new CN and serial, and curl
    --cacert with the new pair got 200. A junk key file then kept the
    second pair, logged once.
  - From the Windows box over the LAN: plain http got 400; https with
    the key got 200, and without it 401.
  - magpie web --addr 0.0.0.0:3462: https network links. From Windows,
    http got 400 and https with the key got 303.
- gofmt -l clean. go vet passed on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -tags nogui for ./internal/cli, ./internal/daemon, and the TLS
  tests of ./internal/gateway and ./internal/gui: all pass at the rebased
  head.
- Two reds in the full suite (`go test -tags nogui ./...`) are the same
  on origin/main f074996d9; both are filed:
  - TestGatewayHeldByAContainer failed 2 of 5 there (#2107).
  - The gateway package runs past go test's default 10m under load:
    1208s on main and 1221s here, both passing with -timeout 40m
    (#2108).
2026-10-14 13:36:03 +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 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 2076943915 plugin: a plugin declares its own switches, shown in its provider's editor and read by the plugin (#2038, Vocllum)
Vocllum asked that a plugin can offer the user generic on/off options
without magpie knowing what each one is for. A plugin now declares them
on its auth hook, beside checkin:

  auth.options: [{ key, label, description?, default?, confirm? }]

and reads the user's values through input.magpie.option(provider, key)
or input.magpie.options(provider). Each call reads the current values,
so a change reaches the plugin without a restart. magpie only keeps the
value and hands it over: nothing is scheduled or run when an option
changes. The check-in switch (settings.pluginCheckins) and the check-in
plugins are unchanged.

- host.js: optionsOf keeps a key matching [a-z0-9_-]{1,40} with a
  non-empty label, drops repeats, caps the label at 60 characters and
  the description and confirm at 300, takes default only when it is
  true, and keeps at most 16. The values come at init and through
  setProviderOptions.
- Go: plugin.Option, Provider.Options, OptionOn and SetProviderOptions
  (sent only to a host that is running). settings.PluginOptions is kept
  by the plugin's provider id, then the key. POST
  /api/settings/plugin-option {provider, key, on} checks the key the same
  way and hands the values to the host. The generic settings save keeps
  them, as it keeps PluginCheckins. /api/providers' plugins[].options
  carry each option's resolved `on`.
- GUI: a "Plugin options" field in a plugin provider's editor. Each
  option is a segs Off/On beside the plugin's label and description, put
  in with textContent. A confirm text is asked through confirmAction
  before turning an option on. Changes wait for Save, which posts each
  one before the provider. Strings are added for zh, zh-TW, ja and de.
- Docs: provider-plugins.md (a new section), reference.md, gui-shell.md
  and the tests README.

Run:
- TestPluginOptions (a real host with testdata/options). Red with the
  old host.js (no options listed) and red with setProviderOptions turned
  into a no-op (the plugin still reads the old value).
- TestPluginOptionSetting and TestSettingsSaveKeepsWhatItDoesNotSend.
  Both red with the generic save's PluginOptions line removed.
- plugin-options.test.cjs: 22/22 in Chromium and WebKit, at 1100 and 420
  wide, in en, zh, zh-TW, ja and de. Red on the old app.js (no field).
  The screenshots were looked at: long text wraps and the page has no
  sideways scroll at 420.
- provider-concurrency, plugin-signin, plugin-checkin, provider-price-rate
  and plugin-move-unserved: 68/68.
- go test ./internal/plugin/... ./internal/settings/... ./internal/gui/...
  ./internal/provider/..., gofmt -l, and go vet on darwin, linux
  (-tags nogui) and windows.

Not tried with a real community plugin, since none declares options yet.
The check-in row doesn't take a plugin-declared label or hint; it is
left as it was.
2026-10-14 08:50:41 +08:00
yetone 82f3befd29 daemon: magpie daemon install --web serves the browser page from the service, with a link that lasts (HuanCheng Bai)
HuanCheng Bai on Discord runs `magpie daemon` on a Linux server and asked
for the daemon to serve the web page too, or for an option to turn it on.
`magpie web` run beside it is a second process, and he read it as not
seeing the daemon's state.

- `magpie serve --web[=host:port]` serves the gateway and `magpie web`'s
  page from one process (stats, StartWeb, Wait). The default page address
  is 127.0.0.1:3430. Any other argument is refused, where before it was
  ignored.
- `magpie daemon install --web | --lan | --addr host:port | --no-web` and
  `magpie daemon web [on|off] [--lan] [--addr host:port]`. The unit's
  ExecStart and the plist's ProgramArguments become `serve --web=<addr>`,
  and the key goes into the 0600 file's environment as MAGPIE_WEB_KEY. The
  key is made once. A reinstall with no flags keeps the page and its key
  (read back from the file by daemon.Web), so the link survives restarts
  and reinstalls. `web off` drops it. MAGPIE_WEB_KEY in the shell, when
  set, is used and checked like magpie web's. The page defaults to
  loopback; --lan or a non-loopback --addr prints the network links and
  magpie web --lan's warning.
- `magpie daemon status`, install and `daemon web` print the page's link.
- `magpie web` while the service serves a page prints that page's link and
  exits. Beside a gateway another magpie serves, it says so and points to
  `magpie daemon web on`.
- docs/reference.md (the service section and the Use list), and the
  site's start page (en, zh, ja). The READMEs don't cover the daemon.

Run:
- Tests: TestInstallWithWeb (systemd and launchd, plutil lint, read back,
  reinstall without the page, the shell's key not carried, no key
  refused), TestWebNotInstalled, TestParseDaemon, TestWebOptions,
  TestDaemonStatusPrintsPage and TestServeArgs. Each of these went red
  with its line reverted by hand: withKey, prevKey in webOptions, and the
  status page line.
- Sandbox HOME with a fake launchctl:
  - `daemon install --web --lan` wrote a 0600 plist with
    `serve --web=0.0.0.0:3430` and the key. plutil said OK, and it printed
    the link, the network links and the warning.
  - Reinstalling with no flags kept the key. `daemon status` showed the
    link.
  - `daemon web off` / `daemon web` / `daemon web on` behaved as above,
    with a new key after off.
  - `daemon web bogus` and `serve --lan` gave the usage errors.
- `serve --web=127.0.0.1:3462` served the gateway (3461) and the page in
  one process. The page answered 200 with the key and 401 without, and the
  page and /v1/models both showed 3 models. `magpie web --no-open` beside
  it printed the service's link and exited 0.
- gofmt -l; go vet (gui), and go vet -tags nogui for darwin, linux and
  windows; go test -tags nogui ./... in a sandbox HOME.

Not tried: a real systemd on Linux. The unit text is checked by test only.
2026-10-14 08:32:41 +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 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
yetone b6cf5e3eab gui: magpie web keeps its sign-in when another service on the same address fills or clears the host's cookies, and a page opened without it says why and takes the key (#2033, 321sssrt-bit)
A browser keeps cookies per host, not per port. magpie web's sign-in
cookie on http://<tailscale-ip>:3430 is the same host's as every other
service on that IP's other ports, so one of them could take it away,
and a bookmark then answered only "open the link magpie web printed
when it started".

Reproduced in Docker (linux/arm64, MAGPIE_WEB_KEY fixed, as the
reporter runs it) with Chromium and WebKit on the old binary:
- docker restart, recreate (an update), browser restart: still signed
  in (the key, its derivation and the 400-day cookie are fine);
- another port on the same host setting ~400 cookies: Chromium evicts
  the sign-in (401), WebKit keeps it;
- another port answering Clear-Site-Data: "cookies" (a sign-out often
  does): 401 in both;
- the page opened by another name for the host (localhost vs IP): 401.

Changed:
- the sign-in cookie is sent with Priority=High, so Chrome evicts it
  last when the host's cookies overflow (with it, the flood case stays
  signed in);
- every magpie_web_<port> cookie the browser sends is tried, so a stale
  one sent first no longer hides the right one;
- an HTML page opened without the sign-in gets a page that says which
  case it is (no cookie sent for this address, or a cookie holding
  another key) and a field to paste MAGPIE_WEB_KEY into; POST
  /_magpie/sign-in sets the cookie and goes back to the page asked for
  (local paths only: no scheme, host, //, /\ or the sign-in itself).
  The key is never in the page. API calls get a plain 401 that now
  says the reason too, and the turn-away is logged with it.
- docs/reference.md's Docker web section says how long a sign-in lasts
  and what can take it away.

Run:
- TestWebGuardBookmark (link cookie has Priority=High; stale cookie
  first still passes; both reasons; API 401; wrong key 401 with no
  cookie; right key 303 to /?view=usage with a 400-day cookie; external,
  //, /\, javascript:, empty, sign-in-path and CRLF back values all go
  to /). Broken by hand: the old guard fails it (link without
  Priority), dropping Priority alone fails it, reading only the first
  cookie fails it (stale cookie: 401).
- The Docker matrix above again on the new binary: the flood keeps the
  sign-in in Chromium; Clear-Site-Data and the other name get the form,
  and the form signs in (wrong key turned away, right key back to
  /?view=usage, 200) in Chromium and WebKit; the log says "turned away
  ... no cookie sent".
- go test -tags nogui ./internal/gui (ok, 173s), gofmt -l, go vet
  darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: the reporter's own browser and Tailscale address; which
service on their host takes the cookie is not known.
2026-10-14 05:29:30 +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 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