Commit Graph
558 Commits
Author SHA1 Message Date
yetone 47ec2a969f provider: a Sub2API Claude account comes in by its email_address, with its account and organization (#1975)
KKKKKKKEM's Sub2API export of a Claude OAuth account was refused, "the
file doesn't say which Claude account this is": sub2apiEntry read only
credentials.email, and Sub2API keeps a Claude account's email under
Anthropic's own name, email_address. Its CreateAccountModal stores the
token Sub2API was given whole as credentials ({...tokenInfo}: access_token,
refresh_token, expires_at, scope, org_uuid, account_uuid, email_address)
and the uuids and email again in extra (useAccountOAuth's
buildExtraInfo); read in Wei-Shaw/sub2api's source.

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

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

Not tried: a real Sub2API export or account; `magpie accounts import`
itself, which on macOS writes the active Claude sign-in to the Keychain.
It calls the same ImportLogins.
2026-10-13 18:16:03 +08:00
yetone db0af71864 gui: the menu bar can show today's or the last 7 days' tokens and cost (#1984)
Settings → Usage → "In the menu bar" lists two more rows after the
subscriptions: "Tokens and cost today" and "Tokens and cost, last 7 days",
ticked and saved as a card is (ids "usage:today", "usage:7d" in
trayUsages; provider ids are [a-z0-9-], so the prefix can't collide). They
show beside the allowances or alone.

- trayusage.go: a total is a card built from usage.SummarizeTop(p, 0)'s
  Totals (the Usage page's own cached numbers, Input+Output as its
  tokensOf counts them): tokens over cost, in the currency Settings picks,
  "+" when some requests had no known price. On the Mac it is a Plain cell
  (no vendor logo; the bird beside it says whose it is); on Windows/Linux
  the tray's text label and tooltip ("Today in magpie / 1.2M tokens (912K
  in · 318K out) / ≈$3.40+ / 152 requests…"). Quotas aren't fetched when
  only totals are picked.
- Clicked, a total opens the Usage page's Overview at its period
  (quotaView → ?view=usage&tab=usage&period=…, read and dropped from the
  URL) or the panel's Usage tab at that period (panelUseFocus).
- Only today and 7d: the Usage page has no 3-day window, and a menu-bar
  number nobody can open in magpie at the same span would disagree with it.
- The pill names a lone total, and counts a mix as "{n} shown" rather than
  calling it subscriptions. Strings in en/zh/zh-TW/ja/de.
- docs/reference.md and gui-shell.md say so.

Run:
- go test -tags nogui ./internal/gui/ (sandbox HOME): ok. The new
  TestTrayTotals/BesideCards/TrayCount went red with each piece broken by
  hand (no Plain, no text branch, no quotaView branch, 3d accepted).
- tray-totals.test.cjs (new) plus tray-usages, tray-inuse,
  proto-menu-overflow (updated for the two rows), i18n-keys, panel-usage,
  allowance-open-read, tray-cell-click: 46/46 in Chromium and WebKit, five
  languages, 1100 and 420 wide. tray-totals fails 5/5 against the old
  app.js.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- The Mac cell image rendered and looked at (bird, "1.2M" over "$3.40").

Not tried: a real macOS menu bar, nor a Windows or Linux tray; the tray
tooltip is English, as the existing tray tooltips are.
2026-10-13 18:15:18 +08:00
yetone 5241de909a gateway: an image URL a caller sends is downloaded only from public addresses
An images request (/v1/images/edits, /v1/images/generations) may name a
reference image by URL. For a model that takes the image as bytes (an
images API's multipart edit, Gemini's own API, Code Assist), magpie
downloaded the URL itself with the gateway's client, to any address and
through any redirect, and sent what came to the vendor as the image.

fetchPicture, the one place a caller's URL is downloaded (all three draw
paths go through it), now uses publicClient (image_fetch_guard.go):
- the host is resolved and every address must be public (publicAddr:
  not loopback, RFC 1918, fc00::/7, link-local incl. 169.254.169.254,
  CGNAT 100.64/10, unspecified, multicast, documentation/reserved
  ranges, Teredo, nor an IPv4-mapped, NAT64 or 6to4 form of one);
- the request is pinned to the address checked (Host and TLS
  ServerName keep the name), so a name resolving differently later
  changes nothing; a direct dial is checked again in the dialer's
  Control on the address actually connected;
- through a proxy (magpie's, the provider's, the system's) the proxy is
  chosen by the name and sent the pinned address (CONNECT or SOCKS);
  a plain http:// URL through an HTTP proxy is asked for by address in
  Host too, since Go writes the absolute URI from Host;
- redirects (at most 5) go through the same transport; only http(s);
  no keep-alives; the existing 64 MB / stall / 5-minute limits stay;
- what comes back must sniff as image/*, else 400 without the body.

Policy: a request from this computer (local(): loopback, no proxy or
tunnel headers, and not fromBrowser) keeps downloading from anywhere,
since its sender reaches those addresses already and a local agent may
serve images on localhost. Everyone else, a gateway key's holder
included, is held to public addresses. Vendor-returned image URLs
(FetchImage for b64_json, imagemcp, video content) are unchanged: they
are the vendor's, not the caller's. No other gateway path downloads a
caller's URL: chat/Responses/Anthropic/Gemini image URLs are passed on
for the vendor to fetch. Documented in docs/subsystems/gateway-routing.md.

Run:
- go test -race -count=3 -run 'PublicAddr|EditImageURL|PrivateDialer'
- broke by hand, each went red: old client in fetchPicture (all three
  e2e tests), no Unmap (::ffff:100.64.0.1), no pinning (proxy test
  sees the name), no resolve check (redirect to 192.168.1.10 through
  the proxy served), no dialer check, no image sniff, browser allowed
- go test -tags nogui ./internal/gateway/... (full)
- gofmt -l; go vet -tags nogui for darwin, GOOS=linux, GOOS=windows
- not tried: an https:// image through a real HTTP or SOCKS proxy
2026-10-13 18:15:06 +08:00
yetone 6d7b440924 gateway: a request's ms end with its reply, not with what magpie writes down after it (#1939)
bytecode-x's full-suite failures (Millis 3772 for a stream that ended at
~450 ms; Flow 377, so DecodeOf's flow*HeldShare < window told 0/0) came
from after the reply: serve took call.Millis at its very end, after the
answered bookkeeping. answered() saves sticks and servedCandidate's
provider.NoteServed rewrites the last-answer file, both on disk. With
timing stamps added between the last content byte and call.Millis, 12
CPU burners alone gave at most 7 ms of tail (420 samples); with three
dd+sync writers beside them the block between "before served" and
"after served" took 0.7-1.5 s, the whole of the tail, while the stream
itself had ended. A user's busy disk meets the same: a paced reply reads
as one held back and shows no speed, and its duration grows.

- serve keeps `ended`, the time the last try's reply ended (when its Try
  is made), reset at each try; call.Millis is ended-start when a try was
  made, as before otherwise (a lane turn-away). The handed-on records
  of a refused try take try.Millis, the same end.
- decide_group's usage row is timed before servedCandidate, the same
  sibling.
- ttft_test's paced fixture left a leading "~" on its first event (it
  strips it only for i > 0), so those fixtures' first event was no SSE
  event at all (bytecode-x's second point): it now strips it without a
  gap.
- docs/subsystems/gui-shell.md says where a duration ends.

Run: TestSpeedEndsWithTheReply (new: holds sticksSaving for 2 s during a
paced reasoning stream; the request must still take >= 2 s, and its
Millis must not), TestReasoningSpeed*, TestBurstTellsNoSpeed,
TestCodexBackendBurstTellsNoSpeed, TestHiddenReasoning*, TestTTFT*;
full internal/gateway and internal/provider; gofmt -l; go vet darwin,
windows, linux -tags nogui.
Broken by hand: gateway.go's change reverted -> TestSpeedEndsWithTheReply
red ("the reply's ms 2001 count the 2s magpie took saving after it").
Not done: the bookkeeping itself still runs before serve returns, so a
client that waits for the response's end still waits for the disk;
moving those writes off the request path is a separate change. The
decide_group sibling has no test of its own.
2026-10-13 18:11:23 +08:00
yetone af39ee4b5f gateway: a 402 for a usage limit rests the model out of quota, until the window renews (#1979)
Factory answers a Standard pool used up with 402 "You've reached your
weekly standard usage limit (resets in 0h 19min). Switch to Droid Core
...". failure() read every 402 as out of credit, so the whole account
rested a fixed 30 minutes: its Droid Core models (GLM-5.3, the
reporter's fallback) were skipped with it, the "resets in" was ignored,
and renewed() never lifted the rest when the window came back, since it
lifts only failQuota or By=="window" rests (Ziqi-Cui, 09:16Z).

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

Run: TestFactoryStandardOutLeavesCore (built-in and plugin:factory),
TestPaymentRequiredReadByItsWords, TestResetsInWords; full
internal/gateway (327s) and internal/provider ok; gofmt -l; go vet
darwin, windows, linux -tags nogui.
Broken by hand: the new failure() case removed -> both subtests red
(account rested for credit, GLM resting); resetsAfter returning 0 ->
TestResetsInWords red; quotaOfPlugin's notModels ignored -> plugin
subtest red.
Not tried: a live Factory account; Factory's Droid Core used-up
wording is assumed to read like Standard's.
2026-10-13 18:11:23 +08:00
yetone d46fb1e590 gateway: a tool's strict an upstream refuses is asked again without it, and left out after (#1980)
OpenCode 2 sends "strict": false on every tool through
@ai-sdk/openai-compatible. thonatos's custom provider turned it away with
400 "Unsupported Chat Completions API field: tools[0].function.strict",
which magpie relayed, and OpenCode ended the session. The reporter's
@ai-sdk/openai workaround worked only because magpie's Responses->Chat
translation leaves strict out.

What changed: in passthrough's retry loop, a 400 that names a tool's
strict as unsupported, unknown, unrecognized, not permitted or
extra_forbidden (toolStrictRefusal, strict_refused.go) is asked once more
with strict deleted from Chat tools[].function and Responses tools[]
(namespaces recursed), and marked for that provider and API
(toolStrictRefused, markUnfit). The next request leaves it out before
sending. An upstream that never refused it still gets strict, which the
ChatGPT backend needs (#383, TestResponsesToolStrict unchanged). The fix
is in the gateway, not in what magpie writes to opencode.json: any
client's strict reaches the same refusal.

What was run:
- Real OpenCode 2.0.25 in a sandbox HOME against a gateway built at the
  old code and a fake upstream refusing strict: the reporter's exact
  error ("custom-provider: Unsupported Chat Completions API field:
  tools[0].function.strict", opencode rc=1). With this change: answered.
- TestToolStrictLeftOutWhereRefused with the two recorded OpenCode 2.0.25
  requests (Chat and Responses, 12 tools each): first request carries
  strict, the retry none, the next turn none at once (3 upstream
  requests), another provider still gets strict.
- Broken by hand: without the retry branch both subtests get the 400;
  without the pre-send check, "next turn: 200, asked 4 times".
- TestToolStrictRefusalWordings, with negatives (an invalid schema, an
  invalid type for strict, an unsupported 'store').
- gofmt -l; go vet darwin, linux -tags nogui, windows; go test -tags
  nogui ./internal/gateway -count=1 (ok, 324s).

Not tried: the reporter's actual upstream vendor (not named in the
issue); the Responses refusal wording is assumed to match the Chat one.
A translated request (Chat->Responses) that an upstream refuses for
strict isn't retried by this.
2026-10-13 18:11:22 +08:00
yetone ffd0778696 agent: an agent reaching magpie through a reverse proxy isn't drift, and a sync keeps the proxy's path (#1985)
davisjiahao put magpie behind a company nginx (https://ai.corp.example/magpie)
and pointed their agents there with magpie's key. Every agent whose Check
compares its URL exactly called that "unwired", offered Reconnect (which
writes 127.0.0.1 back), and each start's sync replaced the origin but
dropped the /magpie path.

Decision: a URL that isn't magpie's is still magpie when it ends with
magpie's path, the rest is an http/https address on another machine, and
GET <rest>/ answers as the gateway's GET / ({"name":"magpie"}). Something
else there (a relay CC Switch wrote) stays drift. Loopback on another port
is magpie on an older port: drift, never probed. An unknown answer is not
drift (as unreachable/proxied), so Reconnect isn't offered before the
probe has answered.

- reach.go: magpieAt / realMagpieProbe / reachesMagpie, probed in the
  background through the existing cache; answersAsMagpie shared with
  codex_proxy.go's realProxyProbe. offLoopback takes https too.
- applied.go: wiringOff (the choke point for ~40 agents) accepts it;
  Codex's "bypassed" isn't told for a request to the host the config
  keeps magpie at, or one the gateway saw from it after.
- claude.go (managed settings) and reasonix.go: their own exact checks.
- codex.go: codexKeptGateway keeps https, default ports and a path prefix
  (#816's kept address, trusted by magpie's key); viaBase matches the kept
  codexURL, since at.host() falls back to loopback for https.
- keptaway.go: awayPath keeps the path every URL at the away address had.
- Port moves need nothing: Rewire/OnGateway re-set only unwired agents.
- Picking a model in magpie still points the agent at this magpie
  (documented, unchanged).

Run (sandbox HOME, worktree):
- go test -tags nogui ./internal/agent: ok (297s) rebased on 12ecb6d8e.
  Before the rebase only TestFolderVarsAreListed failed, fixed on main by
  c6de0d2a5.
- New proxy_kept_test.go: every agent behind the proxy has no Check/
  unwired drift, at a relay all but Codex are told, SyncCatalog keeps
  https://ai.corp.example/magpie with its path in every file; Claude
  managed settings; unknown-then-not-magpie; loopback not probed; the
  real probe against httptest serving the gateway's handler under
  /magpie/; Codex https kept address, Reached and lastSeen; signed-in
  Codex via openai_base_url; awayPath table.
- Broke each fix by hand, each went red: wiringOff (claude, claude-desktop,
  gemini, opencode... told), claude managed, reasonix, awayPath (every
  synced file lost /magpie), bypassed host and lastSeen, unknown-as-drift,
  codexKeptGateway http-only/no-path, viaBase.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: a real nginx (Host rewriting, auth in front of GET /), the
Windows box, a real CC Switch. No GUI change.
2026-10-13 18:07:03 +08:00
yetone f64d9312ff site, docs: a Privacy page lists everything magpie sends and how to turn it off (#1986)
#1986 asked what the daily count sends, where the id lives and how to stop
it. The answer was spread over one README paragraph and the reference. A
new page, /docs/privacy (en, zh, ja), lists it from the code:

- the daily PostHog batch (internal/stats): a whole example, the label
  rules for agents/providers/models, partner counts, the
  $process_person_profile:false flag;
- every switch: Settings -> Privacy's two toggles, noStats/noUsageStats,
  DO_NOT_TRACK / MAGPIE_NO_STATS, noAutoUpdate (About -> Automatic
  updates), and that a change applies at the next hourly look;
- the files: install-id (made at the first send, not at first run, as the
  issue said) and stats-sent in settings.Dir(), partner-counts.json in
  the cache folder, their paths per OS and portable, and deleting them;
- what usemagpie.ai sees whatever the settings (update feed every 6h,
  notes, partner list with its 1-in-10 sampled count, /go links, the icon
  proxy) and the Cloudflare Web Analytics on the site's own pages;
- public lists fetched (models.dev, open.er-api.com, npm, GitHub) and
  providers' quota reads with the user's own accounts;
- OTLP export, off by default, its env vars;
- why the count stays on by default in releases.

Every docs page in all three languages gets a Privacy link in its nav and
footer. README (en, zh) and start.html's "What does magpie send about
me?" (en, zh, ja) link to the page. docs/reference.md's Files list gains
install-id, stats-sent and partner-counts.json, and Counting users says
when the id is made, the hourly try, and links the page.

Checked against: internal/stats/stats.go, usage.go,
provider/partner_events.go, settings (NoStats, NoUsageStats,
NoAutoUpdate, UpdateEvery 360, otel.go), appdir, update, fx, catalog,
site/worker.js, and the GUI's Settings tabs/labels in index.html, app.js
and i18n.js (zh, ja).

Run: Playwright (Chromium and WebKit) on all three pages at 1100 and 420
wide, light and dark: no horizontal scroll, no element past the viewport,
no page errors (24/24), screenshots looked at for zh at 420 dark. Every
href/anchor in site/public/docs resolves; relative links in README and
reference resolve. node site/worker.test.mjs passes.
Not run: the page on the deployed worker (the site deploys by hand with
wrangler, so it is live at the next deploy); the language redirect for
/docs/privacy was not exercised beyond the worker's existing tests.
2026-10-13 18:02:01 +08:00
yetone 9e76fcdc68 plugin, cli, gui: a plugin's "password" question is typed unseen, as an API key is (#1982)
A sign-in method's prompts could only be "text" or "select", so a token a
plugin asks for (the Qoder plugin's PAT sign-in, magpie-community/plugins#103)
showed on screen as it was typed, in the app and in `magpie plugin login`.

What changed:
- internal/gui/assets/app.js renderPluginAsk: a prompt of type "password"
  gets a password field (masked), the same field an "api" method's key
  gets. A "text" prompt is unchanged.
- internal/cli/plugins_cli.go askPrompt: on a terminal a "password" prompt
  is read with term.ReadPassword (no echo); piped in it is read as a line,
  as a script answers it, and an empty answer still goes to the plugin's
  validate, as a text one does.
- internal/plugin/providers.go: the Prompt type lists "password". host.js
  passes the type through untouched, so nothing there changes. The TUI has
  no plugin sign-in.
- Docs: docs/reference.md and site/public/docs (en, zh, ja) plugins.html
  say what "password" does and that it is magpie's own (OpenCode has text
  and select).

The answer is only sent to /api/plugin-signin/prompt and the sign-in, as a
text answer is; nothing logs or shows it.

What was run:
- TestAskPromptPasswordIsUnseen (internal/cli): with the password branch
  disabled by hand it fails with `password on a terminal =
  "typed-in-the-open", <nil>, hidden reads 0; want pt-secret read unseen`;
  restored it passes.
- plugin-password-prompt.test.cjs: Chromium and WebKit, en/zh/zh-TW/ja/de,
  1100 and 420 wide, 11/11 each. With app.js put back it fails with
  expected 'password', actual 'text'. plugin-signin and
  plugin-signed-out-account 16/16 in both engines; i18n-keys passes in both.
- gofmt -l clean; go vet for darwin, GOOS=linux -tags nogui and
  GOOS=windows on internal/cli, internal/plugin, internal/gui; go test
  -tags nogui of those three packages in a sandbox HOME: ok.

Not tried: a real Qoder PAT through the community plugin (its PR isn't
merged), and the CLI on a real Windows console (term.ReadPassword is the
same call `magpie plugin login` already uses for an API key).
2026-10-13 18:01:20 +08:00
yetone 12ecb6d8e9 gateway: a gateway key held to a budget, models or accounts is told none of this magpie's accounts, only its own limit and routes (#1981)
321sssrt-bit shared magpie on the LAN with a gateway key held to a budget,
and that key still read every account's quota and balance. A held key
(heldKey: a budget, models or accounts) is someone else's to use, so it
now gets 403 with code gateway_key_held (refuseHeld) on
/v1/magpie/quotas, quotas/history, quotas/cards, POST quotas/refresh and
/v1/magpie/concurrency. That holds from loopback as well as the LAN, the
same as usageSummary already did. /v1/magpie/route tells it only the
routes of its own requests. Route.callerKey is set by trace.beginFor at
all five begin sites, so a route begun without it fails closed. It still
reads its own limit at /v1/magpie/limit. Unrestricted keys and the local
owner are unchanged.

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

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

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

Not tried: two real machines over the LAN; the tests drive the handler
with LAN remote addresses. An older client shows "isn't shared" (or its
cached cards until they expire) against an updated host until it updates
too.
2026-10-13 17:59:36 +08:00
yetone 42216ea609 gateway, gui: one model out of its pool rests on that model's rows only, not on the account's other models (#1960, WardLu)
An Antigravity account out of its Claude & GPT pool (claude-opus-5.5
refused until Sunday) rests that model alone: the gateway keys the rest
by restID and still sends gemini-3.8-flash, in its own pool, to the
account. Routing's page didn't know a rest could be one model's: it
kept rests by key or account, so the stage marked the account's
gemini-3.8-flash row "quota used up · back at Sun 17:53", and the row
under Accounts and keys said the whole account was out.

- gateway: Rest.Model names the model a rest is for when it rests by
  restID (a pool, a model not served, a paid model beside free ones);
  "" for an account- or key-wide rest.
- routing.js: restModel reads it (or, for a kept request from before,
  the model on the end of Rest.Key). The stage keeps a model's own rest
  by key and model, so only that model's row rests; an answered try
  ends the account's rest and its own model's. Accounts and keys keeps
  an account's model rests apart from its own: the account isn't shown
  as out, a line names the models resting with why and when, and Try
  now lifts those rests. An account resting as a whole is as before.
- docs/subsystems/gateway-routing.md says so.

Run: routing-model-rest.test.cjs (new), Chromium and WebKit, 1100 and
420, en/zh/zh-TW/ja/de, 20/20; with the old routing.js it fails
("old@x.test: gemini-3.8-flash rests with Opus"). All 74 routing/rest
GUI test files in both engines (456 each, 0 fail).
TestPoolRefusalRestsTheModelOnly checks Rest.Model, set and read back.
go test ./internal/gateway ./internal/gui, gofmt -l, go vet
darwin/linux/windows (-tags nogui).
Not tried: the reporter's real Antigravity account in the app.
2026-10-13 17:40:47 +08:00
yetone 692a779d3d library: an instruction set can be kept in a file of your own, such as ~/.agents/AGENTS.md (新v学员 on Discord)
新v学员 keeps one user-level ~/.agents/AGENTS.md by hand and wants every
agent to follow it. Only Factory Droid, omp and Cline CLI read that file
natively; Codex, Claude Code, Gemini, OpenCode, Pi, Amp and the rest
don't. Rather than teach magpie a new agent target, a set of shared
instructions can now be kept in that file instead of a copy in the
library, and the library writes it into every agent that is on, as it
does any set.

What changed:
- InstrSet.File: a set kept in a file of the user's own. Its text is
  read from that file, Save writes to it (kept aside in the backups
  first, written atomically, never removed: emptied, it stays empty),
  and Remove lets go of the set without touching the file.
- The file is refused when it is relative, a folder, an agent's own
  instructions or override file (magpie writes into those), a file
  holding magpie's marked block, inside the library, or another set's.
  A file not there yet is made on the first save.
- The GUI checks the active linked file every 30s (KeepLinked) and
  writes a change made in an editor into the agents.
- Carried by davsync or a backup, a linked set goes as its text; where
  the file is stays this computer's. Put back, the set keeps its file
  and the file gets the carried text, never emptied for a text not
  carried. A profile restored with no text doesn't empty it either.
- GUI: New set has "Keep in a file…" (filled with ~/.agents/AGENTS.md);
  a linked set is tagged "Your file", says where it is kept, and warns
  when Droid or omp is on, as they read ~/.agents/AGENTS.md themselves
  and would get it twice. Strings in zh, zh-TW, ja and de.

Run:
- gofmt -l; go vet for darwin, linux/amd64 -tags nogui and
  windows/amd64 on ./internal/library ./internal/gui.
- go test ./internal/library ./internal/gui -count=1: ok.
- New TestLinkedSet, TestLinkRefused, TestLinkedSetCarried. Each was
  broken by hand and went red: putText writing a linked file like a
  library one, Collect not stripping File, Put not restoring it,
  SyncLinked not syncing, linkable not checking agents' own files.
- library-linked-set.test.cjs in chromium and webkit, at 1100 and 420,
  in en, zh, zh-TW, ja, de: 22 pass; red with the file left out of
  create. library-instr-sets and i18n-keys still pass.

Not done or tried:
- No CLI to link a set (`magpie library instructions set <file>` still
  copies once), and the headless `magpie serve` doesn't watch the file:
  after an edit there, `magpie library sync` writes it out.
- Not tried with real Droid or omp reading the same file.
2026-10-13 17:28:26 +08:00
yetone 113672508a claude: a re-told conversation says whose Claude Code's "[Image: …]" notes are, so a text-only turn isn't read as carrying the history's images (#1751)
arvakme's request from Pi over /v1/chat/completions: a read tool's image in an
earlier turn, then a text-only question. Through the Claude subscription the
model quoted "[Image: source: …-magpie-claude-work-501/<uuid>/images/1.png]"
and said the message had an image attached.

Why: a new run is told the whole conversation in one message, and Claude Code
2.1.296 notes every image block of the message it is given in a note of its
own after the message, so after </current_turn>. Read from its binary: with
the session kept on disk (the shared work folder, where the bridge drops
--no-session-persistence for savedSession) it stores each base64 image to
<tmp>/<session>/images/N.png and the note names the path; with the session
off it still notes any image it scaled down ("[Image: original 3000x2000,
displayed at 2000x1333 …]"). So turning persistence off was not enough. Images
under url sources are not noted.

What changed: when the history has images, the current turn's opening says
the notes after it are the history's (or, when the turn has images too, the
history's first and then the turn's), in currentTurnOpen. A history with no
image is told exactly as before, and the history's own text is unchanged, so
its cached chunks are too. countImages is shared with start's log line.

Run against the real model (owner's Max account, its access token in a
sandbox CLAUDE_CONFIG_DIR, Claude Code 2.1.296 with the bridge's flags and
the stream-json message renderClaudePrompt makes from arvakme's request, a
120x60 red PNG):
- old prompt, session kept (as the bridge runs): sonnet-5-5 2 of 2 said an
  image was attached and quoted the path; opus-5-5 2 of 2 quoted it and
  offered to read the file. Old prompt with a 3000x2000 image and the session
  off: 2 of 2 said attached (the size note).
- new prompt, session kept: sonnet-5-5 3 of 3 "no image attached", the note
  named as the earlier image's; opus-5-5 2 of 2 the same; 3000x2000 history
  image 2 of 2 the same; a new blue image in the turn after the red one in
  the history: 2 of 2 "one image, blue", note 1 the history's, note 2 the
  turn's.
The Anthropic request bodies were also captured from Claude Code against a
local fake API to see where the note lands (a text block after the turn).

TestClaudePromptSaysWhoseImageNotesAre builds arvakme's request through
parseChat; it fails on the old code (historyClose always) and with the mixed
case broken by hand. gofmt, go vet (darwin, GOOS=linux -tags nogui,
GOOS=windows), builds on all three and go test -tags nogui ./internal/gateway/
pass.

Not done: the original report's duplicates (18 image blocks for 10 images
from Codex) are a separate question; Codex desktop itself was not run.
2026-10-13 17:24:46 +08:00
yetone ea1ba22c32 gateway, gui: Codex's composer predictions go where Settings › General says, Off among them (#1970)
pluo's Usage view showed Codex calls of kind composer_predictions at
133k-231k tokens each with no cache read: ChatGPT.app's Codex guesses the
user's next message with a hidden turn on a fork of the thread, on the
thread's own model, reading the whole conversation again each time. It
asks only when the thread's provider is "openai", so through Codex's own
ChatGPT sign-in (and a custom table pointed at magpie). The app's bundle
(fge) asks for {suggestion: string|null} and uses b.suggestion||null.

What changed:
- settings.CodexPredictions: "" as Codex sends it, "off", or a model id
  (provider/model, group/<id>); anything else is refused on load.
- gateway: codexPredictionsTo + codexPrediction, wired beside the
  descriptions at both entrypoints (gateway.go and codex_backend.go).
  Off answers {"suggestion":null} from magpie and sends nothing (the
  title Off path made generic as sentNowhere). A model's answer goes back
  only as the object Codex asked for (predictionJSON: think tags and code
  fences stripped, suggestion trimmed, blank = null). Plain text is never
  taken as a suggestion, since Codex would put it in the user's composer
  as their next message; it gives null and is recorded as a failure
  ("prediction: ...").
- usage: purpose "Prediction" for composer_predictions (purposes.js
  regenerated).
- gui: POST /api/settings/codex-predictions, kept by the general save;
  Settings › General row "Codex composer predictions" (Codex's own / Off /
  magpie's models, the app's picker), hidden in gateway mode; Routing's
  story for the kind says Codex's own switch (Settings › General › Show
  predictions) and magpie's. i18n in zh, zh-TW, ja, de.
- docs: gateway-routing.md's Codex section, reference.md's gateway-mode
  list. site/ docs left for the owner.

What was run:
- go test -tags nogui ./internal/gateway/ (full, -timeout 40m),
  ./internal/gui/ ./internal/settings/ ./internal/usage/: pass.
  New: TestCodexPredictionsSetting (default to ChatGPT, off sent nowhere,
  model routed, plain turn untouched, ledger kinds), TestNoPrediction,
  TestCodexPredictionOnMagpie (/v1/responses and the backend path),
  TestPredictionJSON; gui TestCodexPredictionsSetting.
- Broken by hand, each went red: backend wiring removed; plain text
  accepted as a suggestion; the general save not keeping the setting;
  the Routing story's kind check.
- Playwright codex-predictions.test.cjs: chromium + webkit, 1100 and 420
  wide, en/zh/zh-TW/ja/de (20 pass). routing-kind (with the new kind),
  codex-descriptions, codex-titles, i18n-keys, gateway-mode,
  purpose-filter, routing-purpose-state, settings-general,
  settings-sections, settings-search: pass.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows.

Not tried: the real ChatGPT.app's predictions against magpie (the
feature is gated server-side by /wham/predictions/config and isn't on for
the owner's account); the reply shape is from the app's bundle.
2026-10-13 17:23:00 +08:00
yetone 05edac2c36 daemon: the service's PATH has the Node a terminal gets, nvm's default among them (bookyue on Discord)
What changed: `magpie daemon install` now widens PATH before writing it
into the systemd unit or launch agent, the way the app does when opened
from the Dock (proc.UserPath): the version managers' and npm's folders
that exist, nvm's default Node (not its newest), then the login shell's
own PATH (proc.LoginPath), each after the folders the install's shell
already had. When no node is found even then, the install says so.

Why: the service has only the PATH written into it. With nvm loaded
lazily, or an install run over ssh without a login shell, that PATH had
no node, and plugins (and the MCP servers and agent CLIs they start)
couldn't find it under systemd (bookyue, #feedback 838099).

Run: gofmt -l; go vet darwin, linux -tags nogui, windows (daemon, cli);
go test ./internal/daemon ./internal/cli -count=1 on macOS; the daemon
test binary for linux/arm64 in debian:bookworm-slim (all pass).
TestInstallFindsNvmNode uses the real widening with a sandbox HOME
holding nvm v20 (default) and v22: the unit's PATH has v20's bin, not
v22's, after the shell's own. With the widenPath() call removed by hand
it fails (PATH is the shell's alone, Node() empty).

Not run: a real systemd install with nvm since this change (the earlier
container run, before it, covered install/restart/linger); not tried
with fnm or volta, which UserPath handles the same way for the app.
2026-10-13 17:15:51 +08:00
yetone 5617281f55 cli: magpie daemon install|uninstall|start|stop|restart|status keeps the gateway running as a service (HuanCheng on Discord)
What changed: a new internal/daemon package and `magpie daemon`, which run
`magpie serve` as the user's own service, with no window and no desktop
session.
- Linux: a systemd user unit at ~/.config/systemd/user/magpie.service
  (Restart=on-failure), driven by systemctl --user. status reads
  `systemctl --user show`, and says `sudo loginctl enable-linger $USER`
  when the user doesn't linger. su/sudo without the user's bus, no
  systemd, and WSL without systemd each get an error that says what to
  do.
- macOS: a launch agent, com.yetone.magpie.serve (RunAtLoad, KeepAlive on
  failure), loaded with launchctl bootstrap gui/$UID. Its log is
  ~/Library/Logs/magpie/serve.log.
- Windows and Android: refused, pointing to `magpie autostart on` (or to
  WSL).
- The service carries PATH, the proxy variables, MAGPIE_*, the XDG folders
  and the agents' folder variables from the install shell. The file is
  0600 because a proxy can hold a password. It runs magpie by its PATH
  name when that is the same file, so Homebrew's link survives updates.
  It refuses a go-build binary and an AppTranslocation copy.
- Install is refused while `magpie autostart` is on: the tray app serves
  the gateway too, and the two would crash-loop on the port.
- Docs: a reference.md section, and one sentence on the site's start page
  (en, zh, ja).

Why: users on headless Linux boxes asked for a supported way to keep
`magpie serve` up across reboots instead of hand-written units. The
existing `magpie autostart` needs a desktop session (an XDG autostart
entry).

What was run:
- gofmt -l; go vet on darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test ./internal/daemon ./internal/cli on macOS, at origin/main
  5b9530b56.
- The daemon tests cross-built for linux/arm64 and run in a Debian
  container.
- The tests use fake systemctl, launchctl and loginctl on PATH in a test
  home.
- Each guarantee was broken by hand and its test went red: the % escape,
  the autostart refusal, the 0600 chmod, the bootout before re-bootstrap,
  the go-build refusal, the bus advice, the last-exit filter and the
  PATH link.
- Real use on Linux: a Debian bookworm container running systemd as PID 1,
  with the linux/arm64 build, as an unprivileged user.
  - install: the gateway answered on :3425, and the unit was 0600.
  - kill -9: systemd restarted it 5s later.
  - Container restart with linger on: it came back by itself.
  - restart, stop, start and uninstall worked, and the unit and its wants
    link were gone afterwards.
  - Under sudo without XDG_RUNTIME_DIR it printed the bus advice.
- macOS: the darwin build ran `magpie daemon install` under a sandbox HOME
  with a fake launchctl. plutil -lint passed on the plist, and the calls
  were print and then bootstrap.

What wasn't: no real launch agent was loaded on a Mac (deliberately: never
on this machine), so launchd's own acceptance of the plist is checked
only by plutil. The linger advice was checked by the unit test, not seen
from a real SSH login. Windows was not run beyond vet.
2026-10-13 17:05:59 +08:00
yetone 7d6358ff6b gateway: /v1/models can list each model by its bare id too, for apps moved from another proxy (love1sbug on X)
love1sbug moved from CLIProxyAPI: their clients ask for gpt-5.6-sol, and
magpie's /v1/models gave only codex/gpt-5.6-sol. "Provider in model names"
(36ca5432d, 6fa3109ea, 250bdd5c4) changes labels in agents' lists, never
ids, so no setting changed what the list returned. A bare request already
routed (serve: GroupFor, then Resolve); only the list didn't offer it.

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

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

Not tried: a real CLIProxyAPI client against a live gateway, or the
reporter's own setup; no CLI command for the switch (Settings only).
2026-10-13 16:55:27 +08:00
yetone 9b52fb504a gateway: Codex's web search on magpie's models answers, no longer 404 (anton on Discord)
anton on Discord (Linux): asked to look something up, Codex called its
web.run tool, which posts to <base_url>/alpha/search, here
http://127.0.0.1:3425/v1/alpha/search. magpie had no such route and
answered 404, and Codex takes any failed web.run as fatal, so the turn
ended.

Why Codex sends it: since 0.143 (#29909) Codex offers web.run to a
provider that sends x-openai-actor-authorization, as magpie's provider
table does, on a model whose catalog entry says use_responses_lite, as a
ChatGPT account's models do in magpie (codexcat copies Codex's own
entry). The request is codex-api's SearchRequest (id, model, input,
commands.search_query/open/click/find..., settings, max_output_tokens)
and the reply is {encrypted_output, output, results}, output being what
the model is shown.

What changed:
- POST /v1/alpha/search and /alpha/search are served (codex_search.go).
- A ChatGPT account's model goes to the ChatGPT backend's
  /backend-api/codex/alpha/search, as the official client sends it: on
  the account's sign-in (codexSign, no SSE Accept), the model bare, the
  body otherwise as it came (through redaction), only Codex's own
  x-openai-*/x-codex-* headers kept (codexHeader: never magpie's token or
  the actor header). Its own paused sign-in is passed over, the key's
  account and model holds kept, and the next account is asked on a
  non-2xx; the backend's answer is relayed as it is.
- Any other model's search_query/image_query (domains as site:) is
  searched by webSearch, as magpie searches for a model that can't. When
  nothing answers, or only open/click/find were asked, the reason goes
  back as a 200 with output, which the model reads, instead of a failure
  that ends the turn. A ChatGPT search that fails on every account falls
  back to the same, saying why.
- On the Codex backend path a magpie model's /alpha/search is served
  the same, never relayed on Codex's own sign-in; one of Codex's own
  models goes through magpie's accounts when its turns would
  (codexAccounts), else is relayed as before.
- docs/subsystems/gateway-routing.md names the route.

What was run (worktree on origin/main, sandbox HOME, private GOCACHE):
- New tests from Codex's own wire fixture (codex-api endpoint/search.rs):
  TestCodexWebRunSearchesOnChatGPTAccount (both paths; acct-1 429 ->
  acct-2, bare model, body kept, no magpie token/actor header, turn
  metadata kept), TestCodexWebRunChatGPTFailsSearchedByMagpie,
  TestCodexWebRunOnOtherModelSearchedByMagpie (no searcher hint, search
  API asked "OpenAI news site:openai.com", open-only, bad JSON 400, and
  a stub ChatGPT backend that fails the test if reached).
- Broken by hand three ways, each red: without the /v1 route (404 as
  anton saw), without the codexBackend case (relayed to the backend on
  Codex's sign-in), without the ChatGPT forward (searched by magpie).
- go test ./internal/gateway/ -timeout 30m, gofmt -l, go vet darwin,
  GOOS=linux go vet -tags nogui, GOOS=windows go vet.

Not tried: the real codex binary against a sandbox magpie, nor a real
ChatGPT account's /alpha/search; the shape is from Codex's source and
its own test fixture.
2026-10-13 16:49:29 +08:00
yetone dc2f0da820 gateway, gui: Image recognition and Web search pick how hard their model thinks (MOMO on Discord)
MOMO asked on Discord, "外置模型能不能提供思考深度选项": the model that
describes images (Image recognition, analyze_image) and the searcher's
model (e.g. Antigravity's Gemini 3 Flash) had no reasoning level of
their own to pick.

Settings › Models now has a chip beside each of those two pickers. It
opens the app's menu (openProtoMenu, no native select) and offers
Default plus only the levels that model has (Efforts, weakest first;
none shown when the model's levels aren't known, or the row is Off).
The pick is saved as settings.visionEffort / searcherEffort, one of
catalog.EffortRank or empty, and is checked on save. prefsKeep carries
both, so saving another setting keeps them.

Default keeps what magpie did before. Image recognition is still asked
at the least level the model has (classifyEffort), and the searcher
still gets no level. A picked level is fitted to the model's levels at
call time (fitEffort), and only these two calls carry it
(side_effort.go):
- askVisionWith sends reasoning_effort. The image cache key includes
  the level, so changing the level reads the image again.
- searchBody puts thinking (disabled for none, else enabled with
  budgetOf's budget) and output_config.effort (except for pre-adaptive
  Claude) on the searcher's Anthropic body. The gateway's translation
  turns that into each vendor's own form: adaptive or between_tools
  for new Claude, reasoning.effort for Responses, and thinkingLevel
  for Gemini 3 on Code Assist / Antigravity.
- A picked level raises max_tokens by its budget (replyRoom), so the
  thinking doesn't eat the reply.
- ownSearch and Kimi's search service are sent no level. A fallback
  searcher is sent the level fitted to its own model.

docs/subsystems/gateway-routing.md: new "How hard a side model thinks".

Tests:
- TestVisionEffortPicked and TestVisionEffortOnAnthropic check the
  vision body.
- TestSearcherEffortPicked checks the searcher body on new Claude, old
  Claude and Responses.
- TestSearcherEffortOnGemini checks the searcher body through
  buildCodeAssist for antigravity.
- TestSideEffortChecked covers settings validation.
- side-effort.test.cjs covers the chips: levels shown, a pick saved,
  Default clears it, toggle and Escape, no scroll, fit in the row and
  the menu inside the window. It runs in Chromium and WebKit at 1100
  and 420, in en/zh/zh-TW/ja/de.

Run:
- go test -tags nogui ./internal/gateway/ (full, -timeout 30m) on
  origin/main 3a9d73c5c + this change: everything passes except
  TestRateLimitIsWaitedOut "an hour away" (1.9s against its 1s bound,
  load ~190). That test passes on freshly fetched origin/main 41972b25f
  alone (-count=10) and in 8 parallel -cpu 1 copies. Filed as #1971.
- go test -tags nogui ./internal/settings/ ./internal/gui/: ok.
- Broken by hand, each goes red:
  - searchBody dropping the effort fails TestSearcherEffortPicked and
    TestSearcherEffortOnGemini;
  - askVisionWith back to classifyEffort fails TestVisionEffortPicked
    and TestVisionEffortOnAnthropic;
  - the settings check removed fails TestSideEffortChecked;
  - prefsKeep without the two fields fails side-effort.test.cjs.
- GUI:
  - side-effort.test.cjs: 10/10.
  - searcher-pick, images-*, vision-mcp, settings-search/sections/
    general, routing-vision-why and i18n-keys: 123/123.
  - 67 more Settings files: 778 pass. text-size "zh, dark ... 150%"
    failed in WebKit under parallel load; it passes 11/11 alone and is
    #1866.
- gofmt -l is clean. go vet passes for darwin, plus GOOS=linux and
  GOOS=windows with -tags nogui, on gateway, settings and gui. go build
  passes.
- Not tried against a real Antigravity or other real account: the
  request shapes are checked against fakes and the gateway's own
  translators.
2026-10-13 16:40:24 +08:00
Versun b2b015c584 provider: MLX-Serve's decision models classify routing groups through System One, separated from chat models by capabilities
MLX-Serve (github.com/ddalcu/mlx-serve) serves decision models (Clef,
Clef-Flash, Kev, Laya, D1) at POST /v1/systemone (and /v1/decisions). Its
/v1/models lists them alongside chat models, marking them with
capabilities: ["decisions"]. Setting a routing group classifier to an
mlx-serve decision model previously failed because the preset had no
decision endpoint and magpie offered it as a chat model, which MLX-Serve
rejected with 400.

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

Run:
- TestMlxServeDecisionModels: fake MLX-Serve answers with real captured
  fields. Clef-Flash with capabilities: ["decisions"] is a decider, chat
  models reach agents, and RouteDecider plus AskSystemOne post to
  /v1/systemone. TestModels tests clef-flash-4bit via decide. Red without
  mlxServeDecides in listsDecisions.
- TestListedMLXServeDecideTable: real captured response, vision modalities,
  `models` field fallback with omitted input_modalities, chat-only server,
  empty list, and invalid JSON.
- TestMLXServeWithoutDecisionModels: no decision model means none, not Jev.
- Real MLX-Serve on localhost:11234 in sandbox HOME with isolated config:
  provider add mlx-serve, provider refresh, provider test mlx-serve
  clef-flash-4bit (543 ms, decide OK), group add with classifier.
- go test -tags nogui ./internal/provider/..., gofmt -l, GOOS=linux and
  GOOS=windows go vet, cross-OS builds.
2026-10-13 16:34:59 +08:00
yetone 5e30d58fe4 usage: a request's row says the upstream's own stop reason on the Requests page, in /v1/magpie/usage/requests and in the CSV (#1927, Gluxggg)
What changed: the gateway has recorded why the upstream said each reply
ended (Record.Stop: a Responses reply's "completed", Chat's "stop" or
"tool_calls", Anthropic's "end_turn") since c5b57b907, and the Requests
page has a line for it ("Upstream stop reason"). But the page, and
/v1/magpie/usage/requests, read their rows from the packed row cache
(rowChunk), whose list of a row's strings (rowText) never had Stop: every
row came back with it empty, so the line never showed and the API row had
no "stop". rowText now carries it (packedRow.Text grows; the cache is in
memory only, so nothing on disk changes shape). The CSV export gets it
too, as a last column, upstream_stop, after 30869e35a's tier columns.

The same gap, a sibling: 30869e35a (#1784) added TierAsked, TierSent
and TierServed to Record, also without rowText, so the API's rows had
them empty too. They are in rowText now, and TestRowTextHoldsEveryString
sets every string of a Record (but Computer, the chunk's; Source, the
row's own; and the unlogged bodies), packs and unpacks the row, and
names any that came back empty, so the next field added can't be lost
the same way.

Why: #1927 asks whether a /v1/responses reply that ended in
response.completed with no tool call was the upstream's own end or one
magpie made up. In a Responses-to-Responses relay magpie writes no
terminal event of its own (a stream with none ends in response.failed,
#370), and the row's stop reason is the field that shows what the upstream
said; it was recorded in usage.jsonl and lost on the way to every reader.

Run: TestRequestPageKeepsUpstreamStop (the reporter's row, through
Append and QueryPage twice, cached; the packed chunk round trip; the CSV
column) fails with rowText put back ("the upstream's stop reason was
dropped from the page's row") and with the CSV cell left empty ("CSV"),
passes with the change. TestRowTextHoldsEveryString fails with
TierServed left out ("Record.TierServed comes back from the packed row
as \"\""). TestLedger* updated for the new column. go test
-tags nogui ./internal/usage/ ./internal/cli/ ok. gofmt, vets and the
gateway suite: in the series' last push record below.
2026-10-13 16:34:59 +08:00
yetone a65f2131dd gateway: a provider's model can be marked a video or image model in its editor (#1399, shen-joe)
shen-joe's relay serves a video model (agnes-video-2.5-flash), but its
/models list doesn't say "kind": "video". magpie only took a base-URL
provider's video models from that field, and its image models from that
field or from the model's name. So the model could never be asked at
/videos. They asked to tag video models, either in Settings or when
adding the provider.

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

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

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

Run:
- go test ./internal/provider ./internal/settings ./internal/gui
  ./internal/gateway: ok (gateway 1658s).
- TestCustomProviderVideoTheUserMarks, which goes red with the
  KindModels loop in video.go removed.
- GUI model-kind.test.cjs, 16/16 (en/zh/ja/de, 900/420, Chromium and
  WebKit). It goes red with the menu item removed.
- Sibling GUI tests: model-api-gemini, model-copy-id, model-api-preset,
  model-test-one/as/why, provider-detect-models, provider-typed,
  i18n-keys, gui-ja and gui-de.
- gofmt, plus linux and windows go vet -tags nogui.
- Not tried against Agnes's real API (no key).
2026-10-13 16:33:44 +08:00
yetone 3ccbe6bc15 plugins: a runtime for built-in plugins, and Plugins › Built-in to switch them (P0)
Lxxyx on X (https://x.com/Lxxyx_/status/2109506752656150974): magpie has
too much in it. This is P0 of making magpie's parts plugins, as DeepSeek
Harness does: a runtime, plugins.yml, and the first five built-in plugins
the user can switch off.

- internal/pluginrt: a registry (Register from init), a manifest (API
  caret range, Requires/Provides, Essential, InUse, Apply, Parts,
  Defaults) and Reconcile: the plugins no longer wanted, with whatever
  needs a service they provided, are disposed newest first; the wanted
  ones are applied once their services are there. A plugin that fails or
  panics is failed and the rest run. TestPluginsImportOnlyCore keeps the
  boundary: nothing outside plugins/ imports one, none imports another.
- plugins.yml (appdir.Config()): default → preset (essentials | all) →
  the user's rows → in use. A new install is written Essentials, a magpie
  that ran here before (settings.RanBefore) All, so existing users keep
  everything. Writes are locked, whole and keep a .bak; a file that
  doesn't parse is an error, never empty, and is never written over.
- plugins/groups, library, otel, sessions, warmups. In P0 a plugin off
  is the window's alone: its page, sections and rows (data-feature) leave
  the window; the gateway, TUI and CLI serve the same, nothing is
  deleted. One in use stays on.
- The window: Plugins › Built-in, the first tab, a switch per plugin;
  GET/POST /api/plugins/builtin; boot.js says which are off before the
  first paint. CLI: magpie plugin builtin [on|off <id>], plugin preset,
  plugin dump [--json].
- docs/subsystems/plugin-runtime.md, gui-shell.md.

Run: go test ./internal/pluginrt/ ./internal/settings/ ./internal/gui/;
gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows
go vet ./.... GUI: builtins.test.cjs in Chromium and WebKit, 5 languages,
1100/800/420; list-sort, mobile-web, routing-keys-fold, routing-sessions
pass. By hand under a sandbox HOME: a new install gets essentials, an
existing one all, a broken plugins.yml is refused and kept, dump works.
Full suite results after the rebase are in the push notes.
2026-10-13 16:19:13 +08:00
yetone f2b0780fa2 gateway: a held rule fails over within the member it chose, and a fallback outside it isn't kept for the turn (#1946, XcodeFish)
A group of coding-fast and coding-quality, its rule sending turns to
coding-quality: when coding-quality's member failed mid-turn the request
went to coding-fast's members before coding-quality's other one, and the
turn then stayed on coding-fast. Within a turn the rule is held, and
when affinity kept a member the rule's order wasn't applied at all
(gateway.go and nestedRules skipped `hit.Held && aff.Kept`), so the
failover order was the kept one, then the parent's own order.

ruleOver (rules.go), used at the group's rule and every nested group's:
- the kept one stays first while it is of the rule's member that goes
  first (the one it names, or a Then's while that is resting); the
  rule's other members follow it, ahead of the group's others;
- one kept outside that member, which took over when it failed, isn't
  held: once a member of the rule's target is out of its rest, the next
  request of the turn goes back to it (Affinity.Why "rule"). While all of
  it rests, the fallback stays. No new option.
docs/subsystems/gateway-routing.md says so.

Run (before the rebase onto origin/main): go test -tags nogui -count=1 ./internal/gateway/: green but for
TestKimiHeldBurstTellsNoSpeed at load average ~139 (passes 3 of 3
alone; filed as #1963, not on this path),
gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway/.
TestHeldRuleFailsOverWithinItsMember fails on the old code (tried
[kq1 kf1], the reporter's order), and with the go-back part disabled by
hand (round 3 kept on f1).

After the rebase: gofmt, both vets, and go test -run
'Rule|Group|Affin|Nested|Stick|Turn|Classif|Decide|Pause' ./internal/gateway/ green.
2026-10-13 16:18:05 +08:00
yetone a894559e23 library: a project's skills and MCP servers reach Qoder, CodeBuddy, Droid, Cline and Command Code (eirc on Discord)
eirc could give Qoder and other agents skills and MCP servers only
user-wide; Library's project page didn't offer them. Each agent now gets
the project folder or file its own source or docs say it reads:

- Qoder, Qoder CN: skills in .qoder/skills, servers in
  .qoder/settings.json's mcpServers (@qoder-ai/qodercli and
  @qodercn-ai/qoderclicn 1.1.69: projectConfigDirName ".qoder",
  getProjectSkillsDir = <config>/skills; docs.qoder.com/cli/mcp-reference).
- CodeBuddy Code: skills in .codebuddy/skills, servers in .mcp.json, or
  mcp.json when the project has only that (2.164.0 reads the first of
  [.mcp.json, mcp.json]).
- Droid: servers in .factory/mcp.json, skills in .agents/skills
  (docs.factory.com).
- Cline: skills in .agents/skills (CLI 3.0.70 reads .clinerules, .cline
  and .agents /skills).
- Command Code: skills in .commandcode/skills (commandcode.ai/docs/skills).

Left out, unconfirmed: Command Code's project MCP (.mcp.json in its own
transport shape, which would clash with Claude's), Copilot CLI's project
MCP, Zed's .zed/settings.json, WorkBuddy. docs/subsystems/library.md gets
a Projects row.

Run: go test -tags nogui ./internal/library (temp HOME, pinned module
cache); the three new tests in project_targets_test.go fail with the map
entries reverted ("magpie knows of no folder qoder reads a project's
skills from"), and the CodeBuddy mcp.json test fails with that fallback
turned off. gofmt -l clean; go vet -tags nogui on darwin, linux and
windows. No GUI asset changed (the page takes both from sync.go). Not
tried with the real Qoder, CodeBuddy or Droid CLIs.
2026-10-13 16:16:24 +08:00
yetone 110b204313 sessions: Pi's and omp's own calls reach Usage, here and in WSL (#1951, Elenoxe)
Pi in WSL on a provider of its own never reached the Usage page: the
call ledger had no reader for Pi's or omp's session files, so only what
went through magpie's gateway was counted, and Sessions showed tokens
that Usage didn't.

calls_pi.go reads them whole, as call_cache's wholeCallReaders does for
Kimi, from piFiles, ompFiles and wslFiles("pi","omp"):
- each assistant message is a call on its own provider and model, with
  Pi's durationMs or omp's duration/ttft;
- "usage" / "model_usage" entries on the provider they name, and a
  compaction's, branch summary's or tool result's usage on the model in
  use, as Sessions counts them;
- a call through magpie's own entry (provider "magpie", "dial" before
  the rename) is left to the gateway, which logged it already;
- a failed call (no usage) is none;
- a fork's copies of its parent's entries (written before its header's
  time) are the parent's, and a call is keyed by entry id + time.

The fixtures are Pi 1.1.0's and omp 18.9.1's own files, written in a
sandbox HOME against a fake OpenAI-compatible relay (a run, a pi --fork
of it, a session whose calls failed before it went on through magpie);
the magpie lines are the owner's own Pi's, the reply text left out.

Run: go test -tags nogui -count=1 -timeout 45m ./internal/sessions
./internal/usage ./internal/cli ./internal/gui (green); gofmt -l; go vet
-tags nogui on darwin, GOOS=linux and GOOS=windows for internal/sessions.

Broken by hand: with the reader unregistered TestPiCalls finds 0 pi
calls and TestWSLSessionsListed says the distro's pi calls aren't
counted; without the magpie skip TestPiCalls/BesideReplies count the
gateway's calls; without the fork rule reading the fork's file alone
gives its parent's calls too.

Not tried: a real WSL distro (wslFiles is covered by the existing fake
distro), Windows paths at runtime, real "usage"/"model_usage"/
branch_summary entries beyond the fixtures. Grouping the Sessions
agent strip by WSL distro stays open in #1951.
2026-10-13 16:08:07 +08:00
Ha1baraA11 a75fa9e54a gateway, provider: OpenRouter's image-only models draw on its /images API, not chat (#1116, fixes #1105)
OpenRouter answers a chat request for gpt-image-*, seedream, flux,
qwen-image, grok-imagine and the like with 404 "Use the /api/v1/images
endpoint instead", and viaFor sent every OpenRouter model to chat. Models
catalog.ImagesAPI names now go to OpenRouter's POST /images, with reference
images as input_references (image_url parts) and its media_type and
prompt/completion token usage read back; a 404 there is returned as is
rather than retried on chat. Gemini and gpt-5-image stay on chat. The
provider Test probe asks the same endpoint.

Run: go test -tags nogui ./internal/gateway/ ./internal/provider/
./internal/catalog/, go vet (darwin, linux nogui, windows), gofmt. With
the /images dispatch removed, both new gateway tests go red. The real case
(owner's OpenRouter key, sandbox HOME, a throwaway test not committed):
openai/gpt-image-1-mini at quality low drew one image, 200, usage 12/272,
and with that image as a reference drew again, 200, usage 1035/272. The
request shape matches OpenRouter's openapi.json ImageGenerationRequest.
2026-10-13 16:00:31 +08:00
yetone 2362bfced3 redact: a placeholder the model rewrites ({{ PHONE_x }}, a dropped brace, another case) comes back as the value (shensmart on Discord)
shensmart, with personal data masked, saw {{PHONE_…}} left in the
model's replies. Every reply path already goes through redact.Writer
(serve, Codex's upstream, count_tokens, embeddings, image and video
prompts; plugin-served providers write into the same wrapped writer),
and an exact placeholder came back on all of them, split across
Anthropic, Chat Completions, Responses and Gemini SSE events alike. What
didn't come back is a placeholder the model wrote differently from how it
was given: Jinja-style {{ PHONE_x }}, {{PHONE_x} or {PHONE_x}, the bare
PHONE_x, or the hash in upper case. Restore matched only the exact form.

Restore now finds a placeholder's body (KIND_ and the 8 of the hash), in
any case, at a word boundary, and puts the value back when it names one
magpie made, taking with it the braces and spaces the model put around
it (both braces of a side, or one of each side; a lone { on one side is
the text's own). The 40-bit keyed hash means no other text matches.

For streams, partialTail also holds a tail like "{{ PH", "{{PHONE_x}"
(the second brace still to come) and a last word that starts like a kind
magpie has masked (PH, PHONE_b5pu), and Writer.event now looks for the
tail before restoring, so a placeholder whose closing brace is in the
next event is not put back with that brace left behind in the text.

Not changed: the values stay in memory only. The placeholder key is kept
in redact.key, so after a restart the same value gets the same
placeholder, and the agent's history holds the real value (it was put
back), so the next request brings it again; checked by masking, clearing
the map and key as a restart does, and masking the history again.
Writing the map to disk would keep every masked secret in one file.

Run: go test ./internal/redact ./internal/gateway (sandbox HOME), gofmt,
go vet and GOOS=linux/windows go vet on internal/redact.
TestRestoreRewrittenPlaceholder, TestWriterStreamRewrittenPlaceholder and
TestWriterStreamToolArgsRewritten fail on the old redact.go/writer.go;
with the old writer.go alone the stream test fails with "13987654321 }}"
(a stray brace); with wordTail turned off it fails with a bare
PHONE_zdx44tzn left in the text.
2026-10-13 15:57:12 +08:00
yetone b8e23db45a backup, davsync: an import or a sync installs the plugins and names the subscriptions to sign in to (yapechan)
yapechan on Discord (Windows, Synology WebDAV): after an import or a WebDAV
sync no providers showed on the other computer; adding the same provider by
hand made the synced settings and usage apply. No error, a restart didn't
help.

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

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

Run:
- go test -tags nogui ./internal/provider ./internal/backup ./internal/davsync
  ./internal/cli ./internal/gui in a sandbox HOME.
- New tests fail with the change broken by hand: TestPluginsCarried
  (installed-skip and the HandOver guard), TestNotSignedIn,
  TestRestorePluginsAndSignIn ("Needs a key: [ Acme]" without OnlyPicks),
  TestSyncPluginsAndSignIn (bring not installing, Status not naming),
  sync-sign-in.test.cjs (the lines removed).
- sync-sign-in.test.cjs: Chromium and WebKit, en/zh/ja/de, 900 and 440px,
  16/16; it also caught subNames throwing while providers was still null.
  sync-*.test.cjs, s3-sync, i18n-keys, gui-ja, gui-de pass.
- gofmt -l, go vet, GOOS=linux and GOOS=windows go vet -tags nogui on the
  touched packages.
Not tried: a real plugin install from a real sync (the installs are stubbed
in tests); a real Synology server.
2026-10-13 15:52:17 +08:00
yetone cb003877f3 agent: a renamed provider's models follow it in Pi's, OmO's and Prime Agent's enabledModels (#1828, #1919)
The sibling of the StepCode fix before this, and of omp's (e6753190).
Renaming a provider moved Pi's defaultModel and appended the new ref to
settings.json's enabledModels (piScopeWith), but left the magpie/<old>/
entries, which name nothing after the rename; Pi then leaves those models
out of Ctrl+P. piLikeKeyed, which Pi, OmO and Prime Agent are all built
from, now has a RenameRefs hook: magpie/<old>/ entries are renamed, a
glob or a :level kept, and the copy the move just appended is dropped so
the model stays where the user had it. The user's own entries and a name
that only shares a prefix (magpie/deepseekx/...) stay; a list naming none
of the provider's models isn't rewritten. Pi keeps no scope stash of its
own (Disconnect's before-magpie copy is from before magpie wrote), so
there is nothing else to rename.

StepCode's rename helpers move to rename.go as renameRef/renameRefList
so both use one list rule.

Run:
- TestPiEnabledModelsFollowRename (new), for pi, omo and prime-agent:
  red with the hook returning early (old entries kept, magpie/ds/pro
  appended beside magpie/deepseek/pro), green with it.
- go test -tags nogui -count=1 -timeout 80m ./internal/agent on this
  tree (StepCode commit + this): ok, 999s, under a temp HOME. Load
  average ~120 from other sessions; the earlier run of the StepCode
  commit alone hit the default 10m timeout for that reason, not a hang.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
2026-10-13 15:50:20 +08:00
yetone b515538ad6 gateway: the model list names each model's service tiers for every client, so Cindy offers Fast where it is offered (#1914, tsuixl)
Cindy reads supportsFastMode from a model's service_tiers in /v1/models
(a priority entry), and its import link asks /v1/models with no magpie
header. The models handler gave service_tiers (codexTiers, the tiers
Codex here is offered on each model, #1234) only to a magpie asking with
X-Magpie-Drawers, so Cindy never showed Fast on GPT-6-Astra / GPT-6.1-Sol.
Every client now gets them; a model with no tier says nothing, and the
remote-magpie path is unchanged.

The context ring showing "—" in the same report is not touched: per the
reporter's own reading it is Cindy's Codex runtime wanting native
metadata, which /v1/models already carries as context_window.

Run:
- TestModelsListTiersForEveryClient (new): a relay's gpt-6.1-sol lists
  priority, its glm-5 lists none, on a plain GET /v1/models. Red on the
  old handler ("" for gpt-6.1-sol), green now.
- go test -tags nogui ./internal/gateway on every test in the 39 files
  that GET /v1/models plus every *Tier* and *Fast* test: ok (110s).
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- Not tried in a real Cindy: whether Cindy's Fast then sends
  service_tier priority through its Codex runtime is left to the
  reporter on the next release.
2026-10-13 15:50:19 +08:00
yetoneandggbdpq 90ac1f0385 agent: a renamed provider's models follow it in StepCode's enabledModels (#1919, ggbdpq)
Renaming a provider moved StepCode's defaultModel to the new id and
appended it to enabledModels, but the list kept magpie/<old>/ entries
(the model it was on, others the user listed, a glob), which name nothing
after the rename. StepCode now has a RenameRefs hook, as omp has
(e6753190): it renames magpie/<old>/ entries in config.toml's
enabledModels, drops the copy the move just appended, and renames the
scopes kept for Disconnect (OrigScope, LastScope, AppendedScope), so a
reset neither puts the old id back nor leaves the appended one. An entry
that only shares a prefix (magpie/deepseekx/...) and the user's own
entries stay; a list naming none of the provider's models is not
rewritten.

ggbdpq's patch from #1919, taken as written.

Run:
- go test -tags nogui -count=1 -run 'TestStepCode' ./internal/agent: ok.
- With only the RenameRefs hook removed, TestStepCodeEnabledModelsFollowRename
  fails with the scope the issue quotes; TestStepCodeRenameLeavesUserScope
  is a guard and passes on the old code too.
- -race -count=5 on the two new tests: ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- The full ./internal/agent package timed out at the default 10m on a
  machine at load ~120 (many sessions testing at once); the run with
  this and the Pi sibling together is in the next commit's body.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-13 15:50:19 +08:00
Zhizhen He 97751188ea library: an unreadable skill copy stays in place during sync (#1102)
An unreadable subfolder in an agent's copy of a skill hid edits from the
timestamp scan, which ignored read and stat errors. So switching copy/link
mode, refreshing the skill, or removing a duplicate copy could replace the
copy and lose those edits. Shared-folder deduplication could remove
SKILL.md before failing on the unreadable subtree. changedAt and
copyIsFresh now return the scan error. The copy is kept in place for that
sync (Library.blockedSkills) and reported as a Problem naming the path.
This covers agent copies, shared-folder deduplication, project copies and
Claude Desktop copies. Other agents still sync, and a later sync tries
again once the copy can be read.

Merged onto main. #1449 added two callers of changedAt in
skill_changed.go:
- libraryHash doesn't remember a hash for a folder it couldn't wholly read.
- editState says unknown for an agent's copy it couldn't wholly read, so
  an update from GitHub keeps the library's version aside.
TestEditStateUnknownForAnUnreadableCopy covers editState.
docs/subsystems/library.md keeps both new rules.

Run:
- go test -tags nogui ./internal/library/ and ./... (see the PR), go vet
  for darwin, linux with nogui, and windows, and gofmt.
- With changedAt ignoring walk errors again, the four ScanError and
  EditState tests go red.
- With editState ignoring the error, the new test goes red
  (edited true, known true).
- Checked with Unix permissions on macOS only, not as root and not on
  Windows.
2026-10-13 15:44:02 +08:00
yetone f82aba090b davsync, gui, cli: GitHub sync refuses a repository that isn't private (#1130)
The sealed setup is committed on every sync, so a public repository would
hand anyone every version of it, the whole history, to try passphrases on
offline. prepare now reads the repository's "private" field and refuses
before writing when it is false or missing, naming the repository and what
to do. The form's hint, the CLI usage and docs/reference.md say the
repository must be private; sync-backup.md lists the rule and its
verification command now points at ./internal/cli.

Run: go test -tags nogui ./internal/davsync/ and the cli tests
(TestGitHubCmd|TestWebdavCmd|TestS3Cmd|Help) green;
TestGitHubPublicRepositoryRefused goes red with the check removed. GUI:
github-sync, s3-sync, webdav-settings-refresh, sync-other-kind,
sync-not-backup, i18n-keys, gui-zh-tw, gui-ja, gui-de in Chromium and
WebKit, 72/72. Not tried against the real GitHub API.
2026-10-13 15:25:10 +08:00
bingqilinweimaotai 1af326806f sync: magpie's setup syncs to an encrypted file in a GitHub repository, beside WebDAV and S3 (#1130)
A third sync kind: github://owner/repo[/folder] keeps the same sealed
backup WebDAV and S3 keep, as <folder>/magpie/magpie.magpie-backup in a
repository the user already has, written through GitHub's Contents API
with a fine-grained token of its own (Contents read and write), kept in
sync.json apart from the library's GitHub token. The token goes only to
api.github.com: a redirect anywhere else is refused, and the passphrase
may not equal it. Each update is a commit; an empty repository is
initialised by the first backup. Settings › Sync gets a GitHub kind with
Repository, Branch, Folder and token; magpie github mirrors magpie s3.
Inactive servers of every kind are kept in Config.Servers (Other stays
for older clients).

Squashed from yetone/magpie#1130 at 6b5b1c693e1a3a23e177b4d376f3f7f70f3bc23d
onto main. Merge resolutions: the CLI moved to internal/cli since the PR
was cut, so github_cli_test.go moved there (package cli) and the github
command, its help line and `magpie help github` were wired in
internal/cli/main.go and help_cli.go; README's Sync row kept main's
links and took the PR's wording; i18n.js zh-TW kept both sides.
2026-10-13 15:25:06 +08:00
yetone 1133ca0fe2 gui: the window opens on the page you last left, as a Mac app comes back as it was
molvqingtai on Discord asked for Routing to be the first page, and lc for
the sidebar to be reordered by drag. Rather than a setting or a reorder,
the window now reopens on the page the reader last left: show() keeps the
page in localStorage magpie.lastView, and keptView() opens it at start.

- A page asked for in the address (?view=: the tray's links, a reload)
  still wins, Agents too.
- A kept name that is no page opens the first page; one gateway mode
  leaves out (Agents, Library) opens Providers, through show()'s and
  setGatewayMode's existing fallback.
- localStorage is how the window already keeps magpie.navLayout and
  magpie.panelTab across restarts; checked on a copy of the installed
  app's WebKit store (~/Library/WebKit/com.yetone.magpie), which holds
  those keys from earlier runs.
- Opening on the kept page scrolls nothing.

docs/reference.md and docs/subsystems/gui-shell.md say so.

Run:
- internal/gui/tests/last-page.test.cjs (new), Chromium and WebKit, at
  1100 (sidebar) and 420 (header tabs): left on Routing, opened again with
  no ?view= and reloaded -> Routing, nothing scrolled; Settings kept;
  ?view=usage and ?view=agents win; an unknown kept name -> Agents;
  gateway mode with agents/library kept -> Providers, routing kept ->
  Routing. Broken by hand, it goes red: with show() not saving, with the
  kept page not restored, with the kept page beating ?view=, and with
  both gateway fallbacks removed.
- model-rate.test.cjs opened "/" after Providers and took it for Agents;
  it now asks for ?view=agents.
- 171 GUI files that navigate more than once or touch the start page
  (gateway-mode, sidebar*, nav-*, click-scroll, view-*, getting-started,
  side-toggle, panel-*...) plus 151 that open the bare root URL, both
  engines, 5-6 files at once: all green but model-rate (fixed above) and
  load flakes that pass alone here and on origin/main 1e8859838:
  sidebar-overlay-scrollbar (#1863), sessions-toolbar (#1426),
  agent-stale-copies and copilot-ghe (route callbacks outliving the page,
  filed as #1949).
- go test -tags nogui ./internal/gui, gofmt -l, go vet ./internal/gui on
  darwin, GOOS=linux and GOOS=windows -tags nogui.
2026-10-13 15:10:25 +08:00
yetone 419ef30219 gateway: Claude Code gets a safety refusal as Anthropic's own, and switches to its fallback model; how many more accounts are asked is a setting (#1925, DD on Discord)
DD on Discord: through magpie, Claude's safety filter refusing a turn never
makes Claude Code move to its fallback model, as it does on Anthropic's API.
magpie asked every other account and group member (#248), then told Claude
Code a 400 "<model> refused this request", which it takes as an API error.

Claude Code 2.1.296 switches on stop_reason "refusal" in a 200 reply (the
stream's message_delta or a whole message, stop_details giving the
category), and only with a fallback model set; a 400, Anthropic's
"Output blocked by content filtering policy" or magpie's, is never retried.

What changed:
- When nobody is left after a refusal, an agent on Anthropic's Messages API
  gets the held refusal itself, the vendor's 200 with stop_reason and
  stop_details, streamed or whole (holdWriter.handBack): keyed Anthropic
  providers, groups, the Claude subscription. Codex and Chat clients keep
  the 400, since an empty-looking whole reply makes Codex ask again.
- Settings' refusalRetries counts how many more candidates (accounts, then
  group members, another model among them) a refusal is asked of. Unset is
  every one, #248's behaviour (Koohoko asked for it); 0 hands it straight
  back. GUI: Settings > Models > Replies > "Ask again after a refusal"
  (Never ask again, 1, 2, 3, All), en/zh/zh-TW/ja/de. Global, no CLI:
  magpie has no general settings CLI (as noLoopGuard). Other 400s are still
  never asked again; refusals still rest nobody.
- disabled-models.test.cjs wheels to Enable, which the new row put past the
  window's foot at webkit de 420.
- Docs: reference.md "When the safety filter refuses", gateway-routing.md.

Run:
- go test -tags nogui ./internal/gateway (full, -timeout 40m: a first run
  hit the 10m default at load ~70 from other sessions), ./internal/gui,
  ./internal/settings; gofmt -l clean; GOOS=linux and windows go vet.
- GUI: refusal-retries-setting (en, zh, zh-TW, ja, de at 1100 and 420) with
  gui-zh-tw, gui-ja, gui-de, i18n-keys and every tab=models suite
  (disabled-models, images-*, loop-guard-setting, member-model-setting,
  search-*, searcher-pick, vision-mcp), chromium and webkit: 176 pass.
- refusal-retries-setting under load (8 runs at once, load ~200): first
  4 of 8 failed at en/ja 420, a press landing on the first save's "Saved"
  note over the row, then WebKit's wheel still moving the view as the
  press was measured. It now reaches each button clear of anything drawn
  over it (reader.cjs reach) and waits for the scroll to rest: 16 of 16.
Broken by hand:
- handBack off: TestRefusalRetriesNoneHandsClaudeCodeTheRefusal,
  ...CountsTheTries, ...Group, ...ClaudeSubscription and
  TestRefusalWithNobodyLeftIsAnError fail (400 "refused this request").
- count ignored: those plus ...CodexStillTold400 fail (the next key answers).
- GUI keep-on-omit dropped: TestSettingsRefusalRetries fails; the GUI test
  fails with All sent as undefined, and with the row not appended.
Not tried: a real Claude account's refusal, or Claude Code's fallback
switch end to end; the refusal shapes are from Claude Code's source and
Anthropic's docs.
2026-10-13 15:06:20 +08:00
geoqiao 3a9d73c5c6 gateway: a plugin's deferred usage is billed with its step, never told as the prompt
The Cursor plugin collects a tool step's late usage event with the
conversation's next step. It used to add it to that step's prompt_tokens,
which agents read as how full their context is: pi saw 366940 tokens
(181270 + 185670) on a 300k window where 185670 were in use, and compacted.
The plugin now reports it apart, as usage.magpie_deferred (yetone/magpie#1053).

The gateway parses the field into Usage.Deferred and adds it only where it
bills: the usage records (6 sites in serve), the OTel attempt span and route
pricing, as a tier before the request's own, so promptCounted still reads the
request's own prompt. What a client is told (Usage.chat, the Anthropic
encoding) stays the request's own. A reply without the field is handled as
before. docs/subsystems/provider-plugins.md describes the field.

Verified: go test -tags nogui ./... (50 packages ok, sandbox HOME, caches
pinned); gofmt; go vet on darwin, linux (nogui) and windows; go build on the
same three. The new tests were broken by hand and each went red: billed()
ignoring Deferred, cUsage dropping the field, routeUsage without the tier,
Usage.add forgetting it, the decoder ignoring a usage with only a deferred
part, the usage records and the OTel span not using billed(). Not tried: a
real Cursor account on this checkout; the plugin side was run against real
Cursor (composer-2.5, forced late events), where the deferred totals matched
the dashboard's events token for token.

Picked from geoqiao/magpie cursor-deferred-usage (595d6384c), as PRs here
are collaborators-only. Rebased over the service-tier logging (#1784),
keeping its TierAsked/TierSent/TierServed beside billed() at the three
usage.Record sites, and Usage's Tier beside Deferred. Run on this tree:
go test -tags nogui -timeout 40m ./internal/gateway and ./internal/provider
(sandbox HOME); gofmt -l; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows. billed() forced to ignore Deferred: 3 tests and 5 subtests
of deferred_usage_test.go go red.
2026-10-13 14:50:48 +08:00
yetone ab1006bb80 gui: each WorkBuddy, Trae CN, MiniMax, Qoder or plugin account's daily check-in can be turned off on its own (#1902, magicLaLa)
settings.CheckinOff lists the accounts left out, by their entry in the
vendor's check-in file ("workbuddy|<uid>", "trae-cn|<uid>", a plugin's
"<provider>|<account>"). checkinNow skips them, both in the loop and on
Check in now. provider.CheckinAccounts() lists every account a check-in
reaches; /api/settings carries it as checkinAccounts, and
POST /api/settings/checkin-account {key,on} turns one off or on. A full
/api/settings save keeps the list. Settings shows an Off/On switch per
account under each vendor's Daily check-in row when it has 2 or more
accounts; the Usage card says "Auto check-in is off for this account" and
offers no Check in now for it. en, zh, zh-TW, ja, de.

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

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

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

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

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

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

Not run: not tried with real ChatGPT accounts or the Codex app.
2026-10-13 14:35:08 +08:00
yetone 30869e35a7 usage, gateway: each request's log row says the service tier asked, the one each try was sent at, and the one the vendor said it ran at (#1784, zhenghaowen0967)
What changed
- usage.Record has tier_asked, tier_sent and tier_served, and the CSV gets
  them as its last three columns.
  - tier_asked is the client body's service_tier (Claude's speed fast reads
    "fast").
  - tier_sent is the tier the try's last request actually went out at. It
    is noted in forwardOnce after every rewrite (a fast pick's priority,
    Ultrafast turned to priority on a plan without it, buildResponses
    dropping a tier the host can't take) onto the per-attempt wireAt. So a
    handed-on try's own row has its own tier.
  - tier_served is only what the reply said: service_tier at the top level,
    in response.service_tier, or in an Anthropic usage. It is read by the
    relay sniffer and by both translated readers, and is empty when the
    reply says nothing. It is never filled in from the ask.
- Codex's own relayed sign-in (codex_backend) records the same three.
- /v1/magpie/route: Route.tier (asked), and each Try has tier and
  tierServed. The session route has asked_tier, tier, tier_served and each
  try's tier and tier_served.
- docs/reference.md (CSV columns) and gateway-routing.md describe them.

Why
zhenghaowen0967 asked that a request whose Ultrafast was sent as priority
to an account without it show that in usage, per try, without calling
the served tier confirmed unless the reply says so.

What was run
- TestTierRecordedPerTry. With Pro out, the first try is recorded
  ultrafast, the second priority, and the final record has asked=ultrafast,
  sent=priority and served empty while the fake doesn't echo. With an
  echoing fake, served is what it said ("ultrafast", and "default" when
  none was asked). It also checks the CSV columns, and the Codex relay path
  with priority.
- TestUpstreamTierShapes covers the Chat chunk, Responses
  response.completed, a Responses body, an Anthropic message_start and
  message_delta usage, null, an over-long tier and non-JSON, as well as
  bodyTier per protocol.
- Broke it by hand:
  - with forwardOnce's noteWireTier removed, TestTierRecordedPerTry goes
    red (route tries' tier empty, TierSent empty);
  - with the sniffer's Tier line removed, TestUpstreamTierShapes goes red,
    and so does the Codex relay case of TestTierRecordedPerTry.
- go test -tags nogui ./internal/gateway ./internal/usage ./internal/cli;
  ledger_test's CSV expectations gain the three empty columns.
- gofmt -l; go vet on darwin; GOOS=linux and GOOS=windows go vet -tags
  nogui.

Not done
- The served-tier fixtures are built from the shapes OpenAI and Anthropic
  document, not from saved replies. Whether chatgpt.com's Codex backend
  echoes service_tier wasn't tried against a real account.
- Bridges that don't go through forwardOnce (the Claude subscription,
  Cursor's built-in) leave tier_sent empty.
- There is no price multiplier for priority/ultrafast and no GUI column.
2026-10-13 14:22:53 +08:00
yetone 62390fe92e redact: a masked word is never masked inside tool definitions or schemas, so Codex's apply_patch grammar reaches OpenAI intact (#1911, loveNangua)
What changed: MaskJSON masked custom words as raw substrings in every
string of the request, tool definitions included. A word "pd" turned
apply_patch's Lark rule name update_hunk into u{{TERM_..}}ate_hunk and
OpenAI refused the request with 400 "Invalid lark grammar". Definitions
are now kept by where they sit in the protocol, not by a key's name:
the request's top-level tools, tool_choice, functions, function_call,
toolConfig/tool_config, response_format, text (an object), reasoning,
include, output_format, output_config and generationConfig, and the
tools of a Responses input item of type additional_tools or
tool_search_output. Inside them only "description" strings are still
masked. A "tools" or "text" key in tool-call arguments, a message, a
Gemini part or a Responses message item is masked as before.

Run: go test ./internal/redact/ ./internal/provider/ (ok). The new
tests use Codex 0.162.1's real request (copied from the gateway's
testdata) with the top-level tools and as a Responses Lite
additional_tools item, plus Anthropic/Chat/Responses/Gemini schema
cases and negative cases. With the old json.go both tests fail
(update_hunk masked, every schema case changed). gofmt -l clean; go vet
-tags nogui on darwin, linux and windows. Not tried: a real request to
OpenAI with the word set.
2026-10-13 14:14:59 +08:00
yetone 488569227e zhipu: a GLM Coding Plan key at the pay-as-you-go endpoint is asked again at the plan's, and the provider moves there
@cleverpigo on X: "glm coding plan放在codex/chatgpt里显示余额不足没法用". The editor
showed OpenAI https://open.bigmodel.cn/... red with 429 · 余额不足或无可用资源包,
请充值。 next to a green Anthropic https://open.bigmodel.cn/api/anthropic.

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

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

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

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

Not tried: a real Zhipu or Z.ai key. None was available, so the 1113
body and the coding endpoint's answer come from the report and the
presets, not a live call.
2026-10-13 13:59:17 +08:00
Rupert-WLLP-Bai 81f587d7be sessions: omp's sessions in a WSL distro are listed on Windows, on the Sessions page and in Usage's Sessions tab, as Claude Code's, Codex's and Pi's there already are (#1150, #1138)
omp keeps its sessions under ~/.omp/agent in the distro's home, and in
a profile's own folder for omp --profile. wslAgents now names omp, and
allFiles reads wslFiles("pi", "omp"), so a distro's omp sessions show on
Windows marked with their distro and resume through wsl.exe. A session
under a profile resumes with omp --profile <name> --resume <id>; a
profile name that isn't plain ([a-z0-9][a-z0-9._-]{0,63}) gets no resume
command rather than one built from it (resumeCommand takes the session's
path for this).

Squashed from yetone/magpie#1150 at d7968f11b2ef419e30e1a6a169554b12e58c885a
onto main; docs/subsystems/gui-shell.md conflicted and keeps main's
"Streamed output speed" section and the PR's "Stored agent sessions in
WSL" section.

Run at this tree: gofmt; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows; builds for all three; go test -tags nogui on
internal/sessions, internal/gui and internal/agent (agent with
-timeout 45m, it took 17 min on a loaded machine) green.
Broken by hand: with omp taken out of wslAgents, TestWSLSessionsListed,
TestWSLOmpSessionDeleted, TestWSLOmpProfiles, TestWSLStoppedDistroKept
and TestWSLStoppedSinceNotOpened go red.
Not tried: a real WSL distro with omp on the Windows box.
2026-10-13 13:49:16 +08:00
timonwong 79099d6adb provider, gui, tui: Ollama, LM Studio and oMLX take an address, so a server on another port or computer is the preset's provider (#1165)
The three On this machine presets were pinned to localhost and their
default port: one started on another port, or on another computer on
the LAN, had to be rebuilt as a custom provider or typed URL by URL in
the CLI. They now take an Address (scheme, host and port), and each of
their URLs keeps its own path there (provider.AtAddress, AddressOf; no
scheme means http, only http/https, port 1-65535, a pasted path is
dropped, anything else refused with nothing changed).

- GUI: the add and edit editors have a Server address section under the
  key, folded unless the saved address isn't the preset's, opened and
  focused on a refused one. The Endpoints, Test and Refresh follow what
  is typed; URLs are sent only when the address changed, so ones set
  apart (an import, the CLI) are left alone. zh, zh-TW, ja, de.
- TUI: adding a local preset asks for its address before the key (Enter
  keeps the default), and w edits it.
- CLI: the usage shows provider add ollama url=... anthropic=....
- LM Studio's and oMLX's notes say "port N by default".

timonwong's PR head e63cf18e, merged onto main, which had given oMLX a
decision API (#1641) since: presets.go keeps main's oMLX Decide; app.js
keeps both the Vertex block and the address one; the docs row and -run
list take both.

Run: see the next commit.
2026-10-13 13:47:58 +08:00
yetone eba7187368 gateway, provider, cli, gui: a group can route By weight, each member's share set beside it (#1910, DD on Discord)
DD asked for weighted round robin as a group routing, next to In turn.
A provider's keys could already route by weight (#841). Groups could not.

What changes:
- provider: Group.Weights maps a member's spelling to its weight, 1 to
  1000. A member left out, or set to 0, weighs 1. SaveGroup accepts
  routing "weight". It also cleans weights the way it cleans fast and
  off: it strips :fast, drops weights of members that are gone and of
  members weighing 1, and refuses a weight below 0 or above 1000.
  Weights follow a member when it is renamed (RenameMember, Rename,
  RenameGroup) and survive Share/Import.
- gateway: planLevel treats each member of a weight-routed group as one
  unit: a model with its keys in its provider's order, or a nested group
  routed its own way. weightedUnits orders the units by smooth WRR on a
  round per group ("group/<id>"), sharing wrrPick with the keys. The
  round's pick goes first and the rest stay in member order for
  failover. A unit whose head is resting leaves the round. When a
  conversation is kept on another member (session/turn/cache/strict),
  the charge moves to that member (wrrSeat, wrrMove).
- cli: routing=weight (also weighted, wrr). weight=<model>=<n>[,...]
  sets weights and keeps the rest; weight= on its own clears them. The
  group view shows "· weight N" for each member.
- tui: By weight is in the group routing list.
- gui: the group editor offers By weight. Each member then shows
  "Weight N · S%", its share among the members that are on. Clicking it
  edits the number in place: Enter or blur keeps it, Escape cancels,
  and a value outside 1 to 1000 shows a warning. The trace header uses
  group wording for a weight-routed group. Strings are added in zh,
  zh-TW, ja and de.
- docs: reference.md, gateway-routing.md, and site start pages in en,
  zh and ja.

Run:
- go test -tags nogui ./internal/provider ./internal/cli ./internal/tui:
  ok.
- ./internal/gateway: ok in 988s with -timeout 45m. The first run hit
  the default 10m timeout at load average ~170. The test running at
  that moment had been running for 2s; it was not a hang.
- go vet -tags nogui on those packages, for darwin, GOOS=linux and
  GOOS=windows: clean. gofmt -l: clean.
- New group-member-weight.test.cjs: 8/8 in Chromium and WebKit, en and
  zh at 1100, en and de at 420. The WebKit de 420 case also passed six
  runs at once.
- gui-zh-tw, gui-ja, gui-de, i18n-keys, routing-*, group-*,
  panel-routing*, settings-groups and agent-model-groups: all green
  except two.
  - routing-steady (WebKit) is #1804. It is red 2/3 alone on origin/main
    e1b70c13d too.
  - routing-save-blank (chromium en) was red under load only, and 3/3
    green alone. The overshoot in its wheel loop is filed as #1924.

Broken by hand, each red, then restored:
- byWeight forced false:
  --- FAIL: TestWeightedGroup (weighted_group_test.go:69 its turn ...)
- cleanWeights call skipped:
  --- FAIL: TestSaveGroupWeights (groupweight_test.go:39 weights map[...
  an/claude-opus-5-5:0 ... oa/gpt-6.1-sol:high:fast:3 ...])
- CLI weight case renamed:
  --- FAIL: TestGroupWeightCLI (unknown field "weight")
- GUI chip not appended: group-member-weight chromium en 1100 timed out
  on the weight button.
- Not red: the test's "moved nothing" check. A scroll forced on click,
  or padding added above, did not turn it red, because the view's own
  scroll guard and scroll anchoring hold the clicked row in place. It
  only shows that the row stays under the pointer.

Not tried: real accounts through a running gateway. The routing is
proven by the plan-level test with synthetic providers only.
2026-10-13 13:10:30 +08:00
Jianyu c984adfbc7 sessions: a renamed or moved Claude Code project folder is relocated with its sessions, from the Sessions page or the CLI (#1131)
Renaming or moving a project folder left Claude Code's transcripts under
the old encoded project path: magpie listed them with a resume command
for a folder that no longer exists, and Claude Code in the new folder
didn't find them. A Claude Code folder row on the Sessions page now has
Relocate project, which opens magpie's own dialog with the new absolute
path, a read-only preview and a confirm that carries the preview's
token; `magpie sessions relocate-claude --from --to [--confirm <token>]`
does the same in a terminal (inside WSL too).

The whole project store moves, session ids, subagents, tool results and
memory with it; the transcripts' top-level cwd and the sessions index
are rewritten, message text is not. The originals and a recovery
manifest are kept outside Claude's project list, writes are staged
before the originals are renamed, a change since the preview is
refused, and a failed publish rolls back. An existing target store,
recently written files, a malformed transcript, a symlink, an ambiguous
encoded path or a long hashed name are refused. Desktop's stores are
left alone. Recovery is in docs/session-relocation.md.

Jianyu's PR head e8263cde, which conflicted with main: the button moved
into main's folder() row, the CLI test into internal/cli beside
sessions_cli.go, and both sides of sessions_manage.go and i18n.js kept.

Run: see the next commit, which adds the zh-TW/ja/de strings and the
GUI test.
2026-10-13 13:02:09 +08:00
yetone 63a361b5ff gui: a plugin that took over Trae's, WorkBuddy's, MiniMax's or Qoder's check-in keeps that switch after a state refresh (#1912)
The previous commit reads the saved pluginCheckins map before
/api/settings' list, but /api/state has neither the list nor, for a
provider whose own switch was never set, a map entry. Such a plugin follows
the built-in check-in it took over (provider.PluginCheckinOn: traeCheckin
for trae-cn, workbuddyCheckin, minimaxCheckin, qoderCheckin), so a refresh
still drew it off while the scheduler kept checking in. pluginCheckinOn now
falls back to that built-in's switch, from PLUGIN_CHECKIN_INHERITS.

Run: plugin-checkin.test.cjs gains cases for the inherited switch in
/api/state's shape (red with the fallback removed) and a test that the map
names the same ids and settings keys as Go's PluginCheckinOn (red with an
extra entry); plugin-checkin, i18n-keys, gui-zh-tw, gui-ja, gui-de in
Chromium and WebKit: 32 pass. No new strings.
2026-10-13 12:58:32 +08:00
snowlie 762db7c5a2 gui: a plugin's saved auto check-in stays on after a state refresh (#1912, 1939323749)
Reported by 1939323749 with a custom provider plugin on Windows. Read the persisted pluginCheckins map before the derived settings-only list, preserving explicit false and the existing default fallback.

Verified plugin-checkin tests in Chromium and WebKit across en, zh, zh-TW, ja and de, plus all three translation GUI suites. The WebKit English Usage-card regression fails without the fix: saved auto check-in stays on after a state refresh (false !== true).

Reviewed and landed from the reporter's branch (755c1f0): with the old
pluginCheckinOn the new refresh assertion fails in WebKit for every
language; with it, plugin-checkin, i18n-keys, gui-zh-tw, gui-ja and gui-de
pass in Chromium and WebKit.
2026-10-13 12:58:32 +08:00
yetone 5e5b6a5ac3 provider: every account of a provider keeps its queue, limits and routing, not only the first (#1899)
A second WorkBuddy AI account queued requests for 62s with the provider's
queue wait set to 1s. The gateway takes each candidate's QueueLimit,
QueueWait, LaneLimit (MaxConcurrency) and Routing from the Provider value
it is handed. The account the agent is signed in to comes from All, which
lays the user's saved picks from providers.json over it. The other accounts
on beside it come from AlsoOn. For Claude and Codex, AlsoOn copies p, so they
had the picks. Every other sign-in builds its extra accounts afresh: all
plugin accounts (pluginAlsoOn) and the built-in extras (WorkBuddy, Grok,
Copilot, ZCode, Kiro, Devin, Command Code, Qoder, Zed, Factory, MiMo, the
Gemini sign-ins). They had none of the picks. A few getters (LaneLimit,
RPMLimit, AccountCap, proxy) already fell back to providers.json. The queue,
the provider-wide concurrency and routing did not, so an extra account
waited forever on a full lane.

The overlay All does is now withPicks. AlsoOn calls it on every account it
returns, from p as All has it. This one choke point covers every sign-in's
extra accounts, plugin and built-in, moved or not. The LaneLimit, RPMLimit
and AccountCap comments now say what still reads providers.json, and so
does gateway-routing.md's Limits row.

Tests:
- TestPluginSecondAccountKeepsTheQueue (gateway, fake plugin under bun):
  two accounts, one at once each, a queue of 1 and a wait of 1s, every
  request pinned to the second account. The third request gets 429 "queue
  is full" at once, and the queued one gets 429 "waited" after its second.
  The vendor sees only the second key.
- TestWorkBuddyAI: the second account from AlsoOn has the provider's
  queue 1/1s, MaxRPM 7, Routing ordered and LaneLimit 2.

Broken by hand (AlsoOn returning alsoOn's accounts as they are):
- The gateway test fails at its AlsoOn check. With that check off, it
  fails on "no reply in 10s", which is the reporter's symptom.
- TestWorkBuddyAI fails with "queue 0, wait 0s, rpm 0, routing "", at once 0".

Run (sandbox HOME, private GOCACHE, worktree): gofmt -l; go test -tags
nogui on ./internal/provider, ./internal/gateway, ./internal/gui,
./internal/cli and ./internal/agent; GOOS=linux and GOOS=windows go vet
-tags nogui on internal/provider and internal/gateway. Not tried with a
real WorkBuddy AI account.
2026-10-13 12:34:48 +08:00