Commit Graph
1821 Commits
Author SHA1 Message Date
yetone a732f3c493 gateway: models of one API other than chat are grouped by id on their route (#5339)
XYenon (Discord) has the same embedding model at several providers and
asked why it isn't grouped the way chat models are. It wasn't even
listed: a fetched list dropped every embedding, rerank, speech and
transcription model, so "embed-1" on /v1/embeddings was a 404 unless a
hand-made group named it.

- catalog: a fetched list keeps those models, tagged with their API
  (Model.Serves, read from the id by ServesOf: rerank, embed/bge-,
  whisper/transcribe, tts-/-tts). Chat() and Live() leave them out, so
  agents' model lists, gateway keys and Routing's chat pickers never
  see them; LiveServing(id, kind) reads them. The live file says
  "kinded": true; a list fetched before this is fetched again once a
  run (autolist), with no schedule needed.
- provider: KindGroup(kind, ref) is made per request, never stored, so
  it is in neither Groups() nor Catalog(). Its id is
  auto-<kind>:<model> ("group/auto-embedding:embed-1"); its members are
  the providers that serve exactly that id for that API, in the order
  they were added, none off, decide-only, serving none, or with the
  model disabled.
- gateway: embeddings, rerank, speech, transcriptions and videos pick
  the group by route (mediaMembers): a bare id is a kind group when
  more than one provider serves it, the group's own id always; a
  hand-made group still works through offChatList. A group is of its
  own API: an embedding model's id on /v1/rerank is a 404.

Run at bd0f33828 + this change, on WSL magpie-desktop (mote was
running another session's full suite):
- go test -tags nogui -count=1 -timeout 45m ./internal/catalog
  ./internal/provider ./internal/gateway: ok, ok, ok (594s). The first
  run was red in three tests that held a fetched list to leaving its
  embedding model out (TestFetchArkMarksVideoModels,
  TestNvidiaModelScopeLiveList, TestTencentTokenHubList); they now hold
  it kept, tagged embedding, and out of catalog.Chat.
- 22 GUI files over the model lists and Routing pickers, both engines,
  every language (group-pick-drawers image-models-hide video-models-hide
  model-kind routing-kind agent-models agent-models-picker
  agent-model-groups agent-models-only-picked gateway-key-models
  gateway-key-groups group-from-model-add unlisted-models
  models-select-all-api provider-add-models provider-detect-models
  routing-rule-models panel-routing-pick fallback-group group-unlists
  settings-groups i18n-keys): 229 of 244 pass. The 15 reds are in six
  files that a control run of those six at bd0f33828 has red the same
  (14 of 56): #4389, #4964, #5332, #4616 and, new, #5357
  (routing-rule-models webkit 390). agent-models webkit zh's opacity
  0.998 was red here only, a fixed 250ms wait: #5358. No GUI asset is
  changed here; the GUI tests stub /api.
- on mote: TestProviderListBeforeSave (internal/gui; the add form's
  list keeps an embedding model out) and
  TestPiModelsAskedOnTheirNativeAPI (internal/agent), ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of catalog,
  provider and gateway on mote at this head, ok.

Rebased then on origin/main d620ff6b5 (one commit, internal/agent and
internal/sessions only), and b63b28958 (one mover min line) after; at
d620ff6b5 + this on mote: go build ./..., go vet
of catalog, provider, gateway, agent and sessions, go test
./internal/catalog and -run 'Kind|Fetch|Nvidia|Tencent|Serving' of
provider and gateway: ok.

Red on the old code: TestKindGroupsServeEachAPIByRoute (embed-1 404)
and TestVideoKindGroupByTheModelsID (404).
Broken by hand, each red, then restored:
- the fetch dropping serves != "" again: TestFetchKeepsModelsOfOtherAPIs;
- the once-a-run refetch forced off: TestKindlessListFetchedOnce;
- KindGroup's disabled-model check removed:
  TestKindGroupHoldsTheExactModel;
- LiveServing asked with "" (any kind): the rerank-by-embedding-id
  check gets 200 instead of 404.

Known gaps, not done here:
- The Routing group editor still offers only chat and image models, so
  a new hand-made group of different ids (bge-m3 / BAAI/bge-m3) can't
  pick kind models: #5352.
- A bare id whose every member is disabled is a 404, not a 403.
- Rerank, Qwen3-Embedding and bge models that sat among a provider's
  chat models before (textModel's words missed them) leave agents'
  lists now. A hand-made group naming one keeps serving.
- /v1/models lists no kind model; the Routing live view may show the
  raw kind id.
Not tried: real vendors' lists and routes; the full ./... suite at this
head (queued on mote after another session's run; reds get issues).
2026-11-05 16:22:31 +08:00
yetone d620ff6b54 codex: an old OpenAI thread follows Codex onto magpie by its row, and back at the Disconnect (Parry_Moody, Cyrus)
Parry_Moody and Cyrus on Discord: Codex on OpenAI through an API key
before magpie, and for two days the Codex app answered every older
conversation "继续聊天未成功: This chat uses openai, but your current
provider is magpie. Switch to openai to continue."

Cause, from Codex's source (rust-v0.167.0-alpha.3.1, same in 0.166.0):
every thread Codex 0.166 starts is paginated (history_mode 'paginated'
in its state-DB row), and for those thread-store read_thread takes the
provider from the row, never the rollout ("Paginated history may contain
only a suffix, so its display metadata lives in SQLite"). The app sends
thread/resume with modelProvider null (ChatGPT.app 26.1021, Kct in
app-shared), so the row alone decides, and load_for_resume refuses a row
other than the current provider. bringOver moved threads by rewriting
files: plain ones in place, packed ones only from the last 30 days and
128 MB a sync. An older or packed OpenAI thread kept an openai row.

Now sessions.RetagPagedCodexThreads moves every paginated thread on a
provider by its row alone: any age, packed or not, an id of any length,
no file read, written or copied. Each thread is held by its writer lock
(an open one stays: its writer would write the provider back), one
written to in the last minute waits, 200 rows a transaction. It runs
after the in-place relabel in bringOver, bringBack (so a Disconnect no
longer copies a whole paginated history to the trash), bringOfficial and
bringBeside, and giveBeside by ids (RetagPagedCodexThreadIDs). Legacy
threads keep the file path. The Sessions page lists a paginated thread
on its row's provider (codexPagedProviders, memoised on the DB and WAL
stamp), so it isn't offered a Move it had.

Run:
- real codex-cli 0.166.0 (npm latest) on mote in a sandbox CODEX_HOME,
  a fake Responses server: a thread started with OpenAI (API key,
  openai_base_url) is paginated, row openai; with model_provider magpie
  `codex exec resume` failed with exactly "This chat uses openai, but
  your current provider is magpie" (modelProviderMismatch). After
  magpie's RetagPagedCodexThreads on that home (a throwaway test calling
  it, not committed) it resumed and answered; the rollout still names
  openai. Reversed (magpie -> openai) with config back on OpenAI, it
  resumed again. The first retag try moved nothing: the rollout had been
  written <1 minute before, the ActiveWindow skip, as intended.
- mote: gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  for ./internal/sessions ./internal/agent; go test ./internal/sessions
  ./internal/agent: ok (sessions 20.1s, agent 194.4s) on mote, plus go vet on darwin, linux -tags nogui and windows

Broken by hand:
- RetagPagedCodexThreads returning nil (the old behaviour):
  TestCodexPagedThreadsFollowByRow red (250 packed 90-day-old threads
  "on openai, want magpie"), TestRetagPagedCodexThreads red.
- the writer-lock hold skipped: TestCodexPagedThreadsFollowByRow red,
  the open thread moved to magpie.

Not tried: the Codex app GUI itself (the app goes through the same
app-server thread/resume, whose modelProvider it sends null); Windows
and Linux runs (vet only). Codex rebuilds a row from its rollout when a
search listing reconciles it, which puts a retagged thread back on its
file's provider until the next sync; not seen, read from the source.
A legacy thread packed over 30 days still waits for Sessions' Move.
2026-11-05 16:11:14 +08:00
yetone bd0f338282 hermes: a Claude model goes on anthropic_messages, so cache_ttl 1h works; the user's api_mode stays (#5315)
cherish_onlyy (#5315): magpie wrote providers.magpie as chat_completions at
the gateway's /v1 for every model. On chat completions to a custom provider
Hermes sends no cache marks (anthropic_prompt_cache_policy gives
(False, False)), and the marks magpie adds for a Chat client last five
minutes, so prompt_caching.cache_ttl: 1h never reached the vendor. They set
api_mode: anthropic_messages and the gateway's root by hand and got 1h
writes; magpie's next sync or connect wrote chat_completions at /v1 back.

Hermes takes api_mode per providers entry, never per model
(_resolve_named_custom_runtime, hermes_cli/runtime_provider_custom.py;
aliases in config_providers.py's _API_MODE_ALIASES, transport read when
api_mode is absent). On anthropic_messages its adapter strips a trailing
/v1 and the SDK adds /v1/messages, and for a "claude" model on a
third-party gateway it puts its own system_and_3 marks at the configured
ttl (agent/prompt_caching.py, read at d914e233). So magpie now writes two
entries, as dsh already splits its routes:
- magpie: chat_completions at gw/v1, every model not on Messages;
- magpie-anthropic: anthropic_messages at gw (no /v1), the models whose
  native API is Anthropic's Messages and not Responses (hermesOnMessages).
model.provider follows the picked model (hermesRoute), in every profile;
a sync moves a Claude model magpie had set under "magpie" onto
magpie-anthropic, and drops that entry when no model is left for it.
Disconnect takes both out.

The user's own value: an api_mode or transport on one of magpie's entries
that isn't the one magpie writes there (by Hermes's aliases, so "openai"
is still magpie's chat) is the user's (hermesModeIn). It stays through
sync and pick, base_url follows it, and on "magpie" that entry then
serves every model and no magpie-anthropic is written, which is the
reporter's set-up exactly. magpie only ever wrote chat_completions into
providers.magpie, so nothing earlier is mistaken for the user's.

Tests:
- TestHermesClaudeGoesOnMessages: Claude on magpie-anthropic (mode, base
  without /v1, models), deepseek stays on magpie at /v1, Get/Check/Drift
  clean, a pick moves model.provider back, a bot profile too, Disconnect
  removes both entries from every profile.
- TestHermesSyncMovesClaudeOntoMessages: an existing connected config is
  moved on sync, and back when the provider goes chat-only.
- TestHermesKeepsTheUsersAPIMode: api_mode anthropic_messages at gw,
  transport: anthropic, codex_responses: each survives two syncs and
  two picks, base_url kept; api_mode: openai is still magpie's.
- internal/gateway TestHermesHourMarksReachTheVendor: a Hermes-shaped
  /v1/messages turn with 1h marks reaches the Anthropic upstream with
  every mark at 1h; the same turn on /v1/chat/completions goes at 5m.
  This one passes on the old code too: the gateway already passed the
  marks through; it guards that and records why the mode matters.

Run (mote-run, this tree):
- go test ./internal/agent/ -count=1 -timeout 45m: ok
- go test ./internal/gateway/ -run 'TestHermesHourMarksReachTheVendor|TestResponsesToClaudeMarksLastAnHour' -count=1: ok
- go vet ./internal/agent/ ./internal/gateway/, GOOS=linux and GOOS=windows: ok
- gofmt -l: clean
Broken by hand:
- hermesSplit returning (nil, false), the old one-entry behaviour:
  ClaudeGoesOnMessages, SyncMovesClaude and the openai-alias case fail.
- hermesModeIn never reporting the user's mode: all three
  KeepsTheUsersAPIMode cases fail at "sync".
Not tried:
- Hermes itself: it was not run (running it under a temp HERMES_HOME
  rewrites the live launcher); its behaviour is read from its source at
  d914e233. No real 1h cache write was measured against a vendor.
- Group models whose members are all Claude, and Claude Code sign-ins
  (no Native API), stay on chat_completions; GPT on codex_responses is
  #3080.
- Windows and Linux runs of the agent package (vet only).
2026-11-05 15:53:16 +08:00
yetone 465928bcce backup: the default backup folder says a reinstall takes it too; docs say how to keep magpie on another disk (two_2025.)
two_2025. on Discord asked to pick magpie's config folder: on Windows it
is on C:, and a system reinstall without a backup loses everything.
Two ways already exist and neither is said where the user looks:
automatic backups can go to any folder (Settings > Sync and backup >
Backup folder > Change...), but default to auto-backups inside magpie's
own folder, lost with it; and portable mode (a data folder beside
magpie.exe, internal/appdir) keeps everything on another disk. So no
new data-folder setting: moving the live folder would have to repoint
the library's links, agents' configs and a running gateway, and its
pointer would sit on C: and be lost on the same reinstall.

- AutoStatus reports inside: the backup folder is settings.Dir() or in
  it, letter case aside off Linux. The Backup folder row then says a
  reinstalled system or a lost disk takes these backups too, and to pick
  a folder on another disk or a cloud drive's (en, zh, zh-TW, ja, de).
  A folder picked elsewhere says nothing new.
- docs/start (en, zh, ja) #data-folder: pick a backup folder on another
  disk and restore from it after a reinstall, sync for the keys, or run
  portable from D:\magpie with a data folder beside magpie.exe.
- docs/subsystems/sync-backup.md names the field and the tests.

Run (mote, at this tree on origin/main 5db1b07ed):
- go test -count=1 ./internal/backup/ ./internal/gui/: backup ok; gui
  red only in TestMainWindowCorners/macOS_26_SDK (#3949, mote's macOS 27).
- node --test auto-backup, i18n-keys, i18n-en-no-cjk, sync-not-backup:
  49 of 50; the red is i18n-keys "a plugin's words are its own", red on
  main since 73c98ebc2 (#5327, #5332). auto-backup passes in Chromium and
  WebKit, 1100 and 420px, all five languages.
- node --test site/*.test.mjs: 84 of 84.
- GOOS=windows, GOOS=linux and native go vet ./internal/backup/; gofmt -l.
- Windows (win-run on xiaomi-gpu): go test ./internal/backup/ ok
  (TestAutoInsideMagpiesFolder with the upper-case path);
  ./internal/appdir/ red only in TestFoldersJoinedOnce (#4846, untouched).

Again at this commit, rebased on origin/main 435f04151 (mote): go test
./internal/backup/ ok; auto-backup.test.cjs 22 of 22 and i18n-en-no-cjk
ok.

Broken by hand: AutoStatus with inside always false makes
TestAutoInsideMagpiesFolder red ("default folder ... inside false");
the JS line dropped makes auto-backup.test.cjs red (webkit 1100px zh,
zh-TW).

Not tried: the real app on Windows with a backup folder on another
drive and a restore after a reinstall; a portable copy moved to D: from
an installed one (the docs restore a backup into a fresh portable copy
rather than copying the folder, whose library links point at the old
one). Full suite runs after the push.
2026-11-05 15:30:11 +08:00
yetone 435f041514 gateway: an account near its usage cap takes one turn at a time (dyzdyz010)
dyzdyz010 on Discord: two Claude Code accounts, each capped at 90% of its
five hours, Stop at the caps and Check usage near the cap on, and both
read 100%. Routing holds a capped account by its last reading. Turns sent
together (an agent's subagents, several agents) were each planned on the
same reading, so an account a point under its cap took every one of them,
and went as far past it as they used between them. Check usage near the
cap reads the usage again before planning, but every turn read the same
figure: each saw 89%.

- gateway (cap_near.go): within 5 points of a usage cap (carefulNear),
  an account takes one turn at a time. A turn that finds it busy goes to
  the next candidate first, the account moved behind them once; the last
  candidate waits for it. Once its turn comes capHeld judges it again, by
  what the reply before it said (codex.rate_limits, rate_limit_event), or
  by the usage read again when that reply said nothing (at most
  carefulWait). Held, it is passed over, or the agent gets the cap's 429
  when nobody is left. The cap is passed by one turn at most.
- A conversation kept on its account by Stays: Strict takes no turn there
  and goes on past the cap, as before. Neither does an account already
  held when its try begins, let in past its cap on purpose (a Codex reset
  spent for it, its credits).
- docs: gateway-routing.md's capHeld step, providers-accounts.md's cap
  sentence.

Run (wsl-run, magpie-desktop, Go 1.26.8):
- go test -tags nogui -run 'NearCap|FarFromCap' -v ./internal/gateway:
  the five new tests pass.
- go test -tags nogui -race -count=20 -run 'NearCap|FarFromCap'
  ./internal/gateway: ok.
- GOOS=linux go vet -tags nogui ./internal/gateway, GOOS=windows go vet
  ./internal/gateway: ok. gofmt -l: nothing.
- go test -tags nogui -timeout 30m -run
  'NearCap|FarFromCap|CodexNoCredits|Reset|Strict|Cap|Credits'
  ./internal/gateway: ok.
- go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider,
  at this tree rebased on 248853225: ok (gateway 604.9s, provider 90.9s).
- at the pushed head, rebased on 5db1b07ed: the vets ok, and -run
  'NearCap|FarFromCap|CodexNoCredits|Reset|Strict|Cap|Credits|Group'
  ./internal/gateway ok.

Broken by hand (each restored after):
- the whole near-cap block off (`&& false`): TestNearCapTakesOneTurnAtATime
  red (acct-1 took all 4 turns), the two wait tests never saw a turn
  waiting, and TestNearCapClaudeAccountsTakeOneTurnEach red (both turns on
  the account near its cap, the spare never run).
- nearCapAgain a no-op: TestNearCapReadsAgainAfterASilentReply red
  (200, 200).
- capHeld's second look off: TestNearCapWaitsThenHolds and
  TestNearCapReadsAgainAfterASilentReply red.
- the first full run, before the strict exception, had
  TestStrictAffinityGoesPastTheCap red: the strict conversation got the
  cap's 429. The second, without the held-on-entry exception, had
  TestCodexNoCreditsSpendsAReset and
  TestCodexNoCreditsResetAfterTheLastRefusal red: the account a reset
  was just spent for was held again. Both fixed in this commit.
- An unrelated red in the first run,
  TestZCodeTrialRefusalRestsTheTrialAlone/trial_edge_block ("no plugin
  signs in to zcode"), passes alone and was green in the last run; filed
  as #5335.

Not tried: a real Claude or Codex account near its cap; plugin accounts
(their caps go through the same candidate loop, untested here). One turn
alone can still pass a cap by what it spends: an Opus turn on a Pro plan
can take several points of the five hours.
2026-11-05 15:16:13 +08:00
yetone a2f7ed2e81 gateway: a hand-made group of embedding, rerank, speech, transcription or video models is served when its providers have picks
XYenon on Discord: a routing group of embedding models was a 404 on
/v1/embeddings. Picks are of chat models, so membersFound dropped every
member of a provider with picks as unpicked (#3911). 1d8658abc fixed this
for drawings with FindDrawingGroup. The sibling routes still used
FindGroup: retrieval (embeddings, rerank, speech, transcriptions and
translations, which all go through serveRetrieval) and /v1/videos.

provider.FindGroupAlso is FindGroup with an "also keep" test, and
FindDrawingGroup now wraps it. The gateway's mediaMembers keeps a member
that is not on its provider's chat list (offChatList), so a chat model the
user unticked stays out. mediaGroupFirst resolves the group's first such
member, because Resolve reads the agents' catalog and finds none of them.
The routing doc says the same.

Auto groups by kind (non-chat ids never reach autoGroups) are #5339 and
are not in this commit.

Run on mote:
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider:
  ok (gateway 823.6s, provider 180.0s)
- GOOS=linux and GOOS=windows go vet of the two packages: ok
- gofmt -l: clean
- No GUI file changed, so no GUI run.
- At the rebased head (on origin/main 2891ec7a7: 6 commits, balance_probe and
  others, none in group, retrieval or video code): go test -run
  'MediaGroup|VideoGroup|ImageGroup|Retrieval|Embedding|Speech|Transcri|Rerank|Group'
  ./internal/gateway ./internal/provider: ok; gofmt -l: clean

Red on the old code: with media_group.go removed and the three routes back
on FindGroup, TestMediaGroupOfProvidersWithChatPicks fails with 404 "magpie
knows no model "group/emb"" and TestVideoGroupOfProvidersWithChatPicks with
404 for "group/vid". In both, the members' providers have picks that don't
name the embedding/speech/video ids.

Broken by hand: offChatList made to return true lets the unticked chat
model in, and the test goes red ("a group of a chat model the user unticked
was asked: 400 ... chat-model is not an embedding model").

Not tried: a real vendor's embeddings or speech through a group (fakes
only), plugin-served embedding models, and the full suite (it runs after
the push).
2026-11-05 14:57:43 +08:00
yetone 24d315fa85 routing: the request list can be grouped By key, each gateway key's calls under its name
acezan (#help on Discord) asked to see API use on the Routing page the way
it shows each agent's, live and in the history. The list's group bar gets
a third button, By key, after By request and By session. It shows once
Settings has a gateway key (/api/caller-keys). Each head is the key's
current name (else the name the route kept, else its id), with its agents
dim beside it and the usual count, tokens, in progress and cost. Calls with
no key (from this computer, or kept before 75fb76186 named the key) go
under "No gateway key". A row's tooltip names its key too. The choice is
kept in localStorage (magpie.routingGroupBy), and the old
magpie.routingBySession still works. Text added in zh, zh-TW, ja and de.

click-scroll counted two group buttons and now counts three, with By key
hidden when there is no key. purpose-filter clicked .last() for By
session and now picks [data-by="session"].
reference.md and gateway-sessions.md describe By key and Route.CallerKey.

Run (WSL magpie-desktop: mote's disk is full, ld errno=28):
- routing-by-key.test.cjs: 20/20 in chromium and webkit, in en, zh,
  zh-TW, ja and de, at 1100 and 420. Red 20/20 with client.js and
  i18n.js at the parent (waits for By key).
- 254 Routing-related GUI files at concurrency 4. Every red was rerun
  serially, with this change and at origin/main 73c98ebc2.
  - Only purpose-filter and click-scroll were this change's; both are
    fixed above and green now.
  - The rest are red at main too, or flake there: #5045 call-headers,
    #4385 click-scroll wheel, #5049, #1745, #4689, #3402, #4623, #1937,
    #3773 idle-frame (10 frames, passes on rerun), plus routing-rule-*,
    zero-priced-free and others under #4121/#4400.
- Windows: go test ./internal/gui. Reds are #4115/#1827, plus
  TestPluginAgentMissingSaysSo and TestGatewayHeldByAContainer, red at
  main too and filed now as #5324.
Not tried: the real app, the whole GUI suite, the tray panel (no By key
there). A key renamed after a row was drawn shows its old name in that
row's tooltip until the row is drawn again.
2026-11-05 14:47:18 +08:00
yetone 464cc30f91 provider: a relay's found balance query is looked for again each day
A relay added by hand with no Balance URL has its balance found at
/v1/usage or /api/usage/token (248853225). What was found was kept until
magpie quit, so a relay that moved to other software went on being read
at a query that may now mean something else. A query found is now kept
24 hours and then looked for again. If the look finds nothing, the old
query stays when it turns the key away (401/403, so the card says the
relay refused the key instead of going) or the relay can't be reached.

BalanceFound tells the editor where the balance was found, so a wrong
amount can be put right (the GUI commit after this one).

Run on mote:
- gofmt -l: nothing.
- go vet, GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  ./internal/provider and ./internal/gui: ok.
- go test -count=1 -timeout 45m ./internal/provider: ok.

Broken by hand:
- A found query kept for ever again: TestFoundBalanceLookedForAgain fails.
- The kept-on-refusal case taken out: TestFoundBalanceKeptWhenTheKeyIsRefused
  fails.

Not tried: a relay that really moved to other software.
2026-11-05 14:46:23 +08:00
yetone 2488532257 provider: a relay added by hand finds its balance where relays tell it
The same relay user had added yylx.io by hand: no Balance URL, so no
balance anywhere until they deleted it and imported it from the relay's
site, whose link names the query (小鱼 of yylx.io, WeChat, 11-05).

A provider added by hand, or from a relay's preset, with a key and no
Balance URL, at no host magpie knows a query for, is now asked at its
base's origin: /v1/usage (sub2api, $remaining), then /api/usage/token
(new-api, $data.total_available / 500000), with the key's own auth and
headers, as balanceRead asks. A 200 whose field reads is the query. It is
kept in memory per origins and key (the key hashed), and so is finding
none, for 6h (5 min when the relay can't be reached), so a poll asks once.
Nothing is written to providers.json. The card, Check balance and
`magpie provider show` (BalanceQuery) read the found URL; none found is
no card, and the editor's "No Balance URL to ask".

Never asked: a vendor's or local server's preset host (api.openai.com,
api.anthropic.com, api.deepseek.com…), this computer, opencode.ai and
api.cline.bot, a plan whose windows are its card. The subsystem page has
the row.

Run (mote, go1.26.8):
- go vet ./internal/provider; go test -count=1 ./internal/provider: ok.
- The new tests: a sub2api relay read at $10472.14 with /v1/usage asked
  3 times over the probe, a Balance and a card poll; a new-api relay found
  after /v1/usage's 404; a relay answering HTML 200 everywhere has no
  card and is asked twice in all over two polls; the hosts left alone.

Broken by hand: with the probe taken out of balanceRead, the three
HandAdded tests fail (balance "" false; a card with no balance).

Before this, TestOpenCodeZenSaysItTellsNoBalance caught the probe asking
opencode.ai for OpenCode Go and a custom inference provider; those hosts
are left out now.

Real use (mote, sandbox HOME holding only the owner's yylx.io provider,
copied with its key, removed after): `magpie provider yylx-hand` (no
preset) and `magpie provider yylx` (鱼鱼连线's preset, Global region)
both show "balance $19.97 from https://global.yylx.io/v1/usage
$remaining".

Not tried: a real new-api relay; a new-api relay that routes unknown /v1
paths to its upstream.
2026-11-05 14:19:28 +08:00
yetone 2947685999 claude: an interactive run's calls keep the conversation they answered when their line comes late
kay20475 on X (magpie 0.1.3005, local magpie -> shared server magpie ->
Claude subscription, interactive bridge): a Claude Code sub-agent's
requests on one account read 99%, 6%, 6%, 99% from the cache; the two 6%
requests were 169.1k each, 35s apart, about 3s long with a short reply.
That is the shape of Claude Code's AgentSummary: every ~30s it sends the
sub-agent's conversation with its last results and "Describe your most
recent action in 3-5 words", while the sub-agent's own run has already
taken those results.

Cause. Such a request finds no run waiting on its calls and should go on
in a branch of the sub-agent's run's session (branch). branch takes it
only when the conversation stored on the call's line (callLine.told)
matches the one before the reply. park stored that only on lines it
already had. The interactive mode streams a reply first and reads its
session lines from the file afterwards (118-162ms after the call). So the
run parked before noteLines had the call's line, and the line came in
with no conversation. The next park then gave it the next request's
conversation. branch returned nil, and every AgentSummary (and every
fork directive) was told the whole conversation in a new Claude Code,
pasted as one text block. A single block can't match the cache beyond
the tools and system prompt, so 6%, and the next summary missed the same
way because its tail differs.

Fix. park also keeps the conversation for each call the client was shown
(r.shown), as a line with no uuid yet. noteLines keeps it when the line
comes, and branch skips lines with no uuid.

Test: TestClaudeForkBranchesOffTheLeadsSession/interactive now has the
fake write the call's session line after the reply's stream, once the
result is handed over, so after the park, which is the real order.
Broken by hand: with this test and the old claude_subscription.go on
mote, it fails ("told it whole", want "branched at line-...").

Run on mote at this tree (base 4cb7159f1): gofmt -l clean; go vet
./internal/gateway on darwin, GOOS=linux and GOOS=windows ok; go test
-timeout 45m ./internal/gateway (679s) ./internal/claudetui
./internal/claudebridge all ok. The fork/side-question/cut tests
-count=3 ok. The full ./... suite and the GUI suite were not run (no
GUI or other-package change).
Rebased on 351844594 (GUI only since 4cb7159f1): go test -count=1 -run
'Claude|Fork|Branch|Subscription' ./internal/gateway ok (77s) on mote.

Not tried: a real Claude Code AgentSummary against a real account. The
reporter's requests are matched by shape only (size, timing, short
reply). Ruled out: the remote-magpie hop. The bridge doesn't key runs on
headers (only anthropic-beta for safeguards), so losing
x-claude-code-session-id can't move a turn off its run. Not fixed here: a
sub-agent loop with no plain reply, told anew in the interactive mode, is
still pasted as one text, so a new run for it reads only tools+system.
2026-11-05 14:05:54 +08:00
yetone 4cb7159f18 routing: a ChatGPT account whose usage can't be read is asked, not starved
peterpark8527 on Discord: 11 ChatGPT accounts under Use before expiry,
one never used. An account whose wham/usage reading fails (or names no
window, or is held by "When I ask") stayed not known for good:
Use before expiry counted it a fresh week (FreshPace, ~0.6/h), behind
every known week being spent; Smart put it after every known account.
NoteCodexLimits only updated accounts already read, so its replies'
x-codex-* headers never made it known. Its week, once started by
magpie's own turns or warm-up, lapsed unspent. A simulation of 11
accounts over 4 weeks (Pace, Poisson load 30/60/90%) had it at 141 of
~1200 used at 30% load, losing 3406, while every known account was used.

- provider: a reply that tells an unread account's week makes it known
  from that (usedCache.heard), kept over failed readings, until a good
  reading tells it; a 5h window alone still makes nothing up.
- gateway: a Codex account not known, weighed against one known, is
  Learns, like Claude's: asked first once so its reply tells its week,
  and again an hour after its last answer if that told nothing
  (codexAnswered, codexLearnAgain). Of accounts none known the order
  stands, so no week is started before it is needed.
- docs/reference.md: Smart and Use before expiry say so.

Ruled out (by design or not starving): an unstarted Codex week lasts
until its first request, so last is right for it; ties go by decayed
tokens, not a fixed order; a 5h-only account goes by its 5h pace
(ahead); rests are time-bound with probes.

Run:
- wsl-run go test -count=1 -timeout 45m ./internal/gateway
  ./internal/routes ./internal/provider ./internal/middleware: provider,
  routes, middleware ok; gateway had 3 reds (TestAccountProxy,
  TestCodexDrawMovesToNextAccount, TestWeeklyPace's five-hours case):
  accounts none known reordered by answers earlier tests left in
  codexAnswered. Fixed by the known-peer gate above; then wsl-run
  go test -count=1 -timeout 45m ./internal/gateway ./internal/routes:
  ok (809s). The none-known guard's u00 line was added after that run
  and run alone on Windows (win-run -run TestUnknownCodexAccountIsAsked
  ./internal/gateway, with the reds above: ok).
- win-run the two new tests on the old code (73c98ebc2, stand-ins for
  the new names): TestNoteCodexLimitsKnowsAnUnreadAccount and
  TestUnknownCodexAccountIsAsked red.
- win-run go vet ./internal/provider ./internal/gateway ./internal/routes:
  ok; wsl-run go vet of the same: ok. gofmt -l: clean.

Broken by hand: learns' codex case returning false turns
TestUnknownCodexAccountIsAsked red; Allowances not applying heard turns
TestNoteCodexLimitsKnowsAnUnreadAccount red ("the next failed reading
forgot what the reply told"); dropping the known-peer gate turns its
none-known case red ("u01@x.com first, not the first listed").

Not tried: real ChatGPT accounts; the reporter's actual cause is not
confirmed (asked for version, quota, status, plan). Other ways one
account goes unused (90%/98% tiers, rested, model list, group, off)
need their answers. mote was not used: its disk is full.
2026-11-05 13:27:32 +08:00
yetone 73c98ebc20 gateway: a search API's or plan service's ask is routed and archived (axelburks)
axelburks on Discord: when magpie searches for a model through a search
API, the Routing page doesn't say which API answered, and Usage →
Requests lists the row but has no request archive, so the request and
response sent to the API can't be seen.

A model's search (searchWith) was already routed and archived. A search
API's ask (askSearchAPIKeys, a plugin's search hook, a signed-in search
API) and a plan's own search service (Kimi Code, GLM Coding Plan,
WorkBuddy, Codex's searchBy, and searchBy's Kimi branch, which wrote no
row at all before) only wrote a usage row.

Now every ask that writes a row goes through keepSearch
(search_archive.go): a done web_search route, agent magpie, For the
agent searched for, the API's name as model and its host as provider,
seated on the masked key or account; a Recent call with ring-cut
bodies; and with the request archive on, archiveOwn of the exchange as
sent. The row gets RouteID and Archive, which the Requests tab already
opens. Each ask has a searchWire in its context, filled where it is sent
(tapSearch tees the answer as read; the last exchange stands, so GLM's
MCP tools/call is the one kept). A plugin's search is noted as what
magpie handed the hook (key masked) and what came back (PLUGIN method).
The key is replaced by MaskSearchKey in path, query, headers and both
bodies before anything is kept; the archive's own scrub runs on top.
Bodies are kept up to RequestArchiveMaxMB (longer marked cut); archive
off keeps nothing on disk, the route and Recent call stay.

Run (mote's disk filled mid-work, see below; the rest on WSL
magpie-desktop via wsl-run):
- mote-run: go test -run 'Search|Archive' ./internal/gateway ok; GUI
  usage-ledger-search, routing-side-calls, request-archive-usage in
  chromium+webkit, every language and width: 38 pass.
- wsl-run: go test -run 'Search|Archive' ./internal/gateway ok; go vet
  ./internal/gateway ok; GOOS=windows go vet ./internal/gateway
  ./internal/gui ok; GOOS=darwin CGO_ENABLED=0 go vet ./internal/gateway
  ok; GUI usage-ledger-search, routing-side-calls, request-archive-usage,
  search-instead, search-mcp in both engines: 68 pass, 0 fail.
- gofmt -l clean.

Broken by hand: keepSearch's call commented out turns all five new
gateway tests red; taken()'s key masking turned off turns
TestSearchAPIAskIsRoutedAndArchived and TestSearchAPIKeyInQueryNotArchived
red. TestSearchRowKeepsRouteAndArchive (internal/gui) is a guard that the
row's RouteID and Archive reach /api/usage/requests; it passed on the
old code too.

Not tried: real Tavily/Brave/Kimi/GLM/WorkBuddy/Codex accounts (httptest
stubs only); Linux go vet of internal/gui (WSL lacks gtk4/webkitgtk);
web_fetch (search_fetch.go) and a vendor's own search (search_native.go),
which magpie doesn't send, are unchanged. Full suite runs after the push.
No GUI asset, API call or i18n string changed.
2026-11-05 12:40:35 +08:00
yetone 1826c4bd99 providers: a Remote magpie that is this magpie says so and is left out, unless kept (hanslin1666)
B uses A through a Remote magpie provider, and sync carries that
provider to A, where it points at A. Each of its models was one of A's
own, listed again beside it and taken by A's found groups, and a request
through it passed through A's gateway twice.

A fetch of a Remote magpie's list now reads its models' magpie_via: when
the magpie that listed them (the last entry) is this magpie's own
catalog.Self, remote-self.json keeps the provider id and the address it
answered at (noteSelf). Another lister, or a list with no via, takes
the record away; an empty list or a failed fetch changes nothing; a
provider moved to another address is not self until a fetch there says
so. The file is this computer's own, never in a backup or sync.

Such a provider is left out (SelfLeftOut in On, SwitchedOff and
remoteMagpies): not in /v1/models, the catalog or a found group. A
request naming one of its models, an agent's pick synced from B, is
served here with the remote's id taken off (ThroughSelf in Resolve and
ResolveRoute), once through the gateway. A 404 for it says why and how
to keep it.

The Providers row shows "This magpie" (greyed while left out), with the
reason as its title; the editor has a note and a "Use it anyway" tick
(KeepSelf, POST /api/provider/keepself). KeepSelf belongs to the user
and to this computer: Mirror and Restore keep the local value (false for
a provider new here), davsync's hashes blank it, and a provider save
keeps it. Strings in en, zh, zh-TW, ja, de.

Docs: providers-accounts.md (two magpies row), sync-backup.md (what
stays on each computer).

Run at this tree on origin/main 4e85cac01:
- gofmt -l: nothing. app.js 1,309,132 bytes (budget 1,316,874).
- mote: go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  provider, gateway, gui, davsync, catalog: ok.
- mote: go test catalog, davsync ok; gui red only in
  TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27); provider and
  gateway did not build there (mote's disk full, "no space left on
  device"), so they were run on:
- Linux (WSL magpie-desktop): go test -tags nogui provider, gateway,
  gui, davsync: all ok.
- Windows (xiaomi-gpu): go test -run 'RemoteSelf|KeepSelf|RemoteMagpie|
  Mirror|KeepLogin' provider, gateway, davsync: ok.
- mote: remote-self.test.cjs 16 of 16 (chromium and webkit, 1100 and
  420, en zh ja de), before the rebase; the rebase touched no line of it.

Broken by hand, each red, then restored:
- noteSelf a no-op: TestRemoteSelfRecord and
  TestRemoteMagpieThatIsThisOneIsLeftOut red.
- ThroughSelf a no-op: the gateway test red (404 for rem/own/m1).
- On() without SelfLeftOut: the gateway test red (listed, 2 passes).
- davsync hashes without the KeepSelf blank: TestKeepSelfIsNoChange red.
- Mirror without keeping KeepSelf: TestMirrorKeepsKeepSelf red.
- The row's badge removed: remote-self.test.cjs red (chromium 1100 en).
- The tick's onchange a no-op: remote-self.test.cjs red (webkit 420 zh).

Not tried: two real computers syncing each other (the case is built in
one process: the gateway test's Remote magpie is its own gateway);
the Linux and Windows apps' webviews; the whole GUI suite (mote's disk is full);
remote-self.test.cjs again after the rebase.
2026-11-05 12:37:30 +08:00
yetone 10f1e97883 search: a GLM Coding Plan searches its own models with the plan's web search MCP
young02036 on Discord asked for the GLM Coding Plan's Web Search MCP in
magpie's web search. The plan's key is given for that server, so magpie
now asks it with the provider's own key, with nothing to set up: a
Streamable HTTP session at <host>/api/mcp/web_search_prime/mcp
(open.bigmodel.cn or api.z.ai, docs.bigmodel.cn/cn/coding-plan/mcp/
search-mcp-server and docs.z.ai/devpack/mcp/search-mcp-server), the key
as a Bearer, initialize, one tools/call of webSearchPrime with
{"search_query"}, then the session's DELETE.

- provider.ZhipuCodingSearch: only a provider or key on the plan's
  /api/coding/paas/v4 (Zhipu's or Z.ai's host, or the zhipu/zai preset).
  A pay-as-you-go key isn't served by the server and never asks it.
  ZhipuSearches reads p.Keys itself, since KeysOn is counted per list and
  searchesOwn runs on every request. ZhipuSearchKeys lists the plan's
  keys, which are asked in turn.
- searchesOwn/ownSearch: the plan's own models search there first, as
  with Kimi Code and WorkBuddy, and fall to magpie's searcher and the
  search APIs when it fails. This happens only while Settings names no
  searcher (glmSearches): a searcher the user named still searches for
  every model, which is a value the user set.
- It is not offered as a searcher for other providers' models. A plan
  with the Responses base (/api/v1) already searches natively there
  (searchHosts, #660), and making it a no-model service would change the
  searcher those users have now.
- The reply's text is read as a list of results, a list in a JSON
  string, or a list under search_result/results/items/data. isError, or
  words with no results, is an error with the key masked. The query is
  masked as Settings > Privacy says (maskedQuery). Each ask is a request
  log row (logOwnSearch).
- No GUI change: the setting has no switch, the same as WorkBuddy's.
- docs/subsystems/gateway-routing.md has a section on it, and the
  searchesOwn lists there and in plugin-runtime.md name it.

Run (mote, at this tree):
- go test -count=1 ./internal/provider ./internal/settings
- go test -count=1 -run 'Search|GLM|Zhipu|Kimi|LoopGuard|Docs|Guard|WorkBuddy'
  ./internal/gateway: ok
- GOOS=linux and GOOS=windows go vet ./internal/gateway ./internal/provider:
  ok
- gofmt -l: clean

The tests use a fake server only and never reach the network:
- TestGLMCodingPlanSearchesForItsModels: Claude Code's literal WebSearch
  request to a plan's model. The fake gives an event-stream reply with
  a progress notification before the result, and a double-stringified
  result. Then a refusal, an unnamed versus a named searcher beside a
  search API, and a pay-as-you-go key.
- TestReadGLMSearch: each reply shape, and prose.
- TestZhipuCodingSearchAddress: hosts, presets, a plan key beside a
  pay-as-you-go one, a key that's off.

Broken by hand:
- With the old searchesOwn/ownSearch, TestGLMCodingPlanSearchesForItsModels
  is red: the model had no search, 400 "no search tool".
- With glmSearches ignoring a named searcher, the test is red at the
  named-searcher step: the MCP was asked and the named searcher wasn't.

Not tried:
- No real GLM Coding Plan key was available, so nothing was sent to the
  real open.bigmodel.cn or api.z.ai server. The docs give neither the
  tool's argument names nor its reply's shape. search_query and the
  result fields come from Zhipu's Web Search API and a third-party npm
  wrapper (web-search-zaimcp 0.1.2). If the real reply differs, a search
  falls to magpie's other searcher or the search APIs and says why.
- The plan's MCP quota, and how a spent quota is worded.
- A GUI hint in Settings > Web search.
2026-11-05 11:44:31 +08:00
yetone 2260390a01 gateway: a Gemini thought signature goes back only to the provider that gave it
mimi001234 on Discord: Pi (openai-completions) on auto/gemini-4-argon, a
group of google-vertex and google-aistudio-paid. Vertex AI served turns
1 to 14 and signed its calls; on turn 15 it answered 429, the group moved
to AI Studio, and magpie replayed Vertex AI's signatures from
gemini-signatures/. AI Studio answered every try with 400 "Corrupted
thought signature." A signature is the issuing backend's, and only it
takes one.

- The provider that gave a signature is noted beside it,
  gemini-signatures/<key>.by (noteSigner, written through temp and
  rename), wherever a reply is read: decoderFor (every translated path:
  Chat, Anthropic and Responses clients, plugins, search, continuations)
  and sigTidy (a Chat relay, and a Gemini client's reply relayed as it
  came, now only read, in native mode).
- Every request is fitted to its provider: ownSignatures in
  forwardTranslated, chatCallSignatures and geminiBodySignatures in
  passthrough. Another provider's signature goes as Google's documented
  skip_thought_signature_validator on a call, and not at all on text. A
  signature of no known provider (ids from before this change, a note
  that couldn't be written) goes as before.
- A 400 "Invalid/Corrupted thought signature" (signatureRefused) is asked
  again once without signatures at any upstream Gemini's signatures
  reach (signaturesReach), relayed too, not only Vertex AI translated;
  it rests no account (restAfterMarked) and lets a group go on to its
  next member (shapeRefused).

The signer is the provider id, not the account: two accounts of one
provider share signatures as before.

Run on mote (mote-run), the targeted run and vets at this change on origin/main 0e55a7593:
- go test ./internal/gateway -run 'Signature|Signer|Vertex|Gemini|Corrupted': ok
- go test -timeout 45m ./internal/gateway: ok (876s), at this change on
  bf60ea596; the only commit since, 47d583939, touches internal/library
- gofmt -l internal/: clean; go vet ./...; GOOS=linux go vet -tags nogui
  ./...; GOOS=windows go vet ./...; go build ./...: ok

Red on the old code (origin/main 0e55a7593 with the new test file):
TestSignatureGoesOnlyToItsSigner (turn 3: 400 "AI Studio: ... Corrupted
thought signature."), TestCorruptedSignatureTriedWithout and
TestCorruptedSignatureNotTheAccount (rested "backoff" 60s).
Broken by hand on the new code:
- chatCallSignatures without the foreignSignature check:
  TestSignatureGoesOnlyToItsSigner red (AI Studio asked twice: refused,
  then the retry).
- ownSignatures in forwardTranslated commented out:
  TestSignatureGoesOnlyToItsSignerTranslated red the same way.
- the passthrough retry turned off: TestCorruptedSignatureTriedWithout
  red with the 400.

Not tried: real Vertex AI and AI Studio accounts; a Gemini client's
request relayed to Vertex AI end to end (TestGeminiBodyKeepsOnlyItsOwn
covers the body and the noting only); Code Assist relays, whose replies
are not noted, so their signatures count as of no known provider.
2026-11-05 11:42:53 +08:00
yetone 47d5839397 library: sync and backup files carry the hooks
VincentChan on Discord (v0.1.3005) said part of the Library doesn't reach
his other computer through sync. Checked kind by kind what the library part
of a bundle carries: instructions (each set's text, a linked set's file text,
the agents ticked, each agent's own addition), MCP servers, skills and
subagents all go. Hooks didn't: library.Bundle had no field for them, so a
hook made on one computer never reached the other, by WebDAV/S3/GitHub sync
or a backup file.

- library.Bundle.Hooks (*[]*Hook): name, description, event, matcher,
  command, timeout, agents ticked. Collect always sets it, empty too.
  Applied.Hooks (the entries magpie wrote into each agent here) stays out:
  each computer writes them on the sync Put runs, beside the user's own
  hooks, and records its own entries, so an entry the user edited there
  stays theirs.
- Put replaces the hooks with the bundle's, so one taken out on one
  computer goes from the others. A nil list (a bundle from a magpie before
  this) keeps this computer's.
- check refuses a hook with no name, no command, or named twice. The event
  and agents are carried as they come: an event a newer magpie knows is a
  problem on the agent here, not a refused library.
- davsync: an empty list hashes as before the field, so upgrading with no
  hooks syncs nothing.
- The CLI's backup line counts hooks; the GUI's sync/export/import ticks
  say "instructions, MCP servers, skills, hooks and subagents" in every
  language.
- library.md and sync-backup.md updated, and they now name what stays
  this computer's own: projects, skill groups, CopySkills/SkillHow,
  SharedSkills, MCPHub.

Instructions: two sandbox computers through the fake DAV server carried a
named set and a change to it, a set linked to ~/.agents/AGENTS.md and a
hand edit of that file, both computers having their own text first, an
agent's own addition, and an agent installed after the first sync. All
reached the second computer's CLAUDE.md/AGENTS.md (exploration tests, not
kept). So no instructions change here; what VincentChan saw is not
reproduced yet.

Run (worktree at 0e55a7593; origin/main bf60ea596's two commits touch
none of these files):
- mote: go test -tags nogui ./internal/backup ./internal/davsync
  ./internal/cli ./internal/library ok; go vet -tags nogui for darwin,
  GOOS=linux and GOOS=windows on the four packages ok; gofmt -l clean;
  go test ./internal/gui -run 'TestCoreScriptBudget|Words|I18n|Builtins' ok
- GUI (wsl-run, Linux): i18n-keys, github-sync, s3-sync, sync-*,
  webdav-settings-refresh, library-backups-top, gui-de, gui-ja, gui-zh-tw:
  187/187

Broken by hand: with Collect not setting Hooks, Put ignoring them and the
hash not dropping an empty list (the old code), TestCarryHooks,
TestCarryOldBundleKeepsHooks, TestCarryNewerHooks,
TestBackupFileCarriesHooks, TestSyncHooks and TestNoHooksHashAsBefore
went red.

Not tried: a real WebDAV/S3/GitHub remote between two real computers;
Windows and Linux runs of the Go packages.
2026-11-05 11:29:20 +08:00
yetone 234903cb23 cli: magpie model api sets the API a model is asked on, as the editor's picker does (yew_fence_931206)
A relay with many models behind one key can now have each model's API
set from a script, not only in the provider editor's Names, prices &
levels ("API this model is asked on"):

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

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

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

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

Not tried: a real relay account; the reporter's provider. The full
suite runs after the push.
2026-11-05 11:05:38 +08:00
yetone 0e55a75936 remote magpie: a request that goes round magpies pointing at each other stops after 8, and a remote that is this magpie lists its models once
Follows c2c991a5b (cdredfox's two magpies each the other's remote).
hanslin1666 (Discord) has the sibling: device B uses device A through
a Remote magpie provider, and S3 sync carried that provider to A too,
so A has a Remote magpie pointing at itself. Sync carries every
provider (backup.Collect, provider.Mirror), a Remote magpie included.

Two holes c2c991a5b left:
- A remote that is this magpie lists this magpie's own models through
  this one alone ([self]); c2c991a5b kept any via of only self, so
  rem/own/m1, rem/rem/own/m1, ... still grew a level a fetch until
  MaxVia. A via naming this magpie is now taken only when it is
  exactly [self]: the remote's own models, once (what the gateway's
  in-process remote tests need, and what hanslin1666 sees today).
- Nothing stopped a request at request time: a list fetched from a
  magpie older than magpie_via, or one cached before the update,
  could still route round. Each request magpie passes to a Remote
  magpie now says how many magpies it went through (X-Magpie-Hops:
  the count it came with + 1, 1 for an agent's own); one that arrives
  having passed catalog.MaxVia (8) is answered 508 Loop Detected with
  what to turn off, before any vendor or remote is asked. The count is
  read only from a magpie's request (its User-Agent, which needs the
  key anyway), and taken off every request as it arrives, so no vendor
  is sent it. It goes on every path that already passes the caller on
  (passOnCaller: chat, decide, draw, embeddings, video).

Run (mote, at this tree on c2c991a5b):
- go test -timeout 45m ./internal/catalog ./internal/provider
  ./internal/gateway -count=1 on Linux (wsl-run, magpie-desktop):
  catalog ok, gateway ok (590s), provider red only in
  TestClaudeAccountServesModelsListedSinceItsFetch, #3174, which this
  doesn't touch.
- go vet, GOOS=linux and GOOS=windows go vet of catalog and gateway
  (mote): ok. gofmt -l clean.
- The full suite at c2c991a5b (mote, -timeout 45m ./...): 86 packages
  ok, internal/gui red only in TestMainWindowCorners (#3949).

Broken by hand:
- the via rule back to c2c991a5b's: TestFetchLeavesOutWhatCameFromHere
  red (rem/own/m2 through [self self] taken).
- no hops set in passOnCaller and no check in withCaller:
  TestRemoteMagpieRequestLoopStops red (the remote told [ ] passes,
  200 not 508 at 8, the vendor asked).

Not tried:
- hanslin1666's or cdredfox's own machines.
- Paths to a remote that don't go through passOnCaller (the Codex
  socket and native passthrough) don't count hops; a loop through
  them is still cut by the lists.
- Hiding a Remote magpie that is this magpie, or keeping it out of
  sync on the machine it names: not done here (a third machine that
  syncs may want it); it now costs one extra local pass per request
  to it, and its models show twice.
2026-11-05 10:52:06 +08:00
yetone 1fd02d33ce agentplug: an agent plugin can pick the model its agent starts on in a second file (str_, PiG)
str_ on Discord (#help, v0.1.3005): PiG's row on the Agents page only
switched the model list on, where Pi's picks the model it starts on.
PiG, like Pi, keeps its providers in ~/.pig/agent/models.json and the
model a session starts on in settings.json (defaultProvider,
defaultModel; PiG's docs/site/docs/settings.md, startup_model.go). An
agent plugin could name a model key only in the one file connect
writes, so agent-pig 0.1.0 had to be connect-only.

An agent's descriptor can now say `startup: {config, format, model,
keys}`: the other file, the key that holds the model (the id without
magpie's prefix) and keys written beside it. With it the row gets a
model field as a built-in's does. Picking one of magpie's writes
connect's keys into config and the model and keys into startup.config,
each key kept aside as before; a model of magpie's picked in the agent
itself still reads as magpie's; a model of the user's own picked there
while magpie's provider is listed counts as connected (Beside), not
drift, and is kept on disconnect. Sync rewrites the list and leaves the
startup model where it is. Off, or `magpie <id> default` with the plugin
gone (RestoreGone), puts both files back. startup without connect, beside
agent.model, in config's own file, or naming the model key among keys
is refused. An older magpie ignores the field, so agent-pig 0.1.1
(plugins repo) stays connect-only there. Every other agent plugin
already names its model in its own config; pig is the only
connect-only one.

Run (mote):
- go test -count=1 ./internal/agentplug/: ok
- go test -count=1 -run 'TestPlugged|TestPlugin|TestRestoreGone|TestAgent'
  ./internal/agent/: ok
- go vet, GOOS=linux and GOOS=windows go vet of both packages; gofmt -l
  clean
- the four TestPluggedStartup* tests on the old code: red (the row had
  a provider field and only listed models)
- real PiG 0.5.3 (darwin-arm64 release, SHA256SUMS checked) in a sandbox
  HOME, models.json written by agent-pig 0.1.1's own connect and
  settings.json as startup writes it, against a fake OpenAI server:
  `pig -p` sent model deepseek/flash with the gateway key. With an
  enabledModels scope that leaves it out, PiG started on the scope's
  first model (said in the plugin's README).

Broken by hand: no startRestore in Unwire (TestPluggedStartupModel and
OwnPickKept red); no Beside (OwnPickKept red, "wired false").

Not tried: the GUI and the TUI with the real row (app.js unchanged; the
row is the model field every built-in has), Windows and Linux runs of
PiG, a real magpie gateway in front of PiG, a real vendor model.
2026-11-05 10:46:46 +08:00
yetone c2c991a5b3 remote magpie: two magpies each the other's remote no longer list each other's models back without end
cdredfox (Discord) saw 100-200% CPU while magpie used a remote magpie
over Tailscale, gone with the remote off. Their providers mask anyway
and their agent asks auto/ ids, so the earlier unmasked-group lead
doesn't explain it. What does: when A and B are each other's remote,
A's /v1/models (to another magpie) lists rem/<B's models>, B fetches it
as back/rem/..., lists that back to A, and so on: one level deeper on
every 10-minute fetch, without end. Each level is another member of
the found auto/ group and another route round the two machines, masked
again on each pass. On mote, two sandbox magpies in that setup went
from A: [auto/m1 own/m1 rem/auto/m1 rem/up/m1 rem/back/own/m1] to
[... rem/back/rem/back/own/m1, rem/back/rem/auto/m1 ...] after one
more scheduled fetch, and B had back/rem/back/own/m1. A request on the
loop route (rem/back/own/m1) cost A 1.07s CPU over 10 turns against
0.69s for own/m1.

The list a magpie gives another magpie now names, as magpie_via, the
magpies each model passes through, itself last. Each process has a
random id (catalog.Self). A fetched list leaves out a model whose via
has this magpie and another one (it left here and came back), or more
than 8 magpies. A remote that is this magpie itself (via only this id,
as the in-process tests set up) is kept. A magpie older than this sends
no via, and its list is taken as before: both machines need the update.
Stamped on every list a magpie gives: models(), its deciders, and the
drawer and video lists. A routing group's via is its members'
together, so A's auto/m1 holding B's auto/m1 (which holds A's) is left
out at B, and requests no longer go A -> B -> A through groups.
What a user of A loses: B's own auto/ group of a model when it holds
A's model (it reaches A again); B's own models stay listed at A one by
one, and A's group of the model holds them. The cached list keeps Via, so a model a remote served
through others keeps its path in this magpie's list too.

Run (mote, at this tree on 6abacd46c = origin/main):
- go test -timeout 45m ./internal/catalog ./internal/provider
  ./internal/gateway -count=1: ok (catalog 0.7s, provider 120s,
  gateway 670s).
- go vet those three; GOOS=linux and GOOS=windows go vet: ok. gofmt -l
  clean.
- Two sandbox magpies (CLI, nogui build) each the other's remote:
  after two scheduled fetches (18:14, 18:24/18:25) A lists auto/m1,
  own/m1, rem/up/m1 and B auto/m1, up/m1, back/own/m1, each fetch
  taking 1 model; the old build in the same setup went 3 -> 5 models
  on B's second fetch and kept growing (rem/back/rem/back/own/m1).
- go test ./internal/gateway again after the group change: ok (715s).

Broken by hand:
- the loops check in live.go off: TestFetchLeavesOutWhatCameFromHere
  red (back/own/m1 with [self peer] and a 9-magpie model taken), and
  TestRemoteMagpieListLoopsNoMore red (the remote's back/own/m1 taken).
- models() without the magpie_via line: TestRemoteMagpieListLoopsNoMore
  red (own/m1 and rem/up/m1 listed through []).
- viaOf giving a group nil: red (auto/m1 listed through [self], not
  [peer self]).

Not tried:
- cdredfox's own two machines; it isn't confirmed yet that their remote
  also has this machine as its remote. If it doesn't, this isn't their
  cause.
- A loop through a magpie older than this one (no via: still grows
  until both are updated).
- The full suite (runs once after the push).
2026-11-05 10:26:14 +08:00
yetone 681a472cab agent: a Codex thread started during the takeover comes back to OpenAI once it is quiet, not hours later (nb5p on Discord)
nb5p on Discord (v0.1.3001, Codex app): after Send greyed out, Retry in
Codex did nothing. The model picker and Send spun, the same dialog came
back a few seconds later, and the model field read "model unavailable".

With the ChatGPT account Codex is signed in to used up, magpie makes
itself Codex's provider (codex.out), so a turn sent then starts a thread
saved with model_provider "magpie". When the account has room again,
Sync puts Codex back on OpenAI, and its deferred bringBack moves magpie's
threads to OpenAI. It skips a thread written to in the last minute,
which is the one the user was in, and leaves it "for the next Sync".
Nothing schedules one, though: Sync runs on a catalog change, which can
be hours away. The app then can't resume that thread on the provider it
is now on ("This chat uses magpie, but your current provider is
openai", the string still in the Codex the app bundles), so each Retry
failed the same way.

bringBack now asks whether a thread is still on magpie because it was
being written to (sessions.CodexThreadsBusyOn: the state databases' rows
on magpie whose rollout changed within ActiveWindow). If one is, it asks
for one more Sync after ActiveWindow+5s. Only one wait is pending at a
time.

docs/subsystems/agent-wiring.md says so beside bringBack.

Test: TestCodexTakeoverThreadComesBackOnceQuiet. The takeover is on, and
a thread on magpie is written to now. The account comes back, and the
thread stays on magpie while it is written to. A later Sync is asked
for, and that Sync, with the thread quiet, moves it to openai. No other
Sync is asked for after that.

Broken by hand: with the bringBack hook turned off (`if false && ...`),
it fails with "no later Sync asked for" (5.3s). Restored, it passes.

Run on mote at this tree (base 8eb219354, origin/main fetched, nothing
new):
- the new test with -race -count=3: ok;
- go vet ./internal/agent ./internal/sessions for darwin, for linux
  -tags nogui and for windows: clean;
- go build ./...: ok;
- gofmt -l: clean;
- go test ./internal/agent ./internal/sessions: ok.
The full suite at the pushed head is in the report.

Not tried: the real Codex app at the moment an account runs out and
comes back. The resume failure is read from the Codex source and the
string in the app's bundled codex, not seen live. A thread the app keeps
writing to for minutes on end waits one more round each time; that case
was not timed. Nor was a thread the app keeps open with its writer lock
held after it goes quiet: MoveCodexThreads refuses that one too, and
CodexThreadsBusyOn looks at the time only, so no further Sync is asked
for it.
2026-11-05 08:23:05 +08:00
yetone 3d0d790606 codex: the Codex app left on an account that runs out is restarted onto the one Codex is signed in to (nb5p on Discord)
nb5p has two ChatGPT accounts in magpie, B first. The Codex app showed A,
and once A ran out Send was grey for every model, magpie's and another
provider's too.

Cause: magpie's switch back to the first account (or to the account
Codex is kept signed in to) leaves the Codex app's app-server running
unless "Restart the Codex app to follow" is on. The app-server keeps the
account it started on (CodexAppStale), so the app stayed on A while
auth.json said B. magpie read only B, which had room, so nothing moved,
magpie never took over, and the app-server was never restarted: the app
greyed Send on A's allowed false for good.

Fix: on each full look of KeepOnAnAccountWithRoom,
restartCodexAppLeftOnSpent reads the account the app is left on, and
once that is held (codexHeld) marks a spent switch (codexAppSwitched
true), which codexAppStep restarts past the RestartApp tick, as a switch
off a used-up account already does. Once per app-server left.

Run (mote, at this tree):
- go test ./internal/provider -count=1: ok
- TestCodexAppLeftOnASpentAccountIsRestarted: user switches to A, magpie
  switches back to B and leaves the app running, A still has room
  (nothing ended), A runs out with B's room (app-server 7 ended), next
  look (not ended again).
Broken by hand:
- codexAppSwitched(true, false) commented out: red, "ended [], want the
  app-server left on the used-up account".
- the once-per-app-server check off: red, "restarted again: [7]".
Not tried: the real Codex app on a real account running out; the call
in KeepOnAnAccountWithRoom's loop is covered by reading, not by a test.
2026-11-05 07:51:09 +08:00
yetone dabb5722f8 claude: Claude Code routed through magpie stays signed in where the user put it when that account is spent
oreoft on Discord has two Claude accounts: A, the main one, whose sign-in
carries their claude.ai connectors (MCP), and B, a quota account. A's
allowance was used up. They set A first and signed in, B second, and
"跑着跑着" B came first again and became Claude Code's sign-in, and the
MCP broke. They set it back more than ten times.

Cause: the used-up switch (#208). KeepOnAnAccountWithRoom looks at
Claude Code's sign-in every minute or five; A is spent, so NextLogin
returns B and SwitchWhenSpent rewrites Claude Code's live credential to
B. The GUI's list puts the account in use first (loginsInOrder), so B
"moves to first". Each time the user signed A in again, the next look
moved it back.

Decision: when Claude Code's settings send its requests to magpie's
gateway (ANTHROPIC_BASE_URL is the gateway, whether it signs in with
magpie's key or keeps its claude.ai sign-in), NextLogin never moves its
sign-in off a spent account. The gateway already routes every request
to an account with room (it skips spent ones on its own), so moving the
sign-in served nothing and only took away what the user signed in as.
This keeps the user's choice and needs no setting.

Still switching, unchanged:
- not routed (Claude Code asks Anthropic as its own sign-in): the switch
  is the only thing that keeps it working (#208);
- "Only switch Claude Code's sign-in" (SwitchOnly): the gateway serves
  none of those accounts, so switching is all magpie is asked to do;
- the move back to the first account / the kept account
  (returnsToFirst, KeepLoginAs), which go toward the user's choice;
- `magpie accounts switch claude next` and the GUI's own switch.
- Codex is left as it is: the Codex app stops sending once its own
  account is out, so it needs the sign-in moved.

ClaudeThroughMagpie is a provider hook the agent package sets
(claudeRouted, the same check claudeIn's "routed" uses), like
CodexAppRoute.

Run (all on mote via mote-run):
- new TestClaudeRoutedThroughMagpieKeepsItsSignIn (sandbox HOME: A
  spent, B with room; routed: three looks, no switch, credential still
  A's; SwitchOnly: switches to B; not routed: switches to B) with
  TestClaudeSwitchedWhenSpent, TestClaudeSwitchOnly*, TestKeepLoginAs*,
  TestNextLogin*, TestClaudeSwitch*, TestNextInOrder, TestCodexDrain*:
  ok. New TestClaudeThroughMagpieReadsItsSettings (agent): ok.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; GOOS=linux go build -tags nogui;
  GOOS=windows go build: ok.
Broken by hand: with the NextLogin gate turned off ("if false && ..."),
TestClaudeRoutedThroughMagpieKeepsItsSignIn FAILs at line 80, "Claude
Code routed through magpie was signed in to b@example.com".
Not tried: real Claude accounts and a real Claude Code with claude.ai
connectors; Windows and Linux boxes. Full suite runs after the push.
A sign-in already moved to B stays on B until the user switches back
once.
2026-11-05 06:43:51 +08:00
yetone 49e382735f claude: a side question after a run's first reply of words branches by the reply's id
sleepy_shibe (Discord #feedback, magpie 0.1.2948, Claude Code 2.1.318,
claude-opus-5-5, macOS, interactive mode): when the last turn's reply
was words only, the turn after a prompt suggestion found no run
("claude: no run waits for this turn: its run ended 0s ago: the
interactive Claude Code can't go on with this turn") and a new Claude
Code was told the whole conversation as a transcript. With a tool call
in the turn it branched. 3 sessions, 7 times.

Cause (the reporter's reading, checked in a test): the interactive mode
streams a reply and the bridge hears its session line only later, from
the file. resume saves run.lastLine as the turn's backLine. A run's
first reply of words has no line heard yet, so backLine, behindLine and
the shelf's behindLine were empty while behindMsg (from message_start)
held the reply's id. branchAt returned nil at `at == ""` with no log,
and the run was let go. With a tool call, the run waited on the call and
heard the call's line first, so there was a line to cut at (8ac5f98e).
A run after a branch is a new run, so every first reply of words after
one hit it.

Fix, every path that cuts behind a side question:
- branchAt cuts with the reply's id alone when no line was heard.
- cutReply takes an empty uuid with a msg and cuts after the reply's
  last main-thread line; cutSessionAt's empty-uuid check moves to its
  uuid callers (cutSessionWhere does the polling).
- unshelve's search for a session behind a side question accepts a
  behindMsg alone, and cutBehind cuts by cutReply when either is set.
- cutReply waits for the reply's lines up to cutWait before falling
  back to the uuid's line. Before, a run that had heard an earlier
  turn's line cut after it at once when the new reply's lines weren't
  written yet, dropping the last turn.

Tests:
- TestClaudeInteractiveSideQuestionAfterAFirstReplyOfWordsKeepsTheReply:
  the fake writes the reply's line late; first turn words only, the
  suggestion, then "now commit it". The next turn must resume a copy of
  the run's own session (U1 and A1), told only the new turn. On
  origin/main ed7aeb052 it is red and logs the reporter's exact line.
- TestClaudeShelvedSideQuestionAfterAFirstReplyOfWordsKeepsTheReply:
  the same run let go past idleMost; the shelved session (behindLine
  empty, behindMsg set) is found and cut.
- TestClaudeCutReplyWaitsForTheReplysLines, and two id-only cases plus
  two error cases in TestClaudeCutReplyKeepsTheWholeReply.

Broken by hand, each red then restored: branchAt's old guard (the
interactive test), unshelve's old condition and cutBehind's old route
(the shelved test each), cutReply falling back to the uuid without
waiting (the wait test).

Run (mote, at this tree on origin/main ed7aeb052):
- go test -tags nogui -count=3 -run 'TestClaudeCutReply|TestClaudeShelved...|
  TestClaudeInteractiveSideQuestion|TestClaudeCutSession' ./internal/gateway/: ok
- go test -tags nogui -count=1 -timeout 45m ./...: ok, 87 packages, no
  FAIL (gateway 770s, claudetui 75s); log kept whole.
- go vet -tags nogui ./internal/gateway/, GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./..., go build ./..., GOOS=linux go build
  -tags nogui ./..., GOOS=windows go build ./...: ok
- gofmt -l: clean

Not tried: a real interactive Claude Code 2.1.318 with a real account;
the fake reproduces the timing (the reply's row heard after the stream
ended), not the real TUI. A reply split into several rows whose later
rows are not yet written when the cut runs would still be cut short
(as before this change); not seen.
2026-11-05 04:23:56 +08:00
yetone ed7aeb052f plugins: a package that declares magpie.agent is an agent, with a main or without (plugins#737)
miaocell's magpie-agent-deva ships a Bun module as its main beside its
moejs agent file (deva.agent.js), because the agent needs a runtime. The
market's GitHub list decided the kind by whether a main was there, so it
listed the package under Providers, and the Installed row wore a Provider
chip and a provider logo though the module serves no provider.

Now readTagged gives Kind "agent" to any package that declares
magpie.agent; middleware, page and hooks still need no main to be that
kind. The file looked for in the repository is still the module Bun
loads (its main), or the agent file when there is no main. The Installed
row of an agent plugin wears Provider only when its module serves a
provider, and its logo is the agent glyph unless it does. The moejs
descriptor contract is unchanged. The community registry.json already
gives kimi-desktop and reasonix-desktop (both with a main) kind agent;
the plugins repo's check now fails an agent package listed as any other
kind.

Docs: docs/reference.md, docs/subsystems/provider-plugins.md, and
site/public/docs plugins.html in en, zh and ja say an agent that needs a
runtime keeps its agent file and adds a Bun main, and is listed as an
agent either way.

Run (on mote, at this head rebased on b047cfe73):
- TestTaggedAgentWithMain (new; the reporter's real package.json,
  index.mjs and deva.agent.js in testdata): go test -run
  'Tagged|PkgEntry|Readme|GitHub' ./internal/plugin ok. Red with
  github.go at its parent: kind "".
- plugin-agent.test.cjs (new rows: an agent with a main and no
  provider, one switched off, one that serves a provider), chromium and
  webkit, en, zh, zh-TW, ja, de: ok. Red at origin/main b047cfe73: the
  deva row's chips were [Agent, Provider].
- Every plugin*.test.cjs plus i18n-keys, both engines: 1090 of 1094 ok.
  The 4 reds are plugin-move-unserved "Try again takes the models
  unticked" (Model 1 folded behind "Show the other 29"), red the same
  at origin/main b047cfe73; filed as #4410.
- gofmt -l, go vet ./internal/plugin ./internal/gui, GOOS=linux and
  GOOS=windows go vet ./internal/plugin, go test -run 'Budget|I18n'
  ./internal/gui (TestCoreScriptBudget, budget not raised): ok.

Not tried: installing magpie-agent-deva from the real GitHub list in a
running app (the list is read from the test server); Windows and Linux
runs of the GUI tests.
2026-11-05 03:54:41 +08:00
yetone 5ee9a18747 gateway: magpie's own summary ask keeps its status, so a compaction over the byte cap is summed up locally (#4862)
codexCompact asks a summary through the gateway's own handler (wantsWhole)
and reads a 413 as its cue to fit the conversation, then to sum it up
without a model. That ask was treated like a client's turn:

- with Codex's User-Agent, compactsInStream sent it a 200 and the 413 as
  the stream's error, so codexCompact saw no 413 and answered 502 "so
  there is no summary" for every compaction over the vendor's cap;
- with any UA, once the fitting tries took past keepHeldAfter (3s: a 40
  MB upload asked four times, a slow link, -race on CI) keepAlive sent a
  200 and a comment first, and the 413 after it came the same way.

keptAlive.whole (set from wantsWhole) now gets neither a keepalive nor
the in-stream 413. Codex's own turns are unchanged.

9a51d644d (the 4-minute summary limit) is not the cause: the 502 comes
from the status, not the deadline.

Run at this head (mote, mote-run):
- go test -count=3 -run 'TestCompactionOverByteCap' ./internal/gateway ok
- the compaction/keepalive tests -count=2 ok (225s); -race of
  TestCompactionOverByteCap* ok (121s)
- gofmt -l clean

Broken by hand: on the old code TestCompactionOverByteCapSlowFitting
failed 3/3 (502 at ~1.8s); the codex-UA subtest of
TestCompactionOverByteCapEveryTime failed 3/3. Reverting the
compactsInStream half alone turns the codex subtests red; reverting the
keepAlive half alone turns the plain SlowFitting case red.

Not tried: a real Codex compaction over a vendor's byte cap with a real
account; the full suite runs once for this batch (recorded on the last
commit).
2026-11-05 03:07:43 +08:00
yetone 8b902e2879 checkin: a ZCode or Qoder captcha stands for the day, not asked again every 30 minutes (plugins#503)
ZCode's check-in is rechecked (pluginRechecks, 430005726): the loop
asked again 30 minutes after every answer, a captcha included. A
captcha answer means the plugin's claim got 3007 and the plan has to be
claimed in the ZCode app; asked again, the plugin GETs the feed and
POSTs the same claim, and ZCode answers 3007 again. MiniFullC's log
(plugins#503) has an account asked six more times after its captcha in
one evening, followed by 3012 on two accounts. The plugin itself
already says captcha stands for the day (its RECHECK comment); magpie
overrode it.

Now, under a recheck, a captcha or own-app answer (both wait on the
user in the vendor's app) is settled for the day for the loop. A press
still asks at once, and the next Beijing day asks again. inactive,
ineligible, done and claimed are rechecked as before, so a plan dropped
into the feed later in the day is still found. The provider-plugins
page now names ZCode among the rechecking plugins, which it left out.

Run on mote: go test ./internal/provider/ ok (120s); go vet for
darwin, linux and windows ok; gofmt clean.
Broken by hand: with the old recheck line, the new
TestPluginCheckinRecheckLeavesCaptcha is red in all four subtests
(zcode and qoder, captcha and own-app: asked again at 22:47).
Not tried: a real ZCode account (none here); the full suite runs after
the push.
2026-11-05 01:43:41 +08:00
yetone d892dd6a22 gateway: a Claude conversation keeps the folder it named first when its caller moves
EricWvi on X (Claude Code -> local magpie -> a magpie on a server -> a
Claude subscription): the cache read flipped between under 10% and over
90%, each drop on a turn whose folder had changed (.../frontend, then
.../frontend/src). Claude Code 2.1.316 says a cd as a later
"# Environment update" message, "Primary working directory: /y (was /x)".

clientNamedWorkPlace took the last folder named, so a run started again
for the conversation (saved session resumed, branch, replay) got a
different prefix than its first run:
- a caller elsewhere: envTurnsNote names the folder, so append.md changed;
- a caller on this computer: the run worked in the new folder, whose
  session project doesn't hold the saved session, so --resume was lost
  and the whole conversation was told again.
Either way the whole conversation was written to the cache again.

Now the first text that names a folder decides it (within that text, its
last line, so "said twice" in one system prompt keeps its meaning). The
move still reaches the model in the conversation as the caller said it.
No text is added to the prompt; the note's wording is unchanged.

The reporter's per-turn flips on a v0.1.2879 server are the earlier
safeguards restart (git_state.cwd in safeguardsKept), fixed by 59c130603
in v0.1.2882 while the tap is live.

Run (mote, via mote-run, at this tree):
- go test -tags nogui ./internal/gateway -run 'TestClaude|TestWorkDir'
  -count=1: ok (114.9s)
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m: ok (778.6s, mote at load ~45)
- go vet -tags nogui ./... ; GOOS=linux and GOOS=windows go vet
  ./internal/gateway: ok (cgo deprecation warnings only)
- gofmt -l internal/gateway: clean
Broken by hand: without the `if dir != ""` guard,
TestClaudeTUIConversationKeepsItsFolderWhenTheCallerMoves is red in both
subtests (caller elsewhere: append.md names .../frontend/src; caller on
this computer: --resume of another session, not s<pid>).
Not tried: a real Claude Code cd against a real remote magpie and
subscription; whether a model told the first folder in envTurnsNote after
a move misreads the environment update (not measured).
2026-11-05 01:37:56 +08:00
yetone 9a51d644d6 gateway: a compaction's summary late past 4 minutes is magpie's own, sent before Codex gives up (#5275)
hayden4608 on Discord (#5275, asked as urgent): Codex Desktop compacting a
~108k-token conversation on volcengine/deepseek-v4.1-flash. The ~3.1MB
summary request was still being written to Ark at 299s (TryNet Send
~299s, no first byte), Codex gave up at 300s (499), and only then did
magpie log "the reply ended before it was complete; compacting locally".
That local summary went to a request nobody was reading, and
compactFails.done cleared the conversation's count as if it had worked.
Codex sent the same history again, three times, 300s each, and the
conversation never got shorter.

- codexCompact gives the summary compactWithin (4 minutes, a minute
  short of Codex's 300s stream idle timeout, as agentQuietMost). Past it
  the vendor is no longer waited on (the ask's context ends with a
  sideTimedOut cause, so the usage log says "magpie stopped waiting: its
  compaction summary had no answer in 4m0s", not the agent canceling),
  and magpie's own summary (localSummary, saying "no summary came in
  4m0s") goes to Codex while it still waits. Checked after the first
  ask, the ask as plain text, and the as-text ask after tool calls, so
  a late first ask is never followed by another ask of the same body.
- A compaction Codex left before it was answered is counted a failure
  (499, "Codex left before the summary reached it") and nothing is
  written; done() is no longer called for it. After compactFailsMost in
  a row, the next is held with a 400 at once instead of another 300s.

Why the upload was slow: not shown to be magpie's. From here a 3.1MB
whitespace-padded chat request to ark.cn-beijing.volces.com/api/v3 was
read whole in ~1.5s by curl over HTTP/2 and HTTP/1.1, and Go's client
with vendorTransport's settings (HTTP/2, ping health) wrote it in 0.89s
(HTTP/1.1 0.17s) from mote. The reporter's ~10KB/s, and their own 4MiB
control not finishing in 40s by any route, point at the uplink or the
Shadowrocket TUN in their path. Not tried through a TUN.

Run (mote): TestCodexCompactLateSummaryCompactsLocallyInTime and
TestCodexCompactLeftBeforeAnsweredStillCounts green with the fix;
both red on the old code (the first: no answer before the client's 10s; the
second: a completed compaction written to a Codex that left, and the next
not held). go test -run Compact ./internal/gateway ok; go vet of
internal/gateway for darwin, linux and windows ok; gofmt clean.
Full suite: run after the push (go test -timeout 45m ./... on mote, log
teed), result on #5275.

Not tried: a real Codex Desktop session against a slow uplink; a
reporter-side stream_idle_timeout_ms shorter than 4 minutes (then Codex
still leaves first, and the count holds the conversation after 3).
2026-11-05 01:26:12 +08:00
yetone 775630dac9 usage: the compaction picker says each window against the setting now
hayden4608 on Discord (#feedback): "上下文压缩阈值建议这里应该以当前选中的为
基准更直观 而不是以最省token的为基准". Usage › Context's "Other window…"
menu said every value's tokens past the leanest, so the window one had
set (ticked in the menu) read "+N tokens" like any other, and choosing
between them meant subtracting two notes in one's head. The reader
picks away from the setting in use, so that is the baseline now:

- each value says "−N tokens (−x%)" or "+N tokens (+x%)" against the
  setting now's own point on the curve (the replay's cost at the current
  value when the curve has no point there);
- the setting itself says "Your setting now";
- "Fewest tokens" stays, beside the leanest value's numbers (timed: the
  cheapest, as before), so where the minimum is is still shown;
- the menu head says it: "Compact at · against the setting now, from
  your calls of the range".

The chart and the "{pct} fewer tokens" line already compare with the
setting now and are unchanged. New strings in zh, zh-TW, ja and de; the
old head's key is replaced. docs/subsystems/agent-wiring.md says the new
baseline.

context-tune.test.cjs: the menu notes in every language at 360 and
1100 wide, against 300K set (−150M/−11% at 250K, −420M/−30% plus
Fewest at 160K, "Your setting now" at 300K), and again after 250K is
put in (250K is the setting, 300K +150M/+12%); the timed case against
120K set (100K −90M/−9% plus Fewest, 240K −20M/−2%).

Run on mote (mote-run), this tree before the rebase:
- context-tune: 120/120 chromium, 120/120 webkit
- i18n-keys 4/4 and compact-one-value 6/6 in each engine
- go test -run 'Budget|Script|Asset|I18n|Lang' ./internal/gui: ok

Broken by hand: the old context.js under the new test fails 20
subtests in chromium (both menu tests, every language and width).

Not tried: the real app with a real replay; the full GUI suite and
go test ./... (run after the push).
2026-11-05 01:06:30 +08:00
yetone 676b143175 gateway: a model refused for the user's region is asked once more, then the agent is told Google's restriction on that model (#5182)
taoxiaoxin (#5182) runs magpie v0.1.2738 with the built-in Antigravity
provider, calling it with curl. antigravity/gemini-3.8-flash (upstream
gemini-3.8-flash-tiered) answers 400 "User location is not supported
for the API use.", while claude-sonnet-4-6 and claude-opus-4-6-thinking
on the same accounts answer 200. The refusal is per model and comes
from where the user is. A new connection doesn't help, and v0.1.2982
still asked every account and then retried the last two more times.

- gateway.go: regionAsked counts region refusals per provider and
  model within a request. The first one goes on as v0.1.2982 does: the
  next account, or the same one again, on a new connection, which
  covers ggdayup's stale-edge case. On a second refusal, the provider's
  other accounts aren't asked that model (notMates), the last one isn't
  retried (protected), and another provider or model left is asked. Nobody
  rests (restAfterMarked, v0.1.2982).
- fallback.go: regionNote and explained. The agent gets the vendor's
  words plus: "Google doesn't serve <model> to requests from the region
  this one left from: a regional restriction on the model, not on the
  account, so no account rests for it and the provider's other models
  may still answer. Use another provider for <model>, or give the
  provider a proxy in a region Google serves (its Proxy setting)". It is
  added at the four places that word a failed reply through
  Provider.Explain (translated stream and non-stream, pass-through,
  count_tokens). It still goes out as the 400 that SDKs don't retry.
- docs/subsystems/gateway-routing.md: the bullet says this.

Tests:
- TestRegionRefusalOfTheModelEndsAfterOneMoreAsk: one and three
  accounts, stream and not, every ask refused. Exactly 2 asks, then a
  400 that carries Google's words and the note. No account rests and no
  usage is re-read.
- TestRegionNote: Google's and OpenAI's wordings. Nothing is added for
  another 400, or for a 200 that quotes the words.

Run on mote (mote-run):
- go test -count=1 -run Region ./internal/gateway/: ok, every #5182
  test from c32b820a9 included.
- go test -race -count=3 -run 'Region|Antigravity|Fallback|Group'
  ./internal/gateway/: ok (519.7s)
- go vet ./internal/gateway/ for darwin, linux (-tags nogui) and
  windows, and go build ./... for all three: all clean
- gofmt -l: clean.
- The full suite at c32b820a9 (v0.1.2982), go test -timeout 45m ./...:
  every package ok except internal/gui TestMainWindowCorners/
  macOS_26_SDK, which is #3949, open and red on mote's macOS 27. This
  commit doesn't touch internal/gui.

Broken by hand, each with a real FAIL and then restored:
- the second refusal's cut removed: the 1-account case asks 3 times,
  and the 3-account case asks u1 u2 u3 u3 u3, which is the reporter's
  behaviour.
- regionNote left out of explained: the agent gets Google's words
  alone, and every subtest is red.

Not tried: a real Antigravity account in a region Google refuses
gemini-3.8-flash to. That the reporter's Claude models answer from the
same place comes from their report, not from a run here.
2026-11-05 00:59:11 +08:00
yetone 79477604a5 providers: a plugin option that says placement "top" sits under the accounts, above Routing (#5269)
mycf_711 (#5269): WorkBuddy Pro's plugin-level "panel" switch was drawn in
Plugin options, under the whole model list, so it took a scroll every time.
An option in auth.options may now say `placement: "top"`: the provider's
editor draws those in a Plugin options block right under the accounts,
above Routing, and the rest under the models as before. The note that the
plugin reads them goes with the first block. host.js keeps placement only
when it is "top" (anything else is left out, so the option goes under the
models), and plugin.Option carries it to /api/providers. A plugin that says
no placement is drawn exactly as before, and an older magpie ignores the
field. Documented in docs/subsystems/provider-plugins.md and
docs/reference.md.

Run (mote, through mote-run):
- new internal/gui/tests/plugin-option-placement.test.cjs: chromium 31/31,
  webkit 31/31 (1100 and 420 wide, en/zh/zh-TW/ja/de; mixed, top only,
  none or an unknown placement; the top switch posted on Save).
- plugin-options.test.cjs 11/11 and plugin-option-words.test.cjs 21/21,
  i18n-keys 4/4, each in chromium and webkit.
- go test ./internal/plugin ok (TestPluginOptions checks "top" kept and
  "sidebar" left out); go test -run Budget|Script|Asset ./internal/gui ok.
- gofmt -l internal/plugin empty; go vet ./internal/plugin ./internal/gui
  ./internal/cli, GOOS=linux -tags nogui and GOOS=windows vet of
  internal/plugin ok.

Broken by hand:
- app.js put back to its parent: the placement test fails "mixed" and
  "top" in both engines (blocks under the models), "none" still passes.
- host.js's placement line removed: TestPluginOptions fails
  "second = {... Placement:}".

Not tried: a real WorkBuddy Pro plugin (Gitee, private) with the field;
the full go test ./... and the whole GUI suite run after the next commit.
2026-11-05 00:55:36 +08:00
yetone c32b820a91 gateway: a "User location is not supported" refusal rests no account, and the next try goes on a new connection (#5182)
ggdayup (#5182): Antigravity answered 400 "User location is not
supported for the API use." on one kept-alive connection. magpie asked
every account after it on that same connection, each was refused the
same and rested, and the agent got a 400, while a new connection about
12s later was answered. The refusal is about the edge the connection
reached, not about the account.

- routing.go: restAfterMarked returns Rest{By: "off", Until: now} for
  regionRefused, as for zdr and offline, so no account rests and no
  failure is counted.
- upstream_transport.go: regionFresh wraps each of upstreamTransport's
  three transports (any, draws, uploads), so every request through
  s.client is covered. It reads the first 8KB of each reply with
  status >= 400. When those match regionWords, closing the body calls
  CloseIdleConnections, and a pending flag calls it again before the
  next request. That flag covers an HTTP/2 connection that still
  carried another stream when the body closed.
- fallback.go: passing() asks the last candidate again (lastRetries,
  after retryPause), on a new connection, so a user with one account
  is helped too.
- docs/subsystems/gateway-routing.md: a bullet saying all of this,
  including what it doesn't cover.

Tests (region_fresh_test.go, with a fake TLS edge that refuses every
request on the first connection it sees and answers on any other):
- TestRegionRefusalDropsItsConnection uses the real New() client,
  over h2 and h1. After a region 400 the next request goes on a new
  connection and gets 200. A plain 400 INVALID_ARGUMENT keeps its
  connection.
- TestAntigravityRegionRefusalAsksTheNextOnANewConnection: two
  accounts. The second is asked on a new connection and answers, no
  account rests, and Tries[0].Rest.By is "off".
- TestAntigravityRegionRefusalAsksTheLastAgain: one account. It is
  asked again on a new connection and answers.
- TestRegionRefusalRestsNoAccount: Google's and Antigravity's
  wordings, two turns each. Both accounts are asked both times, with
  no rest, no failure counted and no usage re-read. A 500 still rests
  the account.
- TestGroupFailsOverARegionRefusal (#1621) now asserts By "off" and
  no rest.

Run on mote (mote-run):
- go test -count=1 -run 'Region' ./internal/gateway/: ok.
- go test -race -count=3 -run 'Region' ./internal/gateway/: ok (16.5s).
- go vet ./internal/gateway/ for darwin, linux (-tags nogui) and
  windows, and go build ./... for all three: all ok.
- gofmt -l: clean.
- Full suite: run after the push, see #5182.

Broken by hand, one at a time, each with a real FAIL and then
restored:
- regionFresh not wrapping the body: DropsItsConnection h2 and h1
  region, AsksTheNext and AsksTheLast are red (the second request goes
  on the refused connection, and the turn gets 400).
- restAfterMarked's early return removed: AsksTheNext and RestsNoAccount
  are red (By backoff, Failures 1).
- passing()'s region case removed: AsksTheLast is red (the turn gets
  400).

Not tried: a real Antigravity account in a refused region. Nothing here
can reproduce Google's per-edge refusal. Not covered: an HTTP/2
connection busy with another stream at that moment outlives the close
until it is idle. The close also drops other vendors' idle connections,
which costs one handshake each. A user who really is in a refused
region now gets the refusal about 3s later, after the last candidate's
retries.
2026-11-05 00:28:06 +08:00
yetone 18726b9fb6 statusline: a held key is told how to see its line, ?format=json, and /v1/magpie/limit says what holds a key (steven_4422)
steven_4422 (Discord, #feedback): POST /v1/magpie/statusline answered 403
gateway_key_held to a key held to Claude's models, while GET
/v1/magpie/limit told the same key {"limited": false}. They asked for the
line scoped to what the key may use, /limit to agree, and a JSON line for
claude-hud's external usage snapshot.

The scoped view already exists (#2216): the status line goes through
scopeQuotas like the quotas routes, so a held key its owner turns Quotas
on for (Gateway -> Gateway keys, or `magpie gateway-key quotas <id> on`)
is told the accounts it may use of each provider whose every model it may
use, and nothing else. Its 403 never said so. Decision: the switch stays
the gate for every held key, budget, models or accounts alike. What holds
a key says nothing of whether its holder is the owner or a friend (#1981
was a friend's budget key seeing every account's email), and only the
owner knows that, so a model- or account-held key is not told quotas by
default either. The every-model rule of #2216 stays.

- scopeQuotas' refusal (heldQuotasOff) names the switch and what it then
  tells. heldRefused, for the routes the switch doesn't open
  (concurrency, trace, a card outside the scope, writeCards' told-none),
  is unchanged.
- GET /v1/magpie/limit tells a held key heldTo (budget, models,
  accounts), models, quotas and, with it on, quotaProviders (the
  providers newQuotaScope tells it). No account is named. `limited`
  keeps its meaning (the budget) for remote magpies that read it.
- ?format=json on the status line: {"text", "model", "accounts"}, the
  cards the line shows in /v1/magpie/quotas?kept=1's shape (windows'
  used, resetsAt), through the same scope.
- Docs: reference.md, integrating.md, gateway-routing.md; site docker
  and remote pages in en, zh, ja.

Run at this head (4a9cfb52e + this), on mote:
- gofmt -l clean; go vet, GOOS=windows go vet, GOOS=linux go vet -tags
  nogui on internal/gateway: clean.
- go test -run 'TestStatusline|TestHeldKey|TestRemoteMagpieShowsHeldKey|KeyLimit'
  ./internal/gateway: ok.
- TestStatuslineHeldKeyScope (new): this computer and a key held to
  nothing see alpha One, alpha Two and beta; a key held to alpha/* sees
  alpha's two; one held to alpha's Two sees Two alone; one held to
  alpha/m1 sees nothing; the same through ?format=json; Quotas off is
  403 gateway_key_held naming the switch, as text and JSON; /limit's
  heldTo, quotas and quotaProviders for each, and no account id.
Broken by hand, each red: the scope dropped from the handler (every
held key saw every card, text and JSON); /limit's held block skipped;
scopeQuotas back on heldRefused.
Not run before the push: the full suite (mote had three full suites of
other sessions running at load ~70; it runs after, per the rules). Not
tried: a real Claude Code or claude-hud on another computer, a real
Claude account behind a held key, Windows and Linux test runs.
2026-11-05 00:24:13 +08:00
yetone 7661a0aa72 provider: Fetch models ticks each key's own models, the first key's too (young02036)
young02036 on Discord (#feedback, v0.1.2965): "点击供应商的获取模型,给这个
供应商的所有账号默认勾选上可用模型,和新增账号之后默认勾选上可用模型这个功能
好像失效了".

Cause: no later change broke it; the two commits that built it each left
keys out. 0431793db (v0.1.2674) gives a key its own list only when it is
added beside others and its list is short, and says "the keys it had keep
their lists". 1a67ca614 (v0.1.2942) carries on each Fetch only what a key's
list gained and lost, and only for a key that already had a list of its
own ("a key serving every model still does"). So every key on All models
stayed there through every Fetch: the provider's first key, keys added
before per-key lists, and a key whose list wasn't read in the 8s when it
was added. In the reporter's setup that is the key the provider was made
with, so the feature reads as gone.

Fix (refreshKeyModels): a key on All models whose fetched list leaves out
a model the provider's other keys list is given that list. A key whose
list has every model stays on All models, so later additions still reach
it; a lone key stays too. Keys with lists of their own work as before
(un-ticks and ticks kept).

The user's choice is never overridden: a key the user set to All models
(`accountmodels` with none, the picker's All models) is now remembered in
Provider.AccountModelsAll and left alone by Fetch. The editor's save keeps
it, a key replaced in place moves it (moveKeyed), accountSettings and
clone carry it, normalize drops a mark for a key that has a list.
Not covered: a key set back to All models before this release has no mark
and is narrowed once to its own list on the next Fetch; the user can
press All models again and it stays.

Tests:
- TestFetchTicksEachKeysListOnAllModels: keys saved with no lists are
  ticked on Fetch; a key set to All models before and after stays so
  through two fetches; an un-tick survives; a key whose list failed stays
  All models and gets its list once it reads.
- TestFetchLeavesALoneKeyOnAllModels.
- internal/gui TestFetchModelsTicksEveryKeysModels through the real
  routes: provider/save, provider/models, keys/add, accountmodels, the
  editor's save, against an httptest relay with a list per key.
- TestFetchRefreshesEachKeysModels and TestNewKeyTakesItsOwnModels pinned
  the old rule (sk-b / sk-old left on All models); they now expect the
  key's own list.

Broken by hand (mote): the old `was == nil -> continue` put back: the
new provider test, the GUI test (sk-a, the first key: [] want
[m1 m2 m3 m4]) and the two updated tests go red. The AccountModelsAll
check removed: sk-c/sk-d set to All models get narrowed, red. The editor
save not keeping AccountModelsAll: the GUI test's sk-c red.

Run (mote, at this tree): gofmt -l clean; go vet of the touched packages,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... ok;
go test -tags nogui -count=1 -timeout 45m ./internal/provider ./internal/gui
./internal/cli ./internal/gateway ./internal/tui: all ok (provider 223s,
gui 138s, cli 106s, gateway 797s, tui 26s).
GUI: account-models, account-models-available, account-refresh,
gateway-key-models, gateway-key-models-redraw (each in Chromium and
WebKit, as the files run): 94 of 94 pass.

Rebased on origin/main 8e97e26d6 (google.go, migrate_zcode.go): ./internal/provider
run again at this head, ok (157s).

Not tried: a real relay with per-group keys; Windows and Linux test runs
(nothing OS-specific changed). No app.js change.
2026-11-05 00:11:02 +08:00
yetone 0a6cccc3ff groups: a found group the user changed takes in a new provider with its model
Kxsg79bEYFP4 on X: magpie found auto/deepseek-v4.1-flash over two
providers, the user changed the group, then added a third provider (a
plugin's) with the model, and it never joined.

Cause: SaveGroup stores a changed found group under its auto-… id with
the members it had then, and buildGroupsIn skips the found group of
that id ("the user changed it: theirs now"). Nothing recorded which of
the found models the user had taken out, so a stored group could only
stay frozen. Plugin providers, id spelling and a one-time creation were
ruled out: a plugin's models are in providerEntries like any provider's,
and the found group itself has all three.

Fix: SaveGroup stores Group.Seen for an auto-… id: the models magpie
found in it by that save plus those the user names. Reading a changed
found group (joined) appends the found members it neither names nor has
seen, after the user's own. A model the user took out was seen and stays
out (magpie's default never overrides the user's value); a provider kept
out of found groups (AutoGroupSkip) doesn't join; with found groups off
nothing joins. Seen follows a provider's rename/SetModelID
(mapModelRefs) and a fold, and ShareGroup leaves it behind. A group
changed before this (no Seen) takes in nothing, since nothing says what
the user took out; its next save sees what is found then, and providers
added after that join. docs/subsystems/providers-accounts.md says so.

Tests: TestChangedFoundGroupTakesInANewProvider (join, order, routed by
FindGroup, the user's name/routing kept, taken out stays out before and
after joining, rename, skip, share), TestChangedFoundGroupFromBefore-
KeepsItsMembers (old stored group), TestChangedFoundGroupTakesInA-
PluginProvider (the reporter's surface: the fake plugin under real Bun).

Run on mote at base f280b12e5 plus this change:
- gofmt -l: clean
- GOOS=windows go vet ./...: ok; GOOS=linux go vet -tags nogui ./...: ok
- go test -tags nogui -count=1 -timeout 45m ./internal/provider/
  ./internal/cli/ ./internal/gui/ ./internal/tui/ ./internal/agent/
  ./internal/gateway/: all ok (provider 214s, cli 86s, gui 127s, tui 23s,
  agent 372s, gateway 876s)

Broken by hand (each red, then restored):
- joined returning g unchanged (the old behaviour): all three new tests red
- dropping the Seen check and the legacy no-Seen guard: c came back at
  once, and the pre-Seen group took c in
- not mapping Seen in mapModelRefs: c came back as cee/… after Rename
- not clearing Seen in ShareGroup: the shared text carried it

Not tried: a real magpie with the reporter's providers; the GUI suite
(app.js is unchanged, /api/groups only gains a "seen" field); an editor
opened before a provider was added and saved after it treats that
provider as taken out.
2026-11-04 23:28:23 +08:00
yetone 387b386c84 codex: threads of the provider an older beside wiring took down move to OpenAI (yikelizi9438 on Discord)
yikelizi9438 (Windows, the Codex app): models wouldn't load, "This chat
uses custom, but your current provider is openai. Switch to custom to
continue", and "Model unavailable" in the composer. "custom" is CC
Switch's provider id; magpie never names one so. Before #4347
(e02bc8c49, v0.1.2652) a magpie model picked beside the ChatGPT sign-in
took the user's model_provider down, kept in stash codex.provider for
the Disconnect, leaving Codex on OpenAI by openai_base_url. Codex 0.166
resumes a thread only on the provider it is on now
(modelProviderMismatch), so every thread started on custom was refused.
#4347 stopped new configs reaching that state, and d6e3a36ff moves such
threads only when magpie is Codex's provider, so a config already left
so stayed broken after the update.

Now Sync's bringBeside: with Codex on OpenAI routed by the base URL, no
top-level model_provider, and a provider of the user's in the stash
(not openai, magpie, cc-switch-official or a CC Switch OpenAI mirror,
none a profile names), that provider's threads move to openai as
bringOver moves them onto magpie: in place at OpenAI's length, the last
30 days rewritten with a copy kept otherwise. The ids moved are kept
(codex.brought). The Disconnect, which puts the provider back, returns
exactly those (sessions.MoveCodexThreadIDs, only ones still on openai);
OpenAI's own threads stay. If magpie becomes Codex's provider instead,
they go on to magpie (followBeside), where bringBack returns them at the
Disconnect. A reset forgets the record (Codex stays on OpenAI).

Run: TestCodexBesideBringsTakenProvidersThreads red on origin/main
f280b12e5 ("thread ... on \"custom\", want \"openai\""), green here
(mote-run). Broken by hand: with Unwire's giveBeside("") commented out
the test goes red at the Disconnect ("on \"openai\", want \"custom\"").
mote-run: gofmt -l clean; GOOS=windows and GOOS=linux go vet -tags nogui
of internal/agent and internal/sessions; go test -tags nogui
./internal/agent/ ./internal/sessions/ ./internal/gui/ ok (agent 282s, sessions 31s, gui 95s).
win-run (xiaomi-gpu): TestCodexBeside|TestCodexThreads|
TestMoveRecentCodexThreads|TestMovePackedCodexThreads ok.

Not tried: a real Windows Codex app with the reporter's config (their
magpie version and config.toml are unknown; if CC Switch itself switched
them to its official card, the stash has no provider and nothing moves:
the Sessions page's "Move to openai" does it by hand). The followBeside
path has no test of its own.
2026-11-04 23:16:23 +08:00
yetone d6e3a36ffc codex: threads of the provider Codex was on before magpie follow it onto magpie (hxy920830 on X)
hxy920830 on X: "magpie希望codex接入的时候自定义供应商名称,我现在名称被替换成了
magpie,原来的会话可以看到,但是加载不出来模型了". Codex had been on a
provider of the user's own (a relay's [model_providers.<id>] table, or CC
Switch's "custom"). Wired with no ChatGPT sign-in, magpie sets
model_provider = "magpie". bringOver moved only OpenAI's threads onto
magpie, so the relay's threads stayed on their provider. From Codex 0.166
(codex-rs app-server config_manager.rs load_for_resume) a thread resumes
only on the provider Codex is on now. The app lists them (thread/list
with model_providers [] lists every provider) but opening one stops at
modelProviderMismatch: "This chat uses <id>, but your current provider is
magpie". Nothing a user can set changes that, so a setting to rename the
provider wouldn't be needed. The threads should just open.

bringOver now moves the threads of the provider Codex was on before magpie
(stash codex.provider, "openai" when none was set), not only OpenAI's:
- an id of magpie's length ("custom") is relabelled in place
  (RelabelCodexThreads), then packed ones from the last 30 days
  (MovePackedCodexThreads), as OpenAI's already were;
- any other id ("myrelay") can't be written in place, so the threads of
  the last 30 days, plain or packed, are rewritten with a copy kept in
  the trash, newest first, 128 MB a sync (new
  sessions.MoveRecentCodexThreads, sharing MovePackedCodexThreads' body
  with packedOnly off). Older ones are left for Sessions' Move/Resume.
#887's guarantee still holds where it matters. Threads of any other
provider stay put. OpenAI's stay when Codex was on another provider. No
threads move for a provider a profile names (the user picks it with -p),
for cc-switch-official (bringOfficial handles it), or for a distro's
Codex. The Disconnect puts the user's model_provider back and bringBack
returns the threads to it, and CC Switch switching back to that provider
does the same. If Codex leaves magpie for a different provider,
bringBack hands them to that one, as it already did with OpenAI's moved
threads. profileNamed moved up so bringOver can use it.
docs/subsystems/agent-wiring.md says so.

Tests:
- TestCodexThreadsFollowMagpieIn "on a provider of the user's before"
  used to assert that the custom thread stays. Now it moves to magpie in
  place, with no copy, and goes back to custom at Unwire, with
  model_provider custom restored.
- New subtest "on a relay's table of another length": myrelay's plain
  and packed threads move with a copy kept, a 40-day-old one stays,
  OpenAI's stays, and everything goes back at Unwire.
- New subtest "on a provider a profile names": the thread stays.
- New TestMoveRecentCodexThreads: newest first, a copy each, an old
  thread and another provider's stay, and the packed-only move still
  leaves a plain thread.

Run at this tree (on origin/main 823e7c250), on mote through mote-run:
- gofmt -l internal/agent internal/sessions: clean.
- GOOS=windows go vet, GOOS=linux go vet -tags nogui and go vet (darwin)
  of ./internal/agent ./internal/sessions: ok.
- go test -count=1 -timeout 45m ./internal/agent ./internal/sessions: ok
  (296s, 85s). An earlier run before the last tweak (plain file must be
  regular) was ok as well.

Broken by hand:
- bringOver back to OpenAI-only plus packedOnly forced: three of the four
  new assertions in TestCodexThreadsFollowMagpieIn and
  TestMoveRecentCodexThreads fail ("thread ...c3 on "custom", want
  "magpie"", "moved [only the packed one], want the plain then the packed
  one").
- the profileNamed guard dropped: "on a provider a profile names" fails.

Not tried: a real Codex 0.166 app or CLI resuming a moved relay thread
(this reasons from the codex-rs source for rust-v0.166.0, and earlier
commits record real 0.166 resuming moved threads); a real CC Switch
switch; the whole ./... suite (mote was at load ~75-100 with two other
sessions' full suites); a Windows or WSL run.
2026-11-04 22:52:05 +08:00
yetoneandMYCF711 cbb09383fb plugin: a GitHub-tagged package's card says its own name and summary (#3608, plugins#394)
MYCF711's #3608 (and plugins#394): a repository tagged magpie-plugin
outside the community's list showed its repository's name and GitHub's
description on its card under Discover → Unofficial, on GitHub, whatever
its package.json said of itself. Ported from MYCF711's 1cc337001.

Now readTagged keeps package.json's magpie.name (ownName, as main's row
already does since d8cf4f74f) and magpie.summary (ownSummary, by
language), and npm's copy's when the card installs from npm and it says
them. The card shows them in place of the repository's, with an "Its
own words" chip whose tip says nobody reviewed them; no community badge,
and they never resolve a name. GitHub's description stays the English
line for a package whose summary has none.

Changed from 1cc337001, reviewed line by line:
- ownSummary also refuses control and format characters (a bidi
  override, a zero width space) and bad UTF-8, as main's ownName does.
- magpie.summary is read as raw JSON: in 1cc337001 a summary that isn't
  an object of strings ("summary": "text") failed the whole package.json
  parse, and readTagged then left the repository out of the list.
- npm's copy's words win over the repository's when npm's is the one
  installed; 1cc337001 read them from npm only for the NPM type, which
  no card shows.
- Left out: the row chip and InstalledName/ownName on /api/plugins (main
  has them from d8cf4f74f), NPM.Name/Summary (no page reads them), and
  the core budget raise: the card's code is paid for by cutting three
  comments in plugins.js, 1,533,388 of 1,533,802.

Run (mote, at this tree on 538026e62):
- go test -count=1 ./internal/plugin ./internal/gui: internal/plugin ok
  (145s); internal/gui red only in TestMainWindowCorners/macOS_26_SDK,
  filed as #3949 (macOS 27)
- go vet ./internal/plugin ./internal/gui, GOOS=linux -tags nogui and
  GOOS=windows: clean; gofmt -l: nothing.
- node --test internal/gui/tests/plugin*.test.cjs,
  plugins-more-discover and i18n-keys, Chromium and WebKit: 1028 of
  1032; the 4 reds are plugin-move-unserved's "Try again takes the
  models unticked" (en, zh, both engines), filed as #4410 and #4392
- plugin-own-words.test.cjs: en, zh, zh-TW, ja, de at 980 and 420, both
  engines, 22 of 22; with main's plugins.js 0 of 22 ('magpie-officeace'
  for 'OfficeAce').
After the rebase on 823e7c250 (mote): TestCoreScriptBudget ok, go test
  -run 'OwnWords|Tagged' ./internal/plugin ok, plugin-own-words,
  i18n-keys and plugins-more-discover 32 of 32.
Broken by hand:
- npm's words not taken: TestReadTaggedOwnWords red (name "OfficeAce
  dev").
- summary read as map[string]string: TestReadTaggedOwnWords red (the
  package with "summary": "text" not kept).
- ownSummary without the character check: TestOwnWordsBounds red (two
  lines, tab, bidi override, zero width).
Not tried: a real repository with magpie.summary (none tagged has one);
the desktop window itself.

Co-authored-by: MYCF711 <323101370+MYCF711@users.noreply.github.com>
2026-11-04 22:47:11 +08:00
yetone 7b5e773873 provider: a model at a window (claude-opus-5-5@300k) is priced as its model, so Cursor's sized ids have a cost
RyuJeXu on X (tweet 2117971061103100279), building an iOS board on magpie's
usage data: "cursor的用量好像不计费呀". Cursor calls showed no cost.

Cause: the Cursor plugin lists each model once per context size
(claude-opus-5-5@300k, @1m, gpt-5.5@272k, ...), lists them all at cost 0
(no price, pluginPrice), and its reply echoes the asked id, so usage rows
carry the sized id. pricedNames only took a window off grok- ids, so every
other sized id fell through the maker catalogs with no price. The plain ids
(claude-opus-5-5) were priced at the maker's list price all along.

Fix: pricedNames also tries the id with an "@<digits>k|m" window taken off
(modelWindow), for every provider. The window names the context size, not
a different model; long-context tiers still follow the call's own prompt
tokens through Price.At. Dated ids (claude-opus-4-5@20251101) and ids with
anything else after the @ are left alone. The regexp runs only for an id
with an @, since every listed model is priced on each Providers poll.

Tests:
- internal/provider/cursor_price_test.go: a moved Cursor provider prices
  @300k, @1m, upper case, a maker-prefixed id and gpt-5.5@272k/@1m as the
  plain model, through ListPrice, MakerPrice, PricedName(For), and its
  tier at 300K prompt tokens; a dated id, "@272", "@", "@272kb", an
  unknown model and auto stay as they were.
- internal/usage/cursor_window_cost_test.go: a Cursor row for
  claude-opus-5-5@300k costs what the plain id does ($6 each), auto stays
  unpriced, the page total is $12.
- grok_price_test.go: gpt-6-astra@500k under grok is now priced ($10/$50);
  grok-4.7-build@500k still isn't.

Run (all through mote-run, go1.26.8, base 823e7c250, the committed tree):
- gofmt -l internal/provider internal/usage: clean.
- go test -tags nogui -count=1 -timeout 45m ./internal/provider
  ./internal/usage ./internal/usageapi: ok 239s / 75s / 1s.
- GOOS=windows go vet and GOOS=linux go vet -tags nogui of provider,
  usage, usageapi: ok.
- Real catalog (a copy of the owner's models.json) before the change: every
  non-Grok sized Cursor id was unpriced; plain ids priced.

Broken by hand: with the old models.go put back, the two new tests fail on
every sized id (usage total 6 instead of 12) and TestGrokEffortListPrice
fails on gpt-6-astra@500k.

Not tried / not changed:
- No real Cursor call; the owner's ledger copy has only auto rows.
- Cursor's own auto and composer-2.5, and its own spellings (glm-5p3,
  deepseek-v41-flash-1017) and gemini-3.1-pro have no catalog price and
  stay unpriced; the plugin would have to give them a cost.
- Not ./... and no GUI suite: the change is in provider's price lookup
  only.
2026-11-04 22:45:40 +08:00
yetone 127f1e77dc gateway: a turn to another magpie goes as its new input after the turn it kept
LotusDecoder on X runs two magpies, each the other's provider. Codex says
store false, so the leg between them carried the whole conversation
every turn. Now passthrough asks a remote magpie to keep the Responses
turn (X-Magpie-Keep-Turn: magpie/<version>). A magpie that does answers
X-Magpie-Kept-Turn. This side records per route and scope a digest of
each input item as sent, the reply's output types and ids, and the
other magpie's id (remoteTurns: 16 per route and scope, 32 MB, prevTTL).
The next request that continues exactly that input and reply goes as
the items after them with previous_response_id. Anything else goes
whole: an edited history, another answer, a magpie that never said it
keeps (an older one). A refused delta is sent again whole at once, and
the route goes whole for 30 minutes.

The receiving magpie honours the header only from a magpie's hop
(keepTurnAsks): its value starts magpie/ and the User-Agent is magpie's,
or Codex's, which forwardOnce passes on for Codex turns. It keeps the
turn under the caller's prevScope and the usual caps. An id such a
caller names that isn't held gets previous_response_not_found before
any vendor is asked. withCaller takes the header off on arrival, and
X-Magpie- is never a passable request header, so no vendor gets it.

Run on mote (mote-run) at base 93d5c76c0 with this tree:
- gofmt -l internal/gateway internal/provider: clean
- GOOS=linux go vet -tags nogui ./internal/gateway: ok
- GOOS=windows go vet ./internal/gateway: ok
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway:
  ok (1123.7s)
- The five new tests, plus TestRemoteMagpie*, TestPreviousResponse*,
  TestUnknownPreviousResponse and TestPrevStore: 54 passed.
- Again rebased on 538026e62, the same suite: one red,
  TestUnroutedEmptyEncodedStreamIsBounded/gzip ("TempDir RemoveAll
  cleanup: ... magpie/held: directory not empty"). It is #4775's test:
  the held report is written from the timer after the 408, so the test
  can end mid-write. Not this change; fixed in its own commit.
- At the pushed base 50aaa5726: gofmt clean, Linux and Windows vet ok,
  the related tests above (57 passes) ok.

Broken by hand, each red, then restored:
- delta never sent: SentTheNewInput, LostTurnSentWhole and the
  EditedHistory control go red.
- the header honoured from any client: KeepTurnOnlyFromAMagpie goes red
  (curl told kept).
- refusal not remembered: LostTurnSentWhole goes red (turn 3 is tried as
  a delta).
- deltas without the Kept-Turn reply: OlderRemoteMagpieSentWhole goes
  red.
- keptTurnLost check removed: KeepTurnOnlyFromAMagpie goes red (the lost
  id is relayed).
- output marks not compared: EditedHistory "other answer" goes red.
- the withCaller strip and the X-Magpie- never-pass prefix both removed:
  KeepTurnOnlyFromAMagpie goes red (vendor sent the header). Either one
  alone holds it, so removing only the strip stays green.

The new tests don't compile on the old code, since they name the new
header constants and remoteTurns.

Found on the way: a Codex turn reaches the remote magpie with Codex's
User-Agent, not magpie's, so callerFrom's existing X-Magpie-Agent/Via
reading never applies to Codex hops. Unchanged here; keepTurnAsks
accepts that shape.

Not tried:
- two real magpies over a real link, and a WebSocket-fed Codex (only
  HTTP turns in tests);
- an SSE reply over the hop (tee parses SSE through prevReply, which
  prev_response tests cover, but no remote-delta test streams);
- other platforms' test runs (Linux and Windows were vetted only).

Known gaps:
- the reply is matched by type and ids, so a client that edits the
  last answer's text (no ids) gets a delta over the kept one;
- tools and instructions are still sent every turn;
- the remote's kept turns are in memory only;
- a client that copies a hop's headers gets its store-false turns kept
  under its own scope and the caps.
2026-11-04 22:27:11 +08:00
538026e62b gateway: an error frame inside a 200 fails at the status it names (#4855)
mycf_711's wps-lingxi rows read status=200: the plugin's stream already
sent its 200, then wrote {"error":{"message":"灵犀上游返回 AIError:
AI服务异常(上游暂时不可用,可重试)(HTTP 503)",...}}. On main a frame
mid-reply was booked at 200 and rested 60s as "other" with the error
"OK: ...", and one as the first event failed at the 502 the words'
guess gives. Routing never saw the 503 (or AuditFailed's 502).

Now the status an error frame names is what it fails, rests and is
booked at:
- a numeric status or code member, 400-599 (skygunner's patch: held
  stream's errOf, errorReply, carriedStatus, and the sniffer's note on
  the try's header for a reply already streaming, kept from the client);
- else "(HTTP 503)" / "(HTTP 503)" in the words, 429 and 5xx only, as a
  quoted 4xx ("the image link answered (HTTP 404)") may not be the
  provider's;
- a mid-reply call is booked at that status in Routing and Usage.
A quoted string code ("429", "1113") is the vendor's own code, not a
status. Words magpie wrote itself (loop guard, empty reply, relooped)
and too-long words name nothing, whatever members they carry: a LAN
peer's loop guard frame carries 502 in its Gemini shape. Such a frame
also no longer rests the route mid-reply (main rested it 60s as
"other" at 200); the model looping is not the provider failing.

Left out of skygunner's patch: streamFailure giving magpie's own Chat
frames a code and status. A peer magpie would read its loop guard frame
as a named 502.

Run (mote, at a1f1810e9 + this change):
- go test -count=1 -run 'TestRelayStreamErrorFrame|TestNamedStatusOf|
  TestGeminiCompat|TestLoop|Stream|Late|Carried|ErrorReply|Rest'
  ./internal/gateway: first run red on TestNamedStatusOf (a quoted
  "429" read as a status through json.Number), fixed. At this commit
  (on 8a8079680; d02b8a000 under it since changes the GUI only), the same -run with
  |Refus|Fallback added: ok (222s); go vet ./internal/gateway on
  darwin, GOOS=linux and GOOS=windows: clean; gofmt -l: nothing.
- The new tests at a1f1810e9 without the change: every subtest of
  TestRelayStreamErrorFrameSaysItsStatus and
  TestRelayStreamErrorFrameNamesItsStatusInWords red except the 4xx
  quoted case (mid-reply rested at 200, first event booked at 502,
  the peer's loop guard rested).
Broken by hand:
- namedStatusOf without textStatus: first_event and TestNamedStatusOf
  red.
- magpieSaid returning false: the peer loop guard subtest and
  TestNamedStatusOf red.
Not tried: a real wps-lingxi account; the full suite (runs after the
push). AuditFailed (the plugin's "audit_blocked") is counted as the 502
it names, not as a refusal of the request's content; whether a content
refusal there should rest nobody was not checked.

Co-authored-by: vincent <vincent@users.noreply.github.com>
Co-authored-by: MYCF711 <323101370+MYCF711@users.noreply.github.com>
2026-11-04 22:17:49 +08:00
yetone 8a80796805 gateway: the native route passes any path of a keyed provider's own API on, at its host
axelburks (Discord #feedback) asked for /v1/magpie/native/<provider>/...
to reach the whole of a vendor's API, not only Ark's image and video
task paths. Now GET, POST, PUT, PATCH and DELETE of
/v1/magpie/native/<provider>/<path> go to the provider's host at /<path>
(not under the base's /v1 or /api/v3), with the query and body as they
came and the answer streamed back as it comes.

Guards:
- API-key providers only (nativeKeyed): no subscription, OAuth or plugin
  account, no remote magpie, no Vertex. 403 otherwise.
- The gateway's own guards as every route: lanGuard's Host check,
  corsGuard (foreign Origin, null, *.localhost without a key), a key
  beyond loopback, read-only keys refused (PUT/PATCH added to
  readOnlyRefused), and a key held to models/accounts/limits refused
  (nativeHeld, as before).
- nativeTarget refuses an empty path, "." / ".." segments (encoded too,
  across %2F), a backslash, a (encoded) leading slash, "://", a
  scheme-like first segment, and any URL whose host or scheme parsed back
  isn't the base's. 400, vendor not asked.
- The caller's Authorization, x-api-key, api-key, x-goog-api-key,
  Cookie, ?key=, Origin/Referer/Sec-*/X-Forwarded-*/Cf-*, hop and
  X-Magpie-* headers are dropped; Sign puts the provider's key in the
  way it takes one. Set-Cookie, Alt-Svc and HSTS don't come back.
- With masking on, a JSON body is masked (fails closed) and restored in
  the answer; a non-JSON body is a 415. Only a masked request's answer
  goes through restoring; every other answer streams in 32KB reads,
  never held whole.
- Each request is a Requests row and a usage record (Operation
  "native"), with tokens when a JSON or SSE answer reports them.
- Ark's short paths (nativeArkPath) keep their old code path, under the
  key's base, unchanged (nativeArk).

Docs: gateway-routing.md (table row, native route section),
reference.md (path table + paragraph), integrating.md, site
integrate.html en and zh.

Run (mote, darwin arm64, Go 1.26.8):
- go test -count=3 -run 'Native|ReadOnly' ./internal/gateway: ok
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., gofmt -l: clean
- Rebased on origin/main b61c71448 (851468ecb): gofmt -l, go vet
  (darwin, linux nogui, windows) of the touched packages, and go test
  -count=1 -timeout 45m ./internal/gateway ./internal/access: both ok.
- Rebased again on origin/main 34116ec01 (five commits, only the
  gateway-routing doc overlapping, merged clean), 5880a1412:
  gofmt -l, the three go vets of internal/gateway, and go test -run
  'Native|ReadOnly' ./internal/gateway: ok. The whole gateway package
  was not rerun there. The last rebase, over 11d9d0a3a (a routing GUI
  commit sharing no file with this one), was not run again.
- Before the rebase, the same packages at 083821dc9:
  access ok; gateway FAIL on TestSocketTurnBodiesFreed only ("1 of 12
  socket turn bodies still kept"), already filed as #5250 for the same
  symptom on a loaded mote; alone it passes 5 of 5 on this tree
  (-count=5), and the change doesn't touch the Responses socket.

Broken by hand, each red on its test:
- no "."/".." segment check: TestNativeAnyStaysOnTheHost (a/%2e%2e/b,
  ..%2Fx, a%2F..%2Fb reached the vendor)
- nativeKeyed always true: TestNativeAnyRefusals
- nativeHeld skipped: TestNativeAnyRefusals
- caller headers not dropped: TestNativeAnyForwardsAtTheHost
- ?key= passed on: TestNativeAnyForwardsAtTheHost
- route on POST/GET/DELETE only (the old registration):
  TestNativeAnyForwardsAtTheHost
- masking skipped: TestNativeAnyMasks
- no Flush: TestNativeAnyStreamsAsItComes (20s, nothing before the last
  byte)
- no sniffer: TestNativeAnyRecordsUsage
- no lanGuard: TestNativeAnyRefusesPagesWithoutAKey (rebound Host and
  another machine reached the vendor)

Not tried: a real call to Ark or any other vendor through the route;
everything here is against httptest vendors.
2026-11-04 22:05:21 +08:00
yetone 11d9d0a3a5 routing: each account one calm cell in Accounts and keys (danzi002 on Discord)
danzi002 (v0.1.2945): Accounts and keys "显示的好乱啊,没有之前一目了然".
70a98dd85 (v0.1.2929) made the cards compact for ferock4669 and iyou00,
but left each card 3-5 lines of uneven height (tally, latest answer, a
Try now on its own line) in 168px columns: names cut, the status
wrapped, red twice on every resting account and on healthy ones with
old failures, Try now links scattered. Rendered with 9 Codex, 1
WorkBuddy and 3 WorkBuddy AI accounts, zh at 1100/1440, parent
c4245c4c2 against main.

Kept the compact change (still short, long lists still fold) and made
each account one uniform cell instead of reverting:
- a dot for its state: green in use (the provider's not-resting account
  that answered last), amber resting, grey otherwise, red to act on;
- name, plan and a muted Try now on one line, then one line of what is
  left and when it renews, or when it is back, wrapped in full, never cut;
- how it fared (the tally) and when it was read ("as of") on hover;
- red only where the reader must act: sign in again, a restriction or
  verification, a key failing with nothing else to say. Those rows keep
  their tally in sight;
- columns min(240px, 40vw), the usage bar back in the flow (Chromium
  misplaced the absolute bar inside a multicol .rt-lead).
routing-account-windows and routing-wallet-lapse now find "as of" last
in the tooltip instead of on the line.

Run on mote (Chromium + WebKit, en/zh/zh-TW/ja/de, 1100/420 and the
files' own widths):
- new routing-acts-calm.test.cjs: green both engines, all 5 languages.
- every Routing file that renders .rt-act plus i18n-keys and
  panel-routing*: 679 tests, 610 pass; the reds besides mine were
  rest-try-now WebKit, rules-line, rule-drag/remove, row-swap, steady,
  steps-cap, story-shrinks, order-unknown and many-keys webkit zh, the
  same set as main f44fa2ef6 run alone (41 reds there), filed as #5035,
  #5088, #4585, #3593, #4082, #4628, #3789, #3799, #3412, #4629, #3954.
  After fixing my own reds, acts-calm, account-windows, wallet-lapse,
  many-keys, rules-line and key-windows: 135 pass, 1 red (rules-line
  webkit en 1100, #3593/#5035).
- At the pushed head (rebased on 34116ec01): acts-calm,
  account-windows, wallet-lapse and i18n-keys 70/70 pass, the Go size
  budgets pass.
- go test ./internal/gui/...: TestMainWindowCorners/macOS_26_SDK red
  only (#3949, AppKit on macOS 27); the size budgets pass.

Broken by hand, each red in routing-acts-calm (Chromium):
- the resting line red everywhere (.st.rest red): red outside ivy;
- the tally shown on calm rows: "main: its name and what it says";
- columns back to 168px: a one-line status fails;
- no rest class: expected 'rest'.

Not tried: dark mode by eye, the real app on WebKitGTK (Linux) and on
Windows, real accounts (the fixture is synthetic), and the 8-row fold
with more than 8 Codex accounts by eye.
2026-11-04 22:04:17 +08:00
yetone 34116ec012 gateway: Codex signed in to one account lists another account's models
bigfisheatsmall on X: Codex was kept signed in to ChatGPT account A, on
the Free plan. Account B (Team) was the only account on in magpie. dsh
listed B's models and Codex didn't. codexMerged added CodexListed(),
which leaves out every ChatGPT account's own models because it assumes
the backend lists them. But the backend list is fetched with Codex's own
sign-in (A, Free), so B's plan-only models were listed nowhere. Routing
already sent codex/<model> to B (codexAccounts).

- provider.CodexListedBeside(backend) lists an account's own model by
  magpie's id (codex/<slug>) when the sign-in's backend list lacks it.
  codexMerged uses it, and FitOwn keeps those entries.
- spawnChoices (spawn_agent's models) had the same gap. It now uses the
  same rule with the slugs in Codex's models cache.
- buildCodexListTag covers the accounts' own models, so another account
  gaining or losing one has Codex ask for the list again. Every Codex
  asks once after the update.
- TestSyncCatalogAgesCodexCache built its "current" tag by hand from
  CodexListed(). It now uses provider.CodexListTag(), the tag SyncCatalog
  compares against.

Tests (sandbox HOME, fake backend with per-plan lists):
TestCodexListHasAnotherAccountsModels covers the list, routing of
codex/gpt-6.1-sol to the Pro account, and spawn_agent's choices.
TestCodexListOneAccountNoneTwice checks that a single account gets no
codex/ duplicates.

Run on mote at this tree: go vet (darwin, windows, linux) on gateway,
provider and agent: ok. go test -count=1 on provider, agent and
codexcat: ok. go test -run 'Codex|Spawn' on gateway and gui: ok. Run at
the tree before the sync_test change and the buildCodexListTag tidy: the
full gateway package was ok (1224s). Agent was red only in
TestSyncCatalogAgesCodexCache, fixed above.

Broken by hand: on the old codexMerged, the new test fails with "Codex's
list lacks codex/gpt-6.1-sol: [gpt-6-luna gpt-5.6-terra gpt-5.6-luna]".
With only codex_spawn_models.go reverted, it fails with "spawn_agent's
models lack codex/gpt-6.1-sol".

Not tried: real accounts or a real Codex. Not a full go test ./... run.
Not tried: models the backend marks hidden. A Codex here for failover
alone (codexOwnOnly) is unchanged.
2026-11-04 22:00:42 +08:00
yetone 1b579ca4f8 router: Droid and omp get the hub's tools whole; find_tools' description names each server and its tools
tao5010 on Discord (11-04): with the MCP router on, omp, pi and droid
rarely called the servers behind it. Asked for a picture of a cat, the
model searched three times and stopped, and found magpie-image only when
told "我的mcp有啊".

Since v0.1.2950 an agent not in hubSearchesItself with more than 10 tools
is given only find_tools and call_tool. Droid (0.231) defers every MCP
tool to its own ToolSearch, showing the model names only, and omp (18.9)
mounts MCP tools in a catalog by each description's first line. Both were
handed two opaque tools whose description said only how to search, while
the servers were named in initialize's instructions, which Droid doesn't
show and omp shows apart from the tool. Read from droid's binary and
omp's dist/cli.js.

- hubSearchesItself gets droid and omp: they search their tools
  themselves, so they get every tool whole as Claude Code, Codex and Pi do.
- find_tools' description, for every agent still given tools on demand,
  starts with HubLine (each server and what it is for, <= 250 chars), then
  how to search, then hubDetails (each server's tools) within
  hubFindSayMax = 1200 characters.

Ran on mote at this head:
- gofmt -l internal/gateway (clean); go vet -tags nogui ./internal/gateway
  on darwin, GOOS=linux -tags nogui, GOOS=windows
- go test -tags nogui -count=1 -run 'Hub|MCP|FindTools' ./internal/gateway: ok
- repro (sandbox HOME, magpie serve on 127.0.0.1:3563/3564, a fake stdio
  server with generate_image/generate_video/generation_result and one with
  12 tools, router on): the old build (b61c71448) gave omp, droid and
  opencode find_tools + call_tool with the generic description; this
  build gives omp and droid the 15 tools, and opencode's find_tools
  description names magpie-image (Generate and edit images…) and
  generate_image.

Broken by hand: with the old hubSearchesItself and find_tools' old
description, TestHubMCPToolsWhole fails ("droid listed [find_tools
call_tool]") and TestHubFindToolsSaysWhatIsBehind fails on the first
line; both pass with the fix.

Not tried: a real omp, droid or pi turn against this build (none is on
mote with a model). Pi already had every tool whole; its MCP extension
shows a server by a 250-char description, so with many servers
magpie-image may still be cut there. Not checked: whether other agents
(kimi, gemini, opencode, qwen) search their tools themselves. find_tools'
scoring ranks generation_result above generate_image for "image
generation" (unchanged).
2026-11-04 21:57:48 +08:00
yetoneandMYCF711 a1f1810e93 gateway: a 400 that only says the request is too long counts as an overflow once it is past half the model's window (#4420, MYCF711)
A group member answered 400 "内容太长了,请精简输入或开启新对话" at ~730K
on a model it declares at 1M. cfcd6648f added that wording to tooLongRe,
the word list. This change adds the judgment MYCF711 proposed as fix A,
so the next vendor that says it differently isn't missed the same way:
the vendor's words decide, and the request's size rules out other meanings.

tooLongUnsaid lowers its margin from unsaidMargin (1.2 of the window) to
lengthMargin (0.5) when saysLength holds:
- a 400 or 422,
- whose message has length words (lengthWords: 太长, 过长, 超长, 精简,
  缩短, 删减, 开启新对话/会话, too long/large/big, shorten, reduce the
  length/size, start a new conversation),
- no pace word (paceWords),
- and names no part of the request (partWords: a picture, a file, the
  reply, a field, a name, max_tokens),
- and tooLongUnsaid's own checks still hold: no quota, credit, model
  unserved, refusal or region words.
Its message is then "prompt is too long…". The overflow branch already
reads that as an overflow: the next member with room is asked
(failOverflow), nobody rests, and the conversation remembers the refusal.
With no member left, the agent is told the prompt is too long and
compacts. When the request is under the declared window, the message
no longer says "more than its context window". It says "more than <model>
takes here, though its context window is N".

Fix B, the word list in tooLongRe and paceWords, already landed in
cfcd6648f, with more wordings than the four proposed. Nothing was added
to it here.

Tests:
- TestLengthWordsPastHalfTheWindowGoToTheNextMember (new): for
  "请求过长,请精简后开启新对话" (raw and \u-escaped) and "Request too
  large. Please shorten it…", none of them in tooLongRe, a request of
  ~1500 tokens to a member of window 2000 goes to the next member: failOverflow,
  no rest. A short request keeps the vendor's 400 for the agent. A pace
  ("请求过长,已达到速率限制"), a file ("文件过长…") and "Image too
  large" aren't taken as the request's length.
- docs/subsystems/gateway-routing.md says it.

Run (mote, via mote-run, at this tree rebased on origin/main 7818dc316):
- go test ./internal/gateway -count=1 -run 'TestLengthWordsPastHalf|
  TestChineseInput|TestChineseNotTooLong|TestRelayInputCap|
  TestEveryVendorsOverflow|TestMemberTooSmall|Unsaid|TooLong|
  PayloadTooLarge|Roomy|Overflow': ok
- go vet ./internal/gateway, GOOS=linux -tags nogui, GOOS=windows: clean;
  gofmt -l clean. The full suite runs after the push, see the issue.

Broken by hand:
- lengthMargin replaced by unsaidMargin: the new test fails, (a 1, b 0),
  and the agent gets the 400.
- partWords dropped from saysLength: the new test fails, "文件过长,请精简后重试"
  taken for an overflow.

Not tried: the reporter's real vendor. The 0.5 floor comes from the
reporter's two cases, both refused past half of a 1M window. It is not a
measurement of other vendors.

Co-authored-by: MYCF711 <323101370+MYCF711@users.noreply.github.com>
2026-11-04 21:52:48 +08:00
yetone 7818dc316a gateway: a relay's Cloudflare 520 to 524 is asked again before the agent sees it, as a 502 or 503 is (vdaoren)
vdaoren on Discord: an API-key provider's 4xx/5xx now and then went
straight to the agent; they asked for retries on chosen status codes.

What a single API-key provider already did: the last one left is asked
again after a failure that passes (passing, fallback.go): 408, 500, 502,
503, 504 and 529 twice (lastRetries), a 429 that is a short rate limit
three times (rateRetries), pauses 1s, 2s, 4s or a Retry-After up to 8s,
then within the provider's patience (singlePatience, 60s by default,
`magpie provider set <id> patience=`) in rounds (busy, patience.go), all
while the reply is held and nothing has gone to the agent. A plan used
up, no balance, a 401, a request the vendor refuses for its content and a
conversation too long are the agent's at once.

What was missing: Cloudflare's own 520 (unknown error), 521 (origin
down), 522 (connection timed out), 523 (origin unreachable) and 524
(timeout), which a relay behind Cloudflare gives now and then, were in
neither list. Such a 5xx moved on to another member in a group, but on a
lone provider it reached the agent after one try. busyStatus now holds
the one list passing and busy read, with 520 to 524 added. No setting:
the default serves it, and patience= already exists for the length.

TestCloudflareErrorIsTriedAgain (retry_test.go): each of 520 to 524, as
Cloudflare words it to an API client ("error code: 520") and as its HTML
page, twice and then 200, is answered 200 after 3 tries; a stream's 524
then an SSE reply reaches the agent with nothing of the 524 in it; a 401
invalid key and a 400 content_policy_violation are tried once.
Broken by hand (busyStatus's list back to 408..529): red, every 52x case
"520 after 1 tries" and the stream "524 after 1 tries"; the 401/400 cases
pass either way.

Run on mote at this tree (base origin/main b61c71448):
- go test -tags nogui -count=1 -run 'TestCloudflareErrorIsTriedAgain|
  TestLastOneLeftIsTriedAgain|TestRateLimitIsWaitedOut|Patience|Overload|
  Busy' ./internal/gateway/: ok
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: ok (DARWIN-VET-OK, LINUX-VET-OK, WINDOWS-VET-OK)
- gofmt -l internal/gateway: nothing
- go test -tags nogui -timeout 45m ./...: not run before this push;
  two other sessions' full suites held mote, one suite per machine. It
  runs after the push, as agent-rules says, and a red is filed as an
  issue with its output.

Not tried: a real relay behind Cloudflare answering 52x (none at hand);
Windows/Linux runs of the tests (the change has no OS-specific code).
Docs: gateway-routing.md's busy list names busyStatus and 520 to 524.
2026-11-04 21:49:51 +08:00
yetone b61c71448c keys: a custom provider's key can be made for its Gemini API (corddis_114)
corddis_114 on Discord has a relay that gives out a key per protocol,
one of them for Gemini ("gemini sk-d…SarG"), and the key row's protocol
menu offered Any, Anthropic, Chat Completions and Responses only. A
custom provider already serves Gemini upstream (its Gemini URL, the
"Gemini compatible" tab, x-goog-api-key, the model list through
FetchGemini, probes), so only the per-key layer lacked it:

- keyProtocolOK takes "gemini"; WithKey leaves a Gemini key the Gemini
  URL only and takes the Gemini URL from a key made for another
  protocol (it had kept it, so an Anthropic key could be sent to
  generateContent).
- keyFit: a gemini* model (modelFamily Gemini) goes to the key made for
  Gemini first, the other keys in their order behind it; a GPT model is
  never put on the Gemini key (it ranked 0 there before). Claude's rule
  is unchanged.
- app.js: Gemini in PROTO_OPTS ("Gemini API (generateContent) · Gemini
  CLI, Gemini models"), offered when the provider has a Gemini URL;
  keyLacksURL says "No Gemini URL" for a Gemini key without one. The
  note in zh, zh-TW, ja and de. The provider-level tabs and Routing's
  "keys for Gemini" already had it.

Run on mote (go1.26.8):
- go test -timeout 45m ./internal/provider ./internal/gateway: both ok (provider 229s, gateway 938s).
- TestKeyMadeForGemini, TestKeyProtocolGemini, TestKeysMadeForOneProtocol,
  TestKeyForAProtocolWithNoURLIsSaid, TestKeyPoolsByProtocol,
  TestCustomGeminiUpstream ok; internal/gui's budget tests ok.
- GUI (node --test, Chromium and WebKit, en/zh/zh-TW/ja/de, 420 and
  1000px): key-gemini (new, 40/40), key-nourl, proto-menu-overflow,
  key-row-chips-fit, key-plan, key-import, key-weight-fit,
  provider-many-keys, provider-gemini, provider-add-gemini,
  provider-url-each-api, model-api-gemini, provider-base-api,
  routing-keys-fold and i18n-keys ok; the only red in the 360 was
  tencent-cloud's region-strip test (#4321, open).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on provider, gateway, gui ok.

Broken by hand: the old fallback.go turns TestKeyMadeForGemini red
(Gemini models went to the Chat or Anthropic key, GPT to the Gemini
one); the old keys.go turns TestKeyProtocolGemini red (unknown
protocol "gemini"), and WithKey keeping p.Gemini turns it red too (the
Anthropic key speaks [anthropic gemini]); the old app.js turns
key-gemini red in all 40.

Not tried: the reporter's relay or any real Gemini-compatible relay;
the real app's editor.
2026-11-04 21:21:32 +08:00
yetone 4062cda781 provider: a custom provider at a Token Plan's or Ark's address is asked for no access key (ysm119)
ysm119 on Discord saved a custom provider (no preset) at
https://tokenhub.tencentmaas.com/plan/v3 with a plain sk- key on the
OpenAI-compatible tab, and its editor asked for a SecretId and
SecretKey. AccessKeyVendor decides by host alone, so any provider at a
Token Plan's /plan address (or an Ark plan's) got the access-key fields,
and a Singapore Token Plan or Ark one also got a Usage card asking for
them.

Now AsksAccessKey(p) gates the two places a user is asked: the editor's
listing (gui/providers.go) and the keyless Usage cards
(tencentPlanQuotas, volcPlanQuotas). A preset's provider is asked as
before; a custom one only once it has an access key saved (so a key the
user did give is still shown and still used for its usage). The host
rules themselves are unchanged, since presetAccessKey and the presets
read them on providers with no preset of their own.

The key itself was already sent as typed: no Tencent signing exists on
chat, Responses, the model list or a probe; the access key only reads
plan usage. TestCustomTokenHubIsSentAsTyped holds that (Authorization:
Bearer <key>, on Chat and Responses).

Run on mote (go1.26.8):
- go test ./internal/provider ./internal/gui: provider ok; gui red only
  in TestMainWindowCorners (AppKit, #3949, macOS 27 on mote).
- TestPlanCardWithoutAccessKey, TestCustomTokenHubIsSentAsTyped,
  TestProviderListTellsTencentAccessKey ok.
- GUI (node --test, Chromium and WebKit, 5 languages): tencent-access-key,
  tencent-cloud, volc-access-key, usage-access-key-card, i18n-keys and
  the provider editor's key files ok, except tencent-cloud's "a region
  clicked right after the strip scrolled" (#4321, open, same on main).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on provider, gateway, gui ok.

Broken by hand: AsksAccessKey returning AccessKeyVendor(p) always turns
TestPlanCardWithoutAccessKey (my-ark gets a card),
TestCustomTokenHubIsSentAsTyped and TestProviderListTellsTencentAccessKey
(my-tokenhub, my-intl, my-ark asked) red.

Not tried: the reporter's real tokenhub key; the real app's editor.
2026-11-04 21:21:32 +08:00