Commit Graph
88 Commits
Author SHA1 Message Date
yetone 92e8edd7fc windows: magpie is listed in Installed apps, and its Uninstall puts every agent back
Jevik_AI on X uninstalled magpie and rebooted, and Codex's config.toml
still had openai_base_url = "http://127.0.0.1:3425/backend-api/codex";
Rk1ngggg asked whether an update cleans it. magpie's own uninstall
(Settings › About › Uninstall magpie, `magpie uninstall`) already
disconnects every agent and takes Codex's leftovers (#3866), but on
Windows magpie wasn't in Settings › Apps › Installed apps, so it was
removed the way Windows offers for a program it doesn't list: by
deleting the exe and folders, which runs no code.

shortcut.Ensure now writes
HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\magpie
(DisplayName, DisplayIcon, Publisher, InstallLocation, UninstallString,
URLInfoAbout, NoModify, NoRepair) at every installed start, beside App
Paths, and Remove (uninstall's System step) takes it out the same way:
only while it names this exe, or an exe that is gone. Its Uninstall
runs `magpie.exe uninstall --window` (shortcut.UninstallArgs). magpie.exe
has no console, where the terminal's `magpie uninstall` would refuse
for want of one to ask on, so those exact args open the app's window
(or forward to the running app, OnSecondInstanceLaunch) on Settings ›
About with Uninstall magpie's question asked (uninstallView,
?uninstall=1). It asks once: a redraw of Settings doesn't ask again,
and Cancel removes nothing. magpie web opened at that link asks
nothing. Deleting the app by hand still runs no code (macOS
drag-to-Trash included); agent-wiring.md says so.

Run on mote at the pushed head (rebased onto be9dbce02):
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok. go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build: ok.
- go test -tags nogui ./internal/gui ./internal/cli ./internal/shortcut
  ./internal/uninstall: ok (TestCoreScriptBudget included).
- uninstall-settings.test.cjs and i18n-keys.test.cjs: 40 of 40
  (chromium and webkit; the new Installed-apps cases in en and zh at
  1100 and 420).
At d3f40bedd, the same change on c7ebb6f8d, under suite.lock:
- go test -tags nogui -timeout 45m ./...: ok, every package.
- The whole GUI suite (--test-concurrency=4): 22518 of 22800; the 282
  reds are in 53 files the change doesn't reach (model-chip-steady 40,
  usage-agents-hide 22, zero-priced-free 20, provider-fetch-again 14,
  ...), the full-suite reds of #5475; the numbers are on that issue.
  Their run at c7ebb6f8d alone is queued behind other sessions' suites.
- The first full run found the core scripts 147 bytes over
  TestCoreScriptBudget; the page's part was cut to one line (the
  budget is not raised).
On xiaomi-gpu (win-run): go test ./internal/shortcut, incl.
TestInstalledAppsEntry on the real HKCU registry under a test key: ok.

Broken by hand, each red:
- registerAppPath not calling registerUninstall: TestInstalledAppsEntry
  (UninstallString = "") on Windows.
- main.go not taking UninstallArgs to the window:
  TestInstalledAppsUninstallOpensTheWindow (unknown "--window").
- app.js not asking on ?uninstall=1: 4 of 4 Installed-apps GUI cases.
- app.js asking without its once guard (params.delete): the same 4
  ("asked again").

Not tried: a real Settings › Apps › Uninstall click on Windows with an
installed magpie (the test box's install belongs to other sessions); the
second-instance forward (OnSecondInstanceLaunch) has no test of its own.
2026-11-09 22:33:31 +08:00
yetone 39569d5604 claude desktop: an optional Claude Magpie app beside your own Claude (#5671)
baranwang on X asked to keep Claude Desktop's own (1P, Anthropic) sign-in
while using magpie. Turning on "Separate app" in Claude Desktop's row on
the Agents page (or `magpie claude-desktop launcher add`) moves magpie's
3P wiring into ~/Library/Application Support/Claude-Magpie-3p and adds
~/Applications/Claude Magpie.app. That launcher opens Claude.app with
--user-data-dir on that folder, so it runs side by side with the user's
own Claude.app. Its icon is Claude's icon with a magpie badge. Off is the
default, and turning it off (`launcher remove`) moves the wiring back
and removes the app. It is macOS only: Desktop's packaged app strips
CLAUDE_USER_DATA_DIR, and on Windows it hardcodes LOCALAPPDATA\Claude-3p.
The folder ends in -3p because Desktop adds -3p to any other name.
Restarting the isolated app ends only its own process (pkill on its
--user-data-dir) and opens the launcher again.

Run at 1b25cda26 (this change on origin/main be9dbce02); rebased onto
fdabddeb4 (catalog only), then go build ./..., vet and the budget and
launcher tests again: ok. All
on mote:
- gofmt -l clean; go vet ./internal/...; GOOS=linux go vet -tags nogui
  and GOOS=windows go vet on agent, cli, desktopiso, desktopdir, gui.
- go test (whole packages) desktopiso, desktopdir, settings, settingsapi,
  proc: ok. -run Isolated|TestDesktopInstance|TestAddStartsDesktopOnTheFolder|
  TestScript|TestAddLeavesTheirs|ClaudeDesktop|Restart in agent;
  TestClaudeDesktopLauncher|TestEveryRouteHasACommandOrIsNamed|Help in cli;
  TestCoreScriptBudget|TestSettingsSaveKeepsWhatItDoesNotSend|Budget|Desktop
  in gui and gateway: ok.
- An earlier full `go test ./...` at fef23255f had four reds, all from
  this change and fixed here: the route without a command (now in
  notYet), settings_keep's DesktopIsolated, os/exec instead of proc, and
  the core script budget (paid by sharing the switch helper with the
  largest-window line and cutting comments; no raise). A second full run
  of the touched packages queued ~7h on mote's suite lock behind other
  sessions and was stopped; the targeted runs above replace it.
- GUI on mote, both engines: desktop-isolated (new; en, zh, zh-TW, ja,
  de; 1100 and 640; aria-checked, posts, status text, no scroll, no
  select, absent without `isolated`), desktop-longest, click-scroll,
  plain-names, i18n-keys: ok. page-width-steady, panel-fold and
  zero-priced-free are red, the same 33 tests at origin/main be9dbce02
  (diffed): #4541/#5013, #5796, #5262. i18n-keys' "a plugin's words are
  its own" is red on main too (#5332).
- Whole GUI suite on WSL at an older head: 400 of 22778 red across
  ~100 files of other pages, in line with #5559 (478 of 21666 on main
  there). Not rerun on mote.

Real use, on mote in a sandbox HOME with Claude.app 4.23118 linked in:
`claude-desktop magpie`, then `launcher add`, moved the wiring to
Claude-Magpie-3p (deploymentMode 3p, mcpServers and locale carried).
Opening Claude Magpie.app started Claude with
--user-data-dir=.../Claude-Magpie-3p; it wrote configLibrary and
model-catalog there (3P mode) and no -3p-3p folder. A second, 1P Claude
ran beside it on its own sandbox folder. Opening the launcher again
kept one instance; the pkill pattern matched only the isolated pid; both
quit on SIGTERM. `launcher remove` put the wiring back and removed the
app.

Broken by hand: a folder without -3p (Desktop made -3p-3p), the
CLAUDE_USER_DATA_DIR env route (ignored by the packaged app), os/exec in
the quit (TestNoCommandBypassesProc red).

Not tried: a screenshot of the running app (screencapture fails over
ssh); a model request through a gateway from the isolated app; Windows
and Linux (not offered there). Known: the Dock shows Claude's own icon
for the running isolated app, and Chrome pairing is off in a moved
userData folder.
2026-11-09 22:31:16 +08:00
yetone 608c1543e8 gateway: a bare model name goes to the asking agent's own subscription first
freefcw on X: Codex, started by Mirasim, asked for gpt-6-astra by its bare
name. Its own ChatGPT subscription serves it, but magpie sent it to Devin
through the group it found (auto-gpt-6-astra, soonest renewal first).
With found groups off it still went to another vendor: Resolve takes the
first provider in the Providers order, AutoStandIn and agent.Reseat did
the same.

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

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

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

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

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

Reported-by: freefcw (X)
2026-11-09 16:28:02 +08:00
yetone e215d335a6 gateway: a gateway key can cap its requests at once; the rest wait their turn
young02036 on Discord: a provider can be given a concurrency, so why
can't a gateway key? A key now has an optional MaxConcurrency, from 1
to 1000. Left unset (every key today), nothing changes.

- access: Key and Change get MaxConcurrency, and Identity carries it, the
  issuer's cap included. The concurrency-key action refuses a value
  below 0 or above 1000.
- gateway (key_slots.go): every route that asks a model is held to the
  key's cap, however the request came (loopback, LAN, a Remote magpie, a
  Responses socket's turn). One request too many waits in the key's
  queue in arrival order. It shows as "slot" in Active, and its wait goes
  into the try's Queued. A request whose agent goes away while it waits
  leaves the queue and sends nothing. A stream holds its slot until it
  ends. serve's routes (chat, responses, messages, ollama, gemini, the
  Codex backend) wait inside the try, after keepQueued, so a streaming
  agent gets keepalives while it waits. The other model routes (images,
  embeddings, rerank, audio, videos, search, decisions, native) wait
  before their handler runs. forward and codexUpstreamOn take the slot
  too, so nothing reaches a vendor without one. A key issued under
  another waits for its own slot, then for its issuer's.
  /v1/magpie/concurrency lists each capped key under "keys", and counts
  its waiters in "waiting". A key's limit (key_limit) reports the cap.
  Not held, as a provider's MaxConcurrency doesn't hold them: GET,
  HEAD, OPTIONS, count_tokens, :countTokens and MCP.
  TestKeySlotEveryRoute fails when a route is judged neither held nor
  free.
- cli: magpie gateway-key concurrency <id> [<n>|off]. It refuses 0, a
  negative, over 1000, a fraction, a word, --help or an extra argument
  with its usage.
- gui: the key row gets a badge in the provider concurrency badge's
  style. It opens the app's menu with No limit, 1/2/3/5/10 and Other…,
  and Other… takes a number typed in place. A value that isn't a whole
  number up to 1000 is refused and nothing is sent. Browser and
  read-only keys have no badge. Strings are in en, zh, zh-TW, ja and
  de. An unset badge, which a hover shows, gives way before the masked
  key (flex-shrink 8). Without that, at 420px in en and de, the extra
  badge squeezed the key until its copy button slid under the pointer
  that came to drag the row, and gateway-key-arrange went red.
- docs/subsystems/gateway-routing.md describes it.

Run (on mote, at this tree on origin/main 0f8c3d867; rebased onto 627fd1a3b,
which touches none of these files, and the budgets were run again):
- go test -timeout 45m ./internal/access ./internal/gateway ./internal/cli
  ./internal/gui: access, gateway (839s) and cli ok. gui had one red,
  TestGatewayModeStatsNameTheGatewaySessions, run at 00:40 PST: its
  record an hour back falls on yesterday in a day's first hour. It
  passes from 01:09, so it is unrelated; filed as #5690. The Budget/Size
  tests were run again after the CSS change: ok.
- gofmt -l: clean. go vet for darwin, plus GOOS=linux and GOOS=windows
  (-tags nogui), on those packages: ok.
- GUI (node --test, Chromium and WebKit, 1100 and 420 wide, en, zh,
  zh-TW, ja and de): every file that loads the gateway keys (59) plus
  i18n-keys and i18n-en-no-cjk. The reds left are the same on
  origin/main and already filed: gateway-key-models en (#5233, #4081),
  i18n-keys "a plugin's words are its own" (#5332), phone-connect-menu
  at 420 (#4706, #4707). After the flex-shrink fix:
  gateway-connect-keys, gateway-key-arrange, -concurrency, -mcp,
  -own-rotate and -quotas passed 104/104 in both engines, against
  84/84 on base.
- The tests:
  - TestKeyConcurrency, over LAN with cap 2: 2 of 3 requests reach the
    vendor and the third is shown as "slot". Another key isn't held. A
    cancelled waiter leaves the queue and never reaches the vendor. The
    third goes once one ends, every lane is given back, and its Queued
    is at least 40ms.
  - TestKeyConcurrencyKeepsStreamAlive: a waiting stream gets 200 and
    keepalives.
  - TestKeyConcurrencyEager: on embeddings an issued key waits on its
    parent's lane, a cancelled waiter leaves, never more than 1 runs at
    once, and a GET takes no slot.
- A real `serve` in a sandbox HOME (built from this tree, MAGPIE_ADDR
  127.0.0.1:38612) against a fake slow SSE upstream. Steps: `provider
  add fake url=…`, `gateway-key add`, `gateway-key concurrency <id> 1`,
  then three concurrent keyed streams. /v1/magpie/concurrency showed the
  key at busy 1, waiting 2, limit 1 (two in "slot"). The upstream's
  most at once was 1, and it saw 3 requests one after another (200s at
  1.9s, 3.7s and 5.5s, each with [DONE]). Afterwards "keys" was empty.
  `concurrency <id> 2000` exited 1 with its usage.

Broken by hand (each went red, then restored):
- keySlot returns nil: TestKeyConcurrency ("timed out waiting for c
  queued") and KeepsStreamAlive.
- The issuer's lane skipped: TestKeyConcurrencyEager.
- The eager take skipped: TestKeyConcurrencyEager.
- The CLI's bounds check removed: "accepted [concurrency id 0]".
- The GUI's bounds check removed: gateway-key-concurrency.
- Without the flex-shrink line: gateway-key-arrange chromium/webkit en
  and de 420px.

Not tried / not done:
- Full suite not run at push (neither `go test ./...` nor the whole GUI
  suite).
- Not tried with a real vendor account or a second computer on the LAN.
  The LAN path is covered by TestKeyConcurrency's lanServer.
- The key's badge shows the cap, not live running or waiting counts.
  /v1/magpie/concurrency has those.

Reported-by: young02036 (Discord)
2026-11-08 17:52:09 +08:00
yetone cdf734757a agent: OpenMausBot gets magpie's models back, and a Restart for a list it hasn't read
maxleebeta (Discord #feedback, 11-08) picked Antigravity's models in
magpie, and OpenMausBot's model search didn't find them. magpie wrote them
correctly: a sandbox with an Antigravity sign-in lists
antigravity/gemini-3.8-flash[1m] and the others in config.json. OpenMausBot
loses them in three ways, each reproduced on the real app:

- it reads config.json once, at start, so a list magpie writes while it
  runs never reaches its picker;
- a change to any engine in its Settings writes back every engine as it
  held them since it started, so magpie's newer list is replaced by the
  old one;
- an edit of magpie's engine there (updateClaudeEndpoint) keeps only the
  model picked.

Nothing in magpie wrote the list again: a sync runs on a catalog change,
or when magpie starts.

- KeepOpenMausBotListed (gateway.WhileServing, every 30s) writes magpie's
  list again when the file lists other models (ombListStale). The model
  picked in OpenMausBot (ANTHROPIC_MODEL) and its other engines stay. It
  isn't a Check drift: that reads as unwired, and a port change rewires
  only agents without one.
- OpenMausBot gets a Restart on its Agents row (restartApps: OpenMausBot.app,
  OpenMausBot.exe; appReads: ombPart = gateway, first model, list, not the
  key), so one running on an older list is offered a reopen. Its own save
  of the same engine after it starts doesn't count.

The same gap in NewMax, LiveAgent, OpenPencil, OpenBot, Pencil and ZCode
is #5662.

Run (mote, at this tree rebased on origin/main 00198b26e; 06324e99e,
rebased onto since, changes comments and docs only):
- go test ./internal/agent ./internal/cli ./internal/claudecode . : ok
- go vet ./internal/agent ./internal/cli on darwin, GOOS=linux -tags
  nogui and GOOS=windows: ok; gofmt -l: clean
- TestOpenMausBotListWrittenAgain and TestOpenMausBotRestartOnMac, new
- Broken by hand: ombListStale always false turns
  TestOpenMausBotListWrittenAgain red (written back, edited there, the
  loop); dropping restartApps' entry turns TestOpenMausBotRestartOnMac
  and TestRestartAppsOnWindows red.
- Real OpenMausBot 0.1.145 on mote (the app's server under
  ELECTRON_RUN_AS_NODE, sandbox HOME and OMB_DATA_DIR, own port):
  /api/instances kept the start list after a model was added to the
  file; an icon PATCH on its other engine wrote the old list back over
  it; PATCH /api/instances/magpie/claude-endpoint left ["relay/gpt-5.5"].

Not tried: the full go test ./... (mote's suite.lock had six full runs
queued); the Restart on a real Windows OpenMausBot (OpenMausBot.exe is
electron-builder's default name, not seen on the box); magpie's own
keep loop against the real app (the tests cover the file it writes).

Reported-by: maxleebeta (Discord)
2026-11-08 10:55:49 +08:00
yetone d55881730d gateway: a key can be held to some MCP servers and tools
wakaka on Discord (#help, 11-06) asked for gateway keys limited to some
MCP servers and tools, as keys already are to models (#882).

A key's MCP list (caller-keys.json "mcp") holds entries "server" (every
tool of it) or "server/tool"; "-" alone is no MCP server; an empty list
is every server, as before. A key issued under another is held to its
issuer's list too.

Every MCP route checks it:
- magpie's own servers (web search, vision, image, Magpie Browser, plugin
  tools) through serveMCP: initialize/tools/list/tools/call are refused
  or filtered per server and tool, and /v1/magpie/key-limits names "mcp";
- the Library hub ("magpie"): only the backing servers and tools the key
  may use are listed, and a call by name or by fallback is refused;
- /mcp/<name> and /mcp/run/<name>: the server is refused, tools/list is
  filtered in JSON and SSE replies, tools/call refused; a reply the
  filter can't read (an encoded body) is a 502, never passed through.

GUI: "MCP servers" in the key row's menu opens the app's own picker (no
native select) with All, No MCP server, each server and its tools (GET
/api/caller-keys/mcp lists magpie's own servers and the Library's). A
key held to some shows a badge saying which, that opens the same list;
a free key shows nothing more in its row, on hover either. A hover badge
was tried first: it pushed the row past 560px (gateway-caller-keys) and
squeezed the masked key under a drag at 420px (gateway-key-arrange).
CLI: magpie gateway-key mcp <id> github fs/read_file | none | all.
zh, zh-TW, ja, de strings; docs/reference.md and the gateway-routing and
library subsystem pages.

Not covered: a model's own built-in web search (a vendor tool, not MCP).

GET /api/caller-keys/mcp is named in the CLI parity test's notYet (its
list is what `magpie gateway-key mcp` takes; TestEveryRouteHasACommandOrIsNamed
caught it at the rebased head).

Run on mote (mote-run), at the pushed head:
- go test ./internal/access ./internal/cli ./internal/gui
  ./internal/library ./internal/gateway at a9c40186d (this change on
  2ce44dc28): ok except internal/gui's TestMainWindowCorners/macOS_26_SDK
  (#3949, the same message on macOS 27). After the rebase onto a9667daad
  (no file in common): TestCoreScriptBudget, TestCallerKey*,
  TestEveryRoute*, TestGatewayKey*, TestKeyMCP*, internal/access and
  go vet ./internal/... at d36f89224's tree: ok.
- gateway-caller-keys chromium en reads wider than 560px 4 of 6 runs
  alone on this branch and 4 of 6 on origin/main a9667daad: #3797,
  recorded there.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: clean; darwin, linux (nogui) and windows builds ok; gofmt -l
  clean.
- GUI: gateway-key-mcp.test.cjs in chromium and webkit, widths 1100 and
  420, en/zh/zh-TW/ja/de: 20/20. Every gateway-key*, gateway-keys* and
  i18n* file in both engines: ok except gateway-key-models en (red on
  origin/main ecc26a339 too, #4081/#5233) and i18n-keys "a plugin's words
  are its own" (red on main, #5332).
- The whole GUI suite (both engines, every language) with the hover
  badge: 91 reds in 25 files. Rerun alone on this branch and on
  origin/main 54dc257f1: only gateway-caller-keys (560px sideways),
  gateway-key-readonly, models-fold and models-select-all-api were red
  on the branch alone; the badge moved into the row menu for the first
  two. After it, every gateway-key*, gateway-caller-keys, gateway-card,
  gateway-connect-keys, api-key-theme and i18n* file passes in both
  engines, except i18n-keys "a plugin's words are its own" (red on main,
  #5332, none of the three strings are this change's) and 1 of 20
  models-select-all-api "the click scrolled" (#4389; models-fold is
  #4071). The rest are red on origin/main too and each has an issue:
  account-weight #4644, codex-auto-reset #2360, header-centre #3479,
  images-codex-one #4618, key-replace #4126, menu-input-scroll #3402,
  mobile-web #3952, model-chip-steady #4388, model-copy-id #4621,
  models-works-only #4391, nav-timeout #4787, omarchy #4624,
  page-width-steady #5013, phone-connect-menu #4706/#4707,
  plugin-move-unserved #4392.

Broken by hand, each went red: the serveMCP server gate, call check and
list filter, the own-server list filter and key-limits "mcp"
(TestKeyMCPOwnServer); hubTools, hubServersOf, the hubToolNamed
fallback and hubMCPRun (TestKeyMCPHub); /mcp/run (TestKeyMCPRun); the
/mcp/<name> guard and filter (TestKeyMCPProxy); the GUI's "No MCP
server" being exclusive (gateway-key-mcp).
gateway-key-readonly chromium 420 ja was red with the hover badge (the
sibling run, the whole suite and its rerun; green on origin/main) and
passes with the badge in the row menu.

Not tried: a real Library server through a live gateway, the hub with a
real agent, and running on Windows or Linux (vet and build only).

Reported-by: wakaka
2026-11-07 03:21:57 +08:00
yetone 1f439ecc5e gateway keys: a limit can count only some models or providers (zola_xynb)
zola_xynb on X asked for a cap per model or per provider under one
gateway key. A key limit can now name models (access.Limit.Models,
"<provider>/<model>" or "<provider>/*"), so one key can have, for
example, a month of $20 on openai/* next to a month for the whole key.
Limits without models still cover the whole key, as before.

- budget: sums are kept per window and scope, and count a ledger row only
  when its provider/model matches (any of the model's ids). reserve holds
  a request to a scoped limit only when the model it names is served
  there. windowsOf keeps every scope's sums, so the ledger is not read
  again on each request.
- gateway: keyLimited puts the key's spent scopes on the caller
  (withSpent), count_tokens included. A direct request for a spent model
  gets a 429 with Retry-After and no X-Magpie-Limit-Reset, so a remote
  magpie rests only that model. A routing group, a provider's fallback
  and embedding/image/video/decision groups skip spent members
  (groupKeeps, allowedCandidates) and get a 429 only when none is left.
  System One, count_tokens and magpie's own calls for the key are held
  too. Model lists are unchanged. A refusal turned away before routing
  now records its ErrType in the ledger.
- CLI: magpie gateway-key limit <id> add month --cost 20 --model openai/*
  (--model repeatable, --models a,b).
- GUI: the key limit editor has a Models field that opens the app menu
  (multi-pick: All models, every model of a provider, each model). It has
  no <select> and no new screen. The badge, line and tabs name the models.
  Strings are in every language.
- docs: reference.md and subsystems/gateway-routing.md.

Run at d52725d32 (this change on 4ef47b3f4), on mote:
- go test ./... -timeout 45m, under the shared lock, with the log kept
  whole: every package ok except three reds outside this change. None of
  the three touches what changed:
  - TestClosedBeforeSentEveryTimeSaysWhy (#5031, passes alone 3/3)
  - TestMainWindowCorners/macOS_26_SDK (#3949, red alone on macOS 27)
  - TestMoveToPlugin TempDir cleanup (filed #5524, passes alone 2/2)
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., go build ./...: ok. gofmt -l: nothing.
- GUI, chromium + webkit: gateway-key-*.test.cjs, gateway-keys-*,
  i18n-keys, i18n-en-no-cjk and usage-remote-key-limits passed 244/246.
  The new gateway-key-model-limit runs in every language at 1100 and
  420px. The two reds also fail on origin/main 3cbb7e042:
  - gateway-key-models en at 560px (#4081, #4616, #5233)
  - i18n-keys "a plugin's words are its own" (#5327, #5332, #5426, #5482)

Broken by hand; each one turned the named tests red:
- groupKeeps' spent skip removed: ItsModelsAlone and MediaGroups.
- modelAllowed's spent check removed: ItsModelsAlone and AFallback.
- withSpent on count_tokens removed: ItsModelsAlone.
- the scoped refusal sending X-Magpie-Limit-Reset: ItsModelsAlone and
  SystemOne.
- sums counting every model: ItsModelsAlone, TestScopedLimitCountsItsModels
  and TestScopedBesideTheWholeKey.
- embeddings' keyGroupRefusal back to keyModelRefusal: MediaGroups.
- the turned-away row's ErrType dropped: ItsModelsAlone.
- keyHolds not holding for Spent: ItsModelsAlone, AFallback and
  MediaGroups.
- decide.go's 429 back to a 403 stayed green. keyLimited's reserve
  refuses a direct decider first, so that line is a second guard.

Not tried:
- a real vendor account or a real remote magpie.
- the Codex backend path and a video group: they go through the same
  keyLimited/groupKeeps code, but no test of their own.
- the whole GUI suite: only the files above.
- Windows and Linux test runs: vet only.
2026-11-06 20:47:21 +08:00
yetone f9e6061b85 claude: claude-magpie runs Claude Code through magpie, a plain claude left on the user's account
baranwang on X (11-06): `claude` stays on the user's own Claude account,
`claude-magpie` goes through magpie, and nothing is switched back and
forth.

`claude-magpie` runs `magpie claude run [args…]`. That writes a settings
file of magpie's own, <config>/claude-launch/settings.json, connected as
Connect connects Claude Code (the gateway, its key, the shared LAN key when
sharing is on, the model, the tiers) and starts
`claude --settings <file> args…`. Claude Code puts a --settings file's env
and model over the user's settings.json, a claude.ai sign-in and the
shell's variables (tried on 2.1.318), so ~/.claude/settings.json is never
rewritten. ANTHROPIC_API_KEY and the cloud switches (Bedrock, Vertex…) are
blanked in the file, so neither the user's file nor the shell can take a
request past magpie. The file is the agent `claude#launch`, listed nowhere:
the Agents page, Check and Notice see only the user's file. It is set again
when the gateway moved or its key changed.

- /model in a claude-magpie session saves to the user's settings.json
  (Claude Code never writes a --settings file). After the session a magpie
  model picked there moves into the launch file, for the next claude-magpie,
  and the user's file gets its model back. A Claude alias (sonnet) stays.
- Claude Code's own one-time `opus` -> `opus[1m]` rewrite of the user's
  file (migration_opus_to_opus1m), which the launch file's 1M opus tier sets
  off, is undone the same way. Found in the end-to-end run below.
- claude runs as a child so that can happen: on Unix a stopped child stops
  magpie too (^Z, fg; proc.WaitFollowingStops reaps it with WUNTRACED, as
  cmd.Wait can't see a stop), and claude's exit code is magpie's. On Windows magpie
  ignores Ctrl+C while claude has it.
- The command: a launcher beside the `magpie` command. Settings › Command
  line (AddCLI) writes it; `magpie claude launcher [add|remove]` adds it for
  a command put there before. It is a `#!/bin/sh` exec of magpie's stable
  path, or on Windows a .cmd running "%~dp0magpie". A file by that name
  without "written by magpie" is never written over.
- Docs: agent-wiring.md, and the start page in en/zh/ja.

Run at this commit (rebased on origin/main 218b38c59):
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build for darwin, linux (nogui), windows;
  go test ./... -timeout 45m: 85 packages ok; red only
  TestMainWindowCorners (#3949) and TestRenewLoginsKeepsClaudeReading
  (#5481), both red alone on origin/main b020ae102. The run before at
  f22a9ae61 also had proc's TestEveryStartedCommandIsWaited red on this
  change's own Wait4 loop, fixed here by moving it into proc.
- Windows (xiaomi-gpu): go test ./internal/update ./internal/cli: cli ok;
  update red only in TestPackagedByDpkg, red the same on origin/main
  f47390bf3, filed as #4603.
- Real Claude Code 2.1.318 in WSL (magpie-desktop), sandbox HOME, a built
  magpie (`serve` on its own port), a fake Anthropic upstream:
  - `magpie claude run -p "say hi"`: PONG, exit 0; upstream got
    claude-opus-4-6 with the provider's key. A user settings.json with its
    own ANTHROPIC_API_KEY and "model": "opus" kept both values.
  - Interactive in tmux under bash -i: `/model fakeco/glm-4.6` then /exit:
    the user's file is back on opus, the launch file on fakeco/glm-4.6.
    ^Z stops both magpie and claude (T), fg resumes both.
  - `magpie claude launcher add` wrote ~/bin/claude-magpie, and running it
    answered PONG.
- Real Claude Code 2.1.281 on Windows: claude-magpie.cmd beside a built
  magpie.exe, `claude-magpie --version` printed the version through
  `claude --settings <launch file>`, exit 0.

Broken by hand, each red: the blanks dropped; the launch dir override; the
stale-address check; ClaudeLaunchAfter returning early; the opus[1m]
rewrite check; WaitFollowingStops answering 0 for a signal; "$@" turned into $* in the launcher; the model mark check;
AddCLI's launcher loop; --settings dropped from the args; the restore call
dropped.

Not tried: macOS with a real Claude Code (the Unix path ran in WSL only);
Windows interactive (Ctrl+C, /model restore); a real Claude subscription or
API key upstream (a fake upstream only). Known limits: a session that ends
by a crash or kill skips the restore; managed settings (policy) outrank
--settings; magpie has to be running (claude-magpie warns when it isn't);
Claude Code itself reformats the user's settings.json when it runs its
opus migration, values kept.
2026-11-06 17:31:04 +08:00
yetone 9d143eacab uninstall: install.sh --uninstall disconnects every agent first, a deleted magpie too
whimsical_wolf_15477 (Discord): after uninstalling magpie, Codex didn't go
back to its own config. `install.sh --uninstall` deleted the magpie command
and app and left every agent wired to a gateway that no longer runs: Codex
kept openai_base_url (or model_provider = "magpie" and model_catalog_json)
pointing at 127.0.0.1. A magpie deleted by hand undid nothing either, and
`--purge` refused with no magpie left to run.

- `magpie uninstall --keep-data` (uninstall.KeepData): every agent
  disconnected and its own values put back from stash.json, the service,
  autostart, shortcut, scheme and helpers removed, magpie's settings,
  providers and usage kept.
- install.sh --uninstall runs `magpie uninstall --yes --keep-data` (--purge:
  `--yes`) before deleting anything, and stops if it fails. With no magpie
  of its own (deleted by hand) but magpie's config left, it fetches the
  newest release into a temporary folder, checks its sha256, runs that, and
  deletes it after. An older magpie without --keep-data gets the newest one
  for this too. A magpie on PATH that the script didn't install is left to
  its own `magpie uninstall`, and said so.
- MAGPIE_UNINSTALL_SCRIPT=1: under the script magpie doesn't ask to delete
  a path that the script deletes next.
- docs (en/zh/ja start.html #uninstall) and READMEs: what the line does,
  that it works for a magpie already deleted, and Codex's lines by hand.

Run (WSL magpie-desktop; mote's disk is full, nothing run or deleted there):
- go test -tags nogui -run "Uninstall|Help|TestKeepData" ./internal/cli/
  ./internal/uninstall/: ok. node --test site/install.test.mjs: all pass.
- The new install tests against the old install.sh: 5 red. Broken by hand
  (--keep-data case removed, Data() back in KeepData): TestUninstallKeepData
  and TestKeepData red.
- Real e2e: magpie built from this tree, Codex wired in a sandbox HOME
  (not signed in, and ChatGPT signed in), magpie installed and deleted by
  hand; install.sh --uninstall with a local feed. config.toml's diff before
  wiring vs after is the [model_providers.magpie] table only (kept on
  purpose for threads started on magpie); model, effort, openai_base_url,
  model_provider and model_catalog_json are the user's again; settings kept.
- gofmt -l clean; go vet GOOS=windows/darwin/linux (nogui) for the two
  packages; sh -n and dash -n install.sh.

Not tried: macOS's zip path for a deleted magpie run for real (tests cover
it with fakes), Termux, Windows (no install.sh there; docs say download
magpie again and use Settings › Uninstall). The full internal/cli package
timed out at 10m under WSL load in providers_unreadable_cli_test (not
touched here); see the full suite record.
2026-11-05 12:52:46 +08:00
yetone 234903cb23 cli: magpie model api sets the API a model is asked on, as the editor's picker does (yew_fence_931206)
A relay with many models behind one key can now have each model's API
set from a script, not only in the provider editor's Names, prices &
levels ("API this model is asked on"):

  magpie model api <provider/model>... chat|responses|anthropic|gemini|auto
  magpie model api <provider/model>... --reset      (auto)
  magpie model api <provider/model>                 what it is asked on
  magpie model apis [<provider>]                    the settings; with a
                                                    provider, every model

It saves through provider.SetModelPrefs, the editor's Save, into
settings' modelAPIs, so a running gateway reads it on the next request
and the agents' model lists are told once. Choices are those the editor
offers (modelAPIs in app.js): the APIs the provider has a URL for, when
it has two or more; Vertex AI none. --help anywhere prints the usage. A
flag in place of a model, an unknown API, a model the provider doesn't
list, or an API it has no URL for is refused; several models are all
checked before any is written. A saved setting for a model the vendor
no longer lists can still be reset. Documented in docs/reference.md
("The API a model is asked on") and the gateway-routing page.

Run (mote, via mote-run, at this tree on 0e55a7593):
- go test -count=1 ./internal/cli/: ok (46.7s)
- TestModelAPICmd, TestModelAPIReachesTheRunningGateway: PASS. The
  second starts gateway.New().Handler() first, asks relay/mixed (chat
  completions), sets anthropic through the CLI, and the next request
  goes to /v1/messages; after --reset back to chat.
- gofmt -l: nothing; go vet, GOOS=linux go vet -tags nogui,
  GOOS=windows go vet of ./internal/cli; go build, GOOS=linux build
  -tags nogui, GOOS=windows build: ok.

Broken by hand:
- the model/api(s) cases taken out of modelCmd: both tests FAIL
  (unknown command "apis" / "api").
- each model written as it is checked instead of all checked first:
  TestModelAPICmd FAIL "a refused command wrote:
  map[relay/claude-y:anthropic relay/gpt-x:chat relay/mixed:chat]".

Not tried: a real relay account; the reporter's provider. The full
suite runs after the push.
2026-11-05 11:05:38 +08:00
yetone 00d8aac596 routing: Free quota by expiry spends the soonest-lapsing free quota first (wowbbs)
wowbbs (and shamen_xiaohong) keep check-in free accounts in one group:
WorkBuddy CN x2, MiniMax Code, TraeCode CN and Qoder CN. They asked that
the group spend the free quota that lapses soonest first, go on to the next
when one is used up or has lapsed, and use a paid account only when no free
quota is left.

This adds `expiring` (provider.FreeExpiring, routes.FreeExpiring). It is a
group's only, picked in the Routing page's group menu, with
`magpie group set <g> routing=expiring` or in the TUI. Nothing changes for a
group or provider that doesn't pick it. A provider keeps refusing it, as it
refuses `cheap`.

- routes: Seat.FreePlan and Strategy.ByPlan. FreeExpiring has three tiers:
  - free seats (Free, a model at no cost, or FreePlan) by Expires, the
    earliest of the window renewals and Lapse, to the hour; an unknown
    expiry goes last and ties keep their listed order;
  - then the paid seats, as Smart orders them;
  - then the spent and resting seats, by when they come back.
- provider.FreePlan reads an account's plan word: free, trial, 免费, 试用,
  体验, 體驗.
- gateway: weighRouted fills FreePlan when the strategy asks. The trace's
  Weighed rows gain `expires`, so the Routing page's story can say "its free
  quota is lost soonest, in 1d 2h". There are also lines for "a free one with
  no expiry told" and "no free quota left, so the paid one".
- GUI: an option in the group menu, the mode line, the story lines, and
  i18n in zh, zh-TW, ja and de. app.js only adds `expiring` to ROTATION,
  paid for by a shorter comment beside it, so the core is 11 bytes smaller
  than at its base.
- docs: gateway-routing.md (order of keys and accounts) and
  plugin-runtime.md (Seat and Strategies).

Plugins whose usage doesn't say when their free quota lapses got issues
rather than edits:
- magpie-community/plugins#718: Trae sums its packs; the soonest end comes
  from any pack, spent or past, and there is no runsOutAt.
- magpie-community/plugins#719: Qoder's plan is the raw userType
  personal_standard, which doesn't read as free, and its add-on, shared and
  dedicated pools have no expiry.
WorkBuddy (Free plan, resetsAt and runsOutAt) and MiniMax (Free, runsOutAt
on credits) already report what this needs.

Run, all on mote via mote-run at this tree (base 0ee424e3e):
- gofmt -l internal plugins: empty. go build ./....
- go vet of routes, gateway, provider, cli and tui; the same with
  GOOS=linux -tags nogui and with GOOS=windows.
- go test ./internal/routes ./plugins/rotation ./internal/tui: ok.
- provider -run TestFreePlan|Group|Routing: ok.
- cli -run Routing|Group: ok.
- gateway -run TestGroupSpendsFreeQuota|Wallet|Free|Cheapest|Routing|Weigh: ok.
- internal/gui -run Budget|Size: TestCoreScriptBudget is red, already red
  at the base (1,534,154 > 1,533,802, #5139). This change takes the core
  down 11 bytes and doesn't raise the budget.
- GUI, node --test in chromium and webkit, en, zh, zh-TW, ja and de, wide
  and 420px:
  - routing-free-expiring (new), routing-group-strategy, routing-cheapest-first,
    i18n-keys, builtins, group-member-free and provider-count-free: 176 of
    176 pass;
  - every routing-*.test.cjs: 2,478 of 2,520 pass. The 42 reds are in ten
    files (routing-rule-remove, rule-drag, rules-line, rule-models,
    row-swap, steady, order-unknown, steps-cap, story-shrinks and
    keys-fold). Run alone at this tree they give 27 reds, and at the base
    0ee424e3e 25, the same tests. They are filed as #5088, #4585, #3096,
    #3789, #3799, #4627, #4628 and #4629.

Again after rebasing on origin/main 0e804be29: gofmt; vet of routes,
gateway and provider; the same Go tests: ok. routing-free-expiring,
routing-group-strategy and i18n-keys: 62 of 62 pass. The core is 1,534,034
here, against main's 1,534,045.

Red on the old code: TestGroupSpendsFreeQuotaSoonestToExpireFirst at
0ee424e3e gives "pro,wb1,wb2,mm,qoder" where it wants
"mm,wb2,qoder,wb1,pro".

Broken by hand: with FreePlan never set, the gateway test gives
"pro,mm,wb2,qoder,wb1" (red). routing-free-expiring.test.cjs reads strings
that exist only with this change. routing-group-strategy's two menu counts
(11) went red with the new option, and they now count 12.

Not tried: no real account of any vendor. WorkBuddy, MiniMax, Trae and
Qoder check-in accounts were not routed live. The order was tested on
fabricated allowances shaped as their plugins report them. The full
`go test ./...` runs after the push.
2026-11-04 17:11:55 +08:00
yetone 75e30625f5 plugin: a command that serves no pages moves a page's service off the app's port (#5187)
MYCF711 (#5187, Windows, 0.1.2901): magpie plugin update run while the
app runs hung with no output. Its host loads every plugin, and
page-chat's service waits for port 3477, which the app's host holds:
each CLI command that starts a host waited ~6s on it, then kept trying
the port every second in the background, so it could take 3477 from
the app's host when that restarted after the update.

Now magpie run with a command that serves no pages (anything but the
app, tray, tui, web, serve, a bare magpie or a magpie: link opened in
the app; servesPages) sets plugin.ServePages(false), and its host hands
a plugin whose magpie.page.service names an option a free port of its
own in that option (hostOptions). The plugin's other parts load at once
and the app's port is left alone. plugins.json is not changed, and a
service no option moves is started as before. The class, not
page-chat: any plugin page service declared with an option.

Run, at base 0ee424e3e plus this change:
- mote: go vet ./internal/plugin ./internal/cli (darwin), GOOS=linux go
  vet -tags nogui and GOOS=windows go vet of both, GOOS=linux nogui and
  GOOS=windows builds, go test -count=1 ./internal/plugin ./internal/cli:
  ok (280s, 65s). gofmt -l clean.
- Broken by hand: hostOptions handing options unchanged makes
  TestHostServingNoPagesLeavesHeldPort red (the load "didn't finish in
  10s") and TestHostOptionsMoveOnlyTheService red; servesPages returning
  true makes TestServesPages red on daemon, autostart, providers.
- Windows (xiaomi-gpu, win-run): the new tests and TestServesPages ok.
  Sandbox with page-chat and the reporter's git plugin
  (KevinFX-code/magpie-wps-lingxi), nogui builds:
  - 3477 held by bun, magpie plugin update: 13.9s before (page-chat
    "被占着" then "每秒试一次"), 10.6s after (page-chat "listening on
    127.0.0.1:51493").
  - beside magpie serve's host on 3477: 13.98s before, 12.4s after;
    serve's host keeps 3477.

Not tried / not reproduced: the reporter's literal no-output hang. Before
this change, update finished on 0.1.2909 in every setup tried (nogui
CLI with 3477 held, beside nogui serve, beside the release GUI exe in
the interactive session: 6-20s), so this removes the wait and the
port contention seen, not a hang reproduced. Not tried on Linux or the
macOS app.
2026-11-04 16:25:02 +08:00
yetone d136d0fe98 gateway-key: rotating a key can give it a value of the user's own (isaac_bai)
isaac_bai on Discord: a gateway key's value is random, and only rotate
changes it, to another random one; they want to set one easy to pass on.
Adding a key could take an own value since 6b6113aa; an existing key
couldn't.

- access: rotate-key takes Change.Secret. Given, it is checked as an
  added key's own value (ownSecret: 8-256 printable ASCII, no space, not
  sk-magpie-, no other key's value; its own current value is allowed);
  empty, magpie makes one as before. The key keeps its id, name, limits,
  models and accounts, and Named counts a request from this computer
  with it as that key.
- ownSecret now refuses a value that is one of the user's provider keys
  (a provider's Key or any of its Keys, constant-time), for add-key too:
  a client sending it would spend that provider directly.
- CLI: `magpie gateway-key rotate <id> --key <value|->`; docs/reference.md.
- GUI (plugins/gateway/keys.js, outside the core budget): the Rotate key
  dialog has a hidden "Your own key (optional)" field; Enter rotates,
  Escape cancels; an own value says "Gateway key changed. Clients that
  send this key reach magpie now." Strings in zh, zh-TW, ja, de.

Tests: TestRotateToOwnValue (bad values refused, old value still works
after a refusal, trimmed own value authenticates as the same key, is
Named, listed masked; empty makes a new key; add-key refuses a provider
key). TestRotatedOwnValueKeepsTheKeysLimit: after rotating to an own
value the old one is 401 from another computer, the own one 200 from
another computer and from 127.0.0.1, and a 700-token day limit stops
the third request from either (429), every record under the key.
gateway-key-own-rotate.test.cjs: chromium and webkit, en/zh/zh-TW/ja/de,
1000 and 400px.

Run (mote): at the pushed head: TestCoreScriptBudget ok, ./internal/access ok, the
own-key/caller-key gateway tests ok. At f37742e14 with this change (no file the rebase touched):
gofmt -l clean; go vet GOOS=linux and windows (./internal/access ./internal/gateway, cli with
-tags nogui on linux) ok; ./internal/cli red on TestEveryRouteHasACommandOrIsNamed only,
/api/context/reply (#5026, 0872bc2a0, the same at main); GUI: gateway-key-own-rotate 20/20,
every gateway-key-*, redact-*, masking-*, privacy-* file and i18n-keys pass.
Broken by hand: the rotate own-value path off made TestRotateToOwnValue and
TestRotatedOwnValueKeepsTheKeysLimit red (401 from another computer); the provider-key check off
made TestRotateToOwnValue red ("accepted upstream-first-key").
Not run: the whole GUI suite (two runs lost: one to another run of this tree, one to mote
rebooting mid-run); it runs after the push. Not tried: a real client on another computer with
the own value, the real app.
2026-11-03 20:17:00 +08:00
yetone 900ae0fa51 backup, sync: sign-ins go too when picked, sealed, never over a later renewal
qianxunji (#feedback) and curtinp118 on Discord: a VPS restored from a
backup, or a new computer joining sync, had to sign in to every
subscription again. Sign-ins (subscription accounts in logins.json,
Codex's auth.json, plugins' sign-ins in plugin-auth.json) can now go too,
in each place only when picked; all are off by default, so an upgrade
carries nothing new.

- Sync (WebDAV, S3, GitHub): a "Sign-ins" tick in the form, with a line
  saying anyone with the passphrase and the server's file can use the
  accounts, and that an account on two computers can be signed out on one
  when the other renews it. CLI: `magpie webdav|s3|github set sign-ins=yes`.
- Export: "With the sign-ins", off; ticked, the passphrase hint says the
  file holds them. CLI: `magpie backup --sign-ins`.
- Import: "Bring in the sign-ins too, when the file has them", on. CLI:
  `magpie restore --no-sign-ins` leaves them out.
- Back up by itself: "Sign-ins in backups", Off/On. On asks for a
  passphrase (twice) that seals the sign-ins alone (the rest of an
  automatic backup stays unsealed, as before); it is kept in
  autobackup.json (0600), never sent in the view. A backup whose sign-ins
  another passphrase sealed restores without them and says so.

What goes (provider.CollectSignIns, plugin.CarriedAuth): magpie's own
copies only, not an agent's own account, an agent-home row, a hidden or
plugin: row, or a retired built-in. Each record is keyed by agent +
email + org (or the account key); ids two rows share go on neither side.

Restore/import (RestoreSignIns) adds what is missing and updates only
when the incoming copy was renewed later; nothing here is removed.
Before writing over a row it counts every row that could be the same
account (same login, same refresh token, same id): none adds, several
keeps all, one is kept when it isn't magpie's own copy, is held, or is
the agent's live account. Codex's auth.json is written temp-and-rename,
0600, only where Codex is signed out.

Sync merges per record against the last sync's hashes (MergeSignIns):
the later renewal wins; a removal crosses only when the other side still
had it as of the last sync; ApplySignIns re-checks each row's hash
before writing so a renewal in between is kept. A computer with the tick
off sends none, so others remove nothing for it; turning it off, a
Restore, or a replaced server file clears the last-sync record.

Export's and Import's forms moved out of app.js into syncfiles.js,
imported when one opens (as autobackup.js is), so the core is 3.2KB
under its budget with no raise (app.js 3.2KB smaller than before).

docs/subsystems/sync-backup.md has a "Sign-ins, when picked" section;
subscription_signin_test.go's header now says it pins the default.

Run at the pushed head (678d28cba on origin/main bc10a6198):
- wsl-run go test -tags nogui -timeout 45m: backup, davsync, plugin, gui
  ok (TestCoreScriptBudget in it). provider: one red,
  TestCancelledPluginSignInSavesNothing, the late sign-in saved after
  Cancel. It is green 20 of 20 alone, at this head and at origin/main
  alike, and this change adds only new files there whose tests run after
  it; filed as #5047. cli there hung in proc.lookStamp's os.Stat on WSL
  at load 100, so it ran again on mote: one red,
  TestEveryRouteHasACommandOrIsNamed (GET /api/context/reply, #5026),
  the same at origin/main. gateway -run TestCompactionOverByteCapEveryTime
  ok (#4862 on mote's full run). TestMainWindowCorners on mote: red the
  same at origin/main (#3949).
- GUI, on mote: the 16 files that open Sync, plus i18n-keys and
  old-webkit, Chromium and WebKit, every language: 255 of 294 pass. The 39
  reds are segs-press-redraw's searchAllRow (#4566), s3-sync in WebKit
  (#2448) and usage-agents-hide (#3414). The same files at origin/main
  bc10a6198 give the same 39 pass and 39 fail. sync-signins, auto-backup,
  sync-sign-in, i18n-keys and old-webkit alone on WSL: 92/92.
- The whole GUI suite on WSL, stopped at 737 of its tests (1162 files,
  load ~100 there): 9 reds, all WebKit, none in a Sync file:
  account-eye (#4244, #5052), add-button (#4792), account-plugin-user
  and agent-expand-steady. The last two pass at this head and at
  origin/main on mote. The rest of the suite was not run.
- gofmt -l: clean. go vet: darwin (internal/gui, internal/cli),
  GOOS=linux and GOOS=windows -tags nogui for backup, davsync, provider,
  plugin, cli, gui: ok.
- win-run and wsl-run: go test -tags nogui -run
  'SignIns|Carries|AutoBackupSignIns' ./internal/provider
  ./internal/backup ./internal/davsync: ok on Windows 11 and Ubuntu 24.04.
- sync-signins.test.cjs: 20/20, Chromium and WebKit, 1100 and 420px,
  en/zh/zh-TW/ja/de, no horizontal overflow, no page errors.

Then rebased on origin/main 5ee5274bd (12 commits; davsync.go, app.js and
i18n.js merged with no conflict) and run again at the pushed head on mote:
gofmt clean; go test -run 'TestCoreScriptBudget|SignIns|Carries|
AutoBackup|Sync' for gui, davsync, backup and provider: ok; sync-signins,
auto-backup, sync-sign-in, i18n-keys, old-webkit: 92/92.

Broken by hand, each red, then restored:
- RestoreSignIns writing an older token over a newer one:
  TestRestoreSignInsNeverWritesAnOlderTokenOver red.
- The ambiguous-account guard has two layers (more than one match, and
  a single match with another record id); with only the first removed
  the test stayed green, with both removed
  TestRestoreSignInsLeavesAnAmbiguousAccount went red.
- MergeSignIns removing a row renewed here: TestMergeSignInsRemovedOnlyWhenTheOtherSideRemovedIt
  red.
- Codex auth.json written over a signed-in Codex:
  TestRestoreSignInsSignsCodexInOnlyWhereSignedOut red.
- ApplySignIns not re-checking the hash: TestApplySignInsKeepsWhatChangedSinceTheMerge
  red.
- davsync forgetting the last-sync record (st.SignIns = nil):
  TestSyncSignIns red.
- GUI: Export's tick on by default, and auto backup's On posting with
  no passphrase: sync-signins.test.cjs red for each.

Not tried: real accounts carried to a real VPS or second computer (all
Go tests use testenv homes, fake DAV and fake tokens; the Keychain is
never reached); a real vendor's refresh after a carried sign-in, and how
each vendor treats one refresh token used from two machines; the CLI
flags against a sandbox HOME (covered by the cli package's tests only);
auto backup's sign-ins have no CLI switch.
2026-11-03 17:24:19 +08:00
yetone b295d11965 serve, update: one magpie works the gateway; the service waits, the copy an update left stops (#4938)
ox01024's #4938, Bug 2. Two magpies did the gateway's work at once on a
Mac:

- launchd's com.yetone.magpie.serve ran `magpie serve` beside the app.
  It ran startUp (plugin Settle/Refresh, FoldCopies, Hold, the agent
  moves), the plugin host and every account's model fetch, then failed
  to bind, exited 1 and was started again 5s later: 6,035 times in two
  days, a 279MB serve.log, and logins.json.lock held against the app's
  requests until they went 504.
- The copy an update left (.magpie-update/old) handed the socket over,
  hid, and lived on ~3h, its loops writing beside the new one.

What changed:

- cli: `magpie serve` (no --web) checks codexrelay.Leave,
  gateway.ServedBy and gateway.Taken before startUp, as the app's
  serveGatewayLocked does. While the port is held it prints one line
  and looks again every 15s, doing nothing else. Once the port is free
  it serves (serve_wait.go). It waits rather than exiting 0: under
  KeepAlive SuccessfulExit:false a clean exit would leave no service
  after the app quits.
- gui: after a handover the old magpie's loops end with backendCtx:
  - library.KeepLinked (now takes a ctx),
  - provider.WatchQuotas,
  - the menu bar usage loop,
  - the updater's check/auto-restart loop.
  lighten lets its hidden webviews go as lightweight mode does, so
  their polls stop. quitBy exits it at handedOffDrain + 3m whatever
  holds its quit up (gateway.HandedOffDrain getter; exitNow stubbable).
- docs/subsystems/gui-shell.md says both.

Run at the pushed head on mote (mote-run):
- gofmt -l internal/: nothing. go vet ./internal/{cli,gui,library,gateway};
  GOOS=linux go vet -tags nogui and GOOS=windows go vet of the same: ok.
- go test -count=1 -timeout 45m ./internal/cli ./internal/library
  ./internal/gui ./internal/gateway at bf05291e2 + this: cli and
  library ok. Two reds, both already filed:
  - gui TestMainWindowCorners/macOS_26_SDK (#3949). It is red the same
    on origin/main 443e53d6b, run alone.
  - gateway TestCodexPoolSaysTheClientsVersion (#4807). It is red only
    in the full package run, and passes alone 5 of 5 at this head.
- After rebasing on 8819beeb0, on that head: the vets above; cli and
  library in full, ok; gui and gateway with -run for handover, handoff
  and lightweight, ok.
- Sandbox HOME on mote, a fake app answering / as magpie 0.1.2770 on a
  private port (3593), `magpie serve` built from this tree beside it:
  alive after 8s at 0% CPU, nothing written under HOME, one standby
  line. 20s after the fake quit it served the port. The same with the
  old wait call removed: "magpie: listen tcp 127.0.0.1:3593: bind:
  address already in use", exit, and plugins.yml and lock files written
  first.

Broken by hand, each red:
- No wait before startUp: TestServeWaitsForTheGatewayBeforeStartingUp
  ("ran the start-up moves while another magpie served the gateway").
- KeepLinked ignoring its ctx: TestKeepLinkedEndsWithItsContext
  ("went on after its context ended").
- No quitBy in handover.run: TestRestartHandsTheGatewayOver ("has no
  deadline to quit by").

Not tried:
- A real launchd service beside the real app, and a real update
  handover on a Mac. Neither was run: no live app or launchd.
- The lighten change (needs Wails webviews) has no test.
- Not done here: serve.log rotation, `magpie daemon install` beside a
  running app (#4887), the old copy's appPage port, and Bug 1 and
  Bug 3 (ggbdpq has Bug 1).

cdredfox on Discord reports ~270% CPU after v0.1.2770. That fits this,
but it is not confirmed as their cause.
2026-11-03 11:16:02 +08:00
yetoneanderlinerd 1cb4d43013 profiles: a saved profile renames, in its details, the TUI and magpie rename (#2721, erlinerd)
erlinerd's patch on #2721 (profile.Rename, /api/state profile/rename,
a Rename button in the details), reviewed against main and adapted:

- profile.Rename trims both names, refuses an empty, taken or missing
  name and leaves profiles.json as it was, renames by case only
  (home -> Home), and keeps what the profile holds.
- GUI: Rename turns the details' name into a field. Enter renames
  through profileAction, so the chip is renamed at once, pending, and
  rolled back with the error if magpie refuses; the details stay open
  under the new name, with In use kept. Escape or a click away puts
  the name back. The field lives in profilerename.js, imported on
  press, so the core script stays under its budget (no raise; 50 bytes
  under after comments in app.js were cut). While the field is open
  In use, Apply and Rename hide so a 360px panel's field has room.
- TUI: ctrl+e on a profile renames it on the name line.
- CLI: `magpie rename <old> <new>`; a flag is never taken for a name.
- WebDAV: a rename syncs as the old name gone and the new one in
  (davsync test).

Run on mote at 47672f11c (on 70b96126e), and again after rebasing on
52195b6b0 (backup), as 3b279fdee:
- go test ./internal/profile ./internal/cli ./internal/gui ./internal/tui
  ./internal/davsync: ok except TestEveryRouteHasACommandOrIsNamed
  (#4826) and TestMainWindowCorners (#3949), both red on origin/main
  07f4d46c5 too. gofmt clean; GOOS=linux (-tags nogui) and
  GOOS=windows go vet ok.
- GUI, chromium and webkit: profile-rename (en, zh, zh-TW, ja, de;
  900x560 window and 360x420 panel), panel-profiles, profile-confirm,
  profile-in-use, profile-details, hermes-profiles,
  view-wheel-after-click, i18n-keys, gui-de, gui-ja, gui-zh-tw,
  editor-roomy: 219 pass, 0 fail. After the rebase: profile, cli,
  gui, tui and vet again (same two reds only, core budget ok), and the
  GUI files above with auto-backup in place of editor-roomy: 161 pass.
  Then rebased over ea51526b6 (gateway, plugin, provider only; no
  file of this change, no GUI asset) without another run.

Broken by hand, each red, then restored:
- Rename comparing names with EqualFold: TestRename red (case-only).
- Dropping the CLI's "-" check: TestRenameCommand red.
- Dropping `profileOpen = to`: profile-rename 22 of 22 red, both engines.

Not tried: the real app on Linux (WebKitGTK) or Windows; a rename
synced over a real WebDAV server.

Co-authored-by: erlinerd <erlinerd@outlook.com>
2026-11-02 18:37:25 +08:00
yetone 52195b6b07 backup: the setup is backed up into a folder by itself, and any version put back (jwaitq)
jwaitq (Discord) nearly lost their setup on Windows and got it back only
from a Downloads\data folder they happened to have. They asked for
backups made on a schedule into a folder, with a version to go back to.

What changed

- internal/backup/auto.go: Settings › Sync › "Back up by itself". On by
  default: once every 24 hours, the last 7 kept, into
  <config dir>/auto-backups. Interval (1 hour, 6 hours, 1 day, 1 week, or Off), keep (3,
  7, 14, 30) and the folder are the user's to change. autobackup.json holds
  only what the user set; a field they never touched follows the default,
  so a later default never overrides their own value. An unreadable
  autobackup.json makes no backup and says so, never "off" or a default.
- What goes in is the export without API keys (backup.Collect(false)),
  the same bundle and the same handling of secrets as the manual no-keys
  export, with the proxy URL blanked as well (it can carry a password).
  Not sealed, so it opens without a passphrase. Files are 0600 in a 0700
  folder, written to a temp file, fsynced and renamed, and listed only
  when they parse and their sha256 matches, so a half-written file is
  never a version. A temp file over an hour old is removed.
- A backup is made only when the setup changed since the newest one, so
  a quiet week keeps a week of versions, not seven copies of one day.
  The loop runs inside the gateway (WhileServing), first 2 minutes after
  launch, then every 10 minutes it checks whether one is due by the
  newest file's time, so a restart doesn't make an extra one.
- Restore puts a version back the way Import does (additive), after
  first writing the current setup as a "-restore" backup. If that
  backup can't be written, nothing is put back. The row says when the
  undo copy was made, and restoring it undoes the restore. "-restore"
  backups are pruned past Keep like the rest.
- internal/gui/backup.go: GET /api/autobackup and POST
  /api/autobackup/{set,choose,now,reveal,restore}. internal/cli
  settings_parity_test names the two routes in notYet (S2).
- GUI: autobackup.js, imported lazily when Sync is drawn, so app.js and
  the core budget are not raised. The app's own segmented controls and
  menus (no <select>), the folder row with Change…/Show/Default, Back up
  now, and the versions list with Restore behind a confirm. Strings in
  en, zh, zh-TW, ja, de (22 keys each).
- docs/subsystems/sync-backup.md: "Backups by themselves".
- Tests touched beside it: sync-sign-in's "last row" is now the last of
  Sync's own rows (the new rows come after Import); usage-computers
  scrolls its tick to the middle, since in WebKit the sticky Settings
  tabs covered it at the page's end; agent-prefs waits for Settings'
  first draw instead of reading the static index.html's rows.

Tests

- internal/backup/auto_test.go: TestAutoBackupOnSchedule (injected
  clock, no sleeps), TestAutoBackupAfterRestartWaits,
  TestAutoBackupOffOrUnreadable, TestAutoBackupPrunes,
  TestAutoBackupHoldsNoSecrets, TestAutoRestoreRoundTripAndUndo,
  TestAutoRestoreNeedsTheBackupFirst, TestAutoHalfWrittenNeverListed.
- internal/gui/backup_test.go: TestAutoBackupRoutes.
- internal/gui/tests/auto-backup.test.cjs: chromium and webkit, 1100px
  and 420px, en/zh/zh-TW/ja/de; plus "Sync redrawn while the backups are
  being read still shows them", which found a real bug (the rows were
  dropped when Sync redrew during the first read) and is red on the old
  code.

Broken by hand, each test red, then put back: dedup off (OnSchedule),
interval check off (OnSchedule, AfterRestartWaits), keep+1
(Prunes), proxy left in (HoldsNoSecrets), no backup before a restore
(RoundTripAndUndo), restore going on after a failed backup
(NeedsTheBackupFirst), unreadable config read as default
(OffOrUnreadable), checksum not checked (HalfWrittenNeverListed),
os.Rename without the temp step (HalfWrittenNeverListed). And the
redraw fix, reverted: the redraw GUI test red in both engines.

Run on mote (macOS 27) at this change on c9af34446; rebased then onto
019b308f1 (internal/provider only) and built and vetted again, then onto
70b96126e (app.js/app.css editor sizing): TestCoreScriptBudget and
TestAutoBackupRoutes ok on mote; auto-backup, old-webkit, i18n-keys,
sync-sign-in and editor-roomy 152/152 on WSL. The earlier runs:
gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet
of backup, gui, cli ok; go build ./... ok; go test -timeout 45m
./internal/backup ./internal/davsync ok, ./internal/cli and
./internal/gui red only on known reds: TestEveryRouteHasACommandOrIsNamed
for POST /api/usage/checkin-account (#4826) and
TestMainWindowCorners/macOS_26_SDK (#3949).
GUI on Linux (WSL magpie-desktop, Playwright 1.62.0, chromium and
webkit) at 0dd8901a7, whose only difference from this head is Go files
outside this change: auto-backup, gui-de, gui-ja, gui-zh-tw, i18n-keys,
old-webkit, settings-general, settings-lines-wrap, settings-search,
settings-sections, settings-tabs-stick, sync-auto-restore,
sync-not-backup, sync-note-show, sync-other-kind, sync-own-fields,
sync-sign-in, sync-spin, sync-usage-error, webdav-settings-refresh,
github-sync, s3-sync, import-row, menu-scroll, agent-prefs,
usage-computers, account-eye: green. Red the same at origin/main
1aca55909 in the same run: segs-press-redraw searchAllRow (#4566),
balance-fix Sub2API (#4683), agent-panel-name-width (#4203), click-scroll
webkit wheel (#4385), codex-auto-reset webkit de (#4790),
codex-predictions webkit (#2624), codex-credits-first webkit (#4908,
filed now).

Not tried: the whole GUI suite (on WSL at concurrency 4 it ran past 5
hours beside other sessions' runs; I stopped my own run and ran the
files a Settings/Sync change can reach, plus the ones it had shown red);
a real Windows install (jwaitq's system) or the real app with a real
HOME; a restore of a real user's backup.

Asked for by jwaitq on Discord.
2026-11-02 18:24:38 +08:00
yetone 7d1f2ecba3 claudecode: magpie keeps the Claude Code it downloaded at the newest release
alextjy on Discord runs magpie in Docker with Claude Code from
`magpie claude-code install`, and asked whether a magpie update touches
it and how it updates. The download lives in <cache>/claude-code
(/config/cache, on the volume), so a new image keeps it. But nothing
ever updated it: every run magpie starts sets DISABLE_AUTOUPDATER, so it
stayed at the version first installed until the user ran install again.

claudecode.KeepCurrent now runs while magpie serves (a WhileServing
loop): a minute after start and every six hours it asks
downloads.claude.ai for the latest release and downloads a newer one,
checked against the manifest's SHA-256 and size as install does. The
version it replaced is removed on the next look rather than at once,
since a run being started may hold its path (Install, the CLI's, still
removes it at once; a folder with a .part download in it is left
alone). It does nothing when magpie downloaded none, when the machine
has its own `claude` (that one is run and updates itself), or when
DISABLE_AUTOUPDATER is set for magpie, Claude Code's own way to hold a
version. A failed look keeps the download and is logged. It never
downgrades.

The status line of `magpie claude-code`, the Docker docs (en, zh, ja)
and the bridge's subsystem page say so.

Run:
- wsl-run (Ubuntu 24.04, Go 1.26.8): go vet, then go test -race -v
  ./internal/claudecode/ -run 'Keep|Install|Find': all pass.
- Broken by hand on WSL, each red: no newer() check
  (UpdatesMagpiesDownload, LeavesWhatIsntMagpiesToUpdate), no own()
  check (the_machine's_own), pruning at install (UpdatesMagpiesDownload),
  no prune on the next look (UpdatesMagpiesDownload).
- Real use on WSL, sandbox HOME and XDG_CACHE_HOME: a throwaway program
  with a fake 2.1.1 download ran KeepCurrent against the real
  downloads.claude.ai. After 1m34s it logged "updated from 2.1.1 to
  2.1.316", the kept binary's --version said "2.1.316 (Claude Code)",
  2.1.1 was still there for the next look, and the loop ended with its
  context.
- mote, at this tree: GOOS=windows and GOOS=linux go vet -tags nogui of
  both packages, go vet ./internal/claudecode/, go build ., then
  go test -tags nogui ./internal/claudecode/ ./internal/cli/ -timeout 45m:
  VET-OK; claudecode ok 0.680s, cli ok 56.673s.
- gofmt -l clean.

Not tried: the Docker image itself (no docker on the test boxes), and a
Windows run whose replaced binary is still in use (prune leaves what it
can't remove for the next look). Full suite not run: the change is the
claudecode package, one WhileServing line and one CLI status line. A
WSL run of ./internal/cli/ at the default 10m timeout timed out while
the box ran other sessions' full suites; the 45m run above replaces it.
2026-11-01 19:00:51 +08:00
yetone 5dfbca6274 cli: magpie settings list|get|set|reset, through the window's own save (#4745)
Stage 1 of #4745 (StringKe): every setting POST /api/settings saves can
be read and set from the terminal.

- internal/settingsapi holds the save the handler made: Merge (the
  carry of keys a page leaves out, moved verbatim from api.go, plus
  upstream's RouterNote line), the vision/imageGen/searcher checks,
  settings.Save's own checks, catalog.Touched. POST /api/settings and
  `magpie settings` both call settingsapi.Apply, so a value is checked
  and saved one way. It sits outside internal/gui so the nogui build
  has it.
- `magpie settings` (list, the default, with value, default and
  choices; get; set; reset to settings.Defaults()), --json on list and
  get. Body sends the whole file with one key changed, so a key the
  save keeps when absent (noBird, refusalRetries, ...) is set even to
  off. A flag where a key or value goes, an unknown key (with near
  matches named) or a refused value writes nothing and exits 1;
  --help prints usage.
- Parity guards: TestKeysAreWhatTheSaveWrites (each Settings field sent
  changed on its own; what the save takes must equal Keys),
  TestSettingsCLISetsWhatTheWindowSaves (every key the page's prefsKeep
  and savePrefs send is a key), TestEveryRouteHasACommandOrIsNamed
  (each /api route has a command or a reason in notYet, which later
  stages shrink; 36 have one now).
- Item 3 of the stage (per-provider CLI-only fields in the window) is
  left for stage 2.
- The open app's in-process follow-ups (fonts, Dock, tray menu, alerts,
  language, update re-check) run only from the window's save: #4752.

Run (mote, at the pushed head 1c3591b5d + this):
- gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; GOOS=linux go build -tags nogui;
  GOOS=windows go build: clean (before rebase, the vets again after).
- go test internal/settingsapi, internal/settings, internal/cli: ok.
  internal/gui -run Settings|Prefs|Keep after the rebase: ok. The full
  internal/gui run before the rebase had three reds:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, fixed on main in
  b646a9127), TestColdTurnsTaken (fixed on main in 647323409) and
  TestMainWindowCorners/macOS_26_SDK (#3949, mote is macOS 27).
- Real run in a sandbox HOME on mote with a magpie built from this:
  settings --help / help, list, get, set theme dark, noBird on,
  redactWords "acme, globex", usageAlert 85; refused theme neon, `them`
  (names theme), usageAlert lots, trayUsageEvery 4, vision
  nobody/nothing, each exit 1 with settings.json unchanged; set
  usageAlert --help printed usage and wrote nothing. Then `magpie web`
  with MAGPIE_WEB_KEY: GET /api/settings read back each value the CLI
  set; POST /api/settings lang ja, then `settings get lang` said ja;
  reset theme gave system.

Broken by hand, each red, then put back: noBird dropped from Keys
(TestKeys, TestBodySetsOneKeyOnly, the CLI set test and the GUI parity
test red); Body dropping false values (TestBodySetsOneKeyOnly and the
CLI "noBird off" check red); a route taken out of notYet and another
renamed (TestEveryRouteHasACommandOrIsNamed red, 3 errors). On the old
code the new tests don't compile (no settingsapi, no command).

Not tried: a real run on Windows or Linux; the live app reacting to a
CLI write while open (#4752); the GUI node suite (no page file changed).
2026-11-01 15:57:43 +08:00
yetone 788057340b library: Magpie Image Recognition in Discover beside Magpie Image and Web Search (matrix0487 on Discord, #4653)
matrix0487 asked on Discord (#feedback) for all three of magpie's own MCP
servers, image recognition, image generation and search, in the Library's
Discover. Image generation and search were there; image recognition was
an address to copy in Settings only (#4653).

- `magpie mcp vision` (browsermcp.RunVision) relays stdio to the
  gateway's /mcp/magpie/vision, as `mcp search` does. analyze_image's
  relative image path is made one in the agent's folder on the way
  (imageFrom), since the gateway can't know where the agent runs; an
  absolute path, ~, a URL or a drive goes as written.
- library: magpie-vision is a featured, opt-in server (no agents until
  picked), any binary's `mcp vision` is one server (serverKey), and it
  gets the 120s tool timeout (selfTimeout).
- Settings › Models › Images: the Image recognition row has Give agents
  Magpie Image Recognition… / Turn on the Library, none with recognition
  off or in gateway mode. The three links are one helper, libWay, used by
  Image generation and Web search too (no budget raised: core 1,533,011
  of 1,533,105).
- Never a dead tool: Discover lists all three whatever is set up, and one
  that can't answer yet says why (gateway.OwnUnready, set by
  /api/library/market/servers as `unready`): a "Not set up yet" badge on
  its card with the reason as its title, and the reason in its sheet
  (nothing set up, or turned off in Settings / Plugins). It can still be
  added; its tools already answer with the same reason until then.
- Strings in en, zh, zh-TW, ja, de; docs/subsystems/library.md.

Run, all on mote (macOS 27) through mote-run, at this head's tree
(rebased on 21882a68d):
- gofmt -l internal/: clean. go vet darwin; GOOS=linux -tags nogui;
  GOOS=windows: browsermcp, cli, library, gateway, gui, imagemcp ok.
- go test -timeout 45m: internal/library, browsermcp, cli, imagemcp ok;
  internal/gateway ok (whole package, 556s, before the rebase; OwnMCP,
  OwnUnready, VisionMCP, SearchMCP after it). internal/gui: three reds,
  none from this change, each red on origin/main 21882a68d too:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, from 8d8df0639,
  filed #4739), TestMainWindowCorners/macOS_26_SDK (#3949),
  TestColdTurnsTaken (#4510). Budget tests ok.
- New: TestMagpieImageRecognitionIsOptIn, TestVisionBridgePassesLines,
  TestImageFromLeavesTheRest, TestOwnUnreadyWhileNotListed.
- New GUI test vision-mcp-library.test.cjs: chromium + webkit, en, zh,
  zh-TW, ja, de, 1100 and 420px (link opens the sheet with its hint and
  unready line; Library off → Turn on the Library; one added opens
  Discover with all three, only the unready one badged, inside its card;
  gateway mode and recognition off show no link; no horizontal overflow,
  no page errors): 206/206 with search-mcp-library and
  images-library-way. On e84870f17 (old code), chromium: every link and
  Discover case red.
- i18n-keys, gui-de, gui-zh-tw ok; gui-ja's one red is #4580, the same
  on origin/main 21882a68d.
- Broken by hand: serverKey without "vision" → TestMagpieImageRecognitionIsOptIn
  red; imageFrom not joining the folder → both browsermcp tests red.
- Real use, sandbox HOME on mote, nogui build, `magpie serve` on
  127.0.0.1:3591: `magpie mcp vision` initialize / tools/list answered;
  analyze_image of shots/a.png says "magpie has no model that sees
  images…"; missing/b.png names /…/work/missing/b.png (relative path
  resolved); an extra argument exits 1; gateway down answers id 9 with
  "magpie isn't running, so Magpie Image Recognition can't be reached".

Not tried: analyze_image against a real seeing model through the relay
(the sandbox had no provider; the gateway path is the one /mcp/magpie/vision
already serves); a real agent adding it from Discover; WSL (unchanged,
the MCP router serves it there); the whole GUI suite, queued after
mote's running one.

Reported-by: matrix0487 (Discord)
Closes #4653
2026-11-01 14:12:42 +08:00
yetone b1fc435407 library: Magpie Web Search, magpie's search MCP server in Library › MCP (lutra_fs)
lutra_fs on Discord: magpie's search MCP shows in Settings › Models but
not in Library › MCP servers. They were right. The gateway's web search
MCP (/mcp/magpie/web-search) was only an address to copy in Settings ›
Models › Web search. It was never a Library server, so no agent could be
given it from the Library, and the Library didn't list it.

Change:
- `magpie mcp search`: a stdio relay to the gateway's search MCP, made by
  widening browsermcp's Magpie Browser relay into a bridge with its own
  path, title and an optional session (search sends none, and has a 5
  minute client). It takes no arguments. When magpie isn't running, it
  says "Magpie Web Search can't be reached: start magpie".
- library: Magpie Web Search (magpie-web-search) is a featured,
  opt-in server beside Magpie Image and Magpie Browser. It is installed
  with no agents, so the user picks them in its sheet, and it switches
  per agent like any other row. Its command is the full binary path, and
  serverKey treats any binary's `mcp search` as the same server. Each
  agent's tool timeout is at least 120s.
- Settings › Models › Web search › MCP server: under the address there is
  a "Give agents Magpie Web Search…" link that opens its Library sheet,
  or "Turn on the Library" while the Library is off, as Images does for
  Magpie Image. Gateway mode has no link.
- The sheet's hint says where each search goes and what it costs. All
  strings are in en, zh, zh-TW, ja and de.
- docs/subsystems/library.md names magpie's own servers and the new one.
- An agent in WSL gets it through the MCP router, as Magpie Browser
  does. The image-only WSL side() is unchanged.
- The sibling, Image recognition's MCP server, is still in Settings only.
  That is filed as #4653.

Run, at this head (rebased on origin/main a6217e83d), on mote: gofmt -l
is empty. go vet passes for darwin, linux (nogui) and windows.
internal/library, browsermcp, cli and imagemcp pass. The internal/gui Go
package and the GUI files search-mcp-library, search-mcp,
images-library-way, i18n-keys, gui-ja/de/zh-tw, searcher-pick and
search-keys: 197 passed, 2 failed. The 2 reds are both known. gui-ja is
the {agent} ja string, #4580. searcher-pick's chromium en case reads a
null box: red 1 of 3 here and 2 of 3 at a6217e83d, filed as #4274.
internal/gui's three reds are red at base and filed:
TestSettingsSaveKeepsWhatItDoesNotSend #4514,
TestMainWindowCorners/macOS_26_SDK #3949 and TestColdTurnsTaken #4510.

New test: search-mcp-library.test.cjs covers Chromium and WebKit, 5
languages, at 1100 and 420px. On the old code it is red, 52 failed and
10 passed; the passes are its gateway-mode cases, which expect no link.
TestMagpieWebSearchIsOptIn and TestSearchBridgePassesLines are new too.

Broken by hand: with "search" taken out of serverKey,
TestMagpieWebSearchIsOptIn goes red (Have empty).

Real use: on mote, in a sandbox HOME, with a nogui build and the
gateway on 127.0.0.1:3611. `magpie mcp search` answered initialize with
serverInfo magpie-web-search and listed web_search in tools/list.
web_fetch https://example.com returned "Example Domain". With the
gateway killed it gave -32603 "magpie isn't running, so Magpie Web
Search can't be reached…". With an extra argument it exited 1 with
"takes no arguments".

Whole GUI suite on WSL magpie-desktop (load 120 to 180), at the
pre-rebase tree 73595f737: 17260 tests, 16684 passed, 574 failed. The
base, origin/main da0005df8, ran on the same machine: 516 failed, and
324 top-level tests were red. Each of the 161 files with a red was then
run alone on mote at head:
- At head, 118 of them pass alone. They aren't caused by this change.
- 43 fail alone at head, and every one of those also fails alone at
  base. Two pass at base once: login-import is flaky at both (#1307),
  and usage-curve-zoom-back went red once of two at base and passed 2 of
  2 at head.
  view-open-wheel was red 1 of 2 at both, filed as #4723.
- segs-press-redraw ("searchAllRow option 1") fails the same way at
  base, filed as #4566. gui-ja's {agent} string is #4580, and
  usage-ledger is #4078.
- Reds with no issue are now filed one per test: #4680 to #4728.
  Already filed: #4638 claude-mode, #4650 routing-request-model, #4176
  skeleton-bird and #1937 name-suffix-no-names.
Not tried: web_search with a real search API key (mote has none). An
agent in WSL using it directly. A run on the Windows box.
2026-11-01 12:38:01 +08:00
yetone 9162277b91 routing: Until used up stays on the next account once the first is used up (dzxx0496)
dzxx0496 on Discord: with free accounts one after another, the first used
up, requests went to the second; when the first renewed they went back to
it ("如果第一个恢复了,它又优先用第一个了"). No routing did what they asked:
In order and Smart both put the first back first.

A new routing, Until used up (drain, 用完再换): requests stay on one seat
until its quota is used up, then go on to the next in the list and stay
there. A seat counts as used up when its known allowance is at 100% or
it was refused for quota or credit (failQuota / failCredit, routes.Drained
called where the rest is recorded, so a failover inside one request moves
the pool too). A rate limit or other failure only passes it over while
it rests, as In order does. Each pool (a provider, a group/<id>) keeps its
own place; routes.Forget clears it.

Offered wherever a routing is picked: the provider editor, a group's row
menu and editor (app menu, no native select), the TUI, `magpie group set
<id> routing=drain` and a provider's routing=drain. Nothing defaults to
it, so no saved setting changes. SpentShareOf is 100 for it, as for In
order. Words in en, zh, zh-TW, ja and de (i18n.js and the routing
plugin's own), docs/subsystems and the site's start page (en, zh, ja).

Tests:
- internal/routes/drain_test.go: stays on the next when the first renews,
  through a rate limit, all used up, a seat gone, per pool, Forget,
  Drained after a renewal.
- internal/gateway/drain_test.go: a real request path with a fake upstream;
  k1 refused for quota, k2 takes over, k1 renews: drain stays on k2,
  In order goes back to k1. Red without the Drained hook (request 3 went
  to k1). A rate limit comes back to k1; drain is saved on a provider and
  a group.
- routing-drain.test.cjs: the Routing page's why and mode line in 5
  languages, 1100px and 420px, Chromium and WebKit; red on the old assets
  (20 of 20).
- routing-group-strategy, routing-save, builtins: the menu has 11 routings.

Run on mote (macOS) at origin/main 699ddf152 with this commit and its
two neighbours (nb5p chip, dzxx0496 renewal, dzxx0496 Until used up).
Pushed on b2145eac1, whose five commits since change app.css and app.js
only for a key row's chips; at the pushed tree gofmt, the gui, routes
and gateway vets (Linux nogui, Windows), TestCoreScriptBudget (core
1,532,891), the Drain Go tests and 11 GUI files (gateway-model-chip-
height, routing-drain, routing-renews-stay, routing-behind-why,
routing-group-strategy, routing-save, builtins, i18n-keys, gui-de,
gui-zh-tw, key-row-chips-fit) were run again: 190 of 190 ok.
- gofmt -l clean; GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./... and go vet ok.
- go test internal/routes, internal/gateway, internal/provider,
  internal/cli, internal/tui, plugins/rotation: ok; internal/gui's
  TestCoreScriptBudget ok (core 1,532,816 of 1,533,105).
- GUI: routing-*, builtins, gateway-model*, model-chip*, i18n-keys,
  gui-* and codex-credits-last in both engines: 2211 tests, 68 red,
  none new: model-chip-steady 20 (#4388), gui-ja's {agent} string
  (#4580), and 11 routing-* files under load (#4585, #3789, #3799).
  The same 11 files run alone at cdfdb62c6 were 32 of 116 red, and 26
  with the stack, the same tests but rule-remove, whose red languages
  vary run to run (9 cases, then 5). model-chip-steady was 20 of 20 red
  at cdfdb62c6 alone.
Earlier, at f811bf291 with the stack: go test -timeout 45m ./... had 82
packages ok, internal/gui red only on
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
TestMainWindowCorners/macOS_26_SDK (#3949). The whole GUI suite had 301
of 16930 red in 52 files. Those 52 files rerun had 272 red with the
stack and 276 at f811bf291 alone, the same tests.
2026-11-01 09:53:50 +08:00
yetone 5a56bc7d73 gateway: a CI job trades its OIDC token for a short-lived key (#4531)
xazaj on X asked for GitHub OIDC: a GitHub Actions job should get a
gateway key without a long-lived magpie key in the repository's secrets.

A rule (magpie gateway-key oidc add --key <id> --repo owner/name
[--ref …] [--environment …] [--claim k=v] [--ttl 1h] [--issuer URL]
[--audience a]; oidc list, oidc remove) names an issuer (GitHub Actions'
by default, any https issuer), an audience (magpie-<rule id> by default,
so a token asked for one rule opens no other, and the workflow needn't
know the gateway's address), claims (exact or path.Match globs) and the
gateway key the keys are issued under, which must be let issue. A GitHub
rule names the repository or its owner with no wildcard, or every
repository on GitHub could get in. No rule, no exchange.

POST /v1/magpie/keys/oidc with Authorization: Bearer <token> and an
optional {"ttl","models"} verifies the token (RS256 only, keys from the
issuer's discovery document's https jwks_uri, exp required, nbf/iat with
a minute's leeway, the rule's aud and claims, a jti traded once) and
issues a key through access.IssueKey under the rule's key, named
repo@ref (run N), living no longer than the rule. Everything issued keys
guarantee holds: bounded by the issuer's models and accounts, its spend
counted against the issuer, stopped when the issuer is turned off.

- A token is judged only against rules naming its iss, so it can't make
  magpie fetch from a URL of its choosing.
- Keys are cached an hour per issuer, read by one request at a time with
  no lock held across the fetch, asked again for an unknown kid at most
  every 10s, and kept while the issuer is down; with none ever read,
  nothing is let in.
- The route is lanGuard's one exemption from remoteKeyed (that exact
  path, POST, no gateway key): only while shared, past the allow list,
  and a refused token counts against tooManyAuthFails (429 past the
  burst). A read-only key is refused it.

The issue's open questions, decided: rules are generic from the start
(the GitHub repository rule applies to GitHub's issuer); rules are CLI
and file only for now (oidc-rules.json), no GUI.

Docs: docs/subsystems/gateway-routing.md (Trading an OIDC token for a
key, routes table) and site/public/docs remote in en, zh and ja, with
the workflow snippet.

Tests: TestOIDCTokenTradedForKey (no rule, a traded key that works on
chat with its TTL capped and its name, a model past the issuer, another
branch, no token, 51 bad tokens -> 429, issuer turned off, a token on a
model route, loopback, not shared -> 403); TestMatchEachCheck (14 bad
tokens, list aud, replay, the refusal naming the claims);
TestKeysCachedAndKept (8 concurrent tokens one fetch, rotation, a made-up
kid inside and past the gap, the issuer down 2h later, an unnamed issuer
never fetched); TestUnreadKeysLetNothingIn; TestAddRefuses;
TestGatewayKeyOIDCCLI; TestReadOnlyKeyEveryRoute with the new route.
A JWKS from an httptest TLS server, never the network.

Broken by hand, each red then restored: the signature check, the claims
match, the jti check, the exp check, the refetch gap, the GitHub scope
rule, the lanGuard exemption, the throttle and the TTL cap.

Run at this head (rebased on 6a7a690be), on mote: go test ./internal/oidc/...
./internal/cli (whole packages) and go test -run 'OIDC|ReadOnlyKeyEveryRoute|
KeysEndpoint|IssuedKey|AuthThrottle|Route' ./internal/gateway: ok; gofmt -l
clean. At the 13aa33eac base: go vet (darwin, GOOS=linux -tags nogui,
GOOS=windows): ok; node --test site/*.test.mjs: 63 pass.
Full suite (-tags nogui -timeout 45m ./...) on the Linux box at the
13aa33eac base, still running when this was pushed (mote had two other
sessions' suites at load 291); so far every package ok except
internal/agent's TestInstalledVersion, TestGrokInstalled,
TestCopilotFolderFromAnIDEPluginIsNotTheCLI and TestOmpDetectedWithPiDir,
the WSL box's fake-binary reds filed as #4033 and #3548. The rest of the
run goes on #4531.

Not tried: a real GitHub Actions run against a shared magpie; a
connection open when an exchanged key expires.
2026-11-01 05:39:02 +08:00
yetone 0e90572274 browser: Magpie Browser, agents use the user's own browser and its sign-ins
The owner asked for a browser-use MCP of magpie's own, so an agent's
browser keeps working when Claude Code switches accounts, and asked that
it act in the browser the user uses every day: a fresh Playwright
profile is signed in to nothing.

Magpie Browser is an MV3 extension (internal/browserext, ID
dmlhojidlfnkgamkekjhacgkpanbkeko, pinned by its key) that the user loads
once in Chrome, Edge, Arc, Brave or another Chromium browser. It holds a
WebSocket to the gateway's /v1/magpie/browser/extension and carries out
each tool call with chrome.debugger (the DevTools protocol) in the user's
own tabs. The socket is taken only from this computer, with a loopback
Host (no DNS rebinding) and the extension's own Origin; a page or another
extension that connected in its place would be handed every call.

Agents reach it at /mcp/magpie/browser (Streamable HTTP) or through
`magpie mcp browser` (stdio), and the Library's MCP market lists it as
Magpie Browser, opt-in. Like the image server it is magpie's own, but it
is never served to another computer, shared and with a key or not, and
never to a web page, since it acts as the user wherever they are signed
in. 17 tools: navigate (url, back, forward, reload), snapshot (an
accessibility tree with refs, interactive-only on ask), click, type,
press, select, hover, drag, upload, scroll, wait (text, gone, seconds),
dialog, evaluate, text, screenshot (page, full page, element; JPEG or
PNG), console and tabs (list, new, select, close). Each agent session
goes on in its own tab; a link that opens a tab is followed, and a
dialog a click opens is said in the reply.

The Library's sheet for it has Set up the extension…, which writes the
extension to ~/.config/magpie/browser-extension pointed at this gateway
and shows the folder, the three steps to load it, and whether the
browser is connected, polled while the sheet is open.

Run:
- TestBrowserToolsInARealBrowser: the extension magpie writes, loaded in
  a real Chrome for Testing 141 (Playwright's chromium-1234, headless=new)
  with --load-extension, connects, and all 17 tools act in a real tab of
  a fixture site. Green on mote (macOS 27), on xiaomi-gpu (Windows 11,
  win-run) and in magpie-desktop (Ubuntu 24.04, wsl-run). Under a test
  HOME Chrome needs --use-mock-keychain / --password-store=basic, or the
  extension's storage waits on a keychain and it never connects.
- go test ./internal/gateway -run 'Browser|ReadOnly|Image', ./internal/
  browserext, ./internal/browsermcp, ./internal/library, ./internal/gui
  -run 'Library|Browser', ./internal/cli on mote.
- GUI: library-browser-setup.test.cjs (new) in Chromium and WebKit, en,
  zh, zh-TW, ja, de, at 1100 and 420 wide: 22/22. With i18n-keys and
  every library*.test.cjs: 915 pass, 1 fail, i18n-keys' "Unmarked",
  red on main since 5787d758a (#4524, fixed in the next commit).
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
  go vet ./... on mote.
- Again at this commit, rebased on 2e9df9b1b: gofmt -l, the vet trio,
  ./internal/gui -run 'Budget|Size', ./internal/proc (exec guard),
  ./internal/usage, ./internal/browserext, ./internal/browsermcp, and
  i18n-keys (0 fail with the next commit). The full go test ./... runs
  in magpie-desktop (Linux) as this is pushed; mote had another
  session's suite running.

Broken by hand, each red, then restored:
- browser_click's dispatch in background.js turned into a no-op: the
  E2E test is red at "clicked Ada".
- the extension socket's Origin check, its loopback-Host check and
  local(): TestBrowserExtensionOnlyFromItsOrigin red for each.
- browserMCP's local()/fromBrowser() guard: TestBrowserMCPGuarded red.
- a tool dropped from background.js: TestBrowserToolsAreTheExtensions red.
- the sheet's steps left shown once connected: the GUI test is red.

Not tried: loading it by hand (Load unpacked) in the owner's own daily
Chrome or Edge and driving a site they are signed in to; Arc, Brave and
Edge themselves (only Chrome for Testing); Firefox and Safari, which
have no chrome.debugger and are not supported. Chrome shows its "is
debugging this browser" bar while a tab is being driven; that is
Chrome's and cannot be hidden.
2026-11-01 02:29:55 +08:00
yetone 64cdb68035 accounts: import claude reads claude-swap's export (#4532)
StringKe (#4532) is moving from claude-swap (cswap 0.29.0) to magpie,
and `magpie accounts import claude` didn't read cswap's export. It does
now: parseLoginImport takes cswap's format-1 envelope ({version: 1,
swapVersion, encrypted, accounts: [...]}, read from cswap 0.29.0's
transfer.py) and cswapEntry reads each account's
credentials.claudeAiOauth and config.oauthAccount: email, account and
organization uuid, and the organization's name. The tokens are kept as
the file has them; magpie asks Anthropic nothing.

Refused, each with what to do: an encrypted export (decrypt with gpg -d
first), another format version, a Codex entry, and an API-key entry
(added as a key instead). An entry with no refresh token is accessOnly,
as for every other file. cswap's alias becomes the account's name in
magpie (importNames) when the account was added or updated, has no name
yet, and no other account is called that or signed in as it, so the
name stays a selector for one account (the previous commit's rule).

testdata/cswap_0.29.0_export.json is claude-swap 0.29.0's own `cswap
export` output, made from its source in a sandbox HOME in WSL with two
accounts and fake tokens (cswap's add step asked Anthropic once with
the fake refresh token, which it called dead; no real account was
involved).

Run (mote unless said):
- At this commit's tree (on origin/main 47173f593):
  gofmt -l clean; GOOS=linux go vet -tags nogui ./... and GOOS=windows
  go vet ./... ok; go test -timeout 45m ./internal/provider (ok 100.7s),
  ./internal/cli (ok 31.8s), ./internal/gui: red on 11 real-window
  AppKit tests killed at their deadline on mote over ssh (#4125, #2645)
  and TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main
  (#4514); none touches accounts.
- Rebased on origin/main 7aa67e9e5 (4 commits, none in accounts), then
  at the pushed tree: go test ./internal/provider (ok 163.5s),
  ./internal/cli (ok 55.8s), ./internal/gui -run 'Budget|I18n|Key'
  (ok), gofmt -l clean.
- TestImportCswapExport, TestImportCswapRefusals. Broken by hand, each
  red: no cswapEntry, no importNames, the taken-name check off (red on
  "the team seat took pro's name"), the encrypted check off, no
  organization name.
- CLI in a sandbox HOME in WSL: import of the fixture adds max@x.com and
  team@x.com, a second import says both are in magpie already, the alias
  "work" is team's name, `accounts forget claude work` picks it;
  `accounts import --help`, a missing file and an unknown agent each say
  what's wrong.
- On mote over ssh the same import added one account and failed the
  other on the Keychain ("Unable to obtain authorization", no GUI
  session there), and the failed one was still saved, so the second
  import called it "in magpie already". That's addLogin writing
  logins.json before signing Claude Code in, the same for every import
  and sign-in, not this change; not changed here.
- GUI: login-import in Chromium and WebKit on Linux (WSL), green.

Not tried: an export from a real cswap install with real accounts,
Claude Code running on an imported account, or cswap's encrypted export
decrypted and imported. A cswap account's plan (subscriptionType) isn't
carried: magpie reads it on the first usage read, as for CLIProxyAPI.
2026-10-31 18:22:02 +08:00
yetone 149e763e9e accounts: a name you gave an account picks it wherever an email does (#4532)
StringKe (#4532): `magpie accounts switch claude work` failed when "work"
was the alias; accountNamed matched the email only.

provider.AccountByName resolves a name (magpie accounts alias) among an
agent's accounts. It refuses a name two accounts share, and a name that
is another account's email or email part, so a name never picks the wrong
account. It is used by:
- accountNamed: accounts switch/on/off/remove/alias/cap and the rest
  that take <email>;
- provider pool --accounts;
- accountRef (GUI and account-cap): the exact email first, then a name,
  so another account's alias never shadows an email;
- account-cap's display, through AccountRefOf (it filtered by email).

Run (mote, at this commit):
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok
  (104.9s, 33.2s).
- TestAccountsAliasPicksTheAccount, new: switch, alias, pool --accounts
  and account-cap by name; a shared name and another account's email
  refused. Red with each part removed by hand: the accountNamed call,
  pool's resolution, the clash check, the shared-name check, accountRef's
  name step.

Not run: the GUI suite (no GUI file changed); real accounts.
2026-10-31 18:18:37 +08:00
yetone 15b83901ac accounts: switch to the next account with room, or the one with the most left (#4532)
StringKe (#4532), comparing magpie with cswap 0.29.0: there was no "switch
to the next account", and when every account was past its line the
automatic switch stayed on the spent one, where cswap moves to the account
with the most room left.

- `magpie accounts switch <claude|codex> next` (provider.NextInOrder) takes
  the other accounts that are on in magpie, from the one after the account
  the agent is on, wrapping round: the first whose allowance is known and
  has room, else the one with the most room left, and says it is past its
  line. A saved Claude account not read yet is read first (readSpare), as
  the automatic switch's spares are. With no reading of any it refuses
  rather than guess; for any other agent it asks for the account by name.
- NextLogin (shared by Codex and Claude Code): when the account the agent
  is on is spent and every spare is past its line too, it moves to the
  spare with the most room left (roomLeft: the fullest stopping window's
  distance below the switch share, or the account's own cap when lower),
  when that has at least roomMargin (1 point) more than the one it is on,
  so two all but even accounts don't trade the agent each look. A held,
  failed or unknown reading is never moved to. One model's own window
  still counts for nothing, as before.
- docs: reference.md (the automatic switch and `next`; its "a Claude
  account magpie knows nothing of is not moved to" was stale since
  readSpare), providers-accounts.md's Used-up switch row, the en/zh/ja
  start pages' command table, `magpie help`.

Run (on mote, sandbox HOME through the packages' TestMain):
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok
  (144s, 44s), at this change's tree before the next commit's edits.
- TestNextLoginTakesTheMostRoomWhenAllArePast and TestNextInOrder, each
  over codex and claude with three accounts: green; red with the fallback
  taken out of NextLogin (the two "most room" cases, both agents) and with
  NextInOrder not starting after the signed-in account ("the one after
  it", both agents). The "none has more by the margin" case fails without
  roomMargin.
- Built the nogui binary and ran in a fresh sandbox HOME on mote:
  `accounts switch claude next --help` (prints the accounts help),
  `switch claude next` and `switch codex next` with no accounts ("has no
  other account that is on"), `switch gemini next` (asks for a name),
  `switch claude nxt` (no such account), `switch claude` (usage).
- gofmt -l clean. Cross-OS vet: run at the head of this stack.

Not tried: a real switch between real Claude or Codex accounts; the CLI
`next` with real saved accounts (the provider tests cover the choice).
2026-10-31 18:18:37 +08:00
yetone ceeb73a0f1 app: the desktop app writes its log to app.log; magpie log and Settings › About › Log find it
rayem1w on X (0.1.2330, macOS) was asked for ~/Library/Logs/magpie/serve.log
while chasing a Codex "hit a snag" through the gateway, and had no such
folder. Only the launch agent (magpie daemon install, written by launchd)
and a gateway magpie tui left running wrote a log; the app opened from the
Finder, the Dock or the Start menu logged to a stderr nobody reads, on
every system.

Now runGUI and runPanel (magpie, app, tray, panel, a window view, a
magpie: link) call applog.Start before gui.Run. It sends the standard
logger (the gateway, the plugin host, providers and Wails' error handler
all log through it) to app.log as well as stderr, and points
debug.SetCrashOutput at it so a panic's trace is there too:

  macOS    ~/Library/Logs/magpie/app.log
  Windows  %LOCALAPPDATA%\magpie\logs\app.log
  Linux    $XDG_STATE_HOME/magpie/app.log, else ~/.local/state/magpie/app.log
  portable data/logs/app.log

app.log, not serve.log: on a Mac launchd writes serve.log for the service,
another process. The file is 0600. At 5 MiB it becomes app.old.log (two
files at most); when another magpie (an update's new process) rotated it
already, it is only opened again; when it can't be moved it is emptied.
stderr goes first, through a writer that never fails, since io.MultiWriter
stops at a failed writer and an app opened from Explorer has no stderr.

Secrets: the log calls name header names and paths without queries; no
key or token was found logged (grep of log.Print* in gateway, provider,
plugin, gui, agent). scrub masks bearer/basic credentials, key/token query
parameters and sk-, AIza, gh?_ and JWT shapes anyway.

How a user finds it: Settings › About › Log, with the path, Copy and an
Open that shows its folder (POST /api/settings/log/reveal; the row is
hidden in magpie web, which writes no file). magpie log prints where every
log is (the app's, app.old.log, the service's, the tui's background
serve.log); --path the app's alone, -n N its last lines, -f follows it
across a rotation. Docs: reference.md, gui-shell.md, site start (FAQ "Where
is magpie's log?" and the CLI table) and privacy (files on your computer),
en/zh/ja.

Run:
At 227ce6074 on origin/main fbb1b36d1:
- mote: go test ./internal/applog ./internal/appdir ./internal/cli ok;
  -run TestCoreScriptBudget ./internal/gui ok; GOOS=windows go vet
  ./internal/... and GOOS=linux go vet -tags nogui ./internal/... ok;
  gofmt -l clean. GUI, chromium: about-log (5 languages x 1100/420, and
  no row without a log), about-website, i18n-keys: 24 of 25, the one red
  "a plugin's words are its own" ("Unmarked") is the same at origin/main
  fbb1b36d1 (#4524).
- WSL (magpie-desktop), webkit: about-log and about-website 21 of 21.
- Windows (win-run): applog, appdir, tui ok; cli ok but
  TestLibraryMCPHub's TempDir cleanup (#4140, mcp-npm, not this change).
- WSL full go test -tags nogui -timeout 45m ./... at the previous base
  03f609e3f: every package ok but reds that fail the same at origin/main
  03f609e3f alone: TestSettingsSaveKeepsWhatItDoesNotSend (#4514),
  TestNoCommandBypassesProc (#4491), internal/agent's install-detection
  tests (#4033, #3548), and TestCoreScriptBudget, which was this change
  (app.js 321 over): its comment is cut to one line and both budgets
  are raised by the remaining 124 bytes, with no room added.
- Broken by hand: with startLog left out of runGUI, TestTheAppWritesItsLog
  is red ("app wrote no log: open .../Library/Logs/magpie/app.log: no such
  file or directory"); with proc.UserPath taken out of openApp,
  TestGatewayStartsGetUserPath is red ("runGUI doesn't call
  proc.UserPath"). The guard now follows a start into a function or func
  var of this package, since the Wails start sits behind openApp for the
  test.
- Real use on mote: the GUI build, magpie app in a sandbox HOME, wrote
  ~/Library/Logs/magpie/app.log (0600) with its "started" line; magpie
  log and magpie log -n 3 printed it.
Not tried: the app opened from Windows Explorer or a Linux desktop
launcher for real (the paths are unit-tested per OS, the writer on
Windows and Linux); the full GUI suite (running on WSL after the push,
reds filed if they fail at origin/main too).
2026-10-31 14:45:22 +08:00
yetone fbb1b36d1f provider: the Claude keep-alive keeps off accounts, its reading, and its turn (#4532)
stringke read b48881f50 and 42c49e74d and left three notes on #4532
(issuecomment-6540015427). All three hold against the code:

1. Only accounts that were on were kept alive (claudeKeptAlive needed
   l.On). An account switched off as a reserve is still a sign-in the
   user kept for later, and Codex's keep-alive already renews saved
   ChatGPT sign-ins on or off. A run of Claude Code's /usage every eight
   days costs one local run and asks Anthropic nothing magpie doesn't
   already ask, so off accounts are kept too. Setup-token and signed-out
   accounts still aren't. The keep-alive never switches an account on.

2. The run's /usage reading was dropped (`_, err :=
   readSavedClaudeUsage`). The run now goes through the account's
   reading, the way a card's refresh reads a saved account:
   renewClaude forgets the account's minute-cached reading and calls
   loginReading with a keepingAlive ctx (asked, so nothing is held).
   claudeWindows runs Claude Code for it as for savedRefresh, past the
   30-second floor (the keep-alive is an hour apart at most), and keeps
   it in claudeUsage. loginReading keeps it beside the account and on
   disk (keepReading), and the new keepCardRead puts it on the account's
   card in the Usage cache with its history and the menu bar told, the
   way refreshCards does. A card the Usage page doesn't have isn't added.
   The run's own error comes back through the ctx, not the kept reading,
   so a failure is still told apart from a reading kept from before. This
   path doesn't bump the global ask generation, so Claude Code's own
   account isn't read again because of it.

3. A failed run held the hourly slot: still due, and with one renewal a
   look, the accounts after it never had theirs. A renewal that fails, for
   Claude and for Codex (the same loop had the same gap), now waits
   keepAliveRetry (6 hours, in memory) before the hourly look tries it
   again, and doesn't take the look's turn meanwhile. `magpie accounts
   refresh` (every 0) still tries it at once. A success clears it.

The help text, refreshAccounts' comment and providers-accounts.md say so.

Run on mote at 82b45888a plus this change: go test -timeout 45m
-count=1 ./internal/provider/... ./internal/cli/... ok; go test -race
-count=10 -run 'TestRenewLogins|WeeklyOnly|TestClaudeUsage'
./internal/provider ok; gofmt -l clean; GOOS=linux go vet -tags nogui,
GOOS=windows go vet and go vet of ./internal/provider/...
./internal/cli/... clean.

Broken by hand, each on mote:
- l.On put back in claudeKeptAlive: TestRenewLoginsKeepsSavedClaudeSignedIn
  ("renewed what wasn't due" with team@ missing), TestRenewLoginsKeepsClaudeReading,
  TestRenewLoginsFailedWaitsItsTurn and TestRenewLoginsLeavesClaudeSetupToken
  fail.
- renewClaude back to `_, err := readSavedClaudeUsage(...)`:
  TestRenewLoginsKeepsClaudeReading fails ("the account's reading: false").
- renewWaiting taken out of the loop: TestRenewLoginsFailedWaitsItsTurn
  fails at look 2 (the failed account took the turn again).

Not tried: real accounts and real Claude Code (fake runner, sandbox
HOME). The back-off is in memory, so a restarted magpie tries a failed
account on its first look. Codex's back-off is covered only through the
shared loop; there's no Codex-specific test for it.
2026-10-31 14:40:03 +08:00
yetone b48881f507 provider: keep idle saved Claude accounts signed in, by Claude Code itself (#4532)
#4532: a saved Claude account switched on but not needed for weeks
(switch-only) had nothing run on it, its refresh token sat idle, and it
was found signed out when the switch wanted it. Codex's saved sign-ins
already had a keep-alive (RenewLogins, every 8 days, one account an
hourly look).

The same loop now takes saved Claude accounts that are on, not Claude
Code's own, not added by setup-token and not already signed out
(claudeKeptAlive). For one that is due it has real Claude Code run
/usage in the account's own CLAUDE_CONFIG_DIR, the path a card's
refresh takes (readSavedClaudeUsage, inSavedClaudeDir), and
syncSavedClaude keeps whatever sign-in Claude Code refreshed. magpie
asks Anthropic nothing itself: no OAuth or usage endpoint, as removed in
9bf6d43527. A run that went through marks Renewed, so the account is not
run again for 8 days whether or not Claude Code rotated the token. A
refusal goes through NoteClaudeSignInFailure (and syncClaudeDir for an
emptied sign-in), so the row says to sign in again the way a request's
refusal does, and the keep-alive runs nothing more on it. A network
failure marks nothing. Anthropic's refresh-token idle lifetime is not
known, so the interval is Codex's conservative 8 days. The reading
itself is not kept as the card's cache.

`magpie accounts refresh` and its help say the Claude ones are renewed
too; providers-accounts.md describes it.

Run on mote at 93b31f5b7 (this tree): go test -timeout 45m -count=1
./internal/provider/... ./internal/cli/... ok; go test -race -count=10
-run 'TestRenewLogins|WeeklyOnly' ./internal/provider ok; gofmt -l
clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet of
./internal/provider/... ./internal/cli/... clean. The new tests also
passed with TZ=UTC and TZ=Pacific/Kiritimati.
Rebased onto origin/main 847f0c470 (a GUI-only change) and run again
at that tree on mote: provider and cli tests, gofmt, Linux and Windows
vet, all ok.

Broken by hand: with the Claude branch taken out of the loop's filter,
TestRenewLoginsKeepsSavedClaudeSignedIn and
TestRenewLoginsClaudeEmptiedSignIn fail ("renewed what wasn't due: []",
"emptied: []"); with the NoteClaudeSignInFailure call removed, the
refused case fails (Lapsed false).

Not tried: real accounts and real Claude Code; the tests use the
fake Claude Code runner and a sandbox HOME. Whether a /usage run makes
Claude Code refresh a token that is not near expiry is not known; the
run counts as the renewal either way. Left out (per #4532's scope):
per-model windows in the switch and caps, CLI commands, reset cards.
2026-10-31 14:15:52 +08:00
yetone 2eac916170 gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.

A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.

- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
  cost, readOnly} answers 201 with the secret once, no-store. GET lists
  the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
  [--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
  alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
  until/expired/issued by.

Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
  so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
  forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
  Such a request can already use every model with no key and run the CLI,
  so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).

An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.

An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.

Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.

Run at base 07a3312c5 (origin/main, fetched just before):
- mote: go test -count=1 -timeout 45m on access, budget, gwbudget,
  usage, cli, gateway, davsync, agent: ok.
- mote: internal/gui fails TestCoreScriptBudget (#4526),
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and ten AppKit window
  tests killed at their deadline (#4125, #2645). The first three fail the
  same at origin/main 07a3312c5 on mote. This change touches no GUI file.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; node --test site/*.test.mjs (49
  pass).
- win-run: access and budget ok. usage fails TestDesktopSessionAccountMetadata
  the same at origin/main (#1356). cli's TestLibraryMCPHub failed once on
  TempDir cleanup (#4140) and passed alone.
- Real binary on mote, sandbox HOME, port 47811: issued a 1m key with
  curl, read its limit, listed it, saw `gateway-key list` show "until",
  had a page's Origin refused 403, and after 62s /v1/models answered 401
  "the gateway key "sandbox-1" expired at …".

Broken by hand, each restored:
- no expiry check in Check: TestIssuedKeyExpires and
  TestIssuedKeyExpiresOnEveryRoute go red.
- no 401 for a refused key on loopback: TestIssuedKeyExpiresOnEveryRoute
  goes red (the expired key let in as no key).
- budget not counting CallerIssuerID: TestIssuedKeysSpendTheirIssuersLimit
  goes red (5 calls reached the upstream).

Not tried: a Responses WebSocket open across the expiry. The GUI shows
no expiry or issuer yet (issued keys look like plain keys until pruned).
A held issuer's /v1/magpie/usage shows its own rows, not its keys'. The
refused-key 401 doesn't count toward tooManyAuthFails. Issued keys sync
through davsync like other keys, with their expiry.
2026-10-31 13:44:29 +08:00
yetone fdf5e2c65f cli: claude-tui-helper ends on a signal its own way, not of magpie's handler
magpie's process-wide handler (endProbesOnSignal) re-raises SIGTERM. In
claude-tui-helper it killed the helper (exit -15) before the shim's own
handler could stop its Claude Code and remove what it wrote, so a run the
gateway aborted left them behind. The helper's command now lets go of
those signals (leaveSignals) before claudetui.Run.

Run: go test ./internal/claudetui ./internal/cli on mote (macOS) and in
WSL magpie-desktop (-tags nogui), ok; go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./..., go build on mote, ok.
Broken by hand: without leaveSignals, SIGTERM to a real helper in the
sandbox gateway exited -15 and left its temp folder; with it, exit 1 and
the folder removed (termimg.py).
Not tried: SIGHUP from a closed terminal.
2026-10-31 05:00:39 +08:00
yetone 333e7f573b gateway: gateway keys are dragged into the order you want, kept with the keys (alextjy on Discord)
alextjy asked on Discord whether gateway keys can be reordered. They
could not: the Gateway page listed them in the order caller-keys.json
held them, and nothing changed that order.

- access: a "move-key" action puts one key at a place in the list,
  under the same file lock as every other key change. Nothing else
  about the key changes, and the sharing key's mirror in settings is
  left alone (its pointer would otherwise land on another key).
- GUI: the Gateway page's key rows are dragged the way search APIs'
  rows are (shared dragRows, a grip shown on hover only, Alt+Up/Down,
  the existing "Drag to reorder" title). A refused move puts the list
  back from the server. New strings in zh, zh-TW, ja and de.
- CLI: `magpie gateway-key move <id> <place>` (from 1); list already
  prints the stored order.
- Usage > Requests: the key filter lists keys in the user's order,
  removed keys after. The Overview stays a ranking by use.

Run (worktree at 14b451c11, then rebased on origin/main):
- gofmt -l clean; go vet (darwin) on access, cli, usageapi, gui;
  GOOS=linux -tags nogui and GOOS=windows go vet on access, cli,
  usageapi (mote).
- go test access, cli, usageapi: ok (mote). internal/gui: every test
  ok except the real-window AppKit tests #4125 lists
  (TestCoveredWindowStaysUp, TestPanelCloseHidesIt and 7 more), killed
  at their deadlines with pboard not running on mote.
- Broken by hand: with move-key removed, TestMoveKeyKeepsOrder,
  TestGatewayKeyCLIMove and TestLedgerKeyFilterInKeyOrder go red; with
  the mirror exclusion removed and the filter left unsorted,
  TestMoveKeyKeepsOrder ("the sharing key's mirror moved") and
  TestLedgerKeyFilterInKeyOrder go red.
- GUI (WSL): gateway-key-arrange 20/20 (chromium and webkit; en, zh,
  zh-TW, ja, de; 1100 and 420px). Red by hand: no arrange (20 red),
  grip always shown (chromium 10/10 red), drop commits nothing (webkit
  10/10 red).
- GUI (WSL), the 68 files the change can reach (every caller-keys
  fixture user, gateway-*, search-*, usage-ledger*, i18n-keys, gui-ja,
  gui-de, gui-zh-tw, key-page, phone-rows, api-key-*): 900/923. The
  reds were run again at origin/main 43966a53f and fail the same there
  (api-key-theme webkit, gateway-key-limit webkit, gateway-key-models
  webkit, search-first, usage-ledger-open-settled, usage-ledger-ttft,
  usage-ledger), each filed: #3307, #3523, #4081, #3795, #4262,
  #3104/#1876, and #4489 (usage-ledger-ttft, new). phone-rows,
  search-keys and connect-snippet-shell reds of the first run passed
  when run again at the head. usage-ledger's "zh: request routing
  links" went red once at the head (Usage view position on return) and
  passed in the first run.

At the rebased head (on 2ac423f4f): TestCoreScriptBudget and the
other Budget/I18n/Asset tests in internal/gui ok (mote);
gateway-key-arrange, i18n-keys and gateway-caller-keys 27/28 in WSL.
The red is gateway-caller-keys webkit en "wider than 560 right after
the resize" (#3797, red alone on main). A probe of that file, printing
the page width and any element past it, read 560/560 with nothing
wider in both engines, in two runs beside the arrange file.

Not tried: dragging in the real app (WebKitGTK, WKWebView, WebView2),
the full Go suite (started after the push).
2026-10-31 03:48:27 +08:00
yetone 43966a53fb claude: a subscription's run is Claude Code's interactive mode, -p only as the fallback
The owner (10-31): a Claude subscription ran `claude -p`, whose
requests Anthropic labels sdk-cli and counts at about twice the
interactive mode's cli (anthropics/claude-code#97074). Running the real
interactive Claude Code is what its terms describe and uses the plan as
a person does. Wanted inside magpie, on by default, with a way off.

`magpie claude-tui-helper <claude> <-p args>` (internal/claudetui)
stands where `claude -p` stood and speaks the same stream-json. It
turns the -p arguments into the interactive mode's (no -p, no
--dangerously-skip-permissions: --permission-mode default with only
mcp__magpie, and the WebSearch -p was given, allowed; --no-chrome;
--session-id or the --resume given), starts Claude Code in a
pseudo-terminal of its own (no tmux), pastes each message into its
prompt and presses Enter, and tells the session's transcript back as
-p's lines: whole assistant messages, an API error as the turn's error
result with its rate_limit_info, turn_duration as the result. Nothing
sets CLAUDE_CODE_ENTRYPOINT, and the user's ~/.claude and
~/.claude.json are never written. The folder-trust question is
answered only for magpie's own folder or a saved account's config
directory (MAGPIE_CLAUDE_TUI_TRUST).

A Claude Code that doesn't start or show its prompt in 45s becomes
`claude -p` on the same pid, its input still unread, so the turn is
answered all the same; that is remembered for 30 minutes
(<cache>/magpie/claude-tui-broken). An untrusted folder goes to -p
without the mark.

claudeTUI keeps -p for Windows and WSL, Settings › Models › Replies ›
Claude Code's interactive mode Off (claudePrintMode), safeguards,
client cache marks, a JSON schema, images and a first message over
400KB. A TUI run ends instead of taking an image turn, a rewind or an
effort change, and letGo doesn't take one back. The gateway's tests
run with claudeTUIRuns off: their binary has no claude-tui-helper.
docs/subsystems/claude-subscription-bridge.md has the section.

The core's scripts grow 725 bytes with the setting's row;
coreScriptBudget is raised to the exact size, 1,537,356, with no room
added.

Run (rebased on f2eb56c6b and its budget fix):
- mote: go vet of claudetui, gateway, cli, settings on darwin;
  GOOS=windows of claudetui, gateway, cli; GOOS=linux of claudetui,
  gateway; gofmt -l clean.
- mote: go test ./internal/claudetui: TestShimTurnsInteractive (a fake
  interactive Claude Code in the PTY: two turns, a /help pasted as
  words, the arguments it was given), TestShimFallsBackToPrint (failed
  start marks broken; untrusted folder doesn't), TestShimTrustsWhenTold,
  TestPasteable, TestTranslatorAPIError.
- mote: go test ./internal/gateway -run TestClaudeTUIChosen (plain,
  off, WSL, safeguards, cache marks, schema, image, long prompt),
  TestClaudeLean*, TestCleanClaudeEnv.
- mote: go test -timeout 45m ./internal/claudetui ./internal/cli
  ./internal/settings ./internal/gateway: all ok (gateway 524s).
  go test -run Budget ./internal/gui: ok after the raise below.
- Linux (magpie-desktop): go test ./internal/claudetui ok natively,
  the PTY's Linux ioctls among it. GOOS=linux go vet -tags nogui of
  cli, gateway, claudetui, settings ok.
- Linux box, Playwright 1.62, chromium and webkit: claude-tui-setting
  16/16, claude-lean-prompt-setting 16/16, i18n-keys 4/4, mobile-web
  30/30 against 74f1df869's tree. mote's WebKit didn't launch (other
  sessions' GUI suites, running 11-16h, held ~108 WebKit processes),
  so the GUI ran there instead.
- Real Claude Code 2.1.314 on a real Claude account's magpie config dir,
  haiku, through the built helper with the bridge's exact -p arguments
  (an MCP server named magpie with one tool, --tools "",
  --system-prompt-file, --thinking disabled, --effort low,
  --thinking-display): the tool was called without a permission prompt
  and its answer used; the system prompt's end token in every reply;
  a second turn on the same run; a later run with --resume remembered
  the first. All 18 transcript rows say "entrypoint":"cli". Startup to
  init 0.7–1.5s, a haiku turn 1.4–4s. Two messages sent at once are
  one turn, as Claude Code queues them.

Broken by hand:
- each claudeTUI condition taken out in turn (WSL, safeguards, cache
  marks, schema, images, the setting, the 400KB bound): its case red.
  The WSL case first passed with the check gone (its claudeCLI had no
  path); given one, it is red without it.
- the trust check taken out of ready(): TestShimTrustsWhenTold red
  (the run went to -p).

Not tried: a turn through a running gateway into the helper on a real
account (a sandbox HOME would copy the sign-in into a new keychain item
and refresh it apart from the live one); a ~400KB paste; Linux with a
real Claude Code; an API error from the real service (the translator
is tested on its rows). The full go test ./... did not run (mote was held by those suites);
the four packages this touches ran whole.
2026-10-31 03:20:45 +08:00
yetone 4f2d5fc7e0 routing: a group can put its cheapest member first, by each one's price at that hour
liyuanzheng (#general) and lam_em (#feedback) both asked for the same
thing. Off-peak, DeepSeek's own API should come first for deepseek-flash.
At DeepSeek's peak (weekdays 01-04 and 06-10 UTC, billed 2x since
v0.1.2173), another provider should come first, Ollama say. A schedule
editor would make the user copy DeepSeek's hours into magpie. Instead,
a group gets one more routing, "Cheapest first" (`cheap`). Each request
sorts the members by what they cost right then: input + output price per
million, at the peak rate when it is peak hours. A tie goes to the lower
cache-read price. Free models count as 0. A member with no known price
keeps its listed place after the priced ones. Prices come from the same
priceOf the usage ledger bills with, so the user's own ModelPrices,
list prices and maker prices all count, and so does a provider's rate
windows.

- routes: Seat carries Priced/Cost/CacheCost; Strategy.ByPrice; Cheapest
  is a stable sort, so equal prices keep the user's order.
- gateway: weighRouted prices each seat at priceClock() (time.Now; a test
  holds it) through the new provider.PriceAt. The trace's Weighed row
  gets a price (input/output/cacheRead/peak) so Routing can say why.
- It is a group's alone, like Manual. A provider saved with it drops it,
  and `magpie provider set … routing=cheap` refuses it. Groups take it in
  the GUI menu (one more item, no new controls), the TUI and
  `magpie group set <id> routing=cheap` (aliases cheapest, price, cost).
- Routing's mode line says why the first one is first, e.g. "Cheapest
  first: deepseek-v4-flash costs least on ollama-cloud now — $0.150 in,
  $0.600 out a million tokens.", with peak and unpriced variants.
  en/zh/zh-TW/ja/de.
- Docs: gateway-routing, plugin-runtime, reference (it also points at
  Time window and Pause rules for a fixed schedule) and the site's start
  pages (en/zh/ja).

Run, at f7f2d75f2 (this change rebased onto it):
- Red on the old code: TestCheapestFirstGroupFollowsPeakHours (deepseek
  vs ollama with ModelPrices, priceClock held at 14:00 UTC off-peak and
  02:00 UTC peak) and TestCheapestOrdersByPriceNow did not compile
  without Cheapest. TestCheapestFirstIsAGroupsOnly checks that a provider
  drops it and a group keeps it.
- Broken by hand: without `pr = pr.In(at)` the gateway test is red ("at
  DeepSeek's peak ... went to deepseek"). With Cheapest returning the
  order unchanged, both the routes test and the gateway test are red.
  Both were restored.
- Full Go suite on mote (-count=1 -timeout 45m ./..., log kept): every
  package ok except two. internal/provider had
  TestQuotaSpanCarriesEveryWindowField, which is red on origin/main (#4457,
  fixed since in ccbefe2a2). internal/gui had ten AppKit window tests
  killed at their 20-40s deadlines (TestPanelCloseHidesIt,
  TestMainWindowCorners and others). Three of them are red the same way
  on a fresh origin/main f7f2d75f2 copy, under #2645/#4125 (mote has
  several GUI suites running). After the rebase, go vet and the Cheapest,
  SpeedFirstGroup, ParseRouting, ApplyGroupPairs and ProviderRouting tests
  are ok. go vet darwin, GOOS=linux -tags nogui and GOOS=windows are ok,
  and gofmt is clean.
- GUI on WSL (Linux, chromium + webkit): routing-cheapest-first (new,
  3 scenes x en/zh/zh-TW/ja/de x 2 engines), routing-group-strategy,
  builtins, i18n-keys and routing-speed-first gave 95 of 96. The one red,
  routing-group-strategy "webkit en light ... the pick moved nothing", is
  a wheel-scroll timing red. It fails 3 of 3 on origin/main and 1 of 3 here
  (#4459). Core-script budget ok (app.js +9 bytes).
- The whole GUI suite (1025 files) was started on WSL at this tree and
  was still running when this was pushed, at load ~160.

Not tried: real DeepSeek or Ollama accounts, and a real request during
DeepSeek's peak hours. Ollama Cloud's price here is the catalog's, not
checked against a bill.
2026-10-30 23:59:31 +08:00
yetone 0804f2d97d search: Tencent Cloud's Yuanbao Search (wsa) is a built-in search API (plugins#509)
chenjiangzi asked for Tencent Cloud's WSA SearchPro (元宝搜索). It is added
as vendor "wsa", following Doubao Search (dca3e2d71), from Tencent's
own docs:
- API-key method (cloud.tencent.com/document/product/1806/130615):
  POST https://api.wsa.cloud.tencent.com/SearchPro with
  Authorization: Bearer <key> and a JSON body {"Query", "Cnt": 10}.
  Keys come from console.cloud.tencent.com/wsapi/index (KeysURL).
- SearchPro (121811): Response.Pages is an array of JSON strings, each
  with title, url, date, passage and content. The text is passage, or
  content when passage is empty or only the title. Tags are stripped.
- Errors (121818/121820, 130615): HTTP 200 with Response.Error{Code,
  Message}. AuthFailure*, UnauthorizedOperation and ResourceNotFound are
  turned away (403); ResourceUnavailable (欠费), LimitExceeded and
  ResourceInsufficient are out of credit (402); RequestLimitExceeded* is
  rate limited (429); others are plain errors, with the key masked.

The fixtures in testdata are the docs' two example replies. 130615's is
shown with its quotes escaped twice, which isn't JSON; they were
unescaped once and nothing else changed. The GUI's picker is built from
SearchVendors, so no GUI file changes. README (en, zh), the CLI help and
gateway-routing.md name it.

Run on mote (mote-run), at the rebased head:
- go test -run 'SearchAPI|WSASearch|Volcengine|Search' ./internal/gateway/
  ./internal/gui/
  ./internal/provider/ ./internal/cli/: ok
- go vet -tags nogui darwin/linux/windows: ok; gofmt -l clean
- GUI (no GUI file changes; the picker reads SearchVendors):
  search-api.test.cjs in Chromium 4/4 ok. Its WebKit cases and
  searcher-pick timed out at browserType.launch (180s) on mote,
  where ~57 WebKit pw_run launches from several sessions hang. Not
  a result about this change; WebKit not run.

Broken by hand, each made TestWSASearchAPI red: the wsaSearchError call
removed, and Cnt dropped from the body.

Not tried: the real API. No WSA key was available, so the request,
reply and error mapping rest on Tencent's docs only. The full go test
./... is to follow.
2026-10-30 14:56:01 +08:00
yetone f2c6831a31 gateway: a read-only gateway key reads quotas and usage and uses nothing (Steven on Discord)
Steven's ESP32 desk display polls magpie (Docker, on his LAN) every 15s
on GET /v1/magpie/quotas and /v1/magpie/usage and never sends a model
request. Only a key held to nothing was told the usage summary, so the
key kept in the device's flash had to be one that could spend every
account.

A gateway key can now be read-only (access.Key.ReadOnly):
- `magpie gateway-key add <name> --read-only`, `magpie gateway-key access
  <id> [read-only|full]` (`gateway-key --help` lists it; `list` has an
  ACCESS column), and "Make read-only" / "Give full access" in the key's
  menu in Gateway -> Gateway keys, with a "Read only" tag on its row.
- readOnlyGuard (internal/gateway/readonly.go), after callerGuard and
  before withCaller/keyLimited, judges the pattern ServeMux.Handler routes
  the request to. A read-only key is answered GET /, /v1, the quotas,
  their history and cards, the usage summary and its requests, its limit
  and the concurrency. Every other route is refused with 403
  gateway_key_read_only: every model route, count_tokens, the Responses
  WebSocket's upgrade, every MCP server, Codex's and Gemini's backends,
  /v1/models and the Ollama routes, the catch-all, the trace and route,
  debug profiles, and every write (usage ingest, quotas refresh). It is
  default deny, so a route added later is refused until it is classified.
- The key is held to nothing else, so heldKey leaves it alone: it reads the
  usage summary and every account's quotas, as a key held to nothing does.
  None of those routes holds a key's secret.
- The sharing key can't be made read-only, since magpie gives it to its own
  agents (LANSecret). Update refuses it, and the GUI item is off with why.

Older versions: a magpie from before this commit doesn't know `readOnly`
and treats such a key as a full one, so downgrading magpie widens the key.

Tests:
- TestReadOnlyKeyEveryRoute (internal/gateway/readonly_test.go) takes the
  patterns from the router itself (routes() records each HandleFunc). It
  fails when a pattern is in neither readOnlyRoutes nor its refused list.
  It sends every refused pattern, by each method it takes, from
  192.168.1.9 and from loopback, plus a WebSocket upgrade and an unclean
  chat path, and expects 403 gateway_key_read_only with the upstream never
  reached. It checks that every allowed route answers, that no body holds
  any key's secret or the upstream key, that the usage summary names the
  other key's use, and that a full key and a key made full again still
  reach the model.
- TestReadOnlyKey (access) covers add-key and access-key on and off,
  Authenticate, List, and the sharing key refused.
- TestGatewayKeyCLIReadOnly covers --read-only before and after the name
  and beside --key, access, the list column, bad values, and --help.
- gateway-key-readonly.test.cjs runs Chromium and WebKit, 1100 and 420px,
  in en/zh/zh-TW/ja/de. It covers the tag, both menu items and what they
  post, the status line, the sharing key's item off with its why, no
  scroll on click, no sideways scroll, no select, and no left stripe.
  gateway-card.test.cjs now expects the menu's 4th item.
- TestClientPathCoversHandler takes the patterns from routes() instead of
  parsing Handler's source, which moved into routes().

Broken by hand:
- readOnlyGuard passing everything: TestReadOnlyKeyEveryRoute red (103
  lines, /v1/models 200 onward).
- A new `POST /v1/new-thing` route in routes(): red, "in neither
  readOnlyRoutes nor readOnlyRefused".
- The GUI item not off for the sharing key: gateway-key-readonly red 10 of
  10 in Chromium.

Run at the pushed head (on origin/main 0911a65e7), on mote: TestReadOnly*,
TestHeldKey*, TestClientPathCoversHandler, TestGatewayKey*, TestCaller*
in access, cli and gateway ok; TestCoreScriptBudget ok; on Linux
(wsl-run, both engines) gateway-key-readonly, gateway-card, i18n-keys,
gateway-caller-keys and gateway-key-quotas 68/68.

Full Go suite on mote (macOS) at the same change on origin/main
dca3e2d71 (94630237d), -timeout 45m: 78 packages ok; internal/gateway
red only on the four TestAntigravityTurned* and
TestCodexSpentGrokFailingIsTold (red the same at origin/main, #4362);
internal/gui red only on ten AppKit window tests that hit their 30s
bar while mote's launchd throttled every app launch (#4125).

Run on mote (macOS) on origin/main dca3e2d71:
- go test ./internal/access ./internal/cli ./internal/gateway: access ok;
  cli red only on TestLibraryMCPHub's TempDir cleanup (#4140); gateway
  red only on the four TestAntigravityTurned* and
  TestCodexSpentGrokFailingIsTold, red the same at origin/main (#4362).
  TestReadOnly*, TestHeldKey*, TestClientPathCoversHandler,
  TestGatewayKeyCLIReadOnly pass.
- TestCoreScriptBudget ok (no budget raised). gofmt clean; go vet
  darwin (access, cli, gateway), GOOS=windows ./... and GOOS=linux
  -tags nogui ./... clean.
- GUI, earlier at 807048470 on mote: gateway-key-readonly,
  gateway-key-quotas, i18n-keys, gateway-card, api-key-theme,
  gateway-connect-keys and gateway-caller-keys 34/34 in both engines.
  At this tree mote's WebKit hung at launch for every test (#4125), so
  the 43 gateway-*/key-*/api-key-*/caller-*/menu-*/i18n-* files ran on
  Linux (wsl-run, both engines): 501 of 514. The reds in api-key-theme,
  gateway-key-limit, gateway-key-models, key-replace and menu-input-scroll
  are red the same at origin/main e8d42c02d (#4120, #3523, #4081, #4126,
  #3402); gateway-keys-empty's WebKit wait was red 1 in ~13 runs here and
  0 in 4 at main, filed as #4383 (this change doesn't touch its path).
- Full Go suite on Linux (wsl-run, at 807048470 with this change): reds
  only where Linux can't build the GUI (no gtk4/webkitgtk) and in
  internal/agent's install tests (#4033) and the gateway reds above,
  each red the same at origin/main dca3e2d71; plus
  TestClientPathCoversHandler, which parsed Handler's source and is now
  read from routes() (fixed here).

Not tried: a real ESP32 or Docker magpie; a remote client against a
running gateway (only httptest through lanGuard/Handler); the Windows
test runs (vet only); the whole GUI suite (mote's WebKit hung, #4125).
2026-10-30 14:33:01 +08:00
yetone dca3e2d716 search: Doubao Search (Volcengine) as a search API (CyberCaius on Discord)
CyberCaius asked on Discord #help (10-30) for Volcengine's Doubao search
under Settings › Models › Search APIs, or a custom API address. Volcengine's
Doubao Search Custom (豆包搜索 Custom版, once 联网搜索 / 融合信息搜索,
docs.volcengine.com/docs/networked-search/networked-search, the same page
as volcengine.com/docs/87772/2272953) can now be added with its API key:

- provider.SearchVendors: volcengine, "Doubao Search (Volcengine)", at
  https://open.feedcoopapi.com, keys at
  console.volcengine.com/search-infinity/api-key, after DeepSeek. The GUI
  takes its vendors from SearchVendors, so it shows in the Search API
  picker with its Get a key link and base URL field; no GUI file changes.
- askSearchAPI: POST /search_api/web_search, Bearer key (the default, as
  the docs and volcengine/mcp-server's askecho_search_infinity send it),
  body {Query, SearchType: "web", Count: searchHits, Filter: {NeedUrl:
  true}}. The query is cut to the 100 characters the docs allow. NeedUrl
  leaves out its 火山如意 cards, which have no URL to cite.
- readVolcSearch reads Result.WebResults: Summary as the page's text (the
  docs recommend it for models; Content is the whole page, Snippet
  ~200 chars "only for list display"), Snippet when there is no Summary,
  PublishTime as the page's age, a 1970-01-01 time (its image example's
  stand-in) as none, and a result with no Url left out.
- volcSearchError: its errors are in ResponseMetadata.Error, a code the
  docs list, and the docs don't say the HTTP status, so the code decides:
  10401/10403/10409 rest the key as turned away (403), 10406/10408/
  10410/10412 (free searches spent with none paid, no plan, plan spent)
  as out of credit (402), 700429 as rate limited (429). Any other code is
  a plain error, a 200 carrying one included. The key is masked in the
  error as for every vendor.
- A custom address: every search API already takes a base URL (#1580,
  the field under the key in Settings, url= in the CLI), so an endpoint
  that answers as Tavily, SearXNG, Brave, Exa, Firecrawl, You.com,
  DeepSeek or now Doubao Search does can be set there. There is no common
  format across the vendors (each has its own path, body and reply), so
  no separate "custom" vendor was added.
- Siblings: CLI usage (main.go, search_cli.go's api list and empty-state
  hint), README.md, README.zh-CN.md, gateway-routing.md's path list and
  refusal paragraph.

The test's reply is the docs' own web-search response example, byte for
byte (testdata/volcengine_web_search.json); its error replies are the
docs' error example with its "// 该字段为错误码" note taken out (not JSON).
Not tried against the real API: no Volcengine search key in this run.

Run (worktree on origin/main c941e0877, then rebased on d31710c71):
- TestVolcengineSearchAPI (new): red on the old code (no such vendor).
  Broken by hand six ways, each red with its own message: Summary not read
  (Snippet's text), volcSearchError not called (200 10403 read as "no
  Result in it"), query not cut (150 characters went), NeedUrl dropped
  (body {"Filter":{}}), 1970 age kept, 10412 not mapped (plain error, not
  a refusal). Restored: ok.
- go test -run Search ./internal/gateway/, go test ./internal/provider/
  ./internal/cli/: ok, before and after the rebase.
- gofmt -l internal: nothing. go vet -tags nogui ./... on darwin,
  GOOS=linux, GOOS=windows: ok.
- Not run before the push: the full go test ./... . mote had three other
  sessions' full suites running at load 140-230; it runs after the push
  and its result goes on the report.
2026-10-30 13:28:45 +08:00
yetone af8f3a9399 sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
RustCats on X: a fresh magpie showed every agent's session history on
the Sessions page before anyone agreed to it, and asked for a per-agent
choice instead.

- sessions.Reads(agent) (internal/sessions/access.go) is the one gate,
  from settings.SessionReads {Asked, All, Agents}. Every lister asks it,
  the aggregators (allFiles, callFilesWith, callSourcesWith,
  traceLineFiles, wslFiles, DesktopDataDirs) filter by it again, and
  readers of an already-listed session (TranscriptOf, ContentOf,
  SearchSession, SubagentTranscript, CarryOver, ReadCallSource) return
  ErrNotRead, so a cache from before a switch was turned off goes no
  further. The Sessions list, stats, /api/sessions/overview, the call and
  trace indexes, Usage's agent-file calls and the Codex/Pi title readers
  all pass it.
- SettleReads decides once and saves: an install with sessions.json or
  a calls-v* cache read sessions before and keeps all on; a fresh one
  reads none, not asked. A saved value is never replaced; save, sync and
  restore keep it (KeepOwn); only SetSessionReads writes it. An
  unwritable settings.json reads nothing this run.
- GUI: GET/POST /api/sessions/reads. While not asked, the Sessions page
  shows a consent card: each agent found (by a stat of its folder only)
  with a switch, Allow selected and Allow all. Settings > Privacy >
  Agents' session history has "Agents found later" and a row per agent.
  Strings in en, zh, zh-TW, ja, de.
- CLI: magpie sessions read [on|off all|<agent>...]; magpie sessions
  says on stderr when nothing is allowed yet; the TUI's empty Sessions
  page says how.

Read either way, because none of it lists or shows a session: the
gateway's own usage ledger, its projections and the conversations it
recorded (magpie's own records, so usage and cost keep working); the
agents' config and sign-in files; Claude Code's and Codex's
history.jsonl last-used time and a session file's mtime for a quota's
first use; Codex's newest rollout's last line before magpie restarts
Codex (codexTurnOpen).

Tests: TestFreshInstallReadsNoAgentUntilAllowed,
TestSettleReadsKeepsWhatWasThere, TestSessionReadsRoutes,
TestSessionsRead, TestSessionsNotAskedSaysHow, sessions-reads.test.cjs
(26 cases: consent and Settings in 5 languages, Chromium and WebKit,
390 to 900 wide).

Run on mote:
- full Go suite (gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui,
  GOOS=windows go vet, go build, go test -timeout 45m ./...) at this
  change on 8c63c5b78: 79 packages ok; internal/gui red on
  TestSettingsSaveKeepsWhatItDoesNotSend (mine: SessionReads is written
  by SetSessionReads only, the test now sets it so; green after) and
  TestMainWindowCorners (the same on origin/main c1da9ccda, #3949).
- whole GUI suite (make test-ui, concurrency 2) at this change on
  8c63c5b78: 14985 tests, 276 failed in 44 files. Mine: i18n-keys
  (comments named "Allow all"/"Allow selected"; lowercased) and
  account-discovery (read the last Privacy heading; now the one above
  its list); both green after. The 44 files again on origin/main
  c1da9ccda: 36 red there too (#4304, with #3218, #3412, #3414, #3795,
  #4120, #4125). stays-strict green alone; gateway-key-models webkit red
  1 of 3 alone on main too; plugin-github de 440 red on main (#3218).
- at the pushed head (rebased on cd10dfbe6): go build ./...; go test
  internal/sessions, settings, cli, tui ok; internal/gui
  TestSettingsSave*, TestSessionReads*, TestSessions* ok; i18n-keys,
  account-discovery, sessions-reads: 62 pass, 0 fail.

Broken by hand:
- the aggregator filter off with the leaf gates on: green (the leaf
  gates hold); both off: TestFreshInstall red on List, Agents, Calls,
  CallSources, traces, stats, TranscriptOf and Search.
- consentApplies=false and Settings' old save({all}) without the rows:
  all 13 Chromium cases of sessions-reads red.
- sessNothing's hint removed: TestSessionsNotAskedSaysHow red.

Real binary in a sandbox HOME on mote (removed after): a fresh
`magpie sessions` is empty with the hint on stderr; `sessions read`
says not asked, claude off; `read --help` prints usage and saves
nothing; `read on claude` lists the one session; `read off all`
empties it again.

Not tried: the GUI and real app on Windows and Linux; WSL agents in the
consent list (WSL distros are not looked into; Allow all covers them);
a fresh install of a signed release build.
2026-10-29 23:56:05 +08:00
yetone 96a703a591 uninstall: magpie uninstall and Settings › Uninstall magpie put every agent back before magpie's files go
Jevik_AI on X (Windows, portable magpie) deleted magpie's folders by hand.
~/.codex/config.toml kept openai_base_url on 127.0.0.1:3425, and every
Codex turn then failed with a 502, with nothing left that knew why.
Deleting magpie's files never puts an agent back, so there is now an
uninstall that does.

- internal/uninstall: Run goes in this order. System removes the
  background service, opening at login, the Start menu shortcut
  (shortcut.Remove, with its App Paths key), the magpie:// links and the
  privacy model's helper. Agents ends Codex's account failover, then runs
  each connected agent's own Disconnect, or its offline disconnect for an
  app that is closed. That is the same code as the Agents page, so a value
  the user changed by hand since Connect stays theirs (e7f21dba5 for
  Codex). It then ports Codex's rollouts and restarts the Codex app's
  app-server (provider.RestartCodexAppWhenIdle, which says whether one was left on
  the old config). Data deletes magpie's folders, but keeps the Library's
  folder while it holds skills, servers or hooks the user's agents use.
  The executable is left where the user put it.
- `magpie uninstall [--yes]`: refuses while another magpie runs, and
  says which one. On a terminal it lists what goes and asks [y/N]; with
  no terminal, only --yes does it.
- Settings › About › Uninstall magpie: POST /api/uninstall runs System
  and Agents. If anything failed, nothing else is removed and the sheet
  offers Try again. Otherwise POST /api/uninstall/finish starts a
  detached `magpie uninstall --data-after <pid>` (Setsid on unix,
  DETACHED_PROCESS on Windows) and the app quits; the files go once it
  has ended, since WebView2 holds its folder open until then. A Codex app
  still on the old config is named before quitting. magpie web refuses
  both routes. Strings go through t() in all five languages.
- --data-after refuses a pid that is no process (0, negative, its own):
  kill(0) counts as alive, and a run given 0 waited out its 2 minutes.

Not done, and why:
- No restore on quit. Quitting keeps agents on magpie by design: the
  service or the next start serves them.
- No Apps & Features entry or Windows uninstall hook. A portable copy
  registers nothing with Windows, and an uninstaller that ran without
  magpie's own disconnect would leave the configs as they are. The
  `# magpie:` note above each line magpie writes (previous commit) is the
  recovery path for a copy deleted by hand.

Run at this head (db75663a0's tree, on 5d24bc6cc), on mote:
- gofmt -l clean; go vet ./... on darwin (-tags nogui), GOOS=windows and
  GOOS=linux -tags nogui: ok.
- go test -tags nogui -count=1 -timeout 45m on ., internal/uninstall,
  cli, gui (TestCoreScriptBudget included), provider, shortcut, edit,
  agent and proc: all ok.
- GUI at this head: mote was at load 100-120 with other sessions' GUI
  runs. Chromium crashed (SIGBUS) mid-file in settings-search and
  settings-sections after their en cases passed, WebKit failed to launch
  within 180s in s3-sync, settings-search and settings-sections, and
  fonts and title-bar-tools went red on unstable elements (#2984 has
  fonts under load). uninstall-settings had not reported when this was
  pushed.
- At the earlier base b3580c72c, on this machine: the full suite
  (-timeout 45m), red only on #3884, #3632 (both since fixed on main) and
  the core budget, which main's later move of Web search out (#4133) has
  room for now. GUI: 104 Settings and i18n files in chromium and webkit,
  uninstall-settings and i18n-keys green in both; the reds were #3797,
  #3876 and the load reds above.

Tried for real, in a sandbox HOME: `magpie uninstall` end to end with
Codex connected and a sandbox Codex app running (config.toml back
without magpie's lines, magpie's data gone, the exe kept, the app's
app-server restarted onto the restored config); codex-cli 0.162.1
reading the noted config.toml. Other agents were covered by tests only.
Not tried: the GUI's Uninstall in a real app window, a real
--data-after run waiting on a live app's pid, and the Windows box.

Broken by hand: --data-after's pid guard removed ->
TestUninstallDataAfterNeedsAProcess red (0, -1 and its own pid
accepted); restored, green.

At the pushed head (rebased on 51f66fe8b; the uninstall call adapted to
EndCodexFailover's (bool, error) on the way), on mote:
- gofmt clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok;
  go build ./... ok.
- go test -timeout 45m: internal/uninstall, edit, shortcut, cli, agent,
  provider ok; internal/gui red only on TestMainWindowCorners/macOS_26_SDK
  (#3949, macOS 27).
- GUI: uninstall-settings and i18n-keys, 30 pass 0 fail.
- WSL (magpie-desktop, CGO_ENABLED=0): uninstall, edit, shortcut,
  provider ok; agent red on TestGrokInstalled, TestOmpDetectedWithPiDir,
  TestZedAppPath, the same at origin/main 51f66fe8b (#4033, #3548).
2026-10-29 17:47:30 +08:00
yetone 0c4e3455ee agents: a line magpie writes into a TOML, YAML or env config has a note above it saying so
Jevik_AI on X deleted magpie's folders by hand. Codex's config.toml kept
openai_base_url = "http://127.0.0.1:3425/backend-api/codex", with nothing
in the file naming magpie, and every Codex turn failed with a 502.

Each line magpie writes that points at the gateway, or at magpie's model
list, now gets a comment line of its own just above it:

  # magpie: Codex on magpie's local gateway; Disconnect in magpie or
  #   `magpie uninstall` undoes it, or delete this line and the model line
  model_provider = "magpie"

- Only a line the write adds or changes, or one that had a note, gets one.
  A line of the user's own that magpie leaves alone gets none.
- The note is never on the value's line. Grok App's providers.rs reads the
  rest of a line as the value, and an end-of-line comment broke
  TestGrokApp in a first try.
- Every write takes the notes out and puts back the ones still needed, so
  a note goes with its line and Disconnect leaves none.
- No note in JSON. A YAML note that would change what the file reads as
  isn't added.
- Wired in run (agent.MarkWritten); tests leave edit.Mark nil so their
  exact bytes stay.

Run at this commit's tree (worktree, sandbox HOME, private GOCACHE):
- gofmt -l clean; go vet darwin, GOOS=windows, GOOS=linux -tags nogui ok.
- go test -tags nogui -run Mark ./internal/edit ./internal/agent: ok.
- ./internal/agent and ./internal/edit whole with edit.Mark forced on for
  every test (a snapshot with lineNote set in agent's TestMain): edit ok;
  agent fails only TestDshRouteKeepsTheAPIPickedInDsh and
  TestDshSearchThroughGateway, which compare exact bytes and see the note
  line. With Mark unset (as shipped) they pass.
- Real Codex: built magpie from this tree, `magpie codex fakeai/fake-1` in
  a sandbox HOME. config.toml got the three notes above model_provider,
  model_catalog_json and openai_base_url; `codex mcp list` and `codex
  features list` (codex-cli 0.162.1) read it, rc 0, and Python's tomllib
  reads the same values. `magpie codex default` took them out.
- Broken by hand: a note on every line, not only changed ones ->
  TestMarkTOML and TestMarkOnlyWhatMagpieWrites red.

- The notes' line filter is withoutNotes, unexported: an exported
  Unmarked put a word the routing plugin translates into a Go file, and
  i18n-keys' "a plugin's words are its own" went red on it. It passes
  now.

Full suite: run with the uninstall commit that follows, recorded there.
2026-10-29 17:42:35 +08:00
yetone 4534561f6b codex: a thread open when magpie quits goes on through a relay, not a 503
idkatbro on X: a Codex session started while magpie was open keeps
failing after magpie quits with "unexpected status 503 Service
Unavailable: Unknown error, url:
http://127.0.0.1:3425/backend-api/codex/responses", until magpie is
opened again.

Cause: Codex signed in to ChatGPT, with more of its accounts on in
magpie, gets openai_base_url = the gateway's /backend-api/codex
(failover). At quit EndCodexFailover takes it out of config.toml, but
a thread already open, in the Codex app and its app-server above all,
keeps the base URL it started with. Every turn after went to a closed
port. With a system or env proxy in between, the proxy answers 503
with an empty body, which Codex shows as "Unknown error"; without one
Codex says "Connection refused" and reconnects. Reproduced on mote
with codex 0.162.1 and a proxy answering 503 for the closed port.
Masking plays no part: it runs only in the gateway, is opt-in, and its
own 503 carries a readable message.

Fix: when quit really ends failover (EndCodexFailover now says so),
the gateway is on loopback, and Codex processes run
(provider.CodexPIDs), magpie starts a detached `magpie codex-relay`
(internal/codexrelay). It waits up to 60s for the gateway's port, then
passes /backend-api/codex/* on to the ChatGPT backend with the same
transforms the gateway applies to Codex's own turns, signed by the
caller's own Authorization; it adds no credential
(gateway.CodexRelay).
- Refused with a readable 400 (Codex retries a 5xx five times over):
  a magpie model, a turn naming one of magpie's Codex accounts, and a
  turn masking would have masked, which is never sent unmasked.
- 403 for any Origin (null too) or a non-loopback Host, as corsGuard.
- Any other path gets 503 "magpie isn't running", never readable as
  magpie by ServedBy.
- It ends once every Codex process it was left for is gone and
  nothing is in flight.
- The next magpie (GUI or `magpie serve`) calls codexrelay.Leave
  first: a POST with the token from a 0600 state file. The relay
  closes its listener at once, so the port is free when Leave returns,
  and finishes its streams (up to 30 minutes). No running turn is cut.

Run (at 6df7dc287 on origin/main 4d9058a98, on mote):
- go vet of the six touched packages; gofmt -l clean.
- go test ./internal/codexrelay and the CodexRelay, CodexFailover,
  CodexProxy, RelayOpenCodex and CodexPIDs tests: ok.
- codexrelay tests on Windows (win-run) and Linux (wsl-run,
  magpie-desktop): ok.
- Windows smoke of the real binary (nogui build): `codex-relay`
  answers / with the readable 503, stays while its watched process
  lives, ends after it.
- Real codex 0.162.1 e2e on mote, sandbox CODEX_HOME, API-key sign-in,
  fake upstream: the relay waited out a port held 2s, then turn 1
  completed (RELAYED-OK); a turn on openrouter/kimi-k2 showed the
  refusal's message; turn 2 was mid-stream when Leave ran, the port
  was free at once, the turn completed, and the relay ended.
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... and a
  Windows build: ok.
- Full suite, go test -count=1 -timeout 45m ./... on mote: every
  package ok but internal/gui, where 10 real-window AppKit tests
  (dock, panel, tray, titlebar, covered window, plugin page) are
  killed at their 20-80s bars. The same 10 fail the same way at
  origin/main 4d9058a98 on mote, run alone: mote's AppKit hang, #4125
  (and #2645, #1936). None of them touches the quit path changed here.
- Rebased on origin/main 1198cff60 to push. Still running there when
  pushed: go vet ./..., Windows and Linux vet of the touched packages,
  and go test of codexrelay, gateway, agent, provider and cli. A red
  it shows gets its own issue.

Broken by hand, each red, then restored:
- Leave without ln.Close(), with a 1s delay before Shutdown injected:
  "the port isn't free after Leave" (with ln.Close: green).
- No pid watch: "relay outlived the Codex it was left for".
- Leave without the token check: an empty token got 204.
- No Origin/Host guard: Origin null got 200.
- No masking refusal, no magpie-model refusal: 200, sent upstream.
- An empty 503 at "/": TestCodexRelayIsNotMagpie red.
- RelayOpenCodex starting nothing: "no relay for the open Codex".
- EndCodexFailover never saying ended: TestCodexFailoverEndsWithMagpie.
- CodexPIDs missing "codex": the Codex app and CLI not found.

Not tried:
- the real Codex desktop app, and a real ChatGPT account. With a fake
  ChatGPT token codex 0.162.1 stops at its own "workspace routing
  discovery" against chatgpt.com before sending a turn, so the
  ChatGPT path is covered by unit tests only;
- a Codex in a WSL distro, and a connected (not failover) Codex: both
  left as they were;
- a magpie that ends without quitting (killed, crashed): still leaves
  failover in place and no relay;
- the relay's memory use as the full binary.
2026-10-29 17:13:05 +08:00
yetone 628ac36fc9 agents: Add magpie says when nothing here opens the app's import link (sungt)
sungt (Discord #feedback, Windows, magpie 0.1.1976, Cindy 0.1.119, Cindy
open): on the Agents page Cindy's 添加 magpie "spins, no response".

What magpie got wrong: Cindy, AionUi and Lody take magpie only through
their import link, which magpie hands to rundll32 / open / xdg-open and
never waits on. A link nothing opens did nothing, the button never awaited
/api/open nor caught its error, and `magpie cindy add` printed "opened"
whatever happened.

- agent.OpenAppLink asks the system, without opening anything, whether
  something opens the link's scheme: Windows' HKCR\<scheme> (what
  Electron's setAsDefaultProtocolClient writes) and then the user's
  UrlAssociations UserChoice; macOS Launch Services (cgo builds); Linux
  `xdg-mime query default`. Only "none", or a registered program whose
  full path is gone, refuses the link (NoLinkHandlerError); anything
  unknown hands it over as before.
- /api/open (Cindy, AionUi, Lody after OpenLody) answers
  code no_link_handler with app, exe and said, an i18n.js key from
  linkSaid that api() puts through t() as it does bunSaid's.
- The import button now waits for /api/open and shows the result: "Sent
  to {name}: confirm adding magpie there", or the reason in the
  reader's language.
- The CLI's add returns the same error.

This is not verified as sungt's cause. Cindy was open, and Cindy
registers cindy:// at every start, so the check most likely passes on
their machine. If so, the spinner is Cindy's own import dialog
(previewProviderImport / fetching magpie's /v1/models). Cindy 0.1.119
wasn't available here. We still need Cindy's log around "received deep
link" from sungt.

Run (worktree at origin/main 536a98316, mote unless said):
- go test -tags nogui -count=1 ./internal/agent ./internal/gui
  ./internal/cli: agent ok, cli ok. gui is red only on
  TestCoreScriptBudget, #4133, which is red on origin/main
  (1531446 > 1530861, from a4e929212's context.js). This change adds 85
  bytes to app.js (1311673, under app.js's own 1311735) and makes the
  total 1531531. No budget was raised.
- node --test, chromium and webkit, every language: import-row,
  i18n-keys, plugin-bun-unstartable, agent-connect-no-models and
  agent-connect-all-hidden (api()'s error paths). Result: 84 pass, 0 fail.
- Windows (win-run): TestCommandProgram, TestOpenAppLinkSaysNothingOpensIt,
  TestSystemLinkHandlerNoSuchScheme (real registry lookup) and
  TestFolderVarsAreListed all pass. Earlier in this work:
  - rundll32 handed magpie's 719-char Cindy link byte for byte to a
    registered handler;
  - a temporary HKCU scheme was read as found, then as gone once its exe
    was deleted, and the key was removed afterwards.
- Linux (wsl-run, magpie-desktop, real xdg-mime): the same applink tests
  pass.
- macOS (mote): Launch Services finds https and mailto, and finds no
  handler for cindy, lody, aionui or a random scheme.
- gofmt -l is clean. go vet passes for GOOS=linux -tags nogui, for
  GOOS=windows, and with CGO_ENABLED=0 for internal/agent.

Red on the old code, each wiring reverted by hand:
- providers.go: TestImportLinkNothingOpens is red (204, link handed over).
- cli main.go: TestImportAddSaysNothingOpensIt is red (nil error, link
  handed to the browser).
- importButton: import-row is red (status "" where the Sent/err line was
  wanted).

Not tried:
- Cindy 0.1.119, or any real Cindy, on Windows.
- A real app whose registered exe was deleted.
- The full go test ./... and the whole GUI suite. mote was running
  another session's full suites, and there is one suite per machine.
2026-10-29 09:24:31 +08:00
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 e8c7dddcb4 notices: the release carries the third-party licence notices
The owner asked for the licence notices in the release package (moejs
alpha.11 compiles Intl's data in, which carries its own notices).
THIRD_PARTY_NOTICES is embedded in the binary (main.go, //go:embed) and
handed to internal/notices; `magpie licenses` prints it, GET /api/notices
serves it, and Settings › About has an Open-source licenses row that
opens it in a dialog, in every language. `make app` copies the file into
the .app's Resources too. The core's scripts are 1,527,245 bytes, their
budget raised to it with no room added; app.js stays under its own.

Run at this head (rebased on origin/main):
- win-run (Windows 11): go vet -tags nogui . ./internal/notices
  ./internal/cli; go test TestNoticesFollowMoejs (.), ./internal/cli,
  TestCoreScriptBudget (./internal/gui): ok.
- wsl-run (Ubuntu 24.04): go vet -tags nogui ./..., go build -tags
  nogui: ok.
Run at the pre-rebase head 14e2d13fb, on mote (macOS):
- gofmt; make app's copy byte-identical to the file; `magpie licenses`
  output equal to the file; GOOS=linux/windows vet and build;
  go test . ./internal/cli: ok. ./internal/gui: only
  TestMainWindowCorners red, the same on origin/main (#3949).
- about-notices.test.cjs: chromium and webkit, en zh zh-TW ja de, 1100
  and 420px: all ok.
Broken by hand: TestNoticesFollowMoejs red with the embedded file cut.
Not run: the GUI suite at this head. The rebase met main's cancelAsk
helper where showNotices sat, and the dialog's Done now uses it (the
same stopPropagation + closeConfirmAsk). The whole GUI suite at
14e2d13fb was cut off when mote went down at load ~50: the files it
reached outside About had reds, most of them 180s browser-launch
timeouts, the rest passing in other languages or the other engine; they
are run again once mote is back, and any that stay red are filed.
2026-10-28 16:40:03 +08:00
yetone add927e604 codex: the Codex app beside the ChatGPT sign-in lists magpie's models too
laddieyao (Discord #general, 10-27): with Codex joined to magpie beside
its ChatGPT sign-in, the Codex desktop app's model picker showed OpenAI's
GPT models alone, while the Codex CLI listed magpie's. The /models
request does reach magpie's gateway and its answer holds magpie's
models. ChatGPT.app 26.1013's picker then narrows app-server model/list
to the models a Statsig config (107580212, use_hidden_models /
available_models) names, while Codex is on its built-in provider, unless
Codex reads its list from a file (model_catalog_json,
hasConfiguredModelCatalog) or names a provider of its own. The CLI has
no such filter.

Where the Codex app is installed (codexReaders has an "app"), and only
joined/beside the sign-in (not magpie as Codex's provider, not account
failover alone), magpie writes the list it hands Codex at
/backend-api/codex/models to ~/.codex/magpie-desktop-models.json and
names it with model_catalog_json. Codex is still on its built-in
provider. With a catalog named Codex asks for no list, so magpie asks
the backend itself, with Codex's live sign-in (provider.CodexLiveList):
its entries go in verbatim, base_instructions and all, merged as the
gateway merges them (codexMerged, factored out of codexModels: picked,
hidden, window, V1, AutoReview edits), magpie's models after them.

- A list not known (not asked yet, or the backend failing) is unknown:
  the file as it was stays, never an empty list; a key naming a file
  that is gone goes, as Codex loads no config then.
- Written via temp+rename at Join, set, settle and every Sync (so a
  change of magpie's models, picks or hidden models rewrites it, as
  SyncCatalog runs on them); the backend list is asked again hourly
  (5 min after a failure) and a change syncs again.
- A model_catalog_json of the user's own stands; none is written beside.
- magpie API, the app gone, or unwire take the key and the file out;
  unroute never restores the desk file as the user's catalog.
- connectinfo counts the file, so a running app on an old list reads
  as needing a restart.
- CLI-only machines: unchanged, the live /models path as before.

Run:
- Real account, sandbox HOME (copy of auth.json, chatgpt Pro; live
  ~/.codex untouched): Join wrote model_catalog_json and the file with
  the real backend's 10 entries (gpt-6.1-sol ... codex-auto-review, each
  with base_instructions) plus relay/claude-opus-5.5 and
  relay/claude-sonnet-4-5. Then the real app-server bundled in
  ChatGPT.app (codex 0.163.0-alpha.10.2, CODEX_HOME sandbox, base URL
  pointed at a dead port) model/list returned all 12, relay models
  visible, and config/read showed model_catalog_json set, which is what
  the app's picker checks to skip its filter.
- New tests: TestCodexDesktopListBesideSignIn, ...CLIOnly,
  ...KeepsTheirs (internal/agent), TestCodexDesktopCatalog
  (internal/gateway).
- Broken by hand, each went red: deskList a no-op (all three agent
  tests), the user's-own branch removed (KeepsTheirs), the gone-file
  branch removed (KeepsTheirs), the keep-last-good rule broken in
  codexDeskRefresh (TestCodexDesktopCatalog).
- go test -tags nogui -timeout 45m ./internal/agent ./internal/gateway
  ./internal/provider ./internal/cli at bc0a99bb6 (on 68bbcc01c):
  agent, gateway, cli ok; provider red on TestUnreadLogins...
  (synctest crash, #3632) and three TestFetch* tests (#3854), both red
  the same at origin/main 68bbcc01c / 5a3292354 run alone, both filed.
- Rebased over e7f21dba5 (Disconnect keeps a hand-set catalog): the
  conflict in unroute merged (the desk key counts as no catalog of the
  user's), and -run 'CodexDesktop|Disconnect|Unwire|Catalog'
  ./internal/agent ok. The packages' run at the final head could not
  build: the machine's disk was full (other sessions).
- gofmt -l clean; go vet ./... on darwin, GOOS=linux, GOOS=windows ok.

Not tried: clicking the real desktop app's picker (the app-server
answer and config were checked, not the GUI); the Windows Store app
(its readers get no version but count as the app; not run there); a
backend list change rewriting the file while the app runs (the app
needs reopening to read a new file, which connectinfo's restart notice
covers).
2026-10-27 18:38:27 +08:00
yetone 3ec3cb704b plugin: turning an agent plugin off or removing it puts the agent's config back first (#3810)
An agent a plugin adds is known only while the plugin is on. Turning
the plugin off or removing it (CLI `magpie plugin off/rm`, or the
Plugins page) left the agent's config on magpie, and `magpie <agent>
default` then said `unknown agent`, with nothing to put it back.

- provider.SetPluginOff (off) and provider.RemovePlugin first call
  provider.PluginAgentGoing, set by internal/agent to UnwirePlugin: the
  agent is disconnected as `magpie <agent> default` does (Disconnect),
  while the plugin still loads. A plugin off already is read from its
  module as it is; one whose module is gone puts back each file whose
  stash names its spec. If that fails, the plugin is left as it was
  and the error says why.
- The stash now records the plugin's spec and the file's format, so
  `magpie <id> default` for the agent of a plugin deleted on disk puts
  the file back from the stash alone (agent.RestoreGone; an older
  stash's format comes from its file's name, agentplug.FormatOf). A
  file that no longer holds magpie's gateway key is the user's and is
  left alone; one that can't be read is unknown: nothing is written,
  the stash is kept. With the plugin only switched off, `default` says
  the agent is off magpie already instead of "unknown agent".
- Turning the plugin back on (or installing it again) does not rewire
  the agent by itself: its config stays as the user had it. Connecting
  it (its switch on the Agents page) puts back the model it was on,
  through Disconnect's `.reconnect`. The CLI says so when it turns off
  or removes a plugin whose agent was on magpie.

Run (this change on origin/main f3c4d7b7a, then rebased onto
0fb0bfda3, which changes only an internal/gateway test; provider and
cli run again at the pushed head):
- gofmt -l: none; go vet -tags nogui on darwin, linux, windows for
  agent, agentplug, cli, provider, gui, plugin: ok.
- go test -tags nogui -timeout 45m -count=1 ./internal/agent
  ./internal/agentplug ./internal/cli ./internal/provider
  ./internal/plugin ./internal/gui: agent, agentplug, cli, plugin, gui
  ok; provider crashes in TestUnreadLoginsWriteErrorsKeepCredentials
  ("close of synctest channel from outside bubble", filememo.Forget),
  the same on origin/main 0fb0bfda3 run alone: #3632, open, not this
  change. At the pushed head: cli ok; provider with -skip
  TestUnreadLogins ok.
- Real use, sandbox HOME, magpie built from this tree, gateway on
  127.0.0.1:3491, web on 3492: `magpie plugin add agent-kilo`
  (@magpie-community/agent-kilo 0.1.0, not on npm, from the plugins
  repo's dist branch), a kilo.jsonc with comments and a provider of its
  own, `magpie kilo magpie/deepseek/deepseek-chat` (wired, provider
  block added). Then, each time from wired: `magpie plugin off` -> cmp
  byte-identical; `plugin on` -> still the user's; `plugin rm` ->
  byte-identical; POST /api/plugins/off and /api/plugins/remove (the
  Plugins page's calls) -> byte-identical; plugin dir deleted and
  plugins.json emptied by hand, then `magpie kilo default` -> put back,
  byte-identical. `magpie kilo default` with the plugin off says it is
  off magpie already.

Broken by hand, each red, then restored:
- PluginAgentGoing left nil: the four off/remove tests fail.
- the SetPluginOff call removed: Off and ModuleGone tests fail; the
  RemovePlugin call removed: Remove and RemovedWhileOff fail.
- Spec not stashed: ModuleGone fails. pluggedOff disabled:
  RemovedWhileOff fails. FormatOf fallback removed: TestRestoreGoneAgent
  fails. The gateway-key check removed: LeavesAFileOffMagpie fails.
- Unwire instead of Disconnect: the Off test fails (How "first", not
  "again"). The off-plugin check in RestoreGone skipped: the Off test
  fails. RestoreGone not called from the CLI: TestGoneAgentDefault
  fails with `unknown agent "kilo"`.

Not tried: the Windows box; a real Kilo CLI reading the restored file;
the GUI suite (no Plugins page code changed: the page's calls reach the
same provider functions, tried above through the web API). Not changed:
an inline JSON object magpie wrote into comes back reformatted (same
values) on any plugin agent's Disconnect, `default` included: #3814.
2026-10-27 10:01:46 +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 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 5b4dec58e4 providers: a vendor's keys saved a provider each are one provider with those keys
yuluo_yx on X: "NVIDIA #595"…"#600" at integrate.api.nvidia.com and
"Mistral #0001"… at api.mistral.ai were a provider each on the
Providers page and a row each on Routing, and with thousands of keys
magpie started slowly. They came from an app that keeps an entry a key
(CC Switch) imported in one batch: ImportFromApps only offered "add as
another key" against providers that existed before the batch, so each
entry became a provider of its own (nvidia, nvidia-2…).

Fold (internal/provider/fold.go):
- FoldCopies runs in startUp, before anything lists the providers, so
  every user who has such copies already finds them folded. Automatic,
  not a one-click offer: they are the same account's keys at the same
  address, what the user wanted is one provider (zero-config rule), and
  nothing is lost: each copy's id goes in the provider's Was, so its
  calls count with it by key (ProviderKeyID is the key's fingerprint,
  unchanged) and a model picked by the old id still resolves.
- Only copies by name fold at start-up: a base name and that name with a
  number after it (" #12", or freeName's " 2"), at least one numbered.
  They must also be alike in all but the key: the provider with id,
  name, keys and on/off left out, their per-model settings, and every
  place that names them (Visible, picked/hidden/ordered models, groups,
  fallbacks). A copy shown to one agent alone, given its own models or
  settings, or named by the user ("Home relay" / "Work relay") stays
  apart. Subscriptions, hidden ones, Vertex and StepFun-signed ones are
  never folded.
- The first copy that is on takes the rest; it is named the base name
  ("NVIDIA") and its key keeps its old name. Others become keys in the
  providers' order, named as they were, off if they were off.
- Group members, weights, rules, classifier, pick and fallbacks name the
  provider once; per-model settings and fetched lists of the folded ids
  go; balance and window history kept by their id moves to their key's
  name, where a provider with several keys reads it.
- A providers.json that doesn't parse is left alone (read() would have
  given its .bak, and a fold would write that over it).
- ImportFromApps folds what one import added by shape alone, whatever
  the entries are called.

Routing needed no change: a provider's keys for one model already fold
into one row ("2400 keys"), opened on click (FOLD_AT, #1319).

Numbers, sandbox HOME with 2400 NVIDIA + 600 Mistral copies (gen.py,
NVIDIA preset + 2 models, Mistral 15 models), `magpie web`, every
outgoing request through a dead proxy:
- before (origin/main 9809a8ac9): first /api/state 200 after 6.38s
  (4.9s on a second try), /api/state 2.6-4.5s and 86,475,466 bytes,
  /api/providers 6.4-8.4s and 11.7 MB, RSS ~1 GB.
- after, first start (folding): first /api/state after 1.73s; later
  starts 0.52s. /api/state 5-13 ms and 100,833 bytes, /api/providers
  25-80 ms and 315 KB, RSS 69 MB. The file ends with 2 providers,
  nvidia with 2400 keys and mistral with 600.
With 3000 keys in one provider nothing else scaled badly enough to
show (#3164 and @NetRozee's thousand-key work already made the key
paths once-per-list), so nothing more was changed.

Tests: TestFoldCopies, TestFoldCopiesIntoOneOn, TestFoldCopiesUnreadable,
TestImportFoldsAKeyAnEntry. Broken by hand, each went red: refs left
out of the shape (a copy shown to Codex alone folded), per-model
settings left out, Off not carried, Was not appended (usage of the
folded id stayed its own), the first-on rule, the history move, the
settings move, the unparseable-file guard, and the import's fold.

Run: gofmt -l (clean); go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./... (clean); go test -tags nogui
./internal/provider ./internal/cli ./internal/settings
-skip TestUnreadLoginsWriteErrorsKeepCredentials: all ok (provider
121s). That test crashes alone on origin/main 834935149 too ("close of
synctest channel from outside bubble", filememo.Forget), filed as #3632.

Not tried: the GUI suite (no asset changed; the pages read the same
APIs), a real CC Switch database with hundreds of entries (the fixture
is CC Switch's schema with four), a user whose copies have different
per-key settings (they stay apart by design), and the full ./... suite
before the push (other sessions' suites were running at load ~110).
2026-10-26 23:27:55 +08:00