Commit Graph
228 Commits
Author SHA1 Message Date
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 bc10a61985 agents: Claude Code's status line, the 5h and 7d use, is a switch on its row (steven_4422)
steven_4422 on Discord asked for the 5h and 7d account use in Claude
Code. magpie has had `magpie statusline` since #1997 (kensenzhao), but
it was found only in docs/reference.md and needed a hand-written
settings.json entry naming a `magpie` the app doesn't put on PATH.

Claude Code's row now has a "status line" square beside ultracode (the
same toggle, now a table, TOGGLES in app.js), and `magpie claude
statusline on|off` in the CLI. On writes settings.json's statusLine as
{type: command, command: "<this magpie's full path> statusline"},
quoted for a POSIX shell (Git Bash on Windows, forward slashes).
The command reads the gateway's kept windows with a 1s timeout and
prints nothing when it can't, as before.

- A status line of the user's own is never written over: the square
  isn't offered while one is there, on is refused, and off and
  Disconnect leave it byte for byte. Ours is a single plain command
  whose program is magpie/magpie-* and first argument statusline, so a
  hand-written one from the reference counts and a compound (&&, |, ;,
  $(...)) is the user's.
- An unreadable settings.json is not written over.
- Disconnect takes magpie's status line out with the rest.
- Quiet: Claude Code reruns a changed statusLine command in its open
  sessions, so no restart notice.
- Not offered for a WSL distro, and a distro's settings.json isn't read
  for the options (a stopped one would start, #3896). A stopped
  distro's fields fall back to magpie's models as options, so without a
  case in wsl.go its square would have listed models
  (TestWSLClaudeNoStatusLine).

Run on mote (go1.26.8, load ~400):
- at f33e6d112 (rebased on 3088872e6): go test -count=1
  ./internal/agent ./internal/cli ./internal/gui. Red:
  TestWSLColdPlaceOpensNothing (mine: Options read a distro's
  settings.json; fixed), TestCoreScriptBudget (5 bytes over after the
  rebase; a comment trimmed, no raise), TestEveryRouteHasACommandOrIsNamed
  (#5026, from 0872bc2a0 on main), TestMainWindowCorners/macOS_26_SDK
  (#3949, macOS 27). go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- GUI at f33e6d112: every agent-*, claude-*, i18n*, field* and tweak*
  file, both engines: 1294 of 1296. agent-stale-copies (webkit ja 980,
  #1949) and claude-subagent-tag (webkit ja 1100, filed #5040) timed out
  under load; at d85b4e49b both files and claude-statusline.test.cjs
  (en, zh, zh-TW, ja, de at 900 and 400 wide) alone: 130 of 130.
- at d85b4e49b (the fixes above): go test ./internal/agent ok;
  TestCoreScriptBudget ok.
- rebased on f37742e14 (a key's spend cap took the core to 21 bytes
  under its budget; this change's 207 bytes are paid for by foldSame's
  comment cut, no raise), at the pushed head: go test ./internal/agent
  ok (318s); TestCoreScriptBudget ok (1,533,597 of 1,533,802);
  claude-statusline, i18n-keys and claude-effort GUI files, both
  engines: 46 of 46.
- gofmt -l clean.

Broken by hand, each red then restored:
- the user's-own guard off: TestClaudeStatusLineLeavesTheUsers
- the Unwire call taken out: TestClaudeStatusLineGoesOnDisconnect
- the file wiped before the write: TestClaudeStatusLineUnreadable
- the compound check off: TestClaudeStatusCommand
- the WSL asleep case off: TestWSLClaudeNoStatusLine
- the here check after the read: TestWSLColdPlaceOpensNothing
- the statusline entry out of TOGGLES: claude-statusline 15/15 red

Not tried: a real Claude Code session showing it (and its hot
reload); Windows Git Bash and PowerShell with a real path; the Linux
AppImage path; WSL is not offered at all.
2026-11-03 16:03:14 +08:00
yetone e41ef6288c providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted
credits that other docker services spend from too, and they want magpie
to stop at a share of it. Their workaround was two magpies behind a
gateway-key limit.

What changed
- provider: KeySpendCaps on a provider, keyed by the key's fingerprint
  (key_spend.go): USD over a local calendar day, a local calendar month,
  or in all since it was set. Since is kept while the cap stays one in
  all. SetKeySpendCap and ParseSpendCap refuse an amount outside
  0 < usd <= 1,000,000 and an unknown period, and leave the saved cap
  as it was. Subscriptions are refused, since an account has its own
  usage-window cap.
- usage: KeySpent(keyID, start) is what magpie's own calls on the key
  cost at the Usage page's prices. Turned-away calls and app-reported
  ones are left out. It reads usage.jsonl once per key and start, keeps
  the sum for 5 minutes, and Append counts each new call into it
  (spentNew). A read that a write races is read again.
- gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap
  holds an account. The next key serves, then the fallbacks. With none,
  the reply is 429 "spend cap reached: ..." naming each key, what it
  spent of which cap, and how to go on. Retry-After is when the soonest
  period renews; a cap in all gives none. A spend hold is not a usage
  cap: Stop at the caps and strictKeep don't end at it (capHeldOnly).
  The trace's barred row carries the cap, the spend and the period.
- GUI: a pill on each key's row in the provider editor, for example
  "$7.50 of $20.00 today". It opens the app's menu (No spend cap,
  Per day..., Per month..., In all...) and then takes the amount in
  place, as the lane-limit pill does. A key at its cap gets a line
  under its row: "At its spend cap · back in ...". Every string is in
  all five languages. The pill and the line are in keyspend.js, which
  app.js imports when it draws a key's row, so the core's script
  budget is not raised. /api/providers' keyList carries spend, and
  POST provider/keyspendcap sets it.
- CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]]
  lists each key's spend and sets or removes a cap.
- docs: providers-accounts.md and gateway-routing.md.

Caveats, also in the tooltips:
- What counts is magpie's priced usage, not OpenAI's bill.
- A model with no known price counts $0.
- Requests already under way when the cap is reached still finish, so
  a key can go a little past it.

Run on mote at the pre-rebase head (3e3196222 + this change):
- go test -count=1 -timeout 45m for internal/provider, usage, cli, gui
  and gateway: provider, usage and gateway ok. Three reds, none from
  this change:
  - cli TestEveryRouteHasACommandOrIsNamed: GET /api/context/reply,
    red on main, #5026.
  - gui TestMainWindowCorners/macOS_26_SDK: macOS 27, #3949.
  - gui TestCoreScriptBudget: from this change. Fixed by moving the
    pill into keyspend.js, then ok on a rerun.
- go vet: plain, GOOS=linux -tags nogui and GOOS=windows -tags nogui,
  all clean. gofmt -l is clean.
- GUI, both engines: key-spend-cap.test.cjs passed 20 of 20 before
  the keyspend.js move, and all of its tests passed again after it.
  It covers en, zh, zh-TW, ja and de at 900 and 400px, a refused
  amount, the set, change and remove posts, and checks for no native
  select, no border stripe and no sideways scroll.
- Also run in both engines: i18n-keys, old-webkit, lane-limit,
  account-cap, key-row-chips-fit, key-weight-fit, key-nourl,
  provider-many-keys, key-switch, key-plan and key-rest-date.
  - key-replace's webkit 420px is red at base 3e3196222 too
    (#4126; base failed 2 of 3 en runs, this change 3 of 3).
  - key-rest-date's webkit zh-TW, ja and de tests time out at
    --test-concurrency=4 with three other files beside it, at base
    too (base 5 reds, this change 7). Run alone at concurrency 2, it
    passes 10 of 10 at base and with this change (#4691).

After the rebase onto 9c51f7fdb, at the pushed head:
- go build ./... and go vet on the five packages: clean.
- go test of the spend tests, TestCoreScriptBudget and the gui
  package's word tests: ok.
- i18n-keys and key-spend-cap in both engines: 24 of 24.

Broken by hand, each red and then restored:
- spentNew taken out of Append: TestKeySpentCountsTheKeysCalls red
  ("after a new call key a spent 3, want 7").
- spendHeld never barring: TestKeySpendCapPassesTheKeyOver red (the
  capped key reached the upstream).
- capHeldOnly keeping spend holds: TestKeySpendCapPassesTheKeyOver red
  (Stop at the caps answered 429 instead of using the fallback).

Not tried:
- a real OpenAI key or real spend;
- the real app window;
- Windows and Linux test runs (vet only);
- the whole GUI suite: mote was running two other sessions' full GUI
  suites at load 250 to 400.
2026-11-03 15:30:44 +08:00
yetone 6b81344301 library: the keep-here switch says sync, and is on while it syncs (bin.90)
bin.90 on Discord read the Library editor's 「只在这台电脑」 switch as a
LAN-sharing switch: "this computer only" says nothing about what it keeps
from where. It is about sync, so it now says so.

- Library editor (MCP servers, skills): the switch is "Sync to your other
  computers" (同步到其他电脑 / 同步到其他電腦 / ほかのコンピュータと同期 /
  Mit deinen anderen Computern synchronisieren), on while the server or
  skill syncs. Its note says off keeps it here, and a sync from the
  others neither removes it nor replaces it.
- The stored value keeps its meaning: `local` true is still kept here.
  The switch shows !local and saves !on, so every saved library.json,
  sync payload and CLI flag (`magpie library mcp local NAME on|off`)
  means what it meant.
- Row tag: "Not synced" (不同步 / 同步しない / Nicht synchronisiert) where
  it said "This computer only", in the Library, the TUI ("not synced ·")
  and `magpie library` output.
- Agents page sibling (the same words for an agent's picks): its menu
  item is "Don't sync picks to your other computers", its tag "Not
  synced". The agentsHere setting is unchanged.
- docs/subsystems/library.md and sync-backup.md name the new labels.

app.js stays in its budget: origin/main 8af751987 was already 31 bytes
over coreScriptBudget (1,533,833 > 1,533,802), so a comment in
setAgentHidden was cut to one line (core 1,533,756 now), no raise.

Run on mote, rebased on 8af751987, budget again at 2cfeda3d3:
- GUI: mcp-local-server, agent-here, i18n-keys, skill-off-here: 78/78
  before the rebase, in Chromium and WebKit, every language, at 390, 640
  and 1100 wide and in the panel; after it agent-here, i18n-keys and
  mcp-local-server 56/56, agent-here again 30/30 after the trim.
- go test ./internal/tui ./internal/cli ok; ./internal/gui ok except
  TestMainWindowCorners/macOS_26_SDK, mote's macOS 27 (#3949, open,
  the same without this change); TestCoreScriptBudget ok after the trim.
- go vet ./internal/tui ./internal/cli ./internal/gui; GOOS=linux go vet
  -tags nogui and GOOS=windows go vet of tui and cli; gofmt -l clean.

Broken by hand: saving `d.local = on` (no negation) turns
mcp-local-server red (expected 'false', got 'true').

Not tried: a real sync between two computers with the switch flipped;
the stored value's meaning is checked through the saved request only.
2026-11-03 12:21:49 +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
yetone 1851ead1a7 library: Pi and omp lock ~/.agents/skills from their versions; Put skills in links every skill there
usrname1833 on Discord asked for two things.

Pi reads ~/.agents/skills itself, so a skill kept there is Pi's whatever
is ticked, with the lock as Codex and OpenCode have. Pi started to in
0.54.0, not 0.19 (its CHANGELOG; userAgentsSkillsDir in
package-manager.js), and omp in 11.0.0 (src/discovery/agents.ts; 10.6.2
doesn't). Target.SharedToo says so from the version, and every reader of
readsShared goes through Target.readsSharedDir: Always (the lock),
syncSkills' inShared (no second link) and a handover's readsSharedHere.
OmO's senpi reads it in every npm version (0.74.0 up), so omo joins
readsShared. A Pi or omp of no known version is taken as older, as
before.

The second ask is a switch: Library > Skills > "Put skills in": each
agent's own folder (the default, today's behaviour) or ~/.agents/skills
(Library.SharedSkills; POST /api/library/skills/where {how};
magpie library skill where agents|shared). On, every library skill on
here gets magpie's link in ~/.agents/skills (syncShared, after
sweepShared), so every agent and tool reading that folder has it and
shows it locked. The files stay in the library rather than moving, so
updates, edit tracking and Off here keep working; existing skills just
get links when it is turned on, nothing is moved. A user's own entry by
the same name is never written over. Off takes out magpie's links there
and nothing else, and agents' own links come back. Per computer:
Collect doesn't carry it. docs/subsystems/library.md says all this.

Not covered, filed: on Windows without link rights the shared entry is
a marked copy, and takeEdits doesn't take edits made in it (#4958).

Run on mote rebased on d76c4b23a (which has 8abdf53a8):
gofmt -l clean; go vet GOOS=linux and GOOS=windows on internal/library,
internal/gui, internal/cli ok; go test internal/library, internal/gui,
internal/cli ok. GUI, every skill-*, library-* and i18n-keys file in
chromium and webkit: 1302 pass, 4 fail, all in library-all (webkit) and
library-null-agents (chromium). Both pass alone at this tree (52/52), so
they are load reds, filed as #4967. skill-where.test.cjs (new) covers en,
zh, zh-TW, ja, de at 900px and 400px. Before the rebase, cli's
TestEveryRouteHasACommandOrIsNamed was red on /api/usage/checkin-account
(not this change); it is green at this base.

Rebased twice more on origin/main (cli's settings_parity_test, app.js,
i18n.js, settings): internal/cli and internal/gui go test ok, i18n-keys
and skill-where green at the pushed tree.

Broken by hand, each red, then restored: since() always false
(TestPiReadsSharedSkillsFromItsVersion, TestSkillsWhereShared red);
syncShared step dropped (red); sweepShared's keepsShared keep dropped
(red on the SameFile no-relink check); the holder line in wanted
(TestSkillsWhereSharedWithKimi red); skillWhereBar not appended
(skill-where 0/11 per engine).

Not tried: a real Pi, omp or OmO run (versions read from their npm
source); the setting on the Windows box or in WSL; the whole GUI suite.
2026-11-03 05:43:12 +08:00
yetone f3681b90c3 gui: the Agents page says a model's load by the picked model and in its picker (axelburks on Discord)
axelburks (Discord #feedback) could see a model's load only on its
provider's page, too deep to judge which model to pick on the Agents
page. A plugin's reported load (magpie.load) now shows there too, as the
same quiet grey badge the provider page uses:

- by the picked model in each agent's model row, before the chevron;
- on each row of that row's model picker, after the speed.

GET /api/model-loads (speeds.go) answers every fresh load (LoadFresh,
5 minutes) by "provider/model" lowercased, the ref /api/model-speeds
uses: plugin.FreshLoads copies the fresh entries under one lock, and
provider.ModelLoads keys them by magpie's provider id, the user's own
listed id too (ModelIDs), with model@size falling back to its model as
ModelLoad does. With no plugin reporting it is one lock and an empty
map. The page reads it when a model picker opens and with the Agents
page's 15s drift check, each throttled to once per 30s, and the drift
read only while a row shows a magpie model. No new poll; /api/state and
Option are unchanged. The core script stays under its budget
(1,533,802) by shortening comments in the picker and agent-row code;
no budget raised. The
route is named in the CLI's route list (read-only, U) like model-speeds.

Run at this head (rebased on origin/main b4073c06a; the rebase onto
dcc84dbc0 touches none of these files), on mote:
- go test ./internal/gui (TestModelLoadsByRef, TestModelLoadsNoneReported,
  budgets) ./internal/plugin ./internal/provider ./internal/cli: ok,
  except TestEveryRouteHasACommandOrIsNamed's POST
  /api/usage/checkin-account, red on main (#4826, e87140242).
- Full go test ./... -timeout 45m before the rebase: 84 packages ok;
  reds were TestEveryRouteHasACommandOrIsNamed (this route, now named,
  and #4826), TestCodexPoolSaysTheClientsVersion (#4807, full-package
  run only) and TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27).
- go vet for darwin, GOOS=linux -tags nogui and GOOS=windows on
  plugin, provider, gui, cli: ok. gofmt -l: clean.
- agent-model-load.test.cjs: chromium and webkit, 1000 and 440px, en,
  zh, zh-TW, ja, de: 40 of 40. Screenshots looked at in both engines.
- Whole GUI suite: not finished. Three whole-suite runs (WSL, mote) were
  cut at 1,266 and 642 tests by load and a session restart; their reds
  were all in provider-editor, Settings and Usage files. Then the files
  a new API call or the Agents row can reach (183: every agent-*, every
  model/picker/speed/load file, the five strict-fixture files, every
  file using .field, ag-open, renderAgents or /api/drift, i18n-keys),
  split mote/WSL, both engines: reds only in model-chip-steady (#4388),
  mobile-web (#3952), model-copy-id (#4621), balance-fix (#4683),
  allow-ips (#4357, output added), agent-update-all (#2988), account-eye
  (#4244), models-works-only, models-select-all-api, model-suffix-own,
  provider-detect-models, provider-models-rest, remote-magpie,
  routing-rule-models, usage-speed (WebKit on WSL, #4218/#4471). Each red
  file was run alone at this head and at origin/main b4073c06a: the same
  reds both sides, except agent-update-all's fixed 200ms wait (#2988),
  red once at the head. codex-subagent-model, red under load, passed
  alone.

Broken by hand, each red, then restored: the picker row's badge line,
fieldBtn's badge line (red at the renderAgents redraw check), the
readLoads painter, and ModelLoads' listed-id loop (TestModelLoadsByRef).

Not tried: a real plugin reporting load in the live app; the tray panel
layout; WebKitGTK in the real Linux app and the Windows app.
2026-11-03 05:21:47 +08:00
yetone 8abdf53a88 cli: Check in now for one account is named in notYet, beside the per-vendor check-ins (#4826)
TestEveryRouteHasACommandOrIsNamed was red on main since e87140242 added
POST /api/usage/checkin-account (Settings' Check in now for one account)
with neither a command in cliForRoute nor a notYet entry. No command
checks in a single account: `magpie accounts checkin` checks in every
account, and the per-vendor routes it covers (minimax-, plugin-, qoder-,
trae-checkin) are already in notYet under stage 3, so this one joins them.

Run at dfd3b720b (origin/main) on mote: go test -tags nogui -count=1
./internal/cli/ ok (100.6s). Without this line the test fails with
"POST /api/usage/checkin-account has no command" (the red on main, #4826).
gofmt -l internal/cli clean. Not tried: nothing outside internal/cli; the
change is a test-only map entry.
2026-11-03 02:44:33 +08:00
yetone 2ab9235711 agents: an agent's picks can be kept to this computer, as an MCP server can
chenxiang0010 on Discord: 「agent当前选择的模型可不可以像mcp那样 只对当前设备生效」.
Sync carries every agent's picks (model, effort...) between computers;
an MCP server has an opt-in "This computer only" that sync and backup
files never carry. Agents now have the same: the row's menu (right-click
or ...) has This computer only, off by default, so an upgrade changes no
pick on any computer.

- settings: AgentsHere, this computer's own (KeepOwn), and kept by a save
  of the Settings page (settingsapi.Apply), which doesn't send it.
- davsync: each kept agent adds "<id>.*" to the own set (withHere, isOwn),
  so a sync neither pushes its fields nor brings the server's; a Restore
  from the server leaves them. sync-state.json records the list as of the
  last sync (Here): hashes before a sync use it and after use the current
  list, so turning it on or off is no change on either side, and a changed
  list forces the sync past its early returns. Turned off, the next pick
  goes up again. Other agents still sync both ways; the implicit own
  fields (hayden4608) are unchanged.
- backup.Restore skips a kept agent in a backup file.
- gui: POST /api/agents/here; the row says "This computer only" beside
  the version (hidden in the tray panel and in a narrow row), menu ticks.
  Core words moved from the library plugin's i18n into core i18n
  (zh/zh-TW/ja/de). Comments in renderAgents cut to pay for it under the
  core budget (no raise).
- cli: the route is named under stage 3 (no command yet).
- docs/subsystems/sync-backup.md describes it.

Run on mote, at the base eb8b840dd (Go and the GUI files below) and again
at this head's base for internal/gui (core budget) and agent-here,
i18n-keys, agent-menu-label:
- go test -tags nogui ./internal/davsync ./internal/settings
  ./internal/backup ./internal/gui ./internal/settingsapi: ok
- go test ./internal/cli: ok but TestEveryRouteHasACommandOrIsNamed,
  red on main for POST /api/usage/checkin-account alone (#4826)
- GOOS=linux and GOOS=windows go vet ./...: ok; gofmt -l: clean
- GUI, chromium + webkit: agent-here (en/zh/zh-TW/ja/de x 1100/640/360),
  i18n-keys, sync-own-fields, mcp-local-server, agent-menu-label:
  90/90 ok
- the whole GUI suite: cut off at test 3783 by a session restart; the
  rest (key-* on) is still running at push. Reds seen so far, under
  three GUI suites at once on mote, none in an agent file: account-eye,
  balance-fix (Sub2API, /api/user/self), codex-auto-reset, context-map,
  editor-advanced-align; being checked at main and filed there.

Broken by hand, each red then restored:
- hereOf returns nil: TestAgentHereThroughSync "B's kept picks went up"
- backup.Restore's kept skip off: "B after a backup file"
- KeepOwn line dropped: TestAgentsHereIsThisComputers "another
  computer's kept agents came in"
- TestSettingsSaveKeepsWhatItDoesNotSend went red on this change before
  settingsapi kept AgentsHere (a Settings save would have dropped it).

Not tried: a real two-computer sync with real accounts; no CLI/TUI
command for the flag; Settings -> Sync doesn't list kept agents; WSL
agent ids (codex@wsl:...) only through the key format.
2026-11-03 02:27:20 +08:00
yetone c47fc516a4 provider: Tencent Cloud's Token Plan is at tokenhub.tencentmaas.com/plan (ysm119)
ysm119 (Discord) showed Tencent's docs: Token Plan's OpenAI base is now
https://tokenhub.tencentmaas.com/plan/v3 and the Anthropic one on
tokenhub.tencentmaas.com is the recommended one, with
api.lkeap.cloud.tencent.com marked as going away.

Tencent's current pages (product/1823/130060 个人版 overview, 130070
Claude Code, 130071 Codex, 130119 quickstart, 136601 CC Switch, all
updated 10-15 to 10-22) give 个人版 the same endpoints as 企业版 China
(130659): chat/responses at https://tokenhub.tencentmaas.com/plan/v3,
messages at https://tokenhub.tencentmaas.com/plan/anthropic, one sk-tp-
key for 通用 and Hy plans.

- The tencent-cloud preset's plan region (and the preset default) are
  at those endpoints, with Responses added (Codex's page uses
  wire_api "responses"). magpie tells regions apart by endpoint, so the
  personal and China enterprise regions, now one address, are one:
  "plan", models the union of both lists. "enterprise" stays an alias
  (regionAliases, RegionID): a key saved on it, an import link with
  region=enterprise and `region=enterprise` on the CLI land on plan.
  Singapore 企业版 (enterprise-intl) is unchanged.
- A Tencent Cloud provider saved at the old lkeap /plan/v3 or
  /plan/anthropic is moved to TokenHub at load (moveEndpoints in
  normalize), and gains the Responses endpoint when it had chat. A
  Responses address the user set stays. A provider of no preset (a
  custom one the user typed lkeap into) keeps its address: that is the
  user's value, and lkeap still answers today.
- An app config still at lkeap (Tencent's OpenClaw page, 130062, still
  gives it) imports as tencent-cloud at the new endpoints.
- Usage: DescribeTokenPlan is 企业版's API (api/1823/132270 lists
  enterprise products only), and Guangzhou's endpoint now serves
  个人版 too, so a Guangzhou provider with no SecretId no longer gets the
  card asking for one (tcSharedRegion); Singapore's still does. The
  editor shows the optional SecretId/SecretKey at the plan region, so a
  personal user sees them too.
- docs/subsystems/providers-accounts.md says all of this.

Run at the pushed head's base f3551387c on mote (rebased onto
d29f02d65, which only touches internal/agent's omp; provider and cli
re-run after the rebase):
- go test -timeout 45m ./...: every package ok except three filed reds
  that touch nothing here: cli TestEveryRouteHasACommandOrIsNamed
  (#4826), gateway TestCodexPoolSaysTheClientsVersion (#4807), gui
  TestMainWindowCorners/macOS_26_SDK on macOS 27 (#3949).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. gofmt -l: nothing.
- GUI tencent-cloud, tencent-access-key, i18n-keys (chromium+webkit,
  en/zh): 24 pass, 4 fail, all "a region clicked right after the strip
  scrolled" (#4321/#4399/#4625; app.js is unchanged here).

Broken by hand, each red then green again:
- normalize without moveEndpoints: TestTencentCloudOldPresetsKeepWorking
  and TestTencentPlanMovedFromLkeap fail.
- the import's movedEndpoints lookup: TestTencentPlanMovedFromLkeap.
- the Guangzhou card skip: TestPlanCardWithoutAccessKey.
- RegionID in ParseImport: TestTencentPlanMovedFromLkeap; in the CLI:
  TestTencentOldRegionAtCLI.

Not tried: no real Tencent key here, so no request reached either host
and no real usage read. Tencent's international personal plan (CodeBuddy
page tencentcloud.com/document/product/1300/81035) is at
tokenhub-intl.tencentcloudmaas.com, a host magpie has no region for; not
added. The 即将下线 label in ysm119's screenshot is not on the pages
fetched, and no retirement date was found (FAQ 130076). The site's
import-link builder still offers "Enterprise plan · China", which now
adds the plan through the alias.
2026-11-02 21:41:56 +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 4dfdd0cd63 provider: a provider switched off is asked for nothing, its plugin's model list included
ChangQiu on Discord switched a provider off long ago, and magpie still
reached it. Routing, fallback, usage and balance reads, warmups,
check-ins and keepalive were already held back (On(), leftAlone,
KeepListsFresh). These were not:

- The plugin host's providers listing ran every plugin's models hook,
  which asks the vendor, and its sign-in renewal (fresh), for every
  plugin provider, on or off. Go now passes the ids switched off
  (plugin.ListingOff, provider.pluginsOff: the provider's id and the
  plugin's own id, read from providers.json alone). host.js lists such
  an id without running a hook (info(..., quiet)), so its row stays and
  keepListed keeps the last list.
- Sync (POST /api/sync, `magpie sync`) fetched every ready provider's
  list. Both now go through provider.RefreshLists, which skips one
  switched off.
- Saving or switching on in the GUI fetched the list even for one left
  off; PrefillNewKeys asked one switched off too.

What still asks one switched off, by the user's own click: the TUI's
refetch, the provider Test button and `magpie provider models <id>`
refetch.

Tests: TestOffPluginProviderAskedNoModels (the fake plugin's models
endpoint counts its hits: 0 while off, the list kept, asked again once
switched on), TestPrefillAsksNoProviderSwitchedOff,
TestPluginsOffNamesThePluginsOwnIDs and
TestRefreshListsAsksNoProviderSwitchedOff.

Run on mote at this head (first at a4916aec1):
- go test -timeout 45m ./internal/provider ./internal/plugin
  ./internal/gui ./internal/cli ./internal/tui ./internal/gateway:
  provider, plugin and tui ok. Three reds, each also red on origin/main
  and filed: gui TestMainWindowCorners/macOS_26_SDK (#3949), cli
  TestEveryRouteHasACommandOrIsNamed (#4826), gateway
  TestCodexPoolSaysTheClientsVersion (#4807).
- After rebasing on ce2e81da1: provider and plugin again, plus darwin
  vet of the four packages. One provider run went red on
  TestClaudeAccountServesModelsListedSinceItsFetch (#3174, full-run
  only). It is green alone 3/3 on this head and on origin/main, and the
  next full provider run was ok on both.
- GOOS=windows go vet of plugin, provider, cli and gui: clean.
  gofmt -l: clean. Linux go vet (WSL magpie-desktop) of plugin and
  provider: clean. cli and gui can't be vetted there: the distro has no
  gtk4/webkitgtk-6.0 headers for wails' cgo.
Broken by hand: with each guard taken out, its test went red ("switched
off, the vendor was asked 2 times", "the vendor asked 2 times",
"pluginsOff = [fakeco onco openai openai-plugin]", "the provider
switched off was asked 1 times").
Not tried: a real plugin provider switched off in the app. Which
provider ChangQiu had switched off isn't known, so his exact case is
not reproduced.
2026-11-02 14:30:45 +08:00
ggbdpq 339ff564e6 fix(gateway): skip a nested group's effort classifier when the group above picked (#4358)
A group reached through a parent group runs its own classifier when it is
effort=auto, even after the parent's classifier already picked the turn's
reasoning: the request goes out at the parent's pick (the outermost pick
stands, gateway.go), so the group in it pays for an answer the turn throws
away. On one reporter's day the group in it answered 27 of 28 such turns,
2-8 s each, and 14 of the 28 parent picks discarded the answer.

ruleFor now takes the pick a group above it already made: with one standing,
the classifier is not asked for the effort again. The intents, when the
group's rules have them, are still asked — they are the group's own routing.
The trace says why nothing was asked. The fallback keeps working: the group
in it is asked as before whenever the group above gave no pick.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-02 07:40:21 +08:00
ggbdpq 3b7fe8e5f3 fix(cli): visible <agent> all clears the models taken out and the only-picked switch
What changed: `magpie visible <agent> all` took only the visibility
narrowing out, leaving HiddenModels and PickedModels in place. An agent
shown none of them — shown only the models picked for it with none picked,
then switched to --show-new, which keeps what it is shown by taking the
rest out — stayed none through `all`, the very recovery `magpie models`
and the gateway's refusal to name a model point at; only deleting
hiddenModels.<agent> from settings.json brought the models back (#4587, a
DSH behind a Docker gateway saw an empty model list; #3432, closed as not
planned, the same for an only-picked agent). `all` now takes the hidden
models and the only-picked switch out together with the narrowing, and its
usage line says so.

Run: go test ./internal/cli/ -run 'TestVisibleAll' -tags nogui — two new
tests fail before the change and pass after it.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-02 05:38:10 +08:00
yetone d89f03aa92 settings: trayNoNumber is a key magpie settings sets, and GET /api/quit is the window's own (#4793, #4794)
da275848b saved trayNoNumber without naming it in settingsapi.Keys, and
8826a15ea added GET /api/quit without naming it in the CLI parity table,
so TestKeysAreWhatTheSaveWrites, TestSettingsCLISetsWhatTheWindowSaves
and TestEveryRouteHasACommandOrIsNamed have been red on main since.
/api/quit only reads which agents the window's Quit question names, so
it is the window's own (W), with nothing to do in a terminal.

Run at a8e98e1ab plus this, on mote: go test -tags nogui -count=1
./internal/settingsapi ./internal/cli ./internal/settings: ok. The same
three tests were red at 6b3a6d42c without it.
2026-11-02 04:51:42 +08:00
yetone ec104b8625 gateway: a Codex account can spend its credits before magpie moves to another account (jojonas_xyz on X)
jojonas_xyz on X: "我账号额度用完了自动给我切了别的号…找不到怎么关掉设置…你怎么知道
我不是想用 credits 呢". (Roughly: "my account ran out of quota and magpie
switched me to another account by itself; I can't find a setting to turn
that off; how do you know I didn't want to use the credits?")

Cause. At 90% or 98% of a window, smart routing's tier put the account
behind every account that still had room, whether or not it had ChatGPT
credits. Codex's own sign-in (NextLogin / SwitchWhenSpent) moved at the
spent share in the same way. The account's credits were spent only once
every other account was used up, and the switch was a log line. The Use
credits switches that existed (on, and "Only after other accounts" from
699ddf152) were only on the Usage page and the panel. None of them meant
"stay on this account and spend its credits".

Change.
- A fourth credits mode, first: settings.CodexCreditsFirst. on, first,
  last and off are exclusive; one mode replaces another.
- routes.Seat.First: a first seat's tier is 0, so routing keeps it in
  front past its windows while it has credits. The trace records
  Weighed.CreditsFirst.
- NextLogin keeps Codex's own sign-in on such an account (spendsFirst).
- The POST /api/codex-credits handler takes "first". The general
  settings save keeps the stored value.
- The CLI: `magpie quota credits <account> first`.
- GUI. No new page and no new component, only the Use credits row that
  already exists:
  - 供应商 → Codex → 账号 ⋯ → 使用积分 → 「先用完积分再换账号」. The
    Providers ⋯ tools now carry the credits row too, which is where the
    reporter looked.
  - 用量 → Codex 账号卡 → 使用积分 → 「先用完积分再换账号」.
  - The menu-bar panel's folded line reads 「开,先于其他账号」.
  - The "First again once it has room" tag on a moved-off account now
    points to the switch in its title.
  - Strings are in en, zh, zh-TW, ja and de.
- "Only after other accounts" (gokoshiki, 699ddf152) is unchanged.
  Its off title now says what off means.
- Docs: docs/reference.md and docs/subsystems/gateway-routing.md.

Budgets: at this head app.js is 1,312,105 of 1,316,874 bytes, and
TestCoreScriptBudget passes (231 bytes under before the rebase). Comments
were condensed; no budget was raised.

Run on mote, at this tree (rebased on origin/main 9d08993c8; the rebase
moved the settings save into internal/settingsapi, which now carries
CodexCreditsFirst beside CodexCreditsLast):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider
  ./internal/routes ./internal/settings ./internal/settingsapi
  ./internal/gui ./internal/cli at 9d08993c8+1: gateway, provider,
  routes, settings and settingsapi ok. Two reds, both filed:
  - internal/gui TestMainWindowCorners/macOS_26_SDK: #3949.
  - internal/cli TestLibraryMCPHub, TempDir cleanup not empty: #4140.
  At the pre-rebase tree (da0005df8+1) internal/gui also had
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestColdTurnsTaken
  (#4510), red the same at da0005df8; both pass at this head.
- New tests:
  - internal/provider/codex_credits_first_test.go
  - internal/gateway/codex_credits_first_test.go (routing and the trace)
  - internal/gui/codex_credits_first_test.go (POST sequence, sandbox HOME)
  - internal/gui/tests/codex-credits-first.test.cjs: the Usage page and
    Providers ⋯ at 900 and 440px, and the panel at 360px; chromium and
    webkit, en zh zh-TW ja de. It also checks for no select, no stripe,
    the i18n keys, and that a click does not move the page.
- The whole GUI suite (make test-ui), at da0005df8+1 on mote at load
  66 to 213, in two parts (a wiped scratchpad cut the first log; its red
  titles were kept): 59 files with a red. 45 of them are red at
  origin/main da0005df8 too, each under an open issue: #4304 (mote
  umbrella), #4600, #4471, #4120, #4119, #4621, and per file balance-fix
  #4682/#4683, gui-ja #4580, page-width-steady #4541, phone-connect-menu
  #4706/#4707, quota-curve #4768, segs-press-redraw #4566, signin-proxy
  #4643/#1814, zhipu-team #4728, model-copy-id #4621 (red 4 of 4 on main).
- The 14 green at da0005df8 were run again at this tree. One was this
  change's: usage-curve-zoom-back. The Codex card's fourth credits line
  (366px, was 344) held the DeepSeek card beside it to 261px, so the
  "card grows" check at 1100px had no room. Its fixture now turns the
  Codex account's credits off, since the count of credits lines isn't
  what it tests; 20 of 20 pass.
- At this head (9d08993c8+1), on mote at load 75 to 84: codex-credits-first,
  codex-credits-last, codex-credits, routing-codex-credits-again,
  panel-options-fold, usage-curve-zoom-back, i18n-keys and the 13 files
  above: 232 tests, 227 pass. Each red has an open issue:
  - models-fold webkit en/zh, "ebody holds" after the click: #4071; red
    the same at 9d08993c8 (run there).
  - account-weight webkit, same "ebody holds": #4644 (red at
    da0005df8+1, green in this run).
  - routing-many-keys chromium de "2 keys in sight at the foot": #4082
    (under load; red again alone here, green at 9d08993c8 in one run).
  - signin-closes-sheet chromium en/zh: #2628 (green alone at this head
    in a second run).
  - signin-again and signin-port-blocked, red once at da0005df8+1 under
    load, pass at this head and at 9d08993c8.

- Rebased last onto 94f6f6092 (three commits; c0477aa72 changes the
  Codex Providers row): go test -run 'Budget|CodexCredits|SettingsSave'
  ./internal/gui ok, and codex-credits-first, codex-credits,
  codex-credits-last, providers-reset-use, i18n-keys and
  usage-curve-zoom-back: 92 of 92 pass.

Broken by hand, each red, then restored:
- spendsFirst forced false: the provider test is red.
- The gateway's l.first forced false: both gateway tests are red.
- codex-credits-first.test.cjs against origin/main's assets: red
  (TimeoutError on the switch).

Not tried:
- No real ChatGPT account with credits went past its window. The routing
  order and NextLogin are tested on fakes only.
- The Linux and Windows apps were not run.

go vet -tags nogui ./... with GOOS darwin, linux and windows on mote:
clean (cgo enum warnings only). gofmt -l on the changed Go files: clean.

Claude has no equivalent: magpie reads no extra_usage and has no Use
credits modes for Claude. Filed as #4662 (see #4241).
2026-11-01 21:19:22 +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 e42ee3b816 library: Magpie Browser's extension sits in ~/Magpie Browser Extension, dragged from the sheet onto chrome://extensions
The owner, on the v0.1.2442 sheet: the extension was written to
~/.config/magpie/browser-extension, a hidden folder no one can find to
choose in Load unpacked.

- Set up writes it to "Magpie Browser Extension" in the home folder
  (browserExtDir), where Finder and Explorer show it, and shows it
  selected in its parent (open -R on the Mac, explorer /select, on
  Windows, the home folder on Linux) rather than opened, to drag from.
- On the Mac the sheet has the folder itself: a press on it that moves
  hands the folder to the system's drag (POST /api/library/browser/drag,
  filedrag_darwin.go: beginDraggingSession from the key window with a
  file URL and the folder's icon, only while the button is still down),
  so it drops onto chrome://extensions as from Finder. Chromium's
  extensions page loads a dropped folder as unpacked
  (drag_and_drop_handler.ts: entry.isDirectory -> loadUnpackedFromDrag),
  with Developer mode on, which step 2 asks for.
- Elsewhere step 3 says to drag the folder from the window that opened,
  or Load unpacked and choose it.
- Old installs: a browser that loaded the hidden folder still does, and
  that folder is kept up to date as long as it has a manifest; the sheet
  offers set up again, into the new folder.

Run at ace58117a on mote: go vet ./internal/gui (darwin), GOOS=linux -tags
nogui and GOOS=windows vet; library-browser-setup and i18n-keys GUI
tests, 46 of 46 (5 languages, Chromium and WebKit, 1100 and 420 wide,
with and without the drag: a click posts no drag, a press that moves
posts one); internal/cli parity tests ok. At df0320156: go test
./internal/gui ./internal/cli, cli ok, gui red only in
TestMainWindowCorners, which is #3949 and red the same at df0320156
without this change.
Not tried: the native drag by hand into a real Chrome (no way to drive
a mouse drag here), and Explorer's /select on the Windows box.
2026-11-01 17:28:15 +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 5d63b3f995 accounts: a Claude import never writes an older sign-in over a newer one (#4532)
Importing a claude-swap export of the account Claude Code was signed in
to wrote the file's sign-in over Claude Code's own (addLogin, using).
cswap exports what it saved when it last switched; Claude Code has
refreshed since, each refresh spending the refresh token before it, so
the file's was spent and Claude Code was signed out. A saved account was
replaced the same way. Only an identical refresh token was caught.

Now a Claude sign-in for an account magpie already has (Claude Code's
own, or a saved one that can still be used) with another refresh token
is taken only when the file's expiresAt is later than what magpie has,
the account's own config directory counted (claudeNewerKept). Otherwise
it is "exists" with why, nothing written. cswapEntry and loginEntry read
claudeAiOauth.expiresAt. The CLI prints the reason.

Run (mote, -tags nogui):
- TestImportCswapKeepsNewerSignIn: older-than-live, undated, newer-than-
  live, older-than-saved. Red with the check turned off by hand (three
  subtests: updated over live / saved), green with it.
- go test ./internal/provider -run 'TestImport|Login' ok.
- go vet ./internal/provider ./internal/cli on darwin, linux, windows;
  gofmt clean.

Not tried: a real cswap export against a real Claude Code sign-in. A
sign-in that was itself imported and never run is saved with expiresAt 1
(so Claude Code refreshes it first), so any dated file still replaces it.
2026-11-01 15:07:37 +08:00
yetone c688211d13 gateway: a ChatGPT (Codex) account gets loaded tools where they were loaded, keeping its cache (#4738)
infinitex233 (#4738, Discord): Claude Code -> magpie -> a Codex account,
and every ToolSearch load dropped cache_read to 0. loadsInPlace sent the
additional_tools item (#2660) only to OpenAI's own API, so for an
account the loaded tool went into the top-level tools and the cached
prefix broke at the tools.

Tried on the real ChatGPT backend first (owner's account, sandbox HOME
on mote with a copied auth.json whose refresh_token was replaced, so the
live token was never rotated; ~/.codex untouched). A probe client sent
Claude Code's shape: ToolSearch with two deferred mcp tools, then the
tool_reference result, then the calls, 4 requests per run.
- additional_tools item (on, and this commit's default): request 2..4
  read 7680-8320 tokens from cache on gpt-5.6-terra, gpt-6-luna and
  gpt-6-sol; the model called read_a and read_b from the item; no
  "turned away additional_tools" in the log.
- tools top-level (off): request 2 and 3 read 0 from cache (8044 and
  8163 tokens in), as the reporter saw.
So the backend takes it, and this makes it the default for a ChatGPT
account (p.Account.Agent == "codex"). Copilot and other sign-ins stay
off: not tried.

- loadsInPlace: AdditionalToolsOff wins, then AdditionalTools, then an
  account is in only if it's Codex's, then OpenAI's API as before.
- `magpie provider set <id> additional-tools=on|off|default`: off is new
  (AdditionalToolsOff, kept through an account's Save by accountSettings
  and through the GUI editor's save like AdditionalTools). The old
  "off"/"no" meant default; now they turn it off where the default is on.
- The 400/422 fallback that names the item still applies, so a backend
  that stops taking it costs one retry and then sends tools top-level.
- No prompt, instructions or identity line changed.

Run (mote, at base 586b59fe7, this commit and the previous together):
- go test -count=1 -timeout 45m ./internal/provider ./internal/gateway
  ./internal/cli ./internal/gui: provider ok 248s, gateway ok 830s,
  cli ok 105s; gui FAIL on two filed reds that this doesn't touch:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, #4739) and
  TestMainWindowCorners/macOS_26_SDK on macOS 27 (#3949).
- Rebased on origin/main 9feb1024c, then again at this head: gofmt
  clean, vet darwin/linux/windows ok, provider ok 179s, cli ok 88s,
  gateway -run 'LoadsInPlace|LoadedTools|Codex|AdditionalTools|InPlace|
  Account' ok 99s, gui -run 'Provider|Settings|Account' red only on
  #4739. The whole gateway and gui packages ran at the base only.
- gofmt -l clean; go vet -tags nogui ./... for darwin, linux, windows ok.
- New TestCodexAccountLoadsInPlace (a fake ChatGPT backend through the
  gateway: the item with read_a, then tools top-level after
  additionalToolsOff in providers.json); TestLoadsInPlaceScope extended
  (Codex on, Codex off, OpenAI off, Copilot off by default and on when
  set); CLI test for off, on after off, default.
- Broken by hand: with the Codex default taken out of loadsInPlace,
  TestCodexAccountLoadsInPlace and TestLoadsInPlaceScope go red.
- GUI node suite not run: no JS changed; the Go editor save only keeps
  one more field, covered by the Go tests above.

Not tried: the reporter's own setup (Windows, gpt-6.1-terra), a real
Claude Code client (the probe sent its request shape), Copilot or any
other signed-in vendor with the item.
2026-11-01 14:59:44 +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 6f3dfc282f sessions: a scan's index is written at its end and on SIGTERM, not a minute later
A refresh's saves waited out saveGap (1 min) after the last one written,
the scan's checkpoints and its end too: the first checkpoint was written,
the rest waited. A magpie ended in that minute (quit, updated, `web` or
`serve` stopped by SIGTERM, whose handler died without sessions.Saved())
kept a few hundred of the files it read, and the next start read every
rollout again.

- A refresh that reads scanFiles (32) files or more is a scan: its
  checkpoints wait scanSaveGap (15 s) and its last save waits for nothing.
  A poll's few changed files still wait out saveGap. Saves folded into one
  take the shortest gap asked, and a shorter one wakes a waiting save.
- The signal handler writes the index before dying, bounded by
  saveOnSignal (5 s).

Real history in a sandbox HOME (11,994 Codex rollouts, 52.5 GB, plus
Claude projects; 17,140 files), index removed, `magpie web` killed by
SIGTERM ~44 s in (right after the first /api/sessions answered):
- v0.1.2521 tree: 1,200 entries kept (1,415 on a second try). Restart:
  /api/sessions 23.63 s, 1:38 of CPU.
- this change: 17,140 kept. Restart: /api/sessions 1.30 s, 3.4 s of CPU.

Tests, on mote: TestScanSavedWithoutTheGap and
TestSignalSavesTheSessionIndex are new. Broken by hand: with the scan's
gaps left at saveGap the first fails ("a scan's last save waited out
saveGap"); with the save call taken out of the handler the second fails
("died without the session index saved"). go test ./internal/sessions/
./internal/cli/ ok. gofmt -l clean; go vet (darwin), GOOS=windows go vet,
GOOS=linux go vet -tags nogui of both packages ok.

Not run: the full suite; the GUI app's own quit and update paths (they
return to main, which already called Saved); Windows and Linux runs.

Picked onto 0c3163804 (origin/main at push); not run again there.
2026-11-01 11:34:13 +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 699ddf1524 gateway: a Codex account can spend its credits only after every other account, key and fallback (gokoshiki on Discord)
gokoshiki wants a Codex subscription first, then an OpenAI API key, then
the subscription's credits. Until now an account at 100% that holds
credits either kept its place and spent them there (on) or was held
(off). This adds a third way per account, "last":

- settings: CodexCreditsLast []string, empty by default, so a setting
  saved before it keeps its order. provider.CodexCreditsLast,
  CodexCreditsMode and SetCodexCreditsMode(user, on|last|off);
  SetCodexCredits(on) still means "in its place" and clears last.
- gateway: candidate.creditsLast is true for such an account once a
  window for the model is used up and it is going on its credits (a
  call ChatGPT counts in no window stays in its place). restLast orders
  ready, then resting, then those, and marks Weighed.CreditsLast.
  restLast runs over the asides too, so such an account goes behind a
  provider's reserves (Accounts at once, 2c6b7c063) as well.
  lastBehind keeps In turn's next turn (after), a new conversation's
  spread (leastHeld) and a subagent's lead (readyForNew) from bringing
  it forward, and a kept conversation moves off it to one not on its
  credits (Affinity.Why "credits").
- CLI: magpie quota credits <account> [on|last|off]; alone it lists
  accounts set off and last.
- API: POST /api/settings/codex-credits takes {user, on, last?}.
- GUI: under a Codex account's Use credits, while on, a second switch
  "Only after every other account, key and fallback", in the Usage
  page's card and the tray panel's (both wrap it to its own line at 360
  to 900px), and the panel's folded brief says "On, after everything
  else". The Routing page's trace says why such an account is behind
  (aside, the kept conversation's why, the row tag). zh, zh-TW, ja, de.
  creditsButton and the new switch share creditsSwitch, and the Codex
  options' comments in app.js were cut, so the core budget holds with
  no raise (1,532,664 of 1,533,105).
- docs: reference.md (quota credits) and gateway-routing.md.

Tests:
- gateway: TestCodexCreditsLastAfterTheOthers (two accounts, In order:
  the one at 100% on its credits goes behind, the trace says so, and
  back in place when turned on), TestCodexCreditsLastAfterTheFallback
  (both accounts at 100% and set last: the API key the provider falls
  back to answers before either one's credits; with the credits in
  their place an account answers on them, as before),
  TestCodexCreditsLastNotKept (a kept conversation moves off it).
  All three red with creditsLast and lastBehind forced false.
- provider: TestCodexCreditsLastMode.
- gui: settings_keep_test carries CodexCreditsLast;
  tests/codex-credits-last.test.cjs (Chromium and WebKit, en zh zh-TW
  ja de; Usage at 900 and 440, the panel at 440 and 360, the folded
  brief, the Routing page's aside and why, every key in I18N). Red on
  the old assets (no .ar-credits-last).

Run at this change on origin/main c76bcaea7, on mote (pushed on fd70def82, whose
one commit since, fd70def82, changes only the Providers poll's Go
files in internal/gui):
gofmt clean; go vet of gateway, provider, gui, cli and settings ok;
their tests ok but internal/gui's #4514 and #3949, both on main. The
8 commits between d6aa9cdf6 and c76bcaea7 touch none of this
change's files.

Run at this change on origin/main d6aa9cdf6, Go 1.26.8:
- mote: gofmt -l clean; go vet ./..., and GOOS=linux and GOOS=windows
  go vet -tags nogui ./...: ok. go test -count=1 -timeout 45m ./...:
  85 packages ok; internal/gui red only on TestSettingsSaveKeepsWhatIt
  DoesNotSend's SearchAll (#4514), TestMainWindowCorners (#3949) and
  TestColdTurnsTaken (#4510), all three on main. TestCoreScriptBudget
  passes.
- WSL magpie-desktop, Playwright 1.62.0, both engines: codex-credits*,
  i18n-keys, gui-ja, gui-zh-tw, panel-options-fold, provider-at-once and
  every routing-* file: 2127 tests, 2064 pass. Every codex-credits and
  codex-credits-last test passed (26). The red files (gui-ja, 19 routing
  files) run again at this tree and at d6aa9cdf6, alike: 200 tests, 61
  and 57 red. gui-ja is #4580; the routing reds are timeouts and
  waits, on both. The one file red at this tree only,
  routing-request-model (WebKit 420px "the model is cut"), is 5 of 5
  green alone at both, and with six copies at once red at both (29 and
  27 of 30 here, 28 and 27 of 30 at d6aa9cdf6): a fixed 150ms wait
  after a resize, filed as #4650. Nothing this change adds to Routing
  draws unless an account is set last (fixtures don't).
- Earlier, at 3564eb04b (this change on 7428f3229), WSL: the whole GUI
  suite beside two other sessions' suites, 16944 tests, 16496 pass;
  its 102 red files again at that head and at 7428f3229, 444 and 425
  red. The files red at the head only, run alone: view-open-wheel,
  usage-accounts, add-button, usage-ledger-open-settled 0 red;
  view-wheel-after-click, view-wheel-unheard and context-map (#3488)
  red alone at 7428f3229 too. mote, the credits and i18n files: 172 of
  174, the two #4580 and a click timeout in quota-curve at load 148
  (alone 30 of 30).

Not tried: a real ChatGPT account at 100% with credits beside a real
OpenAI key; the order is shown with the gateway's fake Codex backend.
2026-11-01 09:08:07 +08:00
yetone 2c6b7c0632 gateway, provider, gui: Accounts at once keeps the first N accounts taking requests, the others in reserve
01huadalang on Discord (#feedback 1566170404542742740): three ZCode
accounts used at once from one address got the address refused with a
405; two were served. They asked for one account to be used until it
runs out, then the next. Even under "In order", ZCode's maxConcurrency 3
spilled a full lane onto the next account (laneMate) and rests spread
the load, so every account was in use at once.

A provider's MaxAccounts (the editor's Advanced → "Accounts at once",
beside Concurrency; `magpie provider at-once <id> [n|off|default]`) is
how many of its accounts or keys take requests at the same time.
provider.AtOnce() is the user's own value, else what its plugin
declares (maxAccounts on the auth hook or package.json magpie, read by
host.js atOnceOf), else no limit; the user's 0 is no limit over the
plugin's. perKeyBarred keeps the first N in the user's own order
(rank), preferring ones not resting, and keepAtOnce puts the rest after
everything as asides with candidate.reserve (Weighed.Reserve). So in any
routing mode a reserve is asked only once the kept ones failed or rest,
and a kept one that rests gives its seat to the first reserve next time.
Guards: laneMate never spills onto a reserve; a full queue (laneErr)
drops the provider's reserves (dropReserves) and turns the request away
with the 429; session affinity moves a conversation off a reserve once
the kept ones can take it (affine "reserve"; Strict still holds).
Routing says "in reserve · {n} at once" on the row and why in the
request's story. zcode 0.1.40 (plugins 26864ec, on npm) declares 2, and
its mover min is raised to 0.1.40 two commits on.

Known leak, in docs/subsystems/gateway-routing.md: a failure that rests
nobody (a 5xx on one try) still passes that one request to the reserve,
as it does to any next candidate.

Tests: TestAtOnceKeepsFirstInUserOrder (every routing mode, a dragged
order, a resting key handing over its seat), TestAtOnceFullLaneWaitsForTheKept,
TestAtOnceReserveTakesOverAndGivesBack, provider TestAtOnce, plugin
host maxAccounts (hook and package.json), gui TestAtOnceSave, cli
TestAtOnceCmd, provider-at-once.test.cjs (both engines, five languages,
900 and 360px).

Broken by hand, each red then restored: laneMate's reserve guard
removed (FullLane times out); affine's reserve case removed
(ReserveTakesOver answers on k3); keepAtOnce disabled (all three red);
dropReserves disabled (FullLane gets no reply); the Routing row's
reserve branch removed (provider-at-once's Routing test red in all 10
engine/language runs).

Core budget: the field adds ~530 bytes to app.js; the neighbouring
editor comments are cut to fit, so TestCoreScriptBudget passes with no
raise.

Run on mote, Go 1.26.8:
- full suite, -timeout 45m, at a7d4c662d (on origin/main e4384fc3c):
  gofmt and vet clean; every package ok but internal/gui, whose reds are
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
  (#3949) and TestColdTurnsTaken (#4510), each red on that main too, and
  TestCoreScriptBudget, fixed by the comment cut above.
- at this tree on bbdd9eb55 (the pushed head less 51f2f22ce and
  73b957069, gateway and provider): gofmt, go vet (darwin, and
  linux and windows with -tags nogui), and internal/gateway, provider,
  gui, cli, plugin and settings: all ok but internal/gui's
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
  (#3949), both red on main; TestCoreScriptBudget passes
- at the pushed head (on 51f2f22ce): go vet of gateway and provider,
  and -run AtOnce|Nameless|ModelAPI|Reserve|FullLane over gateway,
  provider, gui and cli: ok
GUI, Playwright 1.62.0, both engines:
- the whole suite on Linux (WSL) at an earlier head; every red file run
  again at head and at main on mote, the same reds on both (filed:
  #4641 is new, the rest open already, e.g. #4600, #4461, #4082, #4210).
- at a7d4c662d on WSL: every editor-*, provider-* file, i18n-keys,
  gui-ja and seven routing files, 1185 pass, 34 red; all but four red
  on main e4384fc3c too (#4580, #3292, #4394 to #4397, #4600). The four:
  routing-many-keys (#4082) is red on main in two of three reruns as
  well; provider-gemini webkit ja's thumb (#4210) was red in 2 of 3 runs at head beside
  other files (318px off), 0 of 3 at main; alone, 4 of 4 green at both.
  The test reads the thumb 350ms after a click, a fixed wait (#4210,
  numbers added there).
- provider-at-once.test.cjs: green in both engines, five languages, at
  900 and 360px; editor-advanced-align 20 of 20 alone with the next
  commit.

Not tried: real ZCode accounts (none used, per the task) and a real 405,
so whether two at once always stays under ZCode's limit is the
reporter's finding; the user can set 1.
2026-11-01 07:39:08 +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 323159f1cc usage: a Codex reset's confirmation picks which of the account's resets is used (01huadalang)
01huadalang on Discord: resets were used only automatically, or by hand
the one that runs out first. Which account was already the user's to pick
(each account's card has its own Use); which of its resets was not.

- Usage card's "Use a reset" and the menu bar panel's "Use one...": when
  the account holds two or more resets listed with their ids, the
  confirmation has a "Reset to use" pop-up (the app's menu, not <select>),
  soonest first and picked unless another is. Once another is picked it
  names the account and that reset ("The one used is me@'s reset that
  runs out ..."), and says the sooner one is kept and lost if unused.
  Escape closes the open menu first, not the confirmation.
- POST /api/usage/codex-reset takes an optional credit. The server reads
  the account's resets again and spends that credit only if it is still
  held; a gone one is refused and no other is spent in its place. With no
  credit it is as before (the soonest). Auto-use is unchanged.
- ResetCard carries the credit id; `magpie quota reset --card n` is the
  CLI's sibling, its prompt naming the reset.
- askReset's dialog moved out to resetask.js, imported when Use is
  pressed (like signsheets.js), so the core's scripts are 1,530,733 bytes,
  under the 1,533,105 budget with no raise (the pick alone took it 2,068
  over). Five keys in zh, zh-TW, ja, de.

Run on mote (mote-run), at the base 2597c9636:
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok.
- go test -tags nogui ./internal/provider ./internal/cli ok;
  ./internal/gui: only TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestColdTurnsTaken (#4510) red, both filed and the same on main;
  TestCoreScriptBudget ok after the move.
- GUI, Chromium and WebKit, 78/78 each: reset-pick-card (new: en, zh,
  zh-TW, ja, de; Usage at 900 and 390px, panel at 440px), codex-resets-used,
  account-every-reset, codex-reset-lead, reset-each-title, reset-providers,
  reset-reminder, panel-usage, old-webkit, i18n-keys, codex-auto-reset,
  codex-auto-reset-settings, warm-reset-asleep, quota-credits,
  usage-accounts.
- Red on the old code: reset-pick-card against origin/main's assets fails
  at "an account with three resets offers the pick"; TestUseCodexResetCard
  and TestCodexResetsCounted fail without the change.
- Broken by hand, each red then restored: the chosen credit ignored
  (spent [soon]); the held check skipped (a used credit spent); ids dropped
  from each; the credit left out of the POST; the Escape guard removed.

Again at the pushed head (rebased on 88372a39d): go vet ./... ok;
provider, cli ok; gui only #4514 red (TestColdTurnsTaken passed this
time); reset-pick-card, old-webkit, i18n-keys in Chromium 15/15.

Not run: the full go test ./... and the whole GUI suite. mote had two to
three other full Go suites and several whole GUI suites running the whole
time (load 120 to 250), and the WSL box too; one suite per machine.
Not tried: a real account's reset spent (none was, by design: fakes only),
so that Codex's consume takes a credit_id other than the soonest is
inferred from it being the same field the soonest is sent in.
2026-11-01 04:51:55 +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 0ac26fb52d update: a magpie a package manager installed leaves updating to it (shuhai on Discord, AUR magpie-bin)
shuhai (Arch) installs magpie from the AUR's magpie-bin, which puts the
desktop build at /usr/bin/magpie. magpie's own updater saw a folder it
can't write and pkexec on the machine, so it downloaded the release and,
on restart, replaced the package's file as root. pacman's database then
no longer matched the file, and the next `yay` upgrade (magpie-bin lags
the releases, 0.1.2342 against 0.1.2357 today) put an older magpie back.
The two updaters fought each other.

Now magpie asks first who owns the binary it runs from
(update.PackagedBy): pacman's local database, dpkg's .list files, rpm
(`rpm -qf`, only where /var/lib/rpm exists), a Homebrew Cellar path or
/nix/store. Only a system path counts (/usr but not /usr/local, /bin,
/sbin, /opt), with merged-/usr aliases, and packages named magpie* are
looked at first. A packaged binary:

- GUI: the update is shown as available with "pacman installed magpie
  (magpie-bin), so pacman updates it, not magpie: yay -S magpie-bin"
  (apt, dnf, brew likewise; Nix with no command). Nothing is downloaded,
  there is no Download or Install, the Update pill isn't lit, and
  /api/update/install does nothing (state available, stuck "package").
- `magpie update` says the same and exits 1 before downloading. This
  takes the place of the Homebrew-only check it had.

An unpackaged magpie (~/.local/bin, /usr/local/bin, a file pacman doesn't
list in /opt) updates itself as before.

Run:
- mote: go test -tags nogui -run 'Packaged|Homebrew|NotWritable|InContainer'
  ./internal/update ./internal/gui ./internal/cli ok; full
  go test -tags nogui -count=1 -timeout 45m ./... at b1a1b950f: 81 ok, 3
  red. Two are on main and filed: TestNoCommandBypassesProc (claudetui,
  #4491) and TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll, #4514).
  The third, TestCoreScriptBudget, was this change: app.js is now 460
  bytes more (its comments cut to one line, one helper call per path),
  and both budgets are raised by exactly that, with no room added. After
  the rebase on bb5e68cea: TestCoreScriptBudget and the Packaged,
  NotWritable, InContainer and Homebrew tests ok on mote.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build for darwin, linux (nogui), windows.
- WSL magpie-desktop (Ubuntu 24.04), real package: built a 0.1.2300
  nogui magpie, packaged it as a .deb (magpie-aurpk-test) at
  /usr/bin/magpie, dpkg -i. `magpie update` as the user, through
  /bin/magpie, and as root each printed "magpie 0.1.2355 is out" and
  "this magpie was installed with apt (package magpie-aurpk-test), which
  updates it, not magpie: sudo apt install --only-upgrade
  magpie-aurpk-test", exit 1; the file's sha256 was unchanged and
  dpkg -V clean. Package removed after. An unpackaged copy in ~ still
  checked and offered the update.
- WSL GUI, both engines: every update-* file, i18n-keys, gui-de/ja/zh-tw,
  whats-new*, about-*: 390 pass. Reds: i18n-keys "Unmarked" (#4524, on
  main) and update-check's WebKit ResizeObserver notice (the previous
  commit). Rerun of every update-* file after it: 294 pass, 4 red, all
  timing reds filed as #4554 and #4555, none in update-stuck. After
  app.js was cut down, after the rebase: update-stuck, update-auto,
  update-hide and i18n-keys, both engines: 93 pass, 1 red (#4524).

Broken by hand:
- placeExe's and the CLI's package check turned off:
  TestUpdatePackagedLeavesItToTheManager red ("a packaged binary is to be
  replaced"), TestUpdatePackagedSaysTheManager red (it went on to the
  download).
- origin's app.js: the new update-stuck case times out (no text); only
  the pill condition reverted: red in WebKit.

Not tried:
- A real pacman/Arch install: the omarchy VM didn't answer ssh (banner
  exchange timed out twice), so pacman detection is from the database
  layout in tests only.
- rpm and Nix on a real system; Homebrew only through the existing path
  test.
- The whole GUI suite.
2026-10-31 17:28:37 +08:00
yetone 33a284497e plugin options: a switch a provider plugin declares is saved where the plugin reads it (plugins#550)
`magpie plugin options cursor '{"wire_trace": true}'` wrote the entry's
options in plugins.json (a middleware's ctx.options), while a provider
plugin's switches (auth.options, the editor's Plugin options) are read
from settings' PluginOptions (input.magpie.option). The command said
"options set" and Wire trace stayed off.

Now a key that the plugin declares as a switch for one of its providers
(from the providers last listed, else asked of the plugin host) goes to
PluginOptions for that provider, through settings.EditPluginOptions, and
a running host is handed it (SetProviderOptions, 5s, best effort). Only
true or false is taken for a switch. The other keys go to plugins.json
as before; set with switches only, a middleware's options stay, less a
switch written there before. `off` puts every switch back to the
plugin's default and clears plugins.json's options. Shown with no value,
each switch is listed with its value. docs/reference.md and the plugins
page (en, zh, ja) say so.

Run at this head on mote: go test ./internal/cli ./internal/settings
./internal/plugin ok; gofmt -l clean; go vet darwin and GOOS=windows ok;
Linux go vet -tags gtk3 in WSL (magpie-desktop) ok.
Broken by hand: no key read as declared, and both new tests went red
(PluginOptions empty, the old switch left in plugins.json).
Not tried: the real CLI against a running magpie with the Cursor plugin
installed; a plugin not listed yet (the host path) is not in a test.
2026-10-31 16:46:14 +08:00
yetone 7b09d2c951 provider: a model can be listed by an id of the user's at its provider, asked for by its own
zeewell on X (tweet 2116404121930432888): relays serve one model under
ids of their own (deepseek-v4.1-flash-1017, grok-4.6@500k). They want to
give each one their own id at the provider layer. magpie then lists,
routes, groups and finds groups by that id, and the upstream request
still carries the vendor's id.

Choice: a new per-model map, settings' ModelIDs
("<pid>/<local>": "<own id>"), served through the wire names that
already exist. ModelSameAs was not widened. It means "same as another
vendor's model": it lends specs and joins found groups. Making it rename
models everywhere would change every existing user's ids and refs.
ModelWires was not reinterpreted either, for the same reason. ModelIDs is
ModelWires turned round: a wire keeps magpie's id and changes the one
sent, and this keeps the one sent and changes magpie's. Settings.Wires()
merges each entry in as a wire name (wrapped by a "<pid>/*" wire). Every
place that sent a ModelWires name (gateway, usage ledger, request page,
UpstreamName, UpstreamNameAs) reads Wires(), so the upstream id needs no
new path. An explicit ModelWires entry for the same id wins.

- Listed by the local id: Available, liveIDs/liveByID, Serving and
  ListPrice translate through OwnModelID. /v1/models, agents' lists,
  Resolve, routing groups and found groups (auto/<local>, merged with
  every other provider serving that id) all see the local id.
- Only a provider of the user's own (Account == nil) takes one. An
  account's or a plugin's request is built from its list's id, which no
  wire reaches.
- Two variants of one provider given one id: the latest given it wins,
  and the earlier one is listed by its own id again. The CLI names it.
  The editor refuses two rows given one id in one save. A model of the
  provider's own id that a variant is listed by (plain grok-4.6 beside
  grok-4.6@500k) is not listed while the variant has it.
- The user's values are never overridden. SetModelID moves picks,
  contexts, fallbacks, groups' members/rules/fast/placed/off/weights/
  classifier/pick, the pickers' lists, every per-model setting
  (Settings.MoveModel) and gateway keys' models (provider.ModelMoved,
  set by access) to the new id, but only where nothing is under the new
  id yet. Agents' own files are not rewritten: an old provider/<own id>
  still resolves and is sent as it is. Group match patterns and key
  patterns stay as written.
- Key limits: a key held to either id passes for both (modelAllowed:
  the ref, OwnModelID, ListedModelID). Group members use the same check.
- Usage: model = the listed id, served = the vendor's id from its reply.
  The price is the own id's first.

CLI: magpie model id <provider/model> [<id>|--reset], magpie model ids.
GUI: Providers > a provider's editor > Names & levels > "Listed as",
beside Same as. It is staged with the editor's Save and taken back by
Restore default, in zh, zh-TW, ja and de. Accounts have no box.
Docs: providers-accounts.md, gateway-routing.md, and site start.html in
en, zh and ja.

Run (mote-run, at this tree rebased on 841326709):
- go test -tags nogui of internal/gateway, provider, settings, access,
  usage and cli: ok. internal/gui: ok but for
  TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main since
  b09349d17 (#4514, yiqiui's patch); its ModelIDs case passes.
- TestAutoVisionDoesNotBuildListsAgain: 457 allocations with 4 models,
  458 with 400 (main 459), searcherModel within its 50. Reading
  Shared() per list cost 3041; SharedModelIDs parses only modelIDs once
  per file change, the settings path is built again only when what it is
  built from changes, and Serving looks up the own id only when a key is
  listed to some model.
- TestCoreScriptBudget: raised by 1,178 bytes for the Listed as box,
  with a note.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet ok.
- GUI: provider-listed-as (en, zh, zh-TW, ja, de), provider-same-as,
  provider-detect in Chromium on mote and WebKit on the Linux box (mote's
  WebKit launch hangs, #4125): 9 of 9.
Broken by hand, each red: the wire name (wires), the list (list), a key
held to the own id (keyown), the key move hook (hook), liveIDs, liveByID,
moving refs (moverefs) and moving per-model settings (movemodel).
Not tried: a red for ListPrice's or Serving's own-id lookup; a real relay
with variant ids; Match patterns are not rewritten to the new id. The
full Go suite and the whole GUI suite are still running and their reds
get their own issues.
2026-10-31 15:04:44 +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 07a3312c53 library: sync and backup files carry the subagents
xixi_Sean_ on X asked why Sync leaves the Library's subagents out. There
was no reason: the library part of a bundle now carries them.

- library.Bundle.Subagents (*[]*Subagent): name, description, prompt,
  the skills and MCP servers named, the agents ticked. Collect always
  sets it, empty too. Applied.Subagents (which files magpie wrote here
  and their hashes) stays out: each computer writes the files into its
  own agents on the sync Put runs and records its own, so a file the
  user edited there, or one of theirs by the same name, stays theirs.
- Put replaces the subagents with the bundle's, so one taken out on one
  computer goes from the others. A nil list (a bundle from a magpie
  before this) is unknown and keeps this computer's.
- check refuses a subagent whose name isn't one (it is a file name in
  every agent) or comes twice; agent ids are carried as they come, so a
  newer magpie's tick for an agent this one can't give subagents to
  stays and writes nothing here.
- davsync: an empty list hashes as before the field, so upgrading with
  no subagents syncs nothing.
- backup files go through the same Collect/Put; the CLI's backup line
  counts subagents. The GUI's sync/export/import ticks say "instructions,
  MCP servers, skills and subagents" in every language.
- webdav-settings-refresh's "Agents" tick locator also matched the
  library tick's "subagents": it now asks for "Agents' models".
- library.md and sync-backup.md updated. Hooks still aren't carried.

Run (rebased on 0bf5adb11; Go runs at e0c57ffe2, same diff):
- mote: go test -tags nogui ./internal/backup ./internal/davsync
  ./internal/cli ok; ./internal/library -run 'TestCarry|TestSubagent|
  TestLocalServer|TestPutKeeps|TestPutSame|TestRestoreKeeps' ok
- wsl-run (Linux): ./internal/library ./internal/backup ./internal/davsync
  whole packages ok
- win-run (Windows): the same three, -run 'Subagent|TestCarry|TestLibrary|
  TestSyncLibrary' ok
- go vet -tags nogui for darwin, GOOS=linux and GOOS=windows on the four
  packages ok; gofmt -l clean
- GUI (wsl-run, Chromium + WebKit, every language): i18n-keys,
  github-sync, s3-sync, sync-auto-restore, sync-not-backup,
  sync-other-kind, sync-sign-in, sync-spin, sync-usage-error,
  webdav-settings-refresh, library-backups-top, gui-de, gui-ja,
  gui-zh-tw, settings-search, settings-sections: 170/173, then
  webdav-settings-refresh green after the locator fix. The one red left,
  i18n-keys "a plugin's words are its own" ("Unmarked" in
  plugins/routing/i18n.js), is on main already: #4524.
  mote ran five other GUI suites at load 18, where every WebKit
  github-sync case timed out at launch, so the GUI run moved to Linux.

Broken by hand: with Collect not setting Subagents and Put ignoring
them, TestCarrySubagents, TestCarrySubagentKeepsUsersFiles,
TestCarryNewerSubagents, TestBackupFileCarriesSubagents,
TestSyncSubagents and TestNoSubagentsHashAsBefore went red; with Put
treating a missing list as empty, TestCarryOldBundleKeepsSubagents and
TestBackupFileCarriesSubagents went red.

Not tried: a real WebDAV/S3/GitHub remote between two real computers;
the fake DAV server carries it between two sandbox HOMEs.
2026-10-31 13:14:16 +08:00
yetone e6b851b0fe update: magpie update in a terminal restarts the app with its gateway handed over
gaubeebangeel on X has an agent run the magpie upgrade at 4am and had
to give that agent its own provider: magpie couldn't serve it through
the upgrade.

Cause: `magpie update` put the new version in and printed "quit and
reopen magpie to use it" (a .app) or "updated to X" (a binary). The
running app never restarted, so the agent (or the user) had to restart
it by hand, and a plain restart closes the port and drops streams.

Measured before, on mote, a sandbox HOME `magpie serve` with a fake
upstream streaming 61 chunks at 100ms, restarted by SIGTERM + start:
- the stream was cut at chunk 15 of 61 (unexpected EOF); SIGTERM to exit
  took ~18ms, no drain;
- requests during the restart: 289 answered, 5 refused over 87ms.

Now `magpie update`, once the new version is in, POSTs it to the
running app's /v1/magpie/restart (gateway/restart.go). It is answered
only to a program on this computer over loopback; a LAN caller, a page
(Origin / Sec-Fetch) and another Host get 403. The updater's
restartBeside (gui/update_beside.go) restarts only when its own exe was
the one replaced (replaced() now also compares a .app's binary,
bundleExe), takes the version as ready without the feed, and runs the
same restart as Settings' AutoRestart: at once when it cuts nothing
short, else through waitIdle. On macOS and Linux that restart is the
existing SCM_RIGHTS handover, so the port never closes and in-flight
streams finish in the old process. The command prints what happened:
restarting (handing the gateway over), waiting for N requests, another
copy (current), magpie serve (unsupported), not running, or too old
(404: the first update into this version still needs a manual
restart).

Tests:
- TestUpdateInATerminalRestartsTheAppWithoutCuttingIt (darwin, linux):
  a stream through the gateway, the exe rewritten, magpie update's ask
  answered "restarting" with handover; the successor serves a request
  while the stream runs, the stream ends whole, the old one quits only
  after it. Red by hand with the route removed ("magpie update's ask:
  404").
- TestUpdateOfAnotherCopyLeavesTheAppBe, TestRestartAskedOnlyFromThisComputer
  (refused cases never reach the restarter), TestUpdateAsksTheRunningMagpieToRestart
  (each reply, a 404 magpie, none running).

Run at this tree:
- rebased on bdc1617be, at this head on mote: gofmt -l clean;
  GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...;
  go test -run 'TestUpdate|TestRestartHandsTheGatewayOver|TestHandoverNotMade'
  ./internal/gui ./internal/cli and -run 'TestRestartAsked|TestReadOnlyKey'
  ./internal/gateway: ok
- before the rebase (88ecae173), mote: go test -count=1 ./internal/gui ./internal/cli ./internal/gateway:
  gateway ok (535s), cli ok; gui FAIL only on filed reds: the real-window AppKit
  tests killed at their deadline on mote (#4125, #2645) and
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514), both red the same
  run alone at 88ecae173, and TestColdTurnsTaken (#4510, a race in
  full gui runs, not touched here)
- wsl-run (magpie-desktop, -tags nogui): TestRestartHandsTheGatewayOver,
  TestUpdateInATerminal..., TestUpdateOfAnother...: ok
- mote: gofmt -l clean; go vet gui/gateway/cli; GOOS=linux go vet -tags
  nogui ./...; GOOS=windows go vet ./...: ok

Not tried: the real GUI app end to end with a real `magpie update`
against a published release; Windows (no handover there: the restart
waits for an idle gateway and the port closes while the new version
starts, #4521); `magpie serve` / the daemon, which has no handover and
says to restart it the way it was started.
2026-10-31 11:39:04 +08:00
yetone 88ecae1738 routing: By weight spreads a subscription's requests over its accounts
rubbzha on X (tweet 2116346330625036794): a Claude Max account and a Pro
one signed in to one subscription should share its requests by how much
each allows. The provider editor's Routing now offers By weight for
subscription accounts as it does for keys. With it picked, each account
in use shows "Weight N · S%" beside its name, the key weight's chip, and
a click edits it in place (POST /api/provider/accountweight {id, account,
weight}). CLI: `magpie provider account-weight <id> [account [n|default]]`.

The weight is kept per account by its lower-case name
(Provider.AccountWeights), and is moved with a rename (moveAccountSettings).
The gateway's keyWeight reads it from the candidate, with no file read, so
the smooth weighted pick treats accounts as it treats keys: Stays keeps a
conversation on its account, and a resting account is passed over while
the others share its requests. The default is 1. Nothing is prefilled from
the plan, and 1 is stored as no entry, so a value the user set is never
overridden.

Re-derived: ROUTINGS' weight text and routingsOf (the editor), the Routing
page's MODES, provider-row options and its "why first" text for an account,
the routing and accounts subsystem pages, the start docs (en, zh, ja), and
i18n in zh, zh-TW, ja and de (i18n.js and plugins/routing/i18n.js).
app.js is 74 bytes smaller than before (a long comment cut, keyWeight
reused), so neither script budget is raised.

key-weight.test.cjs read #status before accountAction's second round trip
(/api/state) had written it. The same race is now waited on in both tests:
with a 400ms delay injected on /api/state, the old read is red and the
new one is green.

Run (rebased on 03f3e1528; then on ef8dfaa46, where the budget, i18n and
own tests were run again and passed: Budget|I18n|Weight Go tests,
account-weight, key-weight and i18n-keys GUI files 10/10):
- New tests, each red on the old code: TestSetAccountWeight,
  TestAccountWeightMovesWithRename (red with the moveKey line removed),
  TestAccountWeightSharesRequests (6/2 for weights 3/1; alternating with
  keyWeight forced to 1), TestAccountWeightCmd, and
  account-weight.test.cjs (chromium + webkit, widths 1000/560 and web 390,
  en/zh/zh-TW/ja/de; red on 3e5aa1151's assets: no By weight for accounts).
- account-weight, key-weight, routing-weight-chip, account-row-line GUI
  files on the Linux box: 24/24 after the status wait (23/24 before, the
  race above). On mote, 13 of 24 timed out launching a browser at load 24
  with 116 Playwright processes from other sessions (#4125).
- mote `go test -timeout 45m ./...`: every package ok except
  internal/proc's TestNoCommandBypassesProc (claudetui on main, #4491) and
  internal/gui's ten real-window AppKit tests killed at their deadlines
  under load (#2645, #4125). Neither touches this change.
- gofmt -l clean; go vet ./... (darwin), GOOS=windows go vet ./... and
  GOOS=linux go vet -tags nogui ./... ok on mote.
- Whole GUI suite on the Linux box: still running at push; reds are filed
  after.

Not tried: real Max and Pro accounts through the gateway; the Routing
page's own account row under By weight has no GUI test; the whole GUI
suite on macOS WebKit (mote was saturated by other sessions' suites).
2026-10-31 11:03:35 +08:00
yetone 3e5aa11519 provider: Qwen Cloud, Alibaba's international Qwen platform, is a preset with its regions and Token Plan (judi0713)
judi0713 on Discord (v0.1.2288) asked for Qwen Cloud (qwencloud.com).
Its keys are its own, made at home.qwencloud.com, and serve neither
DashScope's nor Bailian's hosts, so none of magpie's Qwen presets took
them.

Two presets, the way Alibaba's other pay-as-you-go/Token Plan pair is
modelled, because each key gets 401 at the other's host:

- qwencloud: pay as you go, sk-ws- keys, at
  https://{region}.maas.qwencloudapi.com/compatible-mode/v1 (Chat) and
  /apps/anthropic (Messages), in six regions named by their ids as
  Alibaba's docs name them: ap-southeast-1 (the default), us-east-1,
  eu-central-1, ap-northeast-1, cn-hongkong, cn-beijing. Catalog alibaba.
- qwencloud-token-plan: sk-sp- keys, token-plan.maas.qwencloudapi.com,
  Singapore only, with the plan overview's text models.

Endpoints, regions, key prefixes and the plan's models are from
docs.qwencloud.com ("Regions and endpoints" and the Token Plan
overview), not guessed. Responses is left out, as in the other
Qwen presets.

The gateway's dashScope() now knows both presets and the
*.maas.qwencloudapi.com hosts, so a Qwen Cloud stream gets the same
enable_thinking handling a DashScope one does. Import (presetAt), the
CLI's region= and magpie://import?preset=qwencloud&region=... map to it.
docs/reference.md, the CLI help and the site's import page (en, zh, ja)
name them. Region names are ids, so no string is new to i18n.js and
nothing in the GUI changed.

Run (mote, at 708213f65 on c272e5582; after it the commit was rebased on
876d477d7, which touches none of these files, and the new helpers' comment
was moved above bedrockRegions' doc comment, no code changed; at the pushed
head the provider tests below ran again, ok):
- gofmt -l: clean.
- go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -tags nogui ./... -timeout 45m -count=1: every package ok
  (gateway 804s, provider 205s) except two reds already filed, in files
  this doesn't touch: internal/proc TestNoCommandBypassesProc
  (claudetui/child_unix.go's exec.Command, #4491) and internal/update
  TestRelaunchOpenTriedAgain (TempDir cleanup not empty, #3881).
- At the pushed head: go test ./internal/provider -run
  'TestQwenCloud|TestQwenTokenPlan|Preset|TestParseImport': ok.
- No GUI change, so no GUI run.

Broken by hand:
- Preset ids renamed: TestQwenCloud red ("no preset qwencloud-token-plan").
- gateway.go's dashScope() back to main: TestDashScopeHosts red on the 5
  new Qwen Cloud entries; the maas.qwencloudapi.com.example case stays
  not-DashScope.

Not tried:
- No real Qwen Cloud key: no request went to qwencloudapi.com.
- The decision model (decide.go's bailianDecides hosts) doesn't know
  Qwen Cloud, and image models on these presets are the next commit's.
- The site isn't deployed by this commit.
2026-10-31 09:58:04 +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 e647a1fd54 plugins: an npm registry of the user's own is used for installs and lookups (timwangdev on X)
timwangdev asked on X for plugins to take a custom npm registry. Zero-config
first: Registry() (internal/plugin/registry.go) takes, in order, the one set
in magpie (settings npmRegistry: `magpie plugin registry <url>|default`, or
Plugins › Discover's new npm registry row), BUN_CONFIG_REGISTRY /
NPM_CONFIG_REGISTRY / npm_config_registry in magpie's environment, then the
login shell's (cached probe only, proc.LoginEnvKnown, never waits on a
shell), install.registry in the plugins folder's or the user's .bunfig.toml,
registry= in the plugins folder's or ~/.npmrc, then the 国内镜像 switch's
npmmirror, then npm's own. The switch no longer puts npmmirror over a
registry the user named: before, bun was handed BUN_CONFIG_REGISTRY=npmmirror
whenever it was on, over the user's .npmrc. bun is told the registry only
where it wouldn't find it itself (magpie's setting, the shell's, the
switch's). magpie's own npm questions (latest version for the market,
Update and the hourly check, README, search) go to the same registry, a
package's @scope:registry= to that scope's, with the .npmrc's
//host/path/:_authToken (${VAR} expanded, longest prefix) sent to that host
alone, dropped on a redirect to another host, never logged or shown.
Download counts stay npm's. Only http(s) with a host, no userinfo, query
or fragment is taken; anything else is refused and not saved, and a bad
value hand-written into settings.json is passed over. /api/plugins says
which registry is in use and where it came from.

The GUI row is in registry.js, imported when Discover draws it, so the
core script budget isn't raised (plugins.js is 292 bytes smaller than
before, one long comment there condensed).

Left out: bunfig [install.scopes] for magpie's own lookups (bun reads them
for installs), .npmrc _auth and username/password, NPM_CONFIG_USERCONFIG
and npm's global npmrc, and internal/agent/cliupdate.go's agent CLI update
lookups, which still ask npm's own.

Run (mote and wsl-run). First at this change on 2ac423f4f:
- go test ./internal/plugin/ ./internal/source/ ./internal/gui/
  ./internal/proc/ ./internal/cli/ ./internal/settings/ -timeout 45m:
  plugin, source, cli, settings ok. gui: only the real-window AppKit tests
  killed at their deadline on mote (dock, panel, titlebar, tray; #2645,
  #4125), TestCoreScriptBudget and TestSettingsSaveKeepsWhatItDoesNotSend
  green after the fixes in this commit. proc: TestNoCommandBypassesProc red
  on origin/main itself (internal/claudetui/tui.go:183), filed as #4491.
- gofmt -l internal: clean. GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok.
- GUI (wsl-run, magpie-desktop): plugin-registry.test.cjs in Chromium and
  WebKit, 5 languages each, 980px and 380px; i18n-keys, old-webkit and
  plugin-market (WebKit): 19/19 pass. On mote the browser runs timed out
  launching (#4125).
Again at this tree rebased on fa5e86cf2 (upstream changed app.js and
i18n.js): go build ./...; go test ./internal/gui/ ./internal/cli/
./internal/plugin/ ./internal/settings/: cli, plugin, settings ok, gui only
the same ten AppKit window tests killed on mote (#2645, #4125), the core
budget green; gofmt clean; plugin-registry (Chromium, WebKit), i18n-keys
and old-webkit on WSL: 22/22 pass.
Rebased once more on 45de2ddb9 (app.js and i18n.js again): gofmt clean,
go vet of gui and plugin ok, TestCoreScriptBudget and
TestSettingsSaveKeepsWhatItDoesNotSend ok, i18n-keys 4/4.

Broken by hand, each red, then restored:
- A: old registryEnv (npmmirror whenever the switch is on):
  TestBunTakesTheUsersRegistry red.
- B: lookups always to npm's own: TestLookupsAskTheUsersRegistry red.
- C: no URL check: TestSetRegistryRefusesWhatIsntOne red.
- D: the switch before the user's registry: Precedence, BunTakes and
  Lookups red.
- E: no token sent: Lookups red.
- F: scopes ignored: Lookups red.

Not tried: a real private registry (Verdaccio, GitHub Packages, Nexus) with
a real token; a real bun install through one; Windows (the login shell
probe is a no-op there, so only env, bunfig and .npmrc apply).
2026-10-31 04:24:59 +08:00
yetone 45de2ddb96 provider: a provider the user counts free goes first under Free first (jiabubu on Discord)
jiabubu asked on Discord #help for a way to mark a provider, model or key
as free, so that Free first routing spends it first. Their example is
ModelScope, which has a free daily quota. Until now routes.Seat.Free
came only from the vendor catalog's Free flag, and there was no way for
the user to set it.

Provider.CountFree ("Free for me" in the provider editor's Advanced fold,
`magpie provider set <id> free=yes|no` in the CLI) makes FreeModel true
for every model of that provider. Routing therefore treats it like a
vendor's free model: Free first uses it before paid ones, and Cheapest
first weighs it at nothing, because PriceAt, which only routing reads,
returns 0 for a free model. Prices shown (ListPrice and the model list)
and the costs Usage counts (EffectivePrice) are unchanged. The mark says
what to spend first, not what a call cost, and a quota that runs out
still bills at the listed price. Key and account (subscription)
providers both carry it, through withPicks, the account literal and the
copy merge.

Tests:
- internal/gateway TestFreeFirstSpendsTheProviderTheUserCountsFree:
  - a Free first group [paidv/m, mine/m] sends its first call to mine
    once mine is marked, and the trace row says Free;
  - EffectivePrice is still the listed 3/15;
  - Cheapest picks mine first;
  - unmarked, paidv goes first again.
- internal/gui TestProviderSaveKeepsCountFree: the preset and typed-in
  providers save the mark and clear it, and /api/providers reports it.
- internal/cli TestProviderSetFree: free=yes and free=no work; the value
  shows in `provider <id>`; free=maybe, an empty value and --help are
  refused and change nothing.
- GUI internal/gui/tests/provider-count-free.test.cjs covers the
  ModelScope preset, a custom provider saved with the mark, and a Codex
  account. It runs chromium and webkit, in en, zh, zh-TW, ja and de, at
  widths 900 and 440. It checks the Advanced fold, the check and save
  POST bodies, that the row fits with no sideways scroll, and that each
  string has a translation in I18N.

Core script budget: rebased on fa5e86cf2, the core's scripts came to
1,538,236 bytes, 880 over coreScriptBudget, which TestCoreScriptBudget
caught. The budget is not raised. countFreeField's comment and five
long comments on the editor's helpers (proxyPicker, concurrencyField,
priceRateField, pluginOptionsField) are cut down, so app.js ends 212
bytes smaller than before this change.

Run (mote via mote-run, at this change's tree on base 8ee75adbf):
- go test of internal/gateway (-run FreeFirst|InOrder), internal/gui,
  internal/cli and internal/provider: ok.
- GUI test: chromium 30/30 on mote. WebKit could not launch on mote at
  all at the time (a bare webkit.launch probe timed out at 60s, and
  other sessions' WebKit launches were stuck there too). WebKit was run
  on Linux instead (wsl-run, magpie-desktop): 30/30.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./... ok; go build for darwin, linux (nogui) and
  windows ok.
- At the pushed head (rebased on fa5e86cf2, comments cut): go test of
  internal/gui, internal/cli, internal/provider and internal/gateway
  -run FreeFirst|CountFree ok (internal/gui was red only on
  TestCoreScriptBudget before the cut); node --check app.js ok; the GUI
  test in chromium 30/30.
- The full Go suite (go test -tags nogui -timeout 45m ./...) is still
  running on mote at ship time, per the owner's ship-at-once rule. Any
  red it finds gets a follow-up commit. The whole GUI suite was not run:
  mote's WebKit cannot launch and the Linux box was running other
  sessions' GUI suites.

Broken by hand:
- With the CountFree line taken out of FreeModel, all three Go tests
  went red, e.g. 'Free first went to "paidv" (free false) first'.
- With `pr.CountFree = in.CountFree` taken out of the preset save
  branch, TestProviderSaveKeepsCountFree went red ("the preset's mark
  wasn't kept").

Not tried:
- A real ModelScope account; the tests use fake upstreams.
- A per-model mark (optional in the request); the mark is
  provider-wide.
- The TUI editor (the CLI setter covers the terminal).
2026-10-31 04:21:21 +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