Commit Graph
336 Commits
Author SHA1 Message Date
yetone ec3dad75ae provider, gateway, gui, cli: Claude's accounts can be kept to Claude Code's own sign-in, magpie serving nothing on them (myduso)
myduso on Discord asked for an exclusive mode on Claude's subscription:
switch the credentials locally and proxy no traffic, since Claude Code
is used on its own and the SDK run magpie's bridge makes spends more of
the allowance than the interactive client.

The switch-only setting Codex has (#1907) now also takes claude. On it,
Provider.KeptToAgent is true and On() false, so the gateway, catalog,
groups, fallbacks, search, draw and embeddings serve nothing on the
Claude accounts, and a request naming them is refused 404 saying they
are kept to Claude Code's own sign-in and how to undo it (switchedOff).
Switching Claude Code's sign-in when an account is used up, and reading
usage, go on: both are gated by leftAlone on the raw Off, which this
doesn't set. Groups magpie found keep their Claude members
(heldOffEntries). Nothing is sent as Claude Code: magpie only writes and
restores Claude Code's own credentials as it already did.

GUI: the tick under Claude's accounts, shown with one account too, drawn
by the block Codex's tick had (one block now, its strings picked by
agent). app.js stays under its budget with no raise (1,311,711 of
1,311,735). CLI: magpie accounts switch-only <codex|claude> [on|off].
Docs: reference.md, subsystems/providers-accounts.md.

Run on mote at this tree on 06950fbbb; then rebased on aeacc6358 (two
app.js comments shorter) and go test -run TestCoreScriptBudget ./internal/gui
run again at the pushed head: ok.
- gofmt -l internal: clean. GOOS=linux go vet -tags nogui ./internal/...
  and GOOS=windows go vet ./internal/...: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/provider
  ./internal/gateway ./internal/cli ./internal/gui: all ok.
- node --test (Chromium + WebKit, every language the file covers):
  claude-switch-only (new), switch-only, keep-login, i18n-keys, gui-ja,
  gui-de, gui-zh-tw: 85 of 93 in one run beside other sessions' full GUI
  suites (load 23-73); the 8 reds (claude-switch-only chromium en/zh,
  gui-de and gui-ja in both engines) were not captured, and those files
  then passed alone twice (35 of 35 each run).
- Earlier, at ecbd694a2 (on ddf31ca30): internal/agent ok; add-sheet,
  api-key-usage pass; account-models and account-proxy 40/40 alone after
  8 browserType.launch timeouts at load 40-70 from other sessions.

Broken by hand, watched red:
- On() without the KeptToAgent term: TestClaudeSwitchOnlyServesNothing-
  AndStillSwitches and TestClaudeKeptToClaudeCodeServesNothing fail (the
  gateway ran Claude Code through the bridge, 200).
- SetSwitchOnly refusing claude: both fail.
- app.js without the claude branch: claude-switch-only 16/16 red in
  Chromium, switch-only (Codex) 16/16 green.

Not tried: real Claude accounts or a real Claude Code (the switch itself
is the existing path, tested with a fake claude in a sandbox HOME); the
whole GUI suite (only the files that open Claude's or a provider's
editor, plus the i18n ones); Linux and Windows test runs (vet only).
2026-10-29 04:15:56 +08:00
yetone e0ea15b8e8 library: an MCP hub, one magpie server in place of every library server (#2679)
With Library → MCP → "MCP hub" on (off by default), each agent that takes
an MCP server over HTTP is given one entry, magpie, at
/mcp/magpie/hub/<agent>, in place of the library servers ticked for it.
magpie runs those servers itself, once for every agent: a command starts
on its first call and ends after 10 idle minutes, a URL server is reached
with its headers and MCP sign-in. Tools are <server>__<tool>; a tool off
in the library is neither listed nor run. Any other app connects at
/mcp/magpie/hub, which serves every library server. Both are guarded as
/mcp/magpie/tools is (local or a gateway key, no foreign page, 4 MiB,
the key's limit per call). An agent that reaches no server over HTTP
(Claude Desktop), has a magpie entry of its own, or sits beside a library
server called magpie keeps each server's own entry, and the page says why.
Off gives every agent its servers back and ends every process the hub
started.

GUI: a switch under the MCP list, a line of what it serves, the address,
and a Connect… sheet. The sheet lists every agent magpie detects that
takes MCP (not a fixed four), each with where it stands; one given none of
the hub's servers has a Connect that ticks it for every server it can
reach (servers/agents-all), so it gets the entry, and the sheet stays
open. Then any other app: Cursor (when it isn't a detected agent), VS
Code, Other, with the JSON and, in the app, "Add to …" through the app's
own install link built in Go (servers/hub-open; the page never sends a
link). CLI: magpie library mcp hub on|off. Design: docs/subsystems/mcp-hub.md.

With #3885 (62045475b): with the hub on, Codex is given the one magpie
URL entry, and the servers behind it never reach runVia, which takes a
command server only; with the hub off Codex gets /mcp/run/<name> as before.
Rebased onto it; the one conflict was both commits declaring base in
syncMCP.

Run:
- At 62045475b + this (the pushed tree), on mote: gofmt -l, go vet,
  GOOS=windows go vet, GOOS=linux go vet -tags nogui clean; go test
  -timeout 45m internal/library (108s), gateway (510s), cli (50s) ok.
  The GUI files and internal/gui weren't run again: 62045475b touches
  neither, and the rebase changed nothing in them.
- At ddf31ca30 + this: go test -timeout 45m for
  internal/library, gateway, cli and gui on mote; gofmt -l; go vet,
  GOOS=windows go vet, GOOS=linux go vet -tags nogui; win-run of
  library-mcp-hub and i18n-keys (both engines, en zh zh-TW ja de, 420px).
  gofmt and the three vets clean; library, gateway (554s) and cli ok;
  gui ok but TestMainWindowCorners, red the same on origin/main ddf31ca30
  on mote (#3949); GUI 26 of 26 pass.
- Earlier base (582bd8036, before TestHubConnectAnAgent and the oneport
  consts): full go test ./... on mote, every package ok but gateway's
  TestClientPathCoversHandler (fixed here: HubMCPPath, HubMCPAll and
  {agent} added to its consts; passes) and internal/gui's AppKit tests.
  Of those, TestMainWindowCorners fails the same on origin/main ddf31ca30
  on mote's macOS 27 (#3949); the other six (dock, panel, plugin page,
  right-to-left) passed rerun alone at load ~95 (#2645).
- win-run of every library-*, gui-*, i18n*, click-scroll and menu-scroll
  GUI file: 49 files, 839 tests, 839 pass.
- Real use in WSL (magpie-desktop), sandbox HOME, real echo MCP server:
  hub on, Cursor given servers → ~/.cursor/mcp.json holds only magpie at
  /mcp/magpie/hub/cursor; initialize, tools/list (echo__echo) and two
  calls ran on one server pid; a foreign Origin got 403; hub off → the
  echo process ended, tools [].

Broken by hand: Connect button removed → 6 GUI cases red; the old row
wrap rule → 6 red (icon on its own line at 420px); EveryServerAgents
call removed from TestHubConnectAnAgent → red (hub "").

Not run: the whole GUI suite (~960 files); Windows agents (VS Code, Cursor
on Windows) against a real hub; an "Add to Cursor" click in the real app
(the link is built and tested, the app's own confirm wasn't driven).
2026-10-29 03:17:58 +08:00
yetone 40f206dff1 vertex: partner models (DeepSeek V4.1 Flash, GLM, gpt-oss) go to Google's OpenAI-compatible chat completions
Dani Ariyanto (Discord) asked for Vertex AI's partner/open models, such as
DeepSeek V4.1 Flash, beside Gemini. Google serves them (Model as a Service)
on an OpenAI-compatible chat completions endpoint in the same project,
https://<host>/v1/projects/<p>/locations/<loc>/endpoints/openapi/chat/completions,
with the same OAuth token. The model goes in the body as publisher/model
(deepseek-ai/deepseek-v4.1-flash-maas). Source: Google's
maas/call-open-model-apis page.

An existing Vertex provider needs no change. A model id with a slash
(VertexPartner) is a partner model, as is every publisher/model id that
models.dev lists for google-vertex as @ai-sdk/openai-compatible. It is
asked on Base(Chat) = <project base>/endpoints/openapi (ListedAPIs, so
ModelAPI can't move it). Gemini ids have no slash and stay on
streamGenerateContent. Speaks is now [chat, gemini].
- vertexEffort (Gemini's levels) no longer applies to a partner model.
  Before, a Codex xhigh was clamped to high.
- The provider's own test probes Gemini only. A partner model answers
  only after the project enables it in Model Garden, so an unenabled
  partner model would turn every Gemini user's test red. A partner model
  is tested by its own model test.
- tinyBody's chat probe uses Base(Chat), so the probe goes to the openapi
  address. That address is the only one Sign lets the token go to.
- A test as Codex is refused for Vertex, as it already is for Claude Code
  ("only of a relay").

The global list adds the three partner models that Google's docs list as
live at global on 2026-10-28:
- deepseek-ai/deepseek-v4.1-flash-maas (Preview, global only)
- zai-org/glm-5.2-maas
- openai/gpt-oss-120b-maas

Left out of the list: Gemma 4 (Experimental) and the models retired on
10-21 (v3.x, glm-4.7/5, qwen3, llama-3.3...). Gemma 4 still routes when
typed in by its full id. us/eu/regions are unchanged.

Docs: providers-accounts.md and gateway-routing.md Vertex rows;
reference.md (the global row, how a partner id routes, Model Garden
enablement, typing one in).

Run (on mote via mote-run):
- go test -tags nogui -run TestVertex ./internal/provider ./internal/gateway: ok.
- New: TestVertexPartnerModel (gateway). It covers Chat, Anthropic and
  Responses clients, streamed and whole, against a fake openapi endpoint
  answering in the shape of Google's docs. It checks the path, the Bearer
  token, the body model and the client's text, that Gemini stays on
  streamGenerateContent, and that xhigh is kept.
- New: TestVertexPartnerModels (provider). It covers Speaks/Base,
  APIs per model, the global list, no partner model at us/us-central1,
  that Test() probes Gemini alone, and TestModels on openapi with the
  minted token.
- TestVertexProviderListed now pins Speaks [chat gemini].
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./..., go build ./...: all ok; gofmt -l clean.
- Full suite: go test -tags nogui -count=1 -timeout 45m ./... at
  80f2bda50 (this change on cb167fcbd): SUITE-EXIT=0, 77 packages ok.
- An earlier full run at base 396e0e463 was red only in
  TestPluginStreamsPastTheBudgetWait. That is #3946, fixed in 7fd77a944
  after that base. It passed 3 of 3 alone at origin/main cb167fcbd.
- The final rebase onto b5d2858f4 (usage, a gateway test, LESSONS) was
  followed by go build and the TestVertex runs again; the suite was not
  run again.

Broken by hand:
- All nine non-test files restored to main, with VertexPartner kept so
  the tests compile: TestVertexPartnerModel red (asked
  publishers/google/models/deepseek-ai/...:streamGenerateContent with a
  Gemini body), TestVertexPartnerModels and TestVertexProviderListed red
  (speaks [gemini]).
- vertexEffort guard removed: red, "effort xhigh sent ... as high".
- Test()'s Vertex chat skip removed: TestVertexTestRequest and
  TestVertexPartnerModels red (a chat probe of the partner model).
- tinyBody back to q.Chat: TestVertexPartnerModels red ("asked only at
  Vertex AI, at its project's address").

Not tried:
- No real Vertex AI account or project here. Nothing reached Google:
  the endpoint, auth and response shapes come from Google's docs only.
- Per-model thinking controls (chat_template_kwargs: DeepSeek thinking,
  GLM enable_thinking) are not mapped. A partner model gets the generic
  chat completions reasoning_effort, and gpt-oss takes it natively.
- Claude on Vertex (publishers/anthropic rawPredict) is out of scope. It
  takes its own request shape and its ids have no slash.
- No GUI change (the API picker reads URL fields, which Vertex has
  none of), so no GUI suite was run.
2026-10-29 00:33:50 +08:00
yetone 6ecc65b6db agent: the CodeBuddy IDE is CodeBuddy too, found with no CLI
bjzhangwn on X: magpie supported CodeBuddy only as its CLI, not the IDE.
The CodeBuddy IDE (4.12.2, codebuddy.ai's CodeBuddy.app,
com.tencent.codebuddy, and codebuddy.cn's CodeBuddy CN.app,
com.tencent.codebuddycn) reads the file magpie already writes for the
CLI: its genie extension's CustomModelsProductProvider loads
~/.codebuddy/models.json's "models" (a string id and url each) and
"availableModels", and lists them in its own picker. So one row,
renamed CodeBuddy, stands for both. desktopApps gets a "codebuddy"
entry, with a "more" list for the second build's bundle id. A `sign`
lists the row with only the IDE installed. That row shows the IDE's
version, is never "CLI not found", and the CLI isn't offered for install.

Tests: TestCodeBuddyIDEIsCodeBuddy uses the real Info.plist bytes of
both builds, cut to their first keys. TestCodeBuddyIDEReadsMagpieModels
reads the written models.json the way the IDE's loader does.

Run (mote, macOS 27):
- gofmt -l: clean.
- GOOS=linux and GOOS=windows go vet of ./internal/agent/... and
  ./internal/sessions/..., plus GOOS=windows -tags nogui ./internal/gui:
  ok.
- go test -timeout 45m -count=1 ./... at d4f1d6480 plus this change:
  76 packages ok. One red, internal/gui TestMainWindowCorners/macOS_26_SDK,
  is #3949 (macOS 27, same output, untouched here).
- Rebased on origin/main 2ff85f8a2: internal/agent and internal/sessions
  ok again at the pushed head.
- Broken by hand, TestCodeBuddyIDEIsCodeBuddy goes red each way: with
  the sign off, and with the CN bundle id wrong.

Real app: the 4.12.2 builds (intl, then CN) ran on mote under a sandbox
HOME with --user-data-dir. Both logged "Loaded custom models config from
user: <home>/.codebuddy/models.json, valid=1" for magpie's entry.

Not tried:
- Hot reload is unconfirmed. In the not-signed-in sandbox, neither a
  rename nor an in-place edit made it load again (the cloud product
  fetch never finished), though its code fs.watches the file and
  debounces a sync.
- No chat through the gateway: it needs a CodeBuddy sign-in.
- The IDE's Windows and Linux install paths, so off a Mac it is found
  by ~/.codebuddy alone.
- The IDE ignores CODEBUDDY_CONFIG_DIR.
2026-10-28 22:48:07 +08:00
yetone 60520ddb3b moejs: v0.1.0-alpha.11, at its new module path github.com/MoeForge/moejs
Gateway middleware and agent plugins run on moejs. alpha.11 moves the
module to github.com/MoeForge/moejs; every other API change since
alpha.4 is an addition. What magpie gets: faster calls, loops, property
lookups and JSON.parse, allocation-free await, a bytecode verifier, a
correct default.pgo, and Intl / toLocaleString in plugin code.

Checked against both tags' source: every name magpie uses (NewRuntime,
Options, Compile, Link, Hook, Value, Arg, Undefined, NativeFunc,
Referrer, the Promise results, Exception) has the same signature, and
Options' defaults (shared frozen builtins, no timers) are unchanged.
fetch, Streams, URL, node:fs and node:buffer live in the separate
webapi and node packages, installed only on request; magpie installs
neither, so a plugin still reaches no network or file.

Intl's CLDR, Unicode, ICU and V8 material is compiled into every build,
and moejs asks a program that includes it to carry sections 1 to 4 of
its notices. THIRD_PARTY_NOTICES holds them verbatim. Release archives
ship no LICENSE today either; that is not changed here.

Doc and site links (docs/, site/public/docs/{,zh/,ja/}plugins.html)
point at the new repo.

Run on mote at this tree: gofmt; go build -trimpath -s -w (60,670,658
bytes on origin/main 58fb3a778, 62,329,250 now, +1.66MB); go vet of
middleware, jsmod, agentplug for darwin, linux and windows; go test
./internal/middleware/... ./internal/jsmod/... ./internal/agentplug/...
ok; go test -run 'Middleware|Strateg|OnUsage|JSPlugin|Agentplug|AgentPlug'
./internal/gateway ./internal/provider ./internal/plugin ./internal/gui
ok.
Not run: the full suite, the GUI suite, a real request through a
middleware in a running gateway.
2026-10-28 14:36:17 +08:00
yetone 6ce0f14b98 gui: magpie web's page port judges every gateway route as from another machine (reported privately by Coffemon)
Since 1b32bdcf (v0.1.1444) the page port of `magpie web` / `serve --web`
hands the gateway's client routes to the gateway. The gateway counts a
loopback request with no forwarding header as an agent on this computer,
which needs no key. A request reaching the page port over loopback without
such a header was answered that way, so the page port gave the gateway's
routes without a gateway key, with sharing off. Before 1b32bdcf every
request there needed the page's key.

Now every request the page port hands over is marked
(gateway.FromPagePort, the X-Magpie-Page-Port header) and local() is false
for it: answered only while magpie is shared (or on the network), with an
enabled gateway key, from loopback too, under any Host or browser marks,
and with MAGPIE_TRUST_PROXY set. While not shared lanGuard refuses it 403,
saying to use the gateway's own address. lanGuard moves the mark into the
request's context and drops the header, so it never goes upstream.
toGateway (another magpie serves the gateway) passes the mark on and adds
the loopback peer as X-Forwarded-For when no forwarding header came, so an
older gateway that doesn't know the mark still asks for a key. Agents on
this computer keep the gateway's own port (3425), key-free from loopback as
before. The page itself calls no client route (checked app.js and
plugins.js: the /mcp and /v1 addresses there are copied, not fetched), so
nothing in the GUI needs a key on the page port. The routes covered are
all of gateway.ClientPath (/v1, /v1beta, the routes without /v1, the Codex
backend path, the search path, /mcp), since the mark is set in onePort for
each of them.

docs/reference.md's one-port paragraph, gui-shell.md and
gateway-routing.md now say the page port answers these routes as from
another machine and that agents here use the gateway's port; the old text
said a same-machine proxy's requests carry forwarding headers, which a
forward that adds none doesn't.

Tests:
- TestWebOnePortServedHere / ServedElsewhere: a loopback request with no
  key and no forwarding header to /v1/chat/completions, /chat/completions,
  /v1/responses, /v1/messages, /v1/models, /v1beta/models, /mcp/github,
  /mcp/magpie/web-search and the Codex backend, under Host 127.0.0.1:3430,
  127.0.0.1, localhost:3430 and a public name, with a browser's marks, a
  CLI's user agent and an IPv6 loopback peer: 403 not shared, 401 shared.
  Red on the old code (404 "knows no model" / "isn't signed in to an MCP
  server": the handlers were reached). The old "for an agent here" 200 is
  now 401; loopback with a gateway key 200. Origin null, foreign Origin
  and rebound Host without a key now 401 (lanGuard asks the key first);
  a foreign Origin with a key still 403. A 429 from the process's
  failed-key bucket counts as the 401 it replaces.
- TestWebOnePortAgentsHereUseTheGatewayPort: the gateway's own Front from
  loopback without a key 200; the page port 403 with the reason and the
  gateway's URL; MAGPIE_TRUST_PROXY=1 doesn't make it local.
- TestPagePortMarkIsNeverLocal (gateway): marked requests never local
  under MAGPIE_TRUST_PROXY; refused unshared; with a key the handler sees
  no header and local false.

Broken by hand, each red, then restored:
- onePort not marking: ServedHere and AgentsHere red; ServedElsewhere
  stays green on the X-Forwarded-For fallback alone (the older-gateway
  path).
- local() ignoring the mark: ServedHere, AgentsHere, PagePortMark red.
- lanGuard not taking the header off: PagePortMark red (handler saw it).

Real try (built binaries, sandbox HOME, MAGPIE_NO_ACCOUNTS=1,
MAGPIE_TEST_SANDBOX; gateway 127.0.0.1:3561, page 3562, a raw TCP
forwarder (a Go listen/dial/copy loop, as socat would be) on 3563 -> 3562,
a fake OpenAI-compatible upstream on 3564 added as a provider):
- `serve --web` (gateway in process), origin/main c37bcdbfc binary: through
  the forward with no key, chat 200 (upstream called), /v1/models 200,
  /v1/responses and /v1/messages reached the provider, /mcp/magpie/web-search
  with Host 127.0.0.1 200; the page's /api/settings 401. 5 upstream calls.
  This change: every one of those 403 with the page-port reason; the
  gateway port's agent chat 200; 1 upstream call (the agent's).
- `serve` plus a separate `magpie web` (served elsewhere): old binary 200
  for chat and MCP through the forward, shared or not, with no key or the
  page's cookie only. This change: 403 not shared; shared, 401 with no key
  and with the page's cookie only, 200 with a gateway key; the page signs
  in through the forward and /api/settings is 200 with its cookie; the
  upstream request carries no X-Magpie-Page-Port.

Run at this head (rebased on origin/main f0ffee34c):
- go test ./internal/gui ./internal/gateway -run 'TestWebOnePort|TestClientPath|TestWebAssets|TestPagePortMark|TestAllowList|TestLAN|TestRebound|TestProxied' -count=1: ok
- gofmt -l internal/gateway internal/gui: empty; go vet (darwin),
  GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet -tags nogui
  ./... (before the rebase), GOOS=linux/windows go vet of gateway, gui and
  cli at this head: ok
- The full suite (go test -tags nogui -count=1 -timeout 45m ./..., one per
  machine, waiting behind another session's run) was not run before this
  push: a security fix ships at once. It runs at this head next; any red it
  names gets its own commit.

Not tried: Windows and Linux beyond vet; nginx (its XFF path is unchanged
and covered by the "through a proxy" cases); a real vendor account; the
GUI suite (no GUI asset changed).
2026-10-27 15:15:29 +08:00
yetone 5215108e53 gui: magpie web shows MAGPIE_PUBLIC_URL at the sidebar's foot and in About's Gateway URL, as the Gateway page does (noahhrreion on Discord)
noahhrreion runs magpie in Docker and sets the gateway's address with
MAGPIE_PUBLIC_URL; the address at the foot of the page didn't show it.
Since #1551 a page other machines open (magpie web) shows
MAGPIE_PUBLIC_URL, while they are let in, as the gateway's address on the
Gateway page, starts Connect and its snippets at it, and uses it for
Settings' MCP addresses. Two places still said the container's loopback:
- the sidebar's gateway line (renderSideGw): it drew providers' and
  boot.js's `url` only. It now draws `publicURL` in magpie web, and
  boot.js's `sideGateway` carries it (same rule as settingsState: shared,
  or MAGPIE_ADDR on the network, as the image's 0.0.0.0 is)
- Settings › About's Gateway URL: in magpie web it is the public URL,
  and the separate Public address row, then the same, is left out
In the app on this computer both stay the local address that agents here
are pointed at, as before. The address list in Share on local network
already gives MAGPIE_PUBLIC_URL alone, and Connect and the copy buttons
were already at it.

Run (worktree at origin/main 11dcc743f + this, darwin/arm64, load ~150):
- go test -count=1 ./internal/gui/: ok (TestBootSaysWhereItsGatewayListens
  now checks publicURL is in sideGateway on the network and absent on
  loopback; the script budget tests pass, not raised)
- gofmt -l clean; go vet darwin and windows on internal/gui. The linux vet
  of internal/gui doesn't build Wails without cgo on this Mac, in Wails
  itself, as on main
- public-url-default.test.cjs, Chromium and WebKit, en zh zh-TW ja de,
  1100 and 420 wide: 26 pass
- the 18 GUI files on the changed caller-keys fixture plus sidebar,
  gateway-port, i18n-keys, settings-general, settings-sections and
  settings-search, 3 wide: 322 pass, 4 fail. Rerun 1 wide, 3 passed and
  gateway-caller-keys webkit stayed red at line 137; it is red 4 of 5
  on 11dcc743f without this change too, #3797. gateway-key-models webkit
  (#2648) and gateway-own-key zh 440 (#3842, filed now) passed alone.
Broken by hand:
- renderSideGw back on g.url: public-url-default's magpie web test red
  at 1100 wide
- About back on s.gateway: red at both widths
- boot.js without publicURL: TestBootSaysWhereItsGatewayListens red
Not tried: a real Docker container with MAGPIE_PUBLIC_URL; the page was
driven with a faked API. Not asked of the reporter yet: whether they open
magpie web, or the desktop app, which keeps the local address.
2026-10-27 13:30:16 +08:00
yetone 19dc5b9252 routing: accounts renewing together spend first the one whose credits left lapse first (zhaocai_83020 on Discord)
zhaocai_83020 on Discord asked how to make several WorkBuddy accounts
spend the credits that expire soonest first. Smart, the default routing,
already took a window's runsOutAt (plugin 0.1.14, cdredfox on X) as its
renewal, but only when it came before the window's reset. Since plugin
0.1.35 (windy on Discord) a WorkBuddy free account's Credits window
resets at the month's end, the same moment on every account (cycleOf,
packages/workbuddy usage.test.mjs CN_FREE: 10-31 23:59:59 +08), so given
credits lapsing after that end ranked alike and kept the accounts'
listed order: the account whose credits were lost first wasn't spent
first.

Allowance.Lapse is the soonest RunsOut in the future of a window that
counts the model, carried to routes.Seat.Lapse. Smart goes by it, to the
hour, only when the renewals tie: the one lapsing first goes first, one
telling none after those that do, the same hour keeps the listed order.
The share-used tiers and the renewal still decide before it. It is read
from the window's structure (RunsOut), not the provider's name; only the
WorkBuddy plugin sends runsOutAt today. Weekly pace and the other
routings are unchanged, as before. The gateway-strategy plugin seat
(middleware/points.go) doesn't carry it, as it carries no Free, Credits
or speed either.

Docs: reference.md (How magpie picks an account), gateway-routing.md,
site docs start.html en/zh/ja (not deployed by this commit).

Run at 2e165fe9d + this change; rebased onto 50606d8c0, which changes only internal/sessions:
  go test -tags nogui -timeout 45m ./internal/routes/ ./internal/gateway/  ok
  go test -tags nogui -timeout 45m ./internal/provider/ -skip
    TestUnreadLoginsWriteErrorsKeepCredentials  ok
    (that test crashes the package with "close of synctest channel from
    outside bubble" in filememo.Forget, untouched here: #3632, open,
    with patches under review there)
  go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet on
    ./internal/routes/ ./internal/provider/ ./internal/gateway/  ok
  gofmt -l on the changed files  clean
New TestSmartSpendsCreditsLapsingFirstWhenRenewingTogether: with
strategies.go put back to origin/main by hand it fails "lapsing first
goes first: ab"; green with the change. The windows are the plugin's
for a real China-site free account (reset at the month's end over 31
days, given credits lapsing on their own day).
Not tried: a real move of requests over several real WorkBuddy free
accounts (no such accounts on this machine), and a GUI run (no GUI
change).
2026-10-27 11:56:05 +08:00
yetone e7173958e9 agent: NewMax, magpie's models in its model picker (jwaitq on Discord)
jwaitq asked in #general (10-27) for NewMax (newmax.cc), an Electron app
built on the Claude Agent SDK. NewMax keeps its settings in
~/.newmax/newmax.db ($NEWMAX_USER_DATA_DIR wins), a SQLite table
settings(key, value) whose "app" row is JSON.stringify of every setting.
Connect adds one Anthropic-format provider, id magpie-gateway, with
magpie's gateway root (NewMax adds /v1/messages itself), its key and up to
20 models (NewMax's MAX_MODELS), appends it to providerOrder and, when
the user had kept NewMax's default, picks it. The row is edited by
splicing raw JSON in one immediate transaction, so every other byte the
user has stays as written. Disconnect removes the entry and its order id,
puts providerId/model back to "default" when they were magpie's, and
deletes the row when magpie made it. NewMax holds settings in memory and
writes the whole row on any change, so magpie refuses to write while
NewMax runs (macOS/Linux, matched on the program, not on a folder named
newmax) and says why in every language.

Run:
- go test -tags nogui -count=1 -timeout 45m ./internal/agent
  ./internal/agentenv ./internal/appdir ./internal/sessions at this head
  (rebased on 5e3dd1d52): ok
- gofmt -l clean; go vet darwin, linux (nogui) and windows on the touched
  packages
- GUI i18n-keys and agent-notice-lang, Chromium and WebKit: 15/15 each
Broken by hand, each red: user entry's name/off overwritten
(TestNewMaxProvider), running check removed (TestNewMaxLeavesAlone), row
kept after off (TestNewMaxMakesItsRow), pick left on magpie
(TestNewMaxProvider), no model cap (TestNewMaxModelCap), the first
process pattern that matched a shell in a newmax folder
(TestNewMaxProcess).

Real use: NewMax 1.1.22 (macOS dmg) in a sandbox HOME and
NEWMAX_USER_DATA_DIR, with this magpie on a sandbox port. Connect was
refused while NewMax ran; after quitting it wrote the row; on relaunch
NewMax's picker listed and picked magpie's models, its ClaudeProxy sent
to magpie's /v1/messages, and "Reply with exactly: pong" came back
"pong" through magpie to a fake Anthropic upstream. NewMax's own 58KB
row afterwards (47 providers) kept magpie's entry as written; disconnect
then removed only that entry, its order id and the pick
(live/deepseek/deepseek-flash -> default), every other byte the same.

Not tried: NewMax on Linux or Windows (Windows has no running check, as
pgrep isn't there); a real vendor reply through NewMax (the sandbox used
a fake upstream).
2026-10-27 11:03:41 +08:00
yetone cc9d68ffd3 agent: Antigravity CLI in a WSL distro is found and wired
mimi001234 (Discord, #general): agy installed in a WSL distro never
showed on the Agents page. wslKinds had no agy, so the distro probe never
looked for it.

agy is now a WSL kind (bin agy, dir .gemini/antigravity-cli), with the
model field offered for a stopped distro too. agy takes magpie only from
how it is started, and no magpie runs inside the distro, so a magpie pick
writes an agy shell function into the distro's own profiles: .bashrc,
plus .zshrc or fish's config.fish when the login shell in the distro's
/etc/passwd is zsh or fish. The function reads settings.json's model at
run time. It adds --model only for a magpie model the user didn't name
themselves, and sets GOOGLE_GEMINI_BASE_URL to place.gw() (the NAT
address, never 127.0.0.1) and GEMINI_API_KEY to the distro's WSL key.
Default removes the block. Check flags a function whose address has
moved, and Sync rewrites it. update.ShellFunction gained ShellFunctionAt,
DropShellFunctionAt and ShellFunctionInAt for profiles given by path
(fnProfile is now ShellProfile). This machine's own agy function is
unchanged. The restart notice is translated (de, zh, zh-TW, ja).
agent-wiring.md and reference.md are updated.

Run at c272f3799 + this change, then at this head (rebased on
65ee8c65c, which touched only gateway and plugin): the whole of
internal/agent and internal/update again, ok, and go build ok.
- go test -tags nogui -timeout 45m ./internal/agent/... ./internal/update/...
  ./internal/cli/...: update and cli ok. agent was red only on
  TestEveryNoticeIsTranslated (the new notice wasn't in i18n.js); after
  adding it, TestEveryNoticeIsTranslated and TestWSLAgy* are ok.
- go test -tags nogui ./internal/gui: ok.
- GUI, chromium and webkit: i18n-keys, agent-notice-lang and
  wsl-agents-setting all pass.
- gofmt -l on the changed files; go vet ./...; GOOS=linux go vet -tags
  nogui ./...; GOOS=windows go vet ./...; go build for darwin, linux
  (nogui) and windows: all clean.
- The bash and zsh functions are sourced in the test with a fake agy. The
  fish function was run in docker alpine:3.20 with fish.

Broken by hand, each red:
- bin "agyx" in the wsl kind: TestWSLAgyFound and TestWSLAgyStopped fail.
- 127.0.0.1 instead of at.gw(): TestWSLAgyPick and TestWSLAgyFunctionRuns
  fail.
- default not dropping the function: TestWSLAgyPick fails on .bashrc.

Not tried: real WSL. The Windows box (10.0.0.132) didn't answer ssh.
Fish wasn't tried inside a real distro.
2026-10-27 09:24:43 +08:00
yetone 9ae7912210 agent: plain agy starts Antigravity CLI on magpie in a new terminal
agy takes magpie's gateway, key (GEMINI_API_KEY, GOOGLE_GEMINI_BASE_URL)
and --model only from how it is started, so a user on magpie had to copy
the launch command at every start (bestony on Discord). Now:

- magpie agy run [args…] execs the real agy with the env and --model when
  agy's settings.json is on magpie's model (a --model/-model the user
  gives wins), and runs agy untouched otherwise. On Windows agy is a child
  through proc and its exit code is passed through. It refuses when "agy"
  on PATH resolves to magpie itself. magpie agy env prints what run adds
  (PowerShell's function reads it, since the desktop exe has no console).
- update.ShellFunction puts a function named agy in a marked block
  (# >>> magpie agy >>> … # <<< magpie agy <<<) of each shell profile
  cliShells finds: .zshrc (ZDOTDIR), the bash profile a terminal reads
  (.bash_profile, or .bash_login/.profile on macOS when that is missing),
  config.fish once its folder exists, and the PowerShell 7 / Windows
  PowerShell profiles where the execution policy runs them. Only the block
  is written, in place, temp-and-rename, CRLF and BOM kept; a profile that
  can't be read is not written; only files inside the home are. The
  function falls back to `command agy` when the magpie it names is gone.
- Set to a magpie model writes the block, stepping out takes it out (the
  file comes back byte for byte), and Sync at start writes it for users
  already wired.
- Notice, Launch tooltip and the connect panel say plain agy works in a
  new terminal, with the command for a terminal open now. Strings in
  i18n.js for zh, zh-TW, ja, de. docs/reference.md and
  docs/subsystems/agent-wiring.md updated.

Run at this head (base a3d4f8c5c, origin/main just fetched):
- go test -tags nogui -count=1 -timeout 45m ./internal/agent/...
  ./internal/cli/... ./internal/update/... ./internal/gui/...
  ./internal/proc/... : all ok.
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... : clean. gofmt -l on the changed files: none.
- GUI (node --test, chromium + webkit): agy-launch, cursor-local-launch,
  agent-connect, agent-connect-no-models, agent-connect-all-hidden,
  agent-connected-unfolded, connect-address-kept, connect-snippet-shell,
  agent-notice-lang, agent-leave-magpie, agent-disconnect, copy-command,
  i18n-keys, gui-de, gui-ja, gui-zh-tw: 0 fail. Not the whole GUI suite.
- Real try, sandbox HOME under the scratchpad, nogui build, fake agy on
  PATH printing its args and the two env vars, env -i:
  magpie provider add deepseek + magpie agy deepseek/deepseek-chat wrote
  the block after the user's two .zshrc lines; `zsh -i -c 'agy -p hi'` got
  --model magpie/deepseek/deepseek-chat, GEMINI_API_KEY=magpie-agy and
  GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:38712; `agy --model x` kept x;
  wiring again left .zshrc's mtime alone and added .bash_profile once it
  existed, and `bash -l -i -c 'agy -p hi'` got the same; `magpie agy env x`
  refused; magpie agy default took both blocks out, .zshrc equal to the
  original, and plain agy ran with no env and no --model.

Broken by hand, each red, then restored:
- no fnInHome check: TestShellFunction, TestShellProfiles red.
- block appended instead of replaced in place: TestShellFunction red.
- unreadable profile treated as empty: TestShellFunction red.
- blank line before the block left on removal: TestShellFunction,
  TestWithFnBlock red.
- --model always added: TestAgyRun red.
- Sync without agyShell: TestAgyShell red. Stepping out without
  agyShell(false): TestAgyShell red.
- app.js typed row off, typed tooltip off: agy-launch 4 of 10 red each.

Not tried: PowerShell on Windows for real (vet only); WSL; a user's own
`alias agy` (an alias beats the function); a terminal already open needs
the copied command; macOS bash started non-login reads .bashrc, which
isn't written; a Documents folder redirected outside the profile isn't
written.
2026-10-27 07:30:16 +08:00
yetone 1885c607e2 gateway: Antigravity answers Codex's switched threads and Hermes' old persona with no setup
Antigravity answers some agents' system prompts with a fake 429 "Resource
has been exhausted", whatever quota is left. Jodiezzzzzz on X (10-27): a
Codex thread begun on GPT-5.x and switched to an Antigravity model got 429
again and again. zgoodz on X: "antigravity在Hermes里一样429". v0.1.1625
told the Codex case as a 400 with "start a new chat", which isn't zero
setup.

What Google matches, each tried on a real Antigravity account on 10-27
(in the system instruction, any case):
- "x-anthropic-billing-header:" (Claude Code)
- "built on Anthropic's Claude Agent SDK" ("running within the Claude
  Agent SDK" goes through)
- "You are Codex, an agent based on GPT-5" / "..., a coding agent based
  on GPT-5"
- new: "Hermes Agent, an intelligent AI assistant created by Nous
  Research", Hermes' earlier default SOUL.md, kept by anyone who edited
  their SOUL.md. Hermes' current default ("You are Hermes Agent, built by
  Nous Research") goes through.
Each goes through with a zero-width space after its first letter.
"Y​ou are Hermes Agent, an intelligent..." still fails, so the
break goes inside the matched phrase itself.

Now codeAssistBody puts that zero-width space into each matched line
(antigravityCloak), in the system instruction only, and only for an
Antigravity account. Gemini CLI's account on the same envelope, and
every other provider and protocol, get the prompt as the agent wrote
it. The text added names nothing; it is one U+200B per line.
`magpie provider set antigravity prompt=as-written` (PromptAsWritten,
kept through Save/withPicks and the GUI's save) turns it off. Then the
v0.1.1625/#2156 fallback stands: a 400 with a hint (now one for Hermes
too, in the Routing page's five languages) and Antigravity skipped for
6h in a group.

Default-on, as the community antigravity-cloak middleware's README
says, changes what Google is sent so a request it means to refuse goes
through. That may be against Antigravity's terms. The owner asked for
it ("破解过 antigravity 提示词让其可以在别的 agent 中使用"), and it is
scoped to Antigravity accounts with an off switch.

Run at this tree (rebased on origin/main):
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/provider/
  ./internal/cli/ ./internal/gui/: gateway, cli and gui ok; provider
  died in TestUnreadLoginsWriteErrorsKeepCredentials ("close of synctest
  channel from outside bubble" in filememo.Forget), #3632, red on main
  since 091153bf; with -skip of that test, provider ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok. go build: ok.
- GUI (node --test, Playwright 1.62, chromium and webkit):
  routing-ag-turned-away, i18n-keys, gui-ja, gui-de, gui-zh-tw,
  routing-js, panel-routing: 45 pass, 0 fail.
- Broken by hand: with the cloak skipped, TestAntigravityAnswersHermes
  AndCodexByDefault and TestOnlyAntigravityIsSentThePromptBrokenUp go
  red; without withPicks' line, "prompt=as-written isn't kept".
- Real account, sandbox HOME with only the Antigravity login copied,
  this build on 127.0.0.1:3496:
  - real Hermes Agent (AIAgent, sandbox SOUL.md = the old persona plus
    one line): "OK", 200. With prompt=as-written: 400 with the Hermes
    hint. Back on default: 200.
  - real Codex 0.162.1: a thread begun on gpt-5.5 (against a local
    fake Responses server), then `codex exec resume <id> -m
    antigravity/gemini-3-flash` through this build: "OK". With
    prompt=as-written: 400 with the Codex hint.
  - a synthetic switched Codex Responses thread, with and without
    web_search: 200.
  - opencode, droid, kimi, pi, gemini-cli, qwen, crush, goose, amp and
    openclaw identity sentences: never refused, as written.
Not tried: Claude models on Antigravity (the sandbox account's Claude
quota is spent, so the Claude Code lines were checked on Gemini 3
Flash only); other agents' whole prompts, only their identity lines;
the Windows box; the whole GUI suite.

The plugins repo's antigravity-cloak 0.1.2 adds the Hermes line for
magpies before this one.
2026-10-27 04:16:20 +08:00
yetone 3fd7e16983 agent: PenguinHarness is installed from the Agents page and served by magpie with nothing to set up
rankyurky asked on Discord #feedback for PenguinHarness (npm
@prismshadow/penguin-cli, command penguin). Every value comes from
Penguin's own source (0.2.17):

- Config: $PENGUIN_HOME (else ~/.penguin/data, every OS) /
  $PENGUIN_PROJECT_ID (else default_project) /.project_config.toml.
  magpie writes [providers.magpie] (base_url, client_type, api_key),
  one [[models]] entry per magpie model (context_window, vision,
  max_tokens, [models.pricing] in usd_per_mtok) and default_model in
  Penguin's own inline spelling. Penguin's server reads the file again
  when its mtime changes, so no restart; a default naming no entry is
  refused by Penguin, so Check fails when one is missing.
- A file magpie creates is 0600 in a 0700 folder, as Penguin keeps it.
  Disconnect restores the user's own default_model (or none), drops a
  magpie vision model, and removes the file when magpie made it.
  Penguin's own entries, providers and command_policy rules are kept.
- A sync that changes nothing writes nothing (bytes and mtime kept), so
  Penguin's watcher isn't woken.
- Install: curl -fsSL https://penguin.ooo/install.sh | sh, or
  irm https://penguin.ooo/install.ps1 | iex on Windows; update: npm, or
  penguin update --yes for the tarball, except on Windows where
  update.ts refuses it.
- WSL: a penguin kind with no restart notice; the WSL test now expects
  an empty Notice for a kind with no restart.
- agentenv: PENGUIN_HOME, PENGUIN_PROJECT_ID; the project id is in
  NotPaths, or appdir dropped a value like "work" as a relative path.
- edit.SetTOMLArrayTables: replaces every [[name]] entry with key =
  value (with child tables) by blocks, or removes them; blank lines
  between replaced entries go with them, and an unchanged result isn't
  written.
- GUI: penguin-color.svg icon; README (en, zh-CN), docs/reference.md
  and docs/subsystems/agent-wiring.md.

Run (worktree at ca9b5048e, GOMODCACHE/GOCACHE pinned):
- go test -tags nogui -timeout 45m ./internal/agent ./internal/edit
  ./internal/agentenv ./internal/appdir ./internal/usage: all ok but
  TestWSLMoreAgentsPick (penguin has no restart notice), fixed in the
  test; rerun -run 'TestWSL|TestPenguin|TestEveryAgent|TestFolderVars|
  TestEveryNotice' ok.
- internal/gui: TestCoreScriptBudget, TestAssetTypesHoldAgainstTheRegistry,
  icon and i18n guards ok; no budget raised.
- GUI Playwright, chromium and webkit: i18n-keys, getting-started,
  agent-cli-missing, agent-update-all, gui-ja, gui-de, gui-zh-tw:
  123 tests, 123 pass. The icon renders in colour in both engines.
- gofmt -l internal/ clean; go vet -tags nogui ./... with GOOS linux,
  windows and darwin clean.
- Real Penguin 0.2.17 (npm, Node 25) in a sandbox HOME against a sandbox
  magpie serve and a fake upstream: penguin run -m "Say PONG" answered
  "PONG from fake" through magpie (usage agent "penguin",
  /v1/responses -> /v1/chat/completions); switching the model in magpie
  took effect with no Penguin restart; a no-op sync kept bytes and
  mtime; magpie penguin default restored the user's custom/my-own and
  left no magpie line; with no prior file it was created 0600 and
  removed on disconnect. The fixture is the file Penguin itself wrote.

- Rebased on origin/main d9a8148d7 and run again there: internal/agent -run
  'TestPenguin|TestWSL|TestEveryAgent|TestFolderVars|TestEveryNotice|
  TestSync', internal/edit, internal/agentenv and the internal/gui
  guards ok; gofmt clean.

Broken by hand, each went red: the no-op skip (mtime test), the 0600
create, the inline default_model spelling, the own-default restore,
removing magpie's file, dropping the vision model, the NotPaths entry,
and both SetTOMLArrayTables fixes (blank-line growth, unchanged write).

Not tried: the full ./... suite (machine load ~190-200, as asked); a
Windows or WSL real binary; Penguin's desktop app; a real vendor key
through Penguin. Penguin sends the openai SDK's User-Agent, so the
agent is named from its key, not its UA.
2026-10-27 01:38:45 +08:00
yetone d9a8148d7c routing: Speed first sends a request to the provider or key that answered the model fastest lately
joeliu96872540 on X: when one model is reachable through several API
channels, they want an option that sends each request to whichever has
been answering fastest, because they compare channel speeds by hand
today. Speed first (`fast`; `fastest` and `speed` also work) is a new
routing beside Free first. It applies to a provider's keys and accounts
(provider editor › Routing) and to a group of one model on several
providers (Routing page › group › Routing).

How it decides. When a streamed answer ends, gateway/speed.go records two
numbers for that account or key and model (restID): the time to first
token and the output tokens per second, as usage.DecodeOf computes them
for the Requests page. Each is a decayed average with a 20m half-life.
After an hour with no answer the record goes stale, and the store holds
at most 4096 records. This is O(1) at the answer choke point, beside
servedCandidate. For a pool routed by BySpeed, weighRouted reads one map
entry per candidate, and only for that pool. The usage history is never
read on a request.

routes.Fastest ranks each awake seat by its estimated time to a
200-token reply: TTFT + 200/TPS. A seat that reported no TPS gets the
median TPS of the others. Seats within 10% of the fastest in their band
keep their listed order, so near-ties don't swap on every request.
Seats with no recent measurement go after the measured ones. One request
in five, counted per pool, goes first to an unmeasured seat, rotating
among them, so each gets measured again. Resting seats go behind the
awake ones, and used-up seats behind those. Rests and failover are the
same as for every other routing.

The request trace gets lateTtft and lateTps, and the row-story sentence
says "answered m fastest lately: first token in 0.8s, 60 tokens a
second". It has a variant for a probe turn and one for when no seat has
been measured yet. i18n covers zh, zh-TW, ja and de. Also updated: the
CLI (`magpie group|provider set <id> routing=fast`, plus a new
`routing=` pair on provider set that refuses manual), the TUI name, the
rotation plugin's Sub, docs/subsystems/gateway-routing.md,
plugin-runtime.md, docs/reference.md and site start.html (en, zh, ja).
There is no new layout: it is one more item in the existing pickers.
app.js stays under its budget with no raise.

Tests:
- routes/fastest_test.go:
  - ordering: fastest first, slow writer loses, alike keep order,
    resting and used-up, median pace, none measured;
  - the probe turn at 5, 10, 15 and 20, rotating between seats;
  - a resting seat never gets a probe turn.
- gateway/speed_test.go:
  - decay, staleness and per-model records, with an injected clock;
  - a group of slowv and fastv routed fast: after the speeds are
    measured and seeded, the request goes to fastv with lateTtft set;
  - the same group routed in order still goes to slowv.
- cli: parseRouting and the provider routing= pair.
- GUI routing-speed-first.test.cjs: the row story for measured,
  no-pace, probe and none, in en, zh, zh-TW, ja and de, in chromium and
  webkit: 40/40.

Broken by hand:
- Fastest returning the listed order: the routes tests and the gateway
  group test go red.
- noteTrySpeed removed: "the streamed answer wasn't measured".
- The client.js case renamed: routing-speed-first 0/20 in chromium.

Run at b5a5caff2 (base 5b4dec58e):
- `go test ./... -count=1 -timeout 45m`, alone on the machine, at load
  130-230. Every package is ok except:
  - internal/provider: TestUnreadLoginsWriteErrorsKeepCredentials
    crashes with "close of synctest channel from outside bubble"
    (#3632, open);
  - internal/gui: TestMainWindowCorners and
    TestTrayCellClickReleasedPanel are killed at their deadline under
    load (#1936, #2645).
- gofmt -l is empty. go vet is ok on darwin, on GOOS=linux with -tags
  nogui, and on GOOS=windows for ./internal/....
- GUI files the change reaches, both engines, every language they test,
  all ok: i18n-keys, gui-de, gui-ja, gui-zh-tw, routing-save,
  routing-save-keeps-the-row, builtins, panel-routing,
  panel-routing-pick, panel-routing-providers, panel-routing-hidden,
  routing-key-windows, key-weight, key-weight-fit, group-member-weight,
  routing-weight-chip, account-arrange and routing-speed-first (40/40).
- routing-group-strategy was 4/18: the menu now has 9 items and the test
  still counted 8. Fixed in this commit; rerun, it is 18/18.
- routing-save-blank (a webkit click timeout) and routing-columns (zh
  "side by side") each failed one subtest at load ~200. Rerun alone,
  they are 4/4 each. Both are already filed (#1924, #1612).

Rebased on 8f023b511, where upstream changed gateway.go, app.js, client.js,
the routing plugin's i18n.js and gateway-routing.md; the rebase was clean.
At this head I reran gofmt, go build ./... and go vet (darwin, linux
nogui, windows) on routes, gateway and cli, and go test for routes, cli,
provider and gateway (the routing and speed tests) and for gui -run
Budget: all ok. The GUI files i18n-keys (4/4), routing-speed-first
(40/40) and routing-group-strategy (18/18) also passed.

Not tried:
- A real run against several channels of one model. Speeds come from
  real answers, so the first minutes after a start are in listed order
  plus probes.
- A non-streamed reply is not measured, a sub-millisecond TTFT is not
  counted, and a restart forgets every speed.
- The Windows runtime: only go vet ran for it.
2026-10-27 01:37:38 +08:00
yetone 4a33cf0a98 update: a Stable channel in Settings → About, and magpie update channel
ssharpcc on X reads every changelog before updating, for fear of a ban
when behind, and with many releases a day that is a lot of reading.
Settings → About → Update channel (zh: 更新渠道, 稳定版 / 每个版本) picks
Every version, the default and today's behaviour, or Stable: one version
a week, the newest that had been out three days as the week began
(Monday 00:00 UTC), and an urgent release at once. usemagpie.ai chooses
it from the release list (the previous commit); a release is urgent when
a line of its notes starts with "**Urgent release:**", which
magpie-releases' release run writes from an `Urgent: <why>` trailer
(magpie-releases 73f6cff).

- settings: updateChannel, "" or "stable"; anything else is refused.
- update: on Stable the feed is asked with channel=stable; What's new
  shows every release since the installed one (up to 1500) instead of
  the newest 40, so a week's notes read as one list.
- gui: the row is segs, never a <select>; a save that doesn't send the
  channel keeps it; switching asks the feed again at once, and a
  download from every version newer than Stable's pick is dropped,
  never restarted into. What's new's notes are kept per channel.
- cli: magpie update channel [stable|every] ("all" too), and it says
  which with nothing after it.
- docs: reference.md's Update channel (the rule and the marker); the
  privacy pages (en, zh, ja) name ?channel=stable on /api/latest.

The full Go and GUI suites were not run: the disk was at 3 GB free and
other sessions had GUI suites and a 45-minute gateway run going the
whole time.

Run, at this tree before the rebase:
- gofmt -l (clean); go vet on darwin, GOOS=linux -tags nogui and
  GOOS=windows for ./internal/update/... ./internal/cli/...
  ./internal/settings/... ./internal/gui/.
- go test -count=1 ./internal/update/... ./internal/cli/...
  ./internal/settings/...: ok. ./internal/gui -run
  'TestUpdateChannelSwitch|TestWhatsNewKeyedByChannel|TestCoreScriptBudget':
  ok (the app.js budget passes).
- GUI, chromium and webkit: update-channel (22: en, zh, zh-TW, ja, de at
  900 and 420 wide: default lit, Stable saved, kept by another save,
  kept over a reload, Every saved back, no click scrolls, no sideways
  scroll at 420), i18n-keys, gui-ja, gui-de, gui-zh-tw and every
  update-*.test.cjs: 253 of 253 pass.
- The live feed: /api/latest?channel=stable answers 0.1.1327 (out
  2026-10-22 21:55 UTC, the last before Friday 10-23 00:00) with 15
  assets after the first real cron run filled the ledger (400 releases
  back to 10-10); /api/notes 0.1.1200..0.1.1327 gives 124 notes, none
  empty (1213 and 1218 were never published).

After rebasing on afc99490f: TestCoreScriptBudget, the channel Go tests
(update, cli, gui) and GUI i18n-keys + update-channel (both engines,
26 of 26) pass again.

Broken by hand, each red: the feed asked without channel=stable
(TestLatestAsksTheChannel); Stable capped at 40 (TestStableNotesAreAll);
any channel saved (TestUpdateChannelSaved); "all" dropped
(TestUpdateChannelCmd); a save without the field clearing it, no new ask
on a switch, the newer download kept (TestUpdateChannelSwitch); one
notes key for both channels, What's new capped at 40 on Stable
(TestWhatsNewKeyedByChannel); app.js's other saves dropping the channel,
Stable's click saving "" (update-channel 11 of 11 red); the zh label or
a de subtitle taken out (update-channel and i18n-keys red).

Not tried: the full go test ./... and the whole GUI suite (above); a
real app switching channel against the live feed; Windows and Linux
runs (vet only); a real urgent release.

Requested by ssharpcc on X.
2026-10-26 21:09:44 +08:00
yetone ea1f9492bc cli: magpie tools lists, and magpie tool calls, the tools magpie's MCP servers give agents (iwinux)
iwinux on Discord (#feedback) wanted magpie's image generation, image
recognition and web search without going through an agent's MCP, and had
written a Python script for generate_image. magpie now has it:

  magpie tools [<name>]
  magpie tool <name> [--<param> <value>…] [<words>…] [-o <file|folder>] [--json]

Both ask the running gateway's own MCP servers (gateway.OwnMCPServers:
image, vision, web-search, plugin tools) over HTTP, with the local token
and the magpie-tool/1 User-Agent, so the tools, schemas, models from
Settings and usage counting are the ones an agent gets. Nothing is
started besides (#3318: the cases sit before startUp, beside mcp).

- Parameters are read against the tool's inputSchema: types (integer,
  number, boolean, array given once per item, object as JSON), enum, -
  and _ alike, --p v or --p=v. The words left over are the tool's one
  required text, else its prompt. An unknown flag or parameter, a missing
  required one, a bad value, a value given twice or both words and the
  same --param are refused with "nothing was called"; no request is sent.
- A file path a parameter takes (its description says file and path)
  is made absolute, since the gateway doesn't know the current folder.
- --help prints toolUsage (static): help is handled before anything runs.
- A still-being-made answer is waited on with generation_result (1s
  between asks, 30 min at most). The gateway's image server now says so
  in _meta too: usemagpie.ai/pending is the id, usemagpie.ai/files the
  files made ({url, inline}); an older gateway is read from its text.
- Images and videos are saved through imagemcp.Target (now exported):
  -o file or folder, else the current folder named from the prompt,
  numbered when more than one, never over a file that is there; a file
  not inline is downloaded by its path from the gateway asked (the token
  goes nowhere else). --json prints the raw answer and saves nothing.
- No magpie at the address: "magpie isn't running at <url>: open the app
  or run magpie serve". MAGPIE_GATEWAY=<url> points at another.

Docs: usage lines in magpie help, docs/reference.md (Use), the gateway
routing subsystem page (_meta and the CLI), README en/zh, site docs start
page en/zh/ja.

Tests (internal/cli/tool_cli_test.go, never the network; every test sets
MAGPIE_GATEWAY to its own httptest server):
- TestToolsListsTheServersTools, TestToolReadsParameters,
  TestToolRefusesWhatItDoesntKnowAndCallsNothing (no tools/call, no file),
  TestToolHelpCallsNothing (no request at all), TestToolSavesTheImage,
  TestToolWaitsOnWhatIsStillMade (pending _meta, then the old text form,
  download with the key from the gateway asked, not the URL's host),
  TestToolErrorIsSaid, TestToolSaysMagpieIsntRunning,
  TestToolDrawsThroughTheGateway (the real gateway.New().Handler() with a
  fake vendor: lists, draws, saves the vendor's PNG).
- TestImageMCPDrawsAndServesTheImage, ...SlowDrawingIsWaitedOn and
  ...MakesVideos now check the _meta. Red on the old behaviour: with
  withMeta setting nothing (what main answers) all three fail ("_meta
  map[], want pending img_…").
- Broken by hand: dropping the unknown-parameter check makes
  TestToolRefuses… red (the --model call was made); saving an inline
  image by its URL instead makes TestToolSavesTheImage red. Both restored.
- TestHelpOnEveryCommandDoesNothing covers tool and tools.

Run with this change on origin/main 630fd1d69, then rebased on cebd0d4c3
(internal/pii, internal/gui, docs and site/ changed between, nothing
this change touches): there
gofmt, go vet of cli/gateway/imagemcp, internal/cli, internal/imagemcp and
the gateway's TestImageMCP/TestVisionMCP/TestSearchMCP again, ok.
At 630fd1d69:
- gofmt -l: nothing. go vet ./...; GOOS=linux go vet -tags nogui
  ./internal/...; GOOS=windows go vet ./internal/...: clean.
- go test ./... -timeout 45m: internal/gateway, imagemcp and the rest ok;
  ten packages failed with "no space left on device" (the machine's disk
  was full from other runs). Those rerun when space was back: agent, cli,
  davsync, gui, library, sessions, settings, tui, usage, usageapi,
  wslrun, plugins/... ok. internal/provider crashes in
  TestUnreadLoginsWriteErrorsKeepCredentials with "close of synctest
  channel from outside bubble" (filememo.Forget), twice: that is #3632,
  open, on main since 091153bf7, nothing this change touches.
- Real try: a nogui build of this head as magpie serve on 127.0.0.1:3482
  under a scratch HOME, a custom provider pointed at a local fake images
  API. magpie tools listed image, vision and web-search with their
  parameters; generate_image "…" --size 1024x1024 -o hero.png saved a PNG
  and the vendor got prompt and size; --n 2 --quality high saved two
  numbered files; --model was refused before calling; analyze_image and
  web_search said what to set up (no vision model or search API there);
  --help asked nothing. Usage counted the calls as magpie's own.

Not tried: a real image vendor, a real vision or search model, a video,
a plugin's tool through magpie tool, Windows and Linux runs (vet only).
2026-10-26 18:42:35 +08:00
yetone a7072926d6 agent: connecting Kiro Crew connects the harness it is set to (wuping9525)
wuping9525 (Discord, Windows): Kiro Crew's Agent Harness was Claude Code,
Claude Code was installed but not connected to magpie, and turning Kiro
Crew on refused with "connect Codex, Claude Code, ... first". On a Mac it
worked only because a harness (Codex/Claude Code) was already connected;
Crew's home is found the same way on Windows (USERPROFILE\.kiro\crew).

Now, when agent.acp_backend names one of magpie's harnesses (codex,
claude, opencode, pi, goose) and that agent is installed but not
connected, connecting Kiro Crew connects it in the same action and runs
Crew on it; the notice says so. The stash's kirocrew.joined records it.
Kiro Crew's Disconnect disconnects that agent again only if magpie
connected it and the user hasn't disconnected it since (kiroCrewUserLeft
in Agent.Disconnect); a disconnect the user made before stays recorded as
theirs. A failed Crew write undoes the join. config.local.json pins,
kas/kiro/deepseek and harnesses not installed behave as before.

Windows: the adapter search also tries npm's .cmd/.exe/.bat shim names,
and the app is detected by ~\.kirocrew-app\.venv\Scripts\kirocrew.exe.
New notice translated in zh, zh-TW, ja, de; docs/subsystems/agent-wiring.md
and docs/reference.md updated.

Run (macOS, sandbox HOME, GOMODCACHE/GOCACHE pinned), at base 11c3fbb19;
after rebasing on 2921471de (no change under internal/agent or internal/gui
since), go vet and go test -run 'KiroCrew|Disconnect' ./internal/agent
again: ok.
- go test -tags nogui -timeout 45m ./internal/agent ./internal/gui: ok
  (252s, 62s)
- new tests: TestKiroCrewConnectsItsHarness (real Claude Code wiring in a
  sandbox), TestKiroCrewLeavesTheUsersHarness (connected before, taken
  back after, off before), TestKiroCrewHarnessNotHere, TestKiroCrewOnWindows
  (kiroCrewOS forced to windows, PATH emptied)
- gofmt -l clean; go vet nogui for darwin, linux, windows; windows build
- GUI: agent-kiro-crew-lang, i18n-keys, gui-de, gui-ja, gui-zh-tw in
  chromium and webkit: 35/35 pass

Broken by hand, each red: no join (ConnectsItsHarness, taken back after,
off before), no kiroCrewUserLeft hook (taken back after), always forgetting
the user's disconnect (off before), no .cmd names and no venv exe
(OnWindows), no leave on Disconnect (ConnectsItsHarness, off before);
notice dropped from the NOTICES list: agent-kiro-crew-lang 9 red.

Not tried: a real Kiro Crew or Windows machine (the Windows box's ssh
timed out); the disconnect preview doesn't show the joined harness's
files, since it copies only Crew's folder.
2026-10-26 16:31:14 +08:00
yetone ef0a03e137 otel: Langfuse is set up from its host and the project's two keys
A user on X asked for Langfuse built in. magpie could already export to
Langfuse over OTLP, but Settings › Observability had the user type the
endpoint .../api/public/otel and a percent-encoded
Authorization=Basic%20<base64(pk:sk)> header by hand.

Settings › Observability now has a Collector row: OTLP or Langfuse.
With Langfuse, the user picks the host (Cloud EU, Cloud US, or
Self-hosted with an address, which also covers Langfuse's JP and HIPAA
regions) and fills in the public and secret keys. Once both keys are
there, magpie saves:
- the endpoint <host>/api/public/otel;
- Authorization: Basic base64(pk:sk), in otel.headers as before, so the
  secret is stored where it was and a backup without keys leaves it out;
- on a first setup, also x-langfuse-ingestion-version: 4, metrics off and
  export on. langfuse.com/docs/opentelemetry/get-started (read 10-26)
  gives the same header for every region and for self-hosted, and says
  that without it OTLP data can arrive up to 10 minutes late.
A Langfuse endpoint set up by hand opens in this view with its keys
decoded into the fields. Opening it saves nothing. Changing a key or the
host keeps the user's other headers, their metrics and export choices,
and an ingestion header they set or left out. Switching from another
collector leaves that collector's headers behind and does not send them
to Langfuse.

The Observability page moved from app.js into the otel plugin
(assets/plugins/otel/page.js, with i18n.js for its words, in Client),
because app.js had 13 bytes of budget left. The app.js and core budgets
are lowered to what is left (1,321,319 and 1,537,645; app.js is
1,321,313 after rebasing on 2620dc319). "Collector" and "Secret key" go
in the core i18n.js because other files use the same words.

Docs: reference.md's Langfuse paragraph (with the env form for magpie
serve) and the en/zh/ja privacy pages.

Run (macOS):
- go test ./... -timeout 45m -count=1 at the pre-rebase head (parent
  e5dd86965): every package ok but internal/provider, which crashed in
  TestUnreadLoginsWriteErrorsKeepCredentials with "close of synctest
  channel from outside bubble" in filememo.Forget. That is #3632, red on
  main since 091153bf7.
- The whole GUI suite (make test-ui, concurrency 4, Chromium and WebKit)
  at the same head: 16 reds. Each red file was run alone here and at the
  parent e5dd86965. The same reds came back at both: menu-input-scroll
  (#3402), old-webkit (#3403) and plugin-card-update's webkit Update
  (#3079). The parent also failed fonts' webkit run. page-width,
  api-key-theme, panel-arrange, panel-balance-order, own-requests,
  library-mcp-health-wsl and plugin-list-error passed alone here: 137
  passes, 7 fails, all of them the three filed above.
- At the pushed head (rebased on origin/main c87a0179b): the budget
  tests; otel, otel-langfuse, i18n-keys, settings-sections, builtins,
  idle-ticks and page-width, both engines, 58 pass; go test
  ./internal/otlp ./plugins/otel ./internal/gui, all ok except
  TestRestartHandsTheGatewayOver (#3451). That test failed 1 of 8 here
  and 1 of 8 on origin/main dce7fe609.
- Before the rebase: otel-langfuse (new: first setup, US, self-hosted,
  hand setup kept, another collector's headers dropped, 5 languages at
  1100/520/360px) with otel, i18n-keys, settings-sections, builtins,
  readable-focus, segs-press-redraw, ux-safety, dialog-backdrop-drag and
  mono-icon-redraw: 113 pass. go vet for darwin, linux and windows on the
  touched packages; gofmt -l clean.
- Broken by hand: with every save treated as a first setup and the old
  collector's headers carried over, otel-langfuse's "set up by hand keeps
  its values" and "another collector's headers" went red.
- New TestOTelLangfuseSetup: settings saved as the page writes them reach
  a fake collector at /api/public/otel/v1/traces with the Basic header and
  ingestion version 4, and nothing on /v1/metrics.
- Real app: a -tags dev build in a sandbox HOME (ports 3461/3462). I
  drove its real Settings page with Playwright: Langfuse, then
  Self-hosted http://127.0.0.1:3463, then both keys. settings.json got the
  endpoint, Basic header, version 4 and enabled. A gateway request then
  reached a local fake collector at /api/public/otel/v1/traces with
  Authorization Basic base64(pk-lf-real-ui:sk-lf-real-ui) and
  x-langfuse-ingestion-version 4.

Not tried: a real Langfuse Cloud or self-hosted project (no account here),
so Langfuse accepting the spans and how they show in its UI aren't checked.
The TUI and magpie serve still have no Langfuse shortcut; serve takes the
env form in reference.md. The Linux app (WebKitGTK) and Windows weren't
tried; the change is form fields and segs, with no motion.
2026-10-26 15:11:37 +08:00
yetone 7499ebb5ef gateway: magpie goroutines answers ahead of the locks a stuck request holds
Two users on X (v0.1.1549 to v0.1.1557, Windows, Codex routing) see
/api/hello answer while /v1/models, Providers and agent requests hang.
`magpie goroutines` (b18a6a080, #3362, since v0.1.1404) can capture the
stuck process, but its route sat behind lanGuard's allow list
(settings.json's file lock) and holdCatalog (provider.Hold, filememo),
so a request stuck holding any of them would hang the dump too.

dumpFirst serves GET /v1/magpie/goroutines, for callers
goroutinesRefused lets in, ahead of lanGuard in Front and ahead of
counted/holdCatalog in Handler. It reads only the request, the
environment and the runtime. Every refused or other request goes on
as before; a caller it lets in is one lanGuard and corsGuard already
let in (loopback, unproxied, no browser marks, loopback Host).

docs/reference.md now says how to run it from an app install, where
magpie isn't on PATH unless Settings > Command line adds it:
macOS /Applications/magpie.app/Contents/MacOS/magpie goroutines;
Windows PowerShell
  & (Get-ItemPropertyValue 'HKCU:\Software\Microsoft\Windows\CurrentVersion\App Paths\magpie.exe' '(default)') goroutines | Out-Host
(| Out-Host so PowerShell waits for the GUI-subsystem exe), or a
portable copy's own path.

Run, at this tree on c0985122b:
- go test -tags nogui -count=1 -timeout 45m ./internal/cli ./internal/gateway:
  ok cli 36.2s, ok gateway 388.7s
- TestGoroutineDumpAnswersWhileRequestsWait -count=3: ok
- gofmt -l: clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/...: exit 0

Broken by hand:
- Front back to lanGuard(s.Handler()): the new test is red at 20.02s
  ("the dump didn't answer while settings.json's lock was held").
- Both refusal checks (dumpFirst and goroutineDump) removed:
  TestGoroutineDumpOnlyToThisComputer red, 25 failure lines.

Real use, Windows box: v0.1.1558 magpie-windows-amd64.exe (SHA256
matches SHA256SUMS) serving a sandbox home on :3447; the App Paths
one-liner above saved the dump and printed "goroutines 41", exit 0;
`& exe goroutines` with and without | Out-Host both saved it.

Not tried: a really stuck app; this build on Windows or macOS (the
real-use run above was v0.1.1558, without dumpFirst); an interactive
PowerShell console without | Out-Host; the Handler-only path has no
red test, since provider.held can't be held from the gateway package.
2026-10-26 05:53:34 +08:00
yetone 0152f66966 provider: a Remote magpie's model list follows the other magpie's, fetched every 10m (6igsteven on Discord)
6igsteven (Discord, 10-24/10-25): GLM-5.3-Trial and GLM-5.3-Flash-Trial
are listed on the magpie that runs the ZCode plugin, and not on the
magpie that uses it as a Remote magpie. The trial entries come from the
ZCode plugin once it reads the account's gift (zcode 0.1.26), and the
other magpie's /v1/models lists them as it lists every catalog entry.
But a Remote magpie is a provider of keys: its list was fetched when it
was added and then only when Fetch models was pressed in its editor
(KeepListsFresh asks only providers with a RefreshEvery, FetchNew only
accounts). So anything listed there later (the trial models, a new
provider, plugin or routing group) never reached this magpie.

A Remote magpie with no RefreshEvery now has a 10m schedule
(RemoteMagpieEvery, RefreshSchedule), so KeepListsFresh refetches it
through the same Refetch as Fetch models. `magpie provider refresh-every
<id> off` on a Remote magpie is kept as "off" rather than "" so the
user's off isn't read as unset. CLI show/refresh-every print the
schedule in force. Other providers are unchanged: no schedule means
only when asked.

Run: TestRemoteMagpieListFollowsTheOtherMagpie (new) with
TestKeepListsFreshFetchesWhatIsDue, TestParseRefreshEvery,
TestSaveKeepsTheListsScheduleAndRules: ok, sandbox HOME, Go caches
pinned. Broken by hand: RefreshSchedule returning RefreshEvery alone
(the old behaviour) fails the new test with "asked [], want [office]";
restored, ok. gofmt -l clean.
Then, at this commit: go test ./internal/provider ./internal/cli ok
(140s, 58s); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows ok; darwin, linux (nogui) and windows builds ok.
Not run: go test ./... - the machine's disk had under 1GB free
(other sessions' work) and load ~200, so a full suite would not fit.
Not tried: a real two-computer setup with a live ZCode gift. A Remote
magpie whose user curated its picks (left a listed model unpicked)
still doesn't take new models by itself (withNewlyListed, by design).
2026-10-25 16:30:48 +08:00
yetone a2ff7e6cab plugin: add takes a community plugin's name (WorkBuddy, think-tags, qoder-cn)
Atlas on Discord (#help, 10-25, Linux): `magpie plugin add WorkBuddy`
said "isn't an npm package name". Worse, a bare `workbuddy` passed the
npm-name check and installed npm's unscoped workbuddy@latest, not
@magpie-community/opencode-workbuddy-auth.

plugin.Add, which the CLI, the Plugins page's field (/api/plugins/add)
and the movers all go through, now resolves a bare name first
(internal/plugin/resolve.go). Case aside, a name one community listing
goes by is its package, at the version given: the package or its bare
name, the short name (workbuddy, think-tags), the shown name (WorkBuddy,
Command Code), a provider id it serves or the subscription it replaces,
and a retired subscription's id through its mover (qoder-cn; provider
sets plugin.SubscriptionPlugin = MovePackage). The CLI says which
package it picked. A name two listings go by, or none that isn't an npm
name, is refused with the community plugins listed. A name no listing
goes by is npm's own package (opencode-gemini-auth keeps working), but
only when the list was fetched within the six hours: when the fetch
fails, the copy kept or built in may not name a newer plugin, so the
name is refused with why, and npm:<name> installs npm's package as
written. market() now says whether its list is a fresh fetch (marketErr).
Scoped names, paths and git specs are unchanged. A backup's or a sync's
plugins go in by their own spec (plugin.AddExact via addPluginExact),
never resolved, so a restore isn't held by GitHub being unreachable.
Update, Upgrade and InstallMissing use add with stored specs, unchanged.

Tests (fake registry over httptest, fake bun; no network):
TestResolveCommunityNames, TestResolveRefusesWhatItCantName,
TestResolveListUnread, TestAddByCommunityName. TestUpdateAllUpdatesAPinnedPlugin
adds an unscoped third-party name, so it now serves a registry.

Broken by hand: Add without resolve -> TestAddByCommunityName red with
the reporter's own error ("WorkBuddy" isn't an npm package name) and
workbuddy -> workbuddy@latest. The unread-list rule turned off (valid
name goes to npm regardless) -> TestResolveListUnread red.

Real use, sandbox HOME, built binary, real npm and GitHub:
`plugin add WorkBuddy` -> installed @magpie-community/opencode-workbuddy-auth@latest,
listed workbuddy and workbuddy-ai; `think-tags` -> middleware-think-tags;
`opencode-gemini-auth` -> npm's, google-plugin listed; `qoder-cn` with
MAGPIE_PLUGIN_MARKET=off -> opencode-qoder-auth; "Work Buddy Pro" ->
refused with the 38 community plugins listed; `twinz` with the list off
or at a dead URL -> refused, saying why and npm:twinz.

Run at this head (rebased on origin/main 42976f9a0): gofmt -l clean;
go vet (darwin) and GOOS=linux / GOOS=windows -tags nogui vet of
plugin, provider, cli, backup, gui clean; go test -timeout 45m
./internal/plugin ok (120s, after the pinned-update fix),
./internal/provider ./internal/cli ./internal/backup ./internal/gui ok.

Not tried: the full ./... suite; Windows and Linux runs of the tests.
No GUI JS changed: the Plugins page's field goes through the same Add,
and its status still says "<typed name> is installed" rather than the
package picked; the installed list shows the package.
2026-10-25 11:52:02 +08:00
yetone 402577c15a gateway: image generation is an MCP server on the gateway, /mcp/magpie/image
JonahFu on X runs magpie in Docker in gateway mode, so he has no Library and
no stdio Magpie Image server, while image recognition is an HTTP MCP server
on the gateway (/mcp/magpie/vision). Now image generation is one too, with
the stdio server's tools: generate_image, generate_video and
generation_result, drawing with Settings › Images › Image generation.

- image_mcp.go: served by serveMCP, so it is guarded as the vision server
  is (local or a shared magpie's caller, a refused Origin 403, POST only,
  the key's limit reserved per call). A drawing is s.images run in-process
  on a clone of the request (caller and key kept), so routing, key models,
  usage and the timeout setting are draw.go's own. It runs as a job (15
  min at most); the tool answers within 20s or gives an id that
  generation_result waits on. Images come back as MCP image content (5 MB
  each at most) and at /mcp/magpie/image/files/<name>, kept in memory an
  hour, 256 MB at most, readable only by the key that made them. Videos
  go through videosCreate/videosGet in-process and are given as
  /v1/videos/<id>/content. Image generation Off is a tool error naming
  where to turn it on, before the arguments are read.
- Input images go through the vision server's reader, now mcpImageSrc
  (vision_mcp.go), so a file path is read only for a local caller.
- The tool schemas live in the gateway (ImageToolProps, VideoToolProps,
  ResultToolProps); internal/imagemcp takes them and adds only its path
  argument. Its tools/list JSON was compared byte for byte with the old one.
- Settings › Models: #imageMcpRow under #visionMcpRow with the address and
  a copy button; the gateway-mode Image generation sub now points at it.
  en, zh, zh-TW, ja, de.
  The two rows are drawn by one helper (mcpRow), which took the vision
  row's own code, so the row costs 462 bytes of app.js.
- core_budget_test: appScriptBudget 1,321,336 -> 1,321,424 and
  coreScriptBudget 1,528,525 -> 1,528,972, the exact sizes with the row,
  with no room added (10-25). Nothing moved out: the row is Settings'
  own, which the core draws.
- search-api.test.cjs: the new row pushed the search row partly below the
  1400px window at 420px, where scrollIntoViewIfNeeded leaves it, and
  magpie puts back a scroll the reader didn't make, so the test's
  coordinate clicks missed. It now brings the whole row on screen with
  the wheel and checks it is still there a second later. Red with the new
  row before this, green after; green on origin/main's GUI either way.
- oneport_test knows ImageMCPPath and ImageMCPFiles (ClientPath covers
  them).

Run (worktree at this commit, on origin/main 94503901c):
- go test -tags nogui -run 'ImageMCP|VisionMCP|ClientPath|SearchMCP'
  ./internal/gateway/ ok; ./internal/imagemcp ok; the image and vision MCP
  tests with -race -count=3 ok.
- Red on the old code: TestImageMCPDrawsAndServesTheImage (the route is
  404).
- Broken by hand, each red: no route (DrawsAndServes), no key check on
  files (Guarded), no Off check (SaysWhenOff), no reserveFor
  (HeldToKeyLimit), no local-only file read in mcpImageSrc (Guarded).
- GUI, chromium and webkit, every language, at this commit: image-mcp,
  vision-mcp, i18n-keys, images-library-way, search-api,
  settings-sections, gui-de, gui-ja, gui-zh-tw (123/123). Before the
  helper and the rebase: image-mcp, vision-mcp,
  images-library-way, images-codex-one, image-timeout-setting,
  images-missing, i18n-keys, gui-de, gui-ja, gui-zh-tw, settings-sections,
  vision-not-marked (201/201); claude-lean-prompt-setting,
  classify-timeout-setting, disabled-models, member-model-setting,
  loop-guard-setting, refusal-retries-setting, search-first, search-order,
  search-mcp, searcher-pick, side-effort, search-api, search-keys (198/198
  after the search-api fix; search-api alone 8/8 twice).
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- Full suite (go test -tags nogui -timeout 45m ./...): the run before the
  helper was red only in TestCoreScriptBudget, fixed above; a run at this
  commit was started and not finished at push (pushed at once, the
  owner's rule), its result goes on the push report.
- Real: magpie serve (nogui) in a sandbox HOME on 127.0.0.1:3592, its
  Image generation a provider pointed at the live gateway's
  codex/gpt-image-2.5. curl: initialize (Magpie Image), tools/list (the
  three tools), Origin https://evil.example 403, GET 405, an unknown file
  404, GET /v1 lists /mcp/magpie/image, Off answers the Off text for both
  tools. generate_image reached Codex through the live gateway and came
  back as the tool error "yetoneful@gmail.com's sign-in has expired".

Not tried: a real image drawn end to end (the only drawing account's
sign-in has expired; image content and file URLs are covered by fake
upstreams), a real video, a call from another computer with a gateway key
(the remote and key paths are covered by TestImageMCPGuarded), Docker.
2026-10-25 06:42:03 +08:00
yetone e3491e2bb0 docs: point dsh's own DeepSeek row at magpie by hand (#3298)
tom047784 (Discord) wants dsh's llm-deepseek row, which keeps DeepSeek's
cache across in-history prompt and tool updates and uploads images
through the Files API, to go through magpie. magpie doesn't take that
row over (the key would mean two things, it would override the user's
own entry, and a file_id belongs to one account while magpie fails
over), so this documents the entry a user writes themselves:
docs/reference.md under "Notes on some agents", and a FAQ entry in
site/public/docs start.html (en, zh, ja).

Checked against @deepseek-ai/dsh-llm-deepseek 0.2.1-rc.2's source
(npm pack into a scratchpad, read only): messagesApiRoot adds /v1 to
baseURL unless it ends in /v1; apiKeyEnv is a credential reference read
from dsh's credentials and then the environment; an explicit models list
replaces DEFAULT_MODELS, whose in-history/addition-only settings are on
deepseek-flash only; any Files failure rebuilds the request inline,
bounded by maxInlineRequestImageBytes (20 MiB) against
maxRequestFilesBytes (128 MiB). Against magpie: internal/agent/dsh.go
drops only magpie-marked llm-deepseek entries and removes
MAGPIE_GATEWAY_KEY on Disconnect; POST /v1/files answers 404; the
catalog ids are deepseek/deepseek-flash and deepseek/deepseek-v4-pro.

Tried: real dsh 0.2.1-rc.2, `dsh --profile headless`, sandbox DSH_HOME
and HOME, a magpie built from this tree on its own port. Through a fake
Anthropic upstream: "say pong" answered; the upstream got
output_config.effort, thinking, tools, dsh_session_log and
dsh_plugin_packages as sent, the provider's key, and no
x-deepseek-harness-* header. A mid-history system message with
tool_addition and the mid-conversation-tool-changes anthropic-beta went
through unchanged (curl). With a real DeepSeek key copied into the
sandbox: dsh read a file with a tool, three calls all 200, cache_read
5760 on a later call; a system message added in the history after two
turns was followed and cache_read_input_tokens was 3456. Usage rows had
agent dsh, /v1/messages and dsh's session; x-deepseek-harness-compact: 1
recorded kind compact.

Not tried: an image turn through dsh (the inline fallback is from the
source and the 404), the desktop app and its Models-page key entry,
Windows.
2026-10-25 05:50:34 +08:00
yetone 1b32bdcfcb gui: magpie web's port answers the gateway's /v1 routes too, so one proxy location serves both (zgcwkj on Discord)
zgcwkj puts magpie behind nginx on one domain and wanted the browser UI
(magpie web / serve --web, 127.0.0.1:3430) and the gateway (:3425) from
one port, so one location works. Now the web port hands every gateway
client route to the gateway: /v1/..., /v1beta/..., /models, /chat/completions,
/responses, /messages, /images, /embeddings, /rerank, /audio, /videos,
/muse-code/models, /backend-api/codex/..., the search path and /mcp/...
(gateway.ClientPath). Everything else stays the page's, behind webGuard as
before. /api/* stays split: on the web port it is the UI's API; Ollama's
/api/* and Claude Desktop's /api/hello still need the gateway port, since
the two can't share the path.

Security: a handed-over request goes through the gateway's whole own
stack, not a copy of it. gateway.Server.Front() is lanGuard(Handler()),
built once; ListenAndServe serves the same handler. When this process
serves the gateway, the web port calls Front() in process; when another
magpie does, toGateway reverse-proxies to gateway.URL(), keeps the Host,
copies Forwarded/X-Forwarded-* back (ReverseProxy strips them), and adds
X-Forwarded-For for a non-loopback peer, so remote, proxied, rebound,
Origin null, *.localhost and foreign-Origin requests are judged exactly as
on the gateway port. The web cookie is never a gateway key. Paths that
aren't clean (/v1/../api, /v1//x, /v1/./x) are not client paths, so they
never reach the gateway as one. The allow list (AllowGuard) still wraps
both.

Tests:
- TestClientPathCoversHandler reads every mux pattern Handler registers
  and fails when one is neither a ClientPath nor /, /api/* or /_magpie/*,
  so a new gateway route has to be placed.
- TestClientPathOnlyClean.
- TestWebOnePortServedHere / ServedElsewhere: with no web cookie, the UI
  API (/api/settings) is never reached for: no Origin (GET, POST),
  Origin null, a foreign Origin, a rebound Host (GET, POST), through a
  proxy (XFF), from another machine, /v1/../api, /v1/%2e%2e/api,
  /v1//api, and with a gateway key. The gateway routes on the web port:
  local agent 200; Origin null POST 403; foreign Origin 403; rebound Host
  403 (with the page's cookie too); proxy or remote without a key 401
  (with the page's cookie too); with a gateway key 200; not shared 403.
- TestWebAssetsAreNoClientPath: no embedded asset shadows a client path.

Run (full packages at the first rebase, on origin/main 0b72ccbef):
- go test ./internal/gateway ./internal/gui -count=1 -timeout 45m:
  ok (gateway 644s, gui 193s).
- Rebased again on origin/main 8b460833e (upstream touched catalog,
  provider, redact and usage only); at this head: the three builds and
  the vets below again, and go test -run 'TestClientPath|TestWeb'
  ./internal/gateway ./internal/gui: ok. The full packages were not
  rerun at this head.
- gofmt -l internal/gateway internal/gui: empty
- go vet ./internal/gateway ./internal/gui; GOOS=linux go vet -tags
  nogui ./internal/gateway ./internal/gui ./internal/cli; GOOS=windows go
  vet ./internal/gateway ./internal/gui: ok
- go build .; GOOS=linux go build -tags nogui .; GOOS=windows go build .: ok

Broken by hand, each red, then restored:
- no onePort (the old web handler): agent 401 not 200, Origin null 401
  not 403 (ServedHere).
- Front without lanGuard: rebound Host 200, proxy without a key 200.
- toGateway not copying the forwarding headers: proxy without a key 200,
  not shared 200 (ServedElsewhere).
- no X-Forwarded-For for a remote peer: another machine 200.
- Host not kept: rebound Host 200.
- ClientPath taking unclean paths: TestClientPathOnlyClean red (4 paths).
  The gui tests stay green under this break, since the gateway's mux
  answers /v1/../api/settings with a redirect, not the UI API; the clean
  check is a second wall.

Real try: the built binary, `magpie serve --web=127.0.0.1:3472` under a
sandbox HOME (MAGPIE_ADDR=127.0.0.1:3471, MAGPIE_NO_ACCOUNTS=1,
MAGPIE_TEST_SANDBOX), then Homebrew's nginx 1.31.7 (bottle unpacked in a
scratch folder, proxy_pass to 3472 with Host and X-Forwarded-For) on
127.0.0.1:3473. Direct on 3472: / 401, /?k= 303, /api/settings 401
without and 200 with the cookie, /v1/models 200, Origin null POST 403,
foreign Origin 403, X-Forwarded-For 403 (not shared). Through nginx, not
shared: /v1/models 403 with the "came through a proxy" reason; the UI
signs in with /?k= and /api/settings is 200 with its cookie. Sharing
turned on and a key added from the UI API through nginx: /v1/models 401
without a key and 401 with only the page's cookie, 200 with the key;
/v1/messages and a streamed /v1/chat/completions with the key reach the
gateway (404: the sandbox has no provider); /api/settings with the key
401; Origin null and foreign Origin without a key 401; /v1/../api/settings
401; /api/tags 401 (the page's API, not Ollama's). A rebound Host on
either port is refused only for a request that looks like a browser's
(Sec-Fetch-Site), the same as the gateway port before.

Not tried: a real model reply (and so a long stream) through the one
port, since the sandbox has no provider; https, WebSocket (Codex's
/backend-api/codex websocket) through nginx; Windows and Linux, other
than vet and build; the GUI suite (no GUI asset changed).
2026-10-25 04:01:52 +08:00
yetone 0b72ccbeff agentplug: connect's models carry /v1/models' native_endpoints and pricing
cleary5779 on Discord builds an agent as an agent plugin and wants, in
connect({ gateway, model, models }), the API each model passes straight
through on and what it costs. Each entry of models (and model) now also
has, by the names /v1/models uses:

  "native_endpoints": ["/v1/chat/completions"],
  "pricing": {"prompt": "0.0000003", "completion": "0.0000012",
              "input_cache_read": "0.00000003"}

Each is left out when not known: a group or a model translated anyway
has no native_endpoints, an unpriced model no pricing, never [] or 0.
The fields connect had (id, name, context, output, images, efforts) are
as they were.

No second lookup: nativeEndpoints moved from the gateway to
provider.NativeEndpoints, and openRouterPricing/perToken to
catalog.OpenRouterPricing/PerToken (internal/catalog/openrouter.go); the
gateway calls them as before. magpieModels already priced each model with
provider.EntryPricer, the price /v1/models gives (m.Price); it now also
keeps NativeEndpoints in catalog.Model.Endpoints (json:"-"), which
plugged's wire turns into the two keys.

Docs: reference.md's agent plugins section (what connect gets, with an
example), agent-wiring and gateway-routing subsystem pages, and the
site's Plugins page in en, zh and ja.

Run at this tree (on origin/main 66b6d6ade), load ~150:
- gofmt -l internal: nothing. go vet on the touched packages,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test ./internal/catalog ./internal/provider: ok (agentplug has no
  tests). go test ./internal/gateway -run 'Models|PerToken|OpenCode|
  Native|Cursor': ok.
- go test ./internal/agent -run 'Plugged|Pi|Price|Alma|ModelOrder|Image|
  Group|Codex': one red, TestCodexThreadsComeBackOffMagpie/disconnect
  (.cache/magpie/sessions.json left in its TempDir), open as #3422; it
  passes 5 of 5 alone and this change doesn't touch sessions.
- TestPluggedConnectSeesEndpointsAndPricing is red with plugged.go's two
  keys taken out (no native_endpoints, no pricing on model or models),
  green with them.
Not run: the full ./... suite (machine at load ~150 with several suites
queued); the whole agent and gateway packages. Not tried: a real agent
plugin reading the fields.
2026-10-25 03:39:50 +08:00
JoeyWu-tech b18a6a080b gateway, cli: magpie goroutines writes the running magpie's goroutine stacks to a file (#3362)
#3362's second ask: an app stuck at something could only be read by
killing it, which ends what was stuck. magpie heap and magpie cpu
already ask the running gateway for a profile over loopback; magpie
goroutines asks it for every goroutine's stack. That works on Windows
too, where there is no SIGUSR1.

GET /v1/magpie/goroutines (goroutines.go) answers the callers
/v1/magpie/heap answers (profileRefused: a program on this computer
over loopback, no browser mark, a loopback Host; a gateway key lets
nothing else in) with runtime/pprof's goroutine profile at debug=2,
the form a crash prints: each goroutine's state and wait ("[select,
4320 minutes]"), its frames with source lines, and who started it. It
is text/plain and no-store, and X-Magpie-Goroutine-Stats names the
process (pid, program, version, window, uptime, goroutine count).
Arguments are words in hex, never what they point at, so the dump
holds no keys, prompts or messages; it does name magpie's source files
and the program's path, which the usage says.

magpie goroutines [<file>] writes it to <file>, else
magpie-goroutines-<date>-<time>.txt in this folder, 0600 and never over
a file there, then prints the file and the process. --help, -h and help
print the usage and ask nothing; a flag it doesn't take, "-", a blank
name or a second file are refused before the gateway is asked. A
magpie older than this one answers 404 and is told to update; with
none answering, it says so.

The refused callers TestHeapProfileOnlyToThisComputer listed move into
profileCallersRefused, which the CPU test and the new one share.

Run on b437e4ad, go1.26.8. internal/gateway and internal/cli are the
same here and at the branch's head (tree 613df3a9), where the checks of
them ran:
- gofmt -l and go vet as in the commit before: clean.
- go test ./internal/gateway -run 'Goroutine|Heap|CPU|Profile': ok;
  ./internal/cli -run 'Goroutines|Heap|CPU|Help': ok.
- Broken by hand: goroutinesRefused letting every caller in makes
  TestGoroutineDumpOnlyToThisComputer red ("Origin null with a key":
  200); debug=1 for 2 makes it red (the parked goroutine isn't in the
  dump); without the route it is red (404), and so is
  TestGoroutinesWritesTheRunningGatewaysDump ("older than this one").
  Restored, green.
- Full suite at this commit, go test -tags nogui -count=1 -timeout 45m
  ./... (tree e5cf04af, 498s): 62 packages ok. 14 reds in 7 packages,
  none in a file this commit touches, each red on b437e4ad without it:
    internal/agent TestInstalledVersion, TestOmpDetectedWithPiDir,
    TestCursorFolderFromTheEditorIsNotTheCLI and TestZedAppPath:
    proc.Look keeps "not found" for a tool written in the tick of its
    folder's last change (#3141).
    internal/agent TestCodexDriftReached: Drift answers from the read of
    Codex's log taken before the test's last insert (#3398).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: a real stuck app; magpie goroutines against the app on macOS
or Windows (the tests serve gateway.New().Handler() on loopback).
2026-10-24 21:33:06 +08:00
yetone b5d46acbed agent: Kiro Crew runs on a harness connected to magpie
Vincent on Discord asked for Kiro Crew (kirodotdev/KiroCrew v0.9.0: the
KiroCrew.app desktop app, the kirocrew CLI, its dashboard and the Gateway
on :5476). Crew has no model provider of its own. It runs each session on
an ACP harness picked by agent.acp_backend (and dispatched members by
agent.member_acp_backend) in $KIROCREW_HOME/config.json, default
~/.kiro/crew (src/kiro_crew/config/paths.py, loader.py, sections.py;
ACP_BACKENDS_MEMBER_DISPATCH in agent_sdk/backends.py).

Connecting sets those keys to an agent already connected to magpie,
tried in this order: Codex, Claude Code, OpenCode, Pi, Goose. One whose ACP
adapter is installed (codex-acp, claude-agent-acp, pi-acp) wins, so one
click is enough. magpie looks for the adapter where Crew does and installs
nothing; when it's missing, the notice gives the npm command. With no harness
connected the connect is refused with a message naming which agents to
connect. A harness set in config.local.json wins over config.json, so magpie
doesn't write it and the row says so. The previous values are stashed. On
Disconnect they are put back, but only for keys that still hold what magpie
wrote, and a file magpie created is removed once it's empty. The row reads as
connected only while its harness is still wired to magpie. deepseek is not
offered: Crew runs it as dsh --profile acp, which magpie's dsh wiring doesn't
reach. KIROCREW_HOME and the adapter path variables are read from the login
shell (agentenv).

Run (Go and the GUI files at base 137187a40, then again after the rebase onto 3d758d034):
- go test -tags nogui ./internal/agent ./internal/agentenv: ok, in a
  sandbox HOME
- gofmt -l is clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/agent/... ./internal/agentenv/...: ok
- GUI: the new agent-kiro-crew-lang.test.cjs (refusals, notice and words in
  en, zh, zh-TW, ja and de; chromium and webkit; 1100 and 420px) 22/22. The
  agent*, gui-*, i18n* and header-relang files (45), concurrency 2 at load
  ~250: 632/633. The red was agent-models-own, chromium en 420, where the dsh
  row's model click timed out at 5s (#1666, filed). After the rebase that
  file and the new one, run alone: 38/38.
- After the rebase: go build ./...; the KiroCrew, Notice, FolderVars,
  EveryPicker and ListsModels tests: ok. go test ./internal/gui: everything
  passed except TestMainWindowCorners, which was killed at its 40s
  measurement at load ~200 (#1936, #2645, both filed; this change touches
  no window code).
- No go test ./... at the pushed head before the push: the machine is at
  load 200-300, other sessions are queued for the suite lock, and ships go
  out at once (owner, 10-22). Queued to run behind them at the pushed
  head.
- Real Kiro Crew: Crew v0.9.0 was installed from source into a sandbox venv,
  and its own loader (load_config_with_content_stamp, overlay_pins) read the
  config.json magpie wrote over the real Codex wiring in a sandbox HOME:
  acp_backend='codex', member_acp_backend='codex'. With a config.local.json
  pin it reads the pinned value and overlay_pins is True. Disconnect gave the
  user's file back as it was, and removed the file magpie had created.

Broken by hand, each red:
- restore off: Connect, PicksAHarness, HarnessPick, MakesItsFile
- the pin check off: LocalPin
- adapter preference off: PicksAHarness
- the member key always written: PicksAHarness, HarnessPick
- harness wiring unchecked in on(): FollowsItsHarness, OnRealCodexWiring
- the ja translation of the pinned refusal removed: the new GUI test, ja at
  both widths

Not tried: Crew's Gateway starting a real session through codex-acp
against magpie's gateway, and none of Crew's harnesses was run under it.
Adapter paths on Windows. A user who pinned agent.model to a kiro-only
model on a non-kiro harness.
2026-10-24 20:59:25 +08:00
yetone 48194bbee0 routing: an In order group's later members aren't said to go after a known allowance (bitssly on X)
bitssly on X (10-24) asked why, with a group set 按顺序 (In order), an
account whose quota isn't known "can't be used", quoting the Routing
page: "opencode:剩余额度未知,排在已知的之后。" and "腾讯-国际:剩余额度未知,
排在已知的之后。"

Cause: the gateway does what the mode says. planGroup/planLevel try an
In order group's members in the order given and never by what each has
left; each member's own accounts go as that member's provider routes
them (Smart by default, where an unknown allowance still comes before
any account at 90% or more and is tried when the known ones fail). The
explanation was wrong. weighed() gives an ordered group's rows their
member's routing (""), so the page's smart() judged each row against
every known row of the whole request: an In order group's later
members read as ranked behind a known allowance, and the first got a
Smart reason ("its allowance renews soonest ...") instead of In order.
A By weight group's first had the same fault.

Change:
- client.js: placeRouting/wholeMembers/weighedWith scope what a row is
  weighed against to its own member when the level that placed it takes
  members whole (order, weight). firstWhy says "In order: {who} is
  first ..." for such a group, and "By weight: it's {who}'s share ..."
  for a weighted one; the unknown, learns, spent and low asides are said
  only of an account weighed against another of its own member. Rebased
  onto 6d707af08 (Creat.wu, memberSplit): its member line now asks the
  scoped someKnown(x), so an unknown account alone in its member gets no
  line at all, and one beside a known account of its own member gets
  6d707af08's one line for the member.
- i18n.js: the By weight line in zh, zh-TW, ja, de.
- routing-order-unknown.test.cjs: In order, Smart and By weight groups
  over Codex (known), OpenCode Zen Free "opencode" (unknown) and two
  WorkBuddy AI accounts (one known, "腾讯-国际" unknown); chromium and
  webkit, en/zh/zh-TW/ja/de, 1100 and 420 wide.
- docs/reference.md: Smart's unknown account is still tried when the
  known ones fail; an In order group keeps its order whatever is known.

Why the quotas are unknown: OpenCode Zen Free is a free tier with no
allowance to report. Tencent Cloud Token Plan and Volcengine access-key
plans are read for the Usage page but not for routing; that class is
#3251. No plugin change.

Run:
- old client.js with the new test: red on the why line (chromium en/zh
  1100: "c@x.test goes first: of those with quota to spare, its allowance
  renews soonest ..." where "In order: c@x.test is first ..." was due).
- at the rebased head (origin/main 1f8f80e4a plus this):
  routing-order-unknown, routing-weight-member-low and i18n-* 64/64.
- go test -timeout 45m ./internal/gui/... at the rebased head: ok but
  TestMainWindowCorners (killed measuring windows at load ~80; red alone
  too; #1936, #2645, AppKit, not this change). Before the rebase: ok
  (112s).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. No Go file changed, so gofmt has nothing to check.
- whole GUI suite at ab287a839 (before the rebase), concurrency 4, load
  50 to 80: files a* to roughly o* ran; reds, all outside routing and
  filed: api-key-theme chromium system (#3307, also 1 of 3 alone),
  fonts webkit narrow (#3227), library-mcp-health-wsl ja (#3350),
  menu-input-scroll chromium en/zh (#3402). The rest of that run is void:
  my own rebase put conflict markers in client.js mid-run. The files from
  n* on are run again at the pushed head after this push.

Broken by hand: someKnown made global again (the old aside scoping):
red, the opencode aside is back under the In order group.

Not tried: the reporter's own trace and accounts (not shared); a Go
test for the gateway's order (unchanged here, covered by the existing
fallback tests); routing reading the access-key plans (#3251).
2026-10-24 19:09:41 +08:00
yetone edff2f819a provider: levels kept of a model's own narrow only what is offered again (#92)
4a3e07f1c made provider.Efforts return the levels a user kept, so the
gateway fitted every request to them. That reversed #92 (47e12df41),
which was explicit that narrowing a model's levels changes only what is
shown and "the levels the vendor is asked at stay as they were": a user
who had trimmed a picker with `magpie model efforts` or Names & levels
would have had their agents' xhigh and max asks lowered unasked. Dani's
request (magpie model spec) needs levels to count only where magpie
knows none for the model.

- Efforts is back to what it was before 4a3e07f1c: the vendor's list's
  or models.dev's levels when known, else the ones the user declared
  (`magpie model spec --reasoning` on a custom provider's model), which
  a request is then fitted to. --reasoning off (reasonless) is as
  4a3e07f1c built it.
- TestModelEfforts' "the vendor is still asked at any level it has" is
  restored as it was.
- TestKeptLevelsBoundTheAsk becomes TestNarrowedVendorLevelsAskAsBefore:
  a models.dev-known model narrowed to low-high is offered low..high and
  still sends xhigh, max and low as asked.
- gateway-routing.md, reference.md, the settings.go comment and spec's
  usage say so: narrowing is display-only, declared levels are fitted.

Run at this tree (base 4a3e07f1c):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider
  ./internal/cli ./internal/settings: ok (gateway 386s).
- gofmt -l empty; go vet darwin, linux -tags nogui, windows clean.
- Broken by hand, each red: 4a3e07f1c's Efforts (TestNarrowedVendor-
  LevelsAskAsBefore: xhigh and max went as high; TestModelEfforts:
  [low high]); declared levels ignored (TestModelSpecReachesTheGateway:
  xhigh sent as xhigh with low-high declared).
- Every other p.Efforts caller (gateway fit, decide, classify, automode,
  rules, side effort) is on the request path and is back to its
  behaviour before 4a3e07f1c.

Not run: the GUI suite (no GUI file changed; the GUI reads entry
Efforts, which still carry the kept levels) and a full go test ./....
2026-10-24 05:51:22 +08:00
yetone 4a3e07f1cf model: magpie model spec sets a model's window, output, vision and levels at once
Dani Ariyanto on Discord (#feedback, 10-24): a custom provider's models
(kenari/*:free) had no window, reply limit, vision or reasoning known,
and there was no one place to say them.

  magpie model spec <provider/model>                 what it has, and whose each value is
  magpie model spec <provider/model> [--context <n>] [--output <n>] [--vision on|off|auto] [--reasoning <levels>|off|auto]
  magpie model spec '<provider>/*' --context <n> --output <n>
  magpie model spec <provider/model> --reset
  magpie model specs

It writes the stores magpie model context/output/images/efforts write
(providers.json contexts; settings.json modelOutputs, modelImages,
modelEfforts, modelReasonless), so every reader that went by those goes
by a spec: entryFor/EntryOf/Served, /v1/models, max_tokens, the GUI's
/api/providers badges and chips, and the agents' model lists. Every
part is checked before anything is written; a refused command writes
nothing. Agents are told once.

Readers that bypassed the stores and now honour them:
- provider.Efforts returns the kept levels, so the gateway fits a
  request to them (fitEffort): xhigh asked of a model kept to low-high
  goes as high. This reverses #92 (47e12df41), which narrowed only the
  lists handed out; docs/subsystems/gateway-routing.md says so.
- entryFor: levels given a model with none known make it Reasoning.
- gateway AutoVision picks by the user's ModelImages (seesAt).
- GUI gateway client: a reasonless model offers no level chips.

Run at this tree (base a93190ae1):
- go test -count=1 -timeout 45m ./internal/{provider,cli,gui,gateway,
  settings,tui,agent,catalog}: all ok (gateway 505s, agent 360s).
- GUI: gateway-*.test.cjs, model-reasonless, plugin-gateway, i18n-keys
  (25 files, both engines, the new file at 1100 and 420 in en, zh,
  zh-TW, ja, de): 225/225 pass. app.js untouched.
- gofmt -l empty; go vet darwin, linux -tags nogui, windows clean.
- Sandbox HOME, built binary, `magpie web` on 47821/47820 and a fake
  Chat vendor on 47811: before, kenari/glm-5:free had no window or
  levels; after spec 128k/16k/on/low-high, /v1/models said 128000,
  16000, image input, [low medium high]; max_tokens 100000 went as
  16000, xhigh as high, low as low; qwen-x with --reasoning off was
  sent no reasoning field; /api/providers had context 128000, output
  16000, images/imageSet, kept [low medium high], reasonless for qwen-x.
  A models.dev sync during the run (GLM-5 202752/131072) didn't move
  the spec; after --reset the vendor's values came back. Bad values,
  an unknown flag and --help wrote nothing (files hashed).

Rebased onto a6a3dbde8 (the ZCode mover's min, one line): at the
pushed head 5af093d8b's tree, ./internal/provider and ./internal/cli
-timeout 45m ok, and the spec tests in gateway and gui ok.

Broken by hand, each went red: AutoVision on raw sees; Efforts on the
full list; the Reasoning line removed; output, vision or context not
written; ParseLevels skipped; agents told twice; --context 0 taken;
help printing modelUsage; old client.js; the GUI named() image and
reasonless branches.

Not tried / not changed: no full go test ./... (another session's
full GUI suite was running). Codex's ChatGPT-model /models pass-through
and the Codex effort dropdown read catalog.Codex(), not a spec. The
TUI shows no spec badges. A Context-tab trace keeps the window it was
recorded with. Pre-existing and the same on origin/main a6a3dbde8: a
GLM-5 relay with no levels known has xhigh sent as high.
2026-10-24 05:31:59 +08:00
yetone ea9454d2d8 usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:

  magpie model alias deepseek-v4.1-flash deepseek-flash
  magpie model alias deepseek-v4.1-flash            (what it is counted as)
  magpie model alias deepseek-v4.1-flash --reset
  magpie model aliases

kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.

Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is priced by the id it was
made under and only then counted under the alias; the alias's own price
is never put on the other id's calls, and a merged row is priced only
when every id in it is. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.

Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.

Run (worktree at f4640c0ae, rebased onto 2b4c0664e with no overlap):
- gofmt -l: clean. go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m (sandbox HOME) internal/usage,
  sessions, provider, cli, settings, gui, tui: all ok.
- Real binary in a sandbox HOME: two usage.jsonl calls priced $2 and
  $100 per M: `magpie usage` showed two model rows ($2.00, $100), and
  after `magpie model alias` one row, 2.0M, 2 calls, $102; the session
  row too. alias/aliases/--reset/loop/self output checked by hand.

Broken by hand, each red then restored:
- no alias in summarizeFrom: TestUsageAlias* red
- nil alias into the gateway projection: TestUsageAlias* red
- statsIn without aliasStats / List without aliasSession:
  TestSessionsCountAliasedModelsAsOne red
- merged usage row keeps Priced true: TestAliasStatsLeavesItsInputAlone red
- loop check off / self check by == / last-good read off / flag check off:
  TestUsageAliasRefusesSelfAndLoops, TestUsageAliasUnreadSettings,
  TestModelAliasCmd red
- GUI save drops UsageAliases: TestSettingsSaveKeepsWhatItDoesNotSend red

Not tried: the GUI pages in a browser (no app.js change; the Usage and
Sessions pages read the same rows), the full go test ./... before push,
Windows box.
2026-10-24 02:48:50 +08:00
yetone 44d8c742bf remote magpie: the guide names Settings → Network and sharing → Share on local network
The Remote magpie provider's guide, its "isn't shared" message and the
gateway's LAN errors said "Settings → Share on local network", but that
switch sits under Settings → Network and sharing. Every place now names
the real path: the en key and its zh, zh-TW, ja and de words in i18n.js,
app.js's message key, the preset's EndpointHint, the gateway's and
agent's English errors, docs/reference.md, docs/integrating.md,
README.zh-CN.md and the remote and docker pages of the site (en, zh, ja).
errRemoteNotShared names no Settings path and app.js matches its prefix,
so it is left as it is.

Run at base 673651e8d with this change:
- gofmt -l: clean. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean.
- GUI (playwright 1.62.0, chromium and webkit, every language): 12 files
  that reach the strings, 121 of 122. The red, quota-name-translated
  (webkit en, 2px past its quota at 440px), fails the same at
  673651e8d without this change; it is #2228.
- go test -timeout 45m ./...: every package ok but internal/gui,
  where TestCoreScriptBudget failed: app.js was 1,338,819 bytes at
  673651e8d itself, over its 1,337,735 budget; origin/main 34ad18ed8
  (#3367) moved code out. This change adds 24 bytes to app.js.

Run again after the rebase onto origin/main 34ad18ed8: gofmt -l clean,
go vet of internal/gui, gateway, provider, agent and tui clean,
go test ./internal/gui/ ok (TestCoreScriptBudget passes), and the same
12 GUI files 121 of 122 with the same #2228 red.
2026-10-23 18:01:03 +08:00
yetone c358e76607 zcode: on Windows, write where ZCode reads, %HOME% before %USERPROFILE%
Gearclickist on Discord: magpie connects ZCode without an error, but
ZCode on Windows never lists magpie as a provider; on a Mac it does.

ZCode 3.14.3 (the same JS in the Mac and Windows builds, diff -rq of the
extracted app.asar) picks its data folder from setting.json's dataBaseDir,
then ZCODE_DATA_BASE_DIR, then process.env.HOME, and only then
os.homedir() (USERPROFILE). magpie used Go's home, which on Windows is
USERPROFILE. With HOME set (Git Bash, MSYS2, Emacs and the like), ZCode
reads %HOME%\.zcode\v2\provider_config.json and magpie wrote
%USERPROFILE%\.zcode\v2\..., a folder ZCode never opens. On a Mac HOME is
Go's home too, so the two always met.

appdir.ZCodeHome gives %HOME% on Windows when it is set, absolute, and
the folder asked about is USERPROFILE (a folder given on purpose is
kept). The agent target, the ZCode credential and team readers and the
library target use it. ZCode's CLI database stays under USERPROFILE (seen
on Windows below), so the sessions reader is unchanged; its comment says
why.

Run:
- go test ./internal/agent/ -run TestZCode; the new
  TestZCodeOnWindowsUsesTheHomeZCodeReads forces zcodeOS=windows with
  HOME and USERPROFILE apart. Broken by hand (ZCodeDataIn(home) back in
  zcode()): red, "ZCode's folder on Windows with HOME set: .../001/.zcode
  ... want .../003/.zcode".
- gofmt -l; go vet for darwin, linux (-tags nogui) and windows.
- Windows box, sandbox folders only, HOME and USERPROFILE set apart:
  ZCode 3.14.3 for Windows, extracted and started there, kept its logs,
  workspace and provider_config.json under HOME\.zcode\v2 and only
  cli\db under USERPROFILE. The old magpie.exe's `zcode provider magpie`
  wrote profile\.zcode\v2\{config,provider_config}.json (the bug); this
  build's wrote home\.zcode\v2\..., beside ZCode's own files, and nothing
  under the profile.
- Full suite (go test -timeout 45m ./..., one at a time on the box):
  68 packages ok, exit 0, at d87be7f13 and again after rebasing onto
  b00c82acf (tree of this commit).

Not tried: the reporter's own machine (their HOME is inferred, not
confirmed); ZCode's picker on the Windows box (it ran over ssh, without
a desktop, and exited with the session), so "lists magpie" is read from
where ZCode keeps its files, not seen; the provider and library siblings
have no forced-OS test of their own; ZCODE_DATA_BASE_DIR and
ZCODE_DESKTOP_HOME_DIR are not followed.
2026-10-22 04:32:46 +08:00
yetone 3c38fe5c99 agent: Zoo Code (VS Code) through its autoImportSettingsPath (wani on Discord)
wani on Discord (#feedback) asked for Zoo Code (zoocode.dev), a fork of Roo
Code for VS Code and JetBrains.

Route: Zoo Code keeps its provider profiles in VS Code's SecretStorage,
which magpie can't write. The one file it reads is the one its
zoo-code.autoImportSettingsPath setting names. On every activation
(src/utils/autoImportSettings.ts, Zoo Code 3.90.0) it imports that file as
Settings → Import does (importSettingsFromPath). magpie writes
<User>/globalStorage/zoocodeorganization.zoo-code/settings/magpie-import.json
with one profile, "magpie": apiProvider openai on the gateway's
/v1 Chat Completions, key magpie-zoo-code, the chosen model, and an
openAiCustomModelInfo built from the catalog (contextWindow, else Zoo's own
128000 default; maxTokens only when an output limit is known). It points
the setting at that file in the default settings.json and in each VS Code
profile's. A value the user set themselves is stashed and restored by
Disconnect. The file sits outside magpie's folder so that a sync keeps an
address the user moved (kept.away skips magpie's own folder). Requests say
"ZooCode/<version>", and usage names them zoo-code.

Limits (also in docs/reference.md → Zoo Code):
- Zoo reads the file only at start: the notice asks for Developer: Reload
  Window.
- While connected, each start switches Zoo back to the magpie profile.
- Disconnect stops the import but can't delete the imported profile
  from SecretStorage. The user switches away from it or deletes it in Zoo.
- VS Code Stable only.

JetBrains is not wired. Zoo Code for JetBrains runs the extension in its own
extension host, which is handed an empty configuration on every start
(RPCManager.startInitialize in Zoo-Code-JetBrains), so the setting never
reaches it. Its secrets sit in ~/.zoo-code/secrets.json, an internal store
with no lock and no documented format. Neither is a clean route.

Tests (internal/agent/zoocode_test.go):
- TestZooCode: connect, model switch, a stale key that Check reports and
  Sync fixes, and disconnect putting the user's own import path back byte
  for byte with the file removed.
- TestZooCodeFresh and TestZooCodeProfiles: VS Code profiles, including one
  made after connecting.
- TestZooCodeDetectAndUA: Roo alone is not detected; ZooCode/3.90.0 maps to
  zoo-code.
Broken by hand (the restore disabled): TestZooCode and TestZooCodeProfiles
went red.
The generated file was checked with bun against Zoo's own zod schemas
(providerSettingsWithIdSchema, isProviderName; zod 4.6.7 from its repo):
valid, every field kept, current profile in apiConfigs.

Run, set -o pipefail, GOMODCACHE pinned, sandbox HOME:
- First full run, with this change on ba319a758 at 49bec8c4f:
  - gofmt -l clean.
  - go vet darwin, GOOS=linux -tags nogui and GOOS=windows: clean.
  - go test -timeout 45m ./...: 67 packages ok, including gateway 2543s,
    gui 509s and library 2326s.
  - internal/agent was red: TestSyncKeepsAnAddressOnAnotherMachine. The
    import file was then in magpie's folder, which kept.away skips, so a
    NAS address was lost. The file was moved into Zoo's globalStorage
    folder. The package also hit the 45m deadline under load (#2544).
- After the fix: -run 'ZooCode|TestSyncKeepsAnAddressOnAnotherMachine|
  TestReverseProxyIsStillMagpie' ./internal/agent was ok in 112.9s.
- At 0aa9c53ce: gofmt -l clean, internal/agent vet clean three ways, and
  go test -timeout 90m ./internal/agent ./internal/library ./internal/gui
  ok (agent 1912s, library 1299s, gui 420s).
- GUI suite in both engines: 283/283 in chromium and 283/283 in webkit
  (playwright 1.62.0). It covers the 44 files the change can reach:
  gui-de, gui-ja, gui-zh-tw, i18n-keys, agent-notice-lang,
  models-add-and-icons, mono-icon-redraw and every agent-*.

After rebasing onto origin/main 049040283 (which changed internal/agent/claude.go):
- go vet ./internal/agent clean three ways; linux nogui and windows
  builds ok.
- -run 'ZooCode|Compact|TestSyncKeepsAnAddressOnAnotherMachine|UserAgent|AgentOf'
  ./internal/agent ok in 35.9s.
- The darwin go build of the binary hit a full disk at link (this
  machine's, 369M free), not a code error.

Not tried: real VS Code (not installed on this machine), Windows and Linux.
2026-10-21 18:43:06 +08:00
yetone f1e4516da2 gui: Codex's and Claude Code's own settings are in the agent's row on the Agents page, not in Settings
The owner, 10-20: Settings › General held Codex subagents, Long
conversations, Codex background compaction, thread titles, thread
descriptions, composer predictions, the auto-review model and the
memories model, apart from the agents they set; "很割裂、很分散,不直观".

They now sit with their agent (AGENT_PREFS): in its opened row on the
Agents page (a Settings list in connectPanel), in a sheet from the
tray panel's row ("Settings" line, openAgentPrefs) and from the agent's
menu ("{agent} settings"). Each row is the one element moved between
those places, so its handlers and state go with it. Settings' search
still finds them, with a row that opens the agent's sheet
(#agentPrefLinks). A gateway has no Agents page and none of them.
Strings for zh, zh-TW, ja and de; docs (reference, agent-wiring,
gui-shell) point at the new place. app.js 1,277,298 bytes and the core
scripts 1,469,058, so both budgets rise.

Run on 6416d639c (the dialog morph, on origin/main 75e769a9f), macOS,
playwright 1.62.0:
- agent-prefs.test.cjs (new) plus the 10 migrated files (codex-titles,
  codex-descriptions, codex-auto-review, codex-predictions,
  codex-memories-settings, codex-async-compact, compact-at,
  settings-general, bare-ids, gateway-mode) and modal-morph: 152/152,
  chromium and webkit, every language, wide and 420px.
- go test ./internal/gui/: ok after the budget rise.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Two GUI tests leaned on the Agents page's old height and are moved with it:
agent-models-loading clicked "elsewhere" at (900, 650), which is now
Codex's Disconnect button in its opened row, so it clicks the page's lead
line; agent-expand-steady clicked Goose's row while Codex's opened row
(~554px with its settings) pushed it out of a 560px view, so it wheels
Goose's link into sight first (reader.cjs reach). codex-subagents-lead
and agent-models-redraw clicked controls below Codex's opened row and
timed out in WebKit ("outside of the viewport"); they wait for the row to
finish sliding open, then wheel the control into sight. With Settings ›
General shorter, segs-press-redraw's sweep left Usage's warm-up tabs
above the view in WebKit; it wheels them back when they are. panel-effort
opened Kimi's row below Codex's opened one the same way. login-allow's
wheel loop read the shorter General page's button 50ms after each wheel and
clicked beside it (de, 440px); it uses reach. mobile-web shut each agent
picker by tapping the Agents tab, which a picker opened low in Codex's
taller row covers on a phone; it taps the header's name (the lead line
can sit under the header's tabs, and a tap there opened Library), wheels
each row and field into sight before tapping it, and says which agent and
field a step timed out on. All seven pass in Chromium and WebKit.

After the rebase onto main (32 commits on), with the test fixes above:
- go test ./internal/gui/ ./internal/plugin/ ./internal/agent/ ok;
  gofmt -l clean; go vet GOOS=linux -tags nogui and GOOS=windows.
- 95 GUI files (every agent-, codex-, claude-, settings- and modal- file,
  and every file either side changed): 1375 pass; the 8 reds were
  segs-press-redraw, fixed above. The 16 other files that click an
  Agents row: 369/370, rail-tip red on main too (#3091).
- The full suite's reds are listed in the dialog morph's commit; each was
  run alone on this head and on origin/main.
- mobile-web's "desktop matches origin/main" compares Settings and the
  Agents page with main's assets, so it is red until this is on main; its
  phone checks pass in Chromium and WebKit.
2026-10-21 02:06:23 +08:00
yetone 94df239265 gateway: answers as an Ollama server, so Copilot in Visual Studio and VS Code lists magpie's models when given the gateway as its Ollama URL (wani on Discord)
Visual Studio 2026's Copilot (Agent preview, bring your own model) takes a
custom endpoint only for OpenAI and Ollama. wani's OpenAI attempt failed
with "Session was not created with authentication info or custom
provider". That error comes from the Copilot runtime in VS: the session was
created without a GitHub token or a BYOK provider config, and nothing
reaches magpie, so magpie can't fix it.

What an Ollama client needs, read from vscode-copilot-chat's
src/extension/byok/vscode-node/ollamaProvider.ts (5863f5a):
- GET /api/version, which must be at least 0.6.4, or no model is listed;
- GET /api/tags, from which it takes each model's "model";
- POST /api/show of each. A model without "capabilities" is skipped. The
  window is model_info["<general.architecture>.context_length"] ?? 32768,
  and the name is general.basename;
- chat on <url>/v1/chat/completions, streamed, with an empty
  "Authorization: Bearer ". magpie already serves that.
It never calls /api/chat. The Copilot SDK under Visual Studio's agent
treats Ollama as an OpenAI API at <url>/v1 too.

ollama.go serves these three routes on Handler's mux, so every guard
/v1/* has covers them too:
- lanGuard: LAN sharing, a gateway key, rebound Host, forwarded loopback;
- corsGuard: a foreign Origin, Origin null and *.localhost;
- a key held to some models: catalogFor/keyAllowed.

/api/show tells:
- capabilities: completion and tools, plus vision from Images and thinking
  from Thinks;
- the window, or 32768 when magpie doesn't know it, since VS Code would
  take a 0;
- general.parameter_count and magpie.embedding_length, because the ollama
  CLI 0.6.8's "ollama show" read them unchecked and panicked without them.
  The real CLI found this.
/api/chat and /api/generate are not served, so "ollama run" doesn't work.

Tests (internal/gateway/ollama_test.go; lan_test.go lists the routes):
- TestOllamaModelRoutes, TestOllamaRoutesHoldAKey, TestOllamaRoutesGuarded
  and TestOllamaClientChats each fail with 404 without the routes.
- Broken by hand, each went red:
  - tags from provider.Catalog() instead of catalogFor: HoldAKey;
  - vision dropped: ModelRoutes;
  - corsGuard skipping /api/: Guarded (200 for a foreign page, Origin
    null and a localhost subdomain);
  - an unknown window told as 0: ModelRoutes;
  - parameter_count and embedding_length left out: ModelRoutes.

Real use, in a sandbox HOME with MAGPIE_NO_ACCOUNTS=1:
- a nogui build on 127.0.0.1:3561, with a custom provider on a fake
  OpenAI upstream (python, 127.0.0.1:3562);
- the real ollama 0.6.8 CLI with OLLAMA_HOST at it: "ollama --version"
  (server 0.12.6), "ollama list" (both models) and "ollama show" all
  worked. Before the model_info fix, show panicked;
- curl replaying VS Code's sequence (version, tags, show, then a streamed
  /v1/chat/completions with an empty Bearer and VS Code's body) streamed
  the upstream's reply, and the upstream got its own key;
- on the same server, a foreign Origin, Origin null and a rebound Host all
  got 403.

Not tried:
- Visual Studio 2026 itself (no Windows VS here);
- VS Code's Copilot itself (VS Code isn't installed);
- JetBrains' Ollama client, which likely needs /api/chat.

Run at this head (macOS):
- gofmt -l .: nothing;
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet
  ./...: clean;
- go test -timeout 45m ./... at e89d6a4f9, load ~300 to 400: 59 packages
  ok. These failed:
  - internal/agent, internal/gateway and internal/library ran past 45m
    (#2544, #2870, #2853);
  - TestClaudeAccountsSpentFallBackToCodex in gateway (#2858);
  - TestSetAnswersWhileDevinAndProvidersHang in gui, at 16s against its
    bound (#1375);
  - TestGatewayHookMixedPiPackage in plugin, starting plugins after 742s
    (#2865).
  Rerun alone:
  - gui's and plugin's tests: ok (gui 35s, plugin 499s);
  - internal/agent ok (2580s), internal/library ok (1112s);
  - internal/gateway in two halves by test name, each ok (1406s and
    1030s). Whole, it timed out again at 45m while starting
    TestRouteKeepsItsFolderShort, not stuck.
No GUI file changed.
2026-10-19 22:32:37 +08:00
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