Commit Graph
2027 Commits
Author SHA1 Message Date
yetone 0f8c3d8672 claude: a deferred built-in the bridge's model calls reaches the client as WebFetch, not mcp__magpie__WebFetch
Claude Code with tool search on leaves WebFetch, WebSearch, CronCreate and
the other deferred built-ins out of tools until a ToolSearch loads them.
The run's model, offered the client's tools as mcp__magpie__<name>, called
mcp__magpie__WebFetch, and toolStart handed that over whole: the 11-02
fix for an unloaded magpie MCP tool (packinggoods) kept the full name for
every cut name the client hadn't declared. The client answered "No such
tool available: mcp__magpie__WebFetch", the model retried, and
status lines such as claude-hud showed a "magpie" MCP failure.

toolStart now keeps the prefix only when the cut name has the router's
form, <server>__<tool> (magpieServerTool): the client names magpie's MCP
tools mcp__magpie__<server>__<tool>, and its built-ins (WebFetch,
WebSearch, CronCreate, CronDelete, CronList, NotebookEdit, Monitor,
TaskStop, SendMessage, EnterWorktree, ExitWorktree: the deferred list of
a real Claude Code session) have no __ and no prefix. A sibling the same
line got wrong: another MCP server's deferred tool, called as
mcp__magpie__mcp__linear__get_issue, is handed over as
mcp__linear__get_issue, the client's name (it was handed over whole too).
toolStart is the one place a called name is mapped back for the client:
streamed and whole messages and the interactive mode's early call
(r.onCall) all go through it; mcpCall's declaredName serves offered
tools only, and the history's names (bridgeName) are unchanged.

Run (on mote, at this tree):
- go test ./internal/gateway -count=1 -timeout 45m: ok
- gofmt -l: nothing; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok; go build: ok
Broken by hand: magpieServerTool returning true (the old behaviour)
turns TestClaudeBridgeHandsOverAnUnloadedMagpieTool red on the new
WebFetch and mcp__linear__ cases ("handed a call of
mcp__magpie__WebFetch, want WebFetch").
Not tried: a real Claude Code client with tool search on (the reporter's
Windows setup); a deferred tool the run's model calls by the bare client
name (WebFetch) is still the run's Claude Code's to answer and isn't
handed over. A client MCP server of its own named "magpie" with a tool
lacking __ would now be cut; magpie's router names every tool
<server>__<tool>.
Rebased on eadc6cdb9 (GUI routing files only); at the pushed head
go test ./internal/gateway -run 'TestClaudeBridge|TestClaudeToolChoice|
BridgeToolName': ok.
Full suite: not run at push.

Reported-by: steven_4422 (Discord)
2026-11-08 16:05:42 +08:00
yetone 1aabc66fd1 gateway: /v1/models answers its ETag, and 304 to a client that has the list already
clyzhicore (Discord) runs a server magpie as the gateway and a local magpie
that takes its /v1/models and writes the models into dsh. They asked for
an ETag or a list you can wait on, so the local side knows a change at
once and a dead connection costs little. The wait is there since
06c4582cc (v0.1.3172: X-Magpie-List-Wait with If-None-Match, and the
Remote magpie follower). What was missing, and is added here:

- A plain GET /v1/models (no wait header) is answered with the same ETag
  a wait answers (listTag of the bytes this caller gets), Cache-Control
  private, no-cache, and 304 with no body, at once, when If-None-Match
  names it (strong or W/, in a comma list, or *). A tag it doesn't name,
  or none, is answered the list as before, same bytes. A refused list
  (400) stays untagged. Any client (a script, curl, another tool) can
  now poll cheaply.
- A wait's answer, 200 or 304, says in X-Magpie-List-Wait how many
  seconds it held. A plain answer doesn't.
- The follower (waitRemoteList) takes a 304 that comes sooner than
  followQuick (5s) without that header as a magpie that doesn't wait.
  This guards the change above: a proxy that drops X-Magpie-List-Wait
  would now get a tagged plain list and an instant 304, and the follower
  would ask every followGap (1s). It now leaves such a magpie to its
  schedule and asks again after followOldAgain (1h), as for one from
  before the wait. Servers from 06c4582cc on hold each wait to its end
  (50s), so their 304s pass.

Compatibility: an old server (no ETag) is still left to the schedule,
as TestRemoteMagpieOldListNotFollowed checks. An old client never sends
If-None-Match without the wait header and gets the same bytes plus an
ETag. The GUI doesn't read the gateway's /v1/models through Wails (whose
304 on WebView2 is a 505, gui/api.go writeJSONSame), so that doesn't
apply.

Hidden models (their second ask) already exist and are not changed: a
provider's "Only through routing groups" (Provider.Unlisted, `magpie
provider listed <id> no`) and a group's listed=no (Group.Unlists, `magpie
group set ... listed=no`, CLI only) keep models out of /v1/models while
groups still route to them.

docs/subsystems/gateway-routing.md says the above.

Run (on mote, through mote-run, first at 04ed05733):
- gofmt -l on the changed packages: clean.
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet
  ./...; go build ., GOOS=linux -tags nogui, GOOS=windows: all ok.
- go test -tags nogui -race -count=1 -timeout 90m ./internal/gateway:
  ok 2145s, no DATA RACE (mote at load ~100-130).
- go test -tags nogui -count=1 -timeout 45m ./internal/provider: ok 126s.
- After rebasing onto origin/main (5 commits, none in these files):
  gofmt -l clean; go vet (darwin, linux nogui, windows) of both
  packages ok; -race -run "ModelsWait|ModelsList|RemoteMagpie": gateway
  ok 12.5s, provider ok 4.8s.

Broken by hand, each red:
- models() back to listModels (no tag on the plain list):
  TestModelsListConditional ("ETag \"\"") and TestModelsWaitTagged ("a
  plain list: 200, ETag \"\"").
- tagNamed never matching: TestModelsListConditional (200 with the body
  for each of the tag, W/, a list and *).
- No X-Magpie-List-Wait on a wait's answers: TestModelsWaitTagged ("a
  wait's list says it held \"\"", same for its 304).
- The followQuick check off: TestRemoteMagpieStrippedWaitNotAskedOver
  ("asked 28 times in 300ms, want 2").

Not tried: two real magpies, or a real reverse proxy that drops the
header (the stripped case is a fake in the test). Not run on Windows or
Linux. The full suite (go test ./...) and the GUI suite: not run at push.
Following a provider added as a plain OpenAI-compatible endpoint (not the
Remote magpie type) is not done: its list URL comes from fetchOne's
several bases, and it still goes by its #2135 schedule.

Reported-by: clyzhicore (Discord)
2026-11-08 15:45:57 +08:00
yetone 37df73b1bb balance: a key holds several credits that expire, each added and removed on its own
tenacious_eagle_96548 (Discord, 11-08) has two promotional credits on one
key, one ending tomorrow and one the day after. v0.1.3305 kept one grant
per key, and its form showed the date only after Enter or a blur, with no
button to confirm.

- OwnBalance.Expiring is now a list (`expirings`, up to 20). Spending
  goes to the grant that ends soonest first (ties by when it was typed),
  and each grant drops out at its day. A write prunes ended grants.
- The pill and the menu say "Expires in N days" per grant, amber from 7
  days. The menu has a Remove item per grant, "Add credit that
  expires…" and "No credit that expires" to clear them all.
- The form shows the amount and the last day together, the day filled in
  30 days ahead, with an Add button; Enter adds, Escape cancels, a bad
  amount or a past day is refused in place. The app's own menu, no
  native select, no stripes. A pill with two or more grants wraps at a
  grant on a narrow row (a class, not :has(), for Safari before 15.4).
- CLI: `--expiring amount@day` can be given several times, `--expiring
  off` clears all, `--expiring-remove [amount@]day` removes one. --help
  prints usage; a day that isn't a date, or is past, is refused.
- /api/provider/keyexpiring adds `{expiring:{amount,until}}`, removes
  `{expiring:{at,until},remove:true}`, clears `{expiring:null}`.

Old data: a v0.1.3305 single `expiring` grant is read as the first grant
and saved as `expirings` on the next write, for every user. An older
magpie reading the new file sees no grants (the balance itself stays).

Run on mote at 1d5b5dc2d plus this change:
- go test -run 'Budget|Balance|Expir|KeyOwn' ./internal/gui
  ./internal/provider ./internal/cli: ok (TestCoreScriptBudget passes,
  not raised). gofmt -l clean. GOOS=linux go vet -tags nogui and
  GOOS=windows go vet on provider, cli, gui: ok.
- GUI (Chromium + WebKit, 900/400px, en zh zh-TW ja de):
  key-balance-expiring, key-own-balance, key-balance-card,
  key-row-steady, key-row-chips-fit, account-rows-fit, old-webkit,
  i18n-en-no-cjk, balance-parts, balance-quota-left: 203/203. A broader
  run (key-*, balance-*, i18n-keys, panel-balance-order) had reds that
  are red on origin/main 04ed05733 too: i18n-keys "a plugin's words are
  its own" (#5332, #5482, #5426) and key-replace WebKit 420px (#4126).
- Real app on mote, sandbox HOME, `serve --web`: the CLI set ¥40 plus
  ¥5 to tomorrow and ¥8 to the day after and printed about ¥53.00 left;
  providers.json has `expirings`. --help, `5@yesterday` and removing a
  credit the key doesn't have each answered as above. In Chromium (en)
  and WebKit (zh) at 900 and 400px: the pill, the menu, the form (day
  2026-12-07), Add ¥3 by Enter, then Remove ¥3 from the menu, each
  checked by text and screenshot.

After a rebase on 437580535, on mote: the same go test
-run (TestCoreScriptBudget included): ok; key-balance-expiring,
old-webkit, key-own-balance: 46/46. Rebased again on 8f6298fb5 (Go
only, no asset changed): the go test -run plus Signin: ok.

Broken by hand, each went red: sorting grants by when typed
(TestTypedBalanceGrantsSoonestFirst); no migration in UnmarshalJSON
(TestTypedBalanceOneGrantMigrated); no Enter handler (GUI en 900); no
wrap rule (GUI en 400, row past the window's edge); Remove sending the
first grant (GUI, at/until mismatch).

Not tried: Full suite: not run at push. No real vendor account (the
grants are typed by the user). The Linux and Windows desktop apps.

Reported-by: tenacious_eagle_96548 (Discord)
2026-11-08 15:27:14 +08:00
yetone 8f6298fb5e providers: a notification when an account in use has to be signed in again, and before a Claude sign-in ends
steven_4422 asked on Discord whether magpie warns when a Claude Code
login is close to expiring or has expired. It didn't, outside the app:
a sign-in that Anthropic, OpenAI, GitHub or a plugin's vendor refused
showed only on the account's row (Sign-in required, Sign in again) and
on the provider row's Signed out pill, and nothing warned before a
Claude sign-in ended. The system notifications covered only usage,
balance, reset, masking and task-done alerts.

What Claude's tokens carry (read from Claude Code 2.1.316): the access
token refreshes itself, but claudeAiOauth.refreshTokenExpiresAt ends the
sign-in. Claude Code sets it from refresh_token_expires_in, or to 30 days
from the sign-in, keeps it over a refresh that sends none, says "Your
login expires in N days · run /login to renew" from 3 days before, and
treats a sign-in past it as none. It skips the warning when the access
token outlasts that end by more than the 3 days.

- provider.WatchSignIns looks a minute after start and then every two
  minutes. It reads only magpie's own files and asks no vendor. It
  covers every account in use of every subscription that is on.
- An account is told of when its row says Sign in again, by the
  Providers page's own test (needsSignIn mirrors renderAccounts): any
  mark on a Claude, Copilot or plugin account, and on another built-in
  (Codex revoked, a refresh that failed, ChatGPT API) a mark that
  signInGone matches.
- A Claude account is also told of 3 days before refreshTokenExpiresAt,
  by Claude Code's rule (claudeSignInEnds).
- Each alert goes out once: a lapse until the account is usable again,
  an end until it moves. The marks are kept in signin-alerts.json, so a
  restart doesn't repeat them, and an unreadable file tells nothing.
- The GUI sends the alert as "<Name> · <user>" with "Signed out — click
  to sign in again" or "Sign-in ends in N days — click to sign in
  again", in en, zh, zh-TW, ja and de. A click opens that provider's
  editor (?view=providers&edit=<id>), where the account's Sign in again
  is. A Linux dismissal still opens nothing (#2513).

Run on mote in a sandbox HOME, on this change over 04ed05733. It was rebased
onto 437580535 after the run, which changes only a gateway test:
- gofmt -l: clean.
- go vet ./...: ok.
- GOOS=linux go vet -tags nogui ./...: ok.
- GOOS=windows go vet ./...: ok.
- go build .: ok.
- go test -count=1 -timeout 45m ./internal/provider ./internal/gui:
  ok internal/provider 163.7s, ok internal/gui 162.2s.

Broken by hand, each red and then restored:
- Gone left false, which is the old code where nothing was told:
  TestSignInAlertClaudeSignedOut is red ("alerts …: []").
- The refreshTokenExpiresAt read turned off:
  TestSignInAlertClaudeEnding is red.
- The once-only mark dropped: TestSignInAlertClaudeSignedOut and
  TestDueSignIns are red ("told again").
- A click on a sign-in alert opening Usage:
  TestSignInAlertOpensItsProvider is red on darwin, windows and linux.

Not tried:
- A real notification on any OS.
- A real Claude account near its refreshTokenExpiresAt.
- A real revoked Codex, Copilot or plugin sign-in end to end.
- The GUI page is unchanged, so no Playwright run.
- Full suite: not run at push.

Reported-by: steven_4422 (Discord)
2026-11-08 15:19:03 +08:00
yetone c736906b17 providers: part of a key's typed balance may expire on a day
tenacious_eagle_96548 (Discord, #general): some vendors split a balance
into money that stays and credit good until a date. A key's balance typed
by hand can now carry that part (`expiring`: {amount, until, at}, in the
balance's currency, until = the last day it counts).

- Spending order: the expiring part is spent first, as DeepSeek spends
  its granted balance before money topped up. It takes the spend from its
  `at` up to its end (midnight after `until`, local time) or now; only
  what it took after `From` comes off the rest, so a refill or typing the
  balance again doesn't count it twice.
- Left is the whole balance. From its end the remainder counts no more,
  and unspent credit is gone.
- Typing the balance again keeps the part in the same currency and drops
  it in the other, where its amount would mean another sum.
- A balance saved before has no part and reads exactly as it did
  (TestTypedBalanceSavedBeforeExpiring).
- Set from the pill's menu: "Credit that expires…" asks the amount, then
  the last day (a day gone by, or the other currency's sign, refused);
  "No credit that expires" takes it off. GUI route provider/keyexpiring;
  CLI `magpie provider key-balance <id> <key> --expiring amount@yyyy-mm-dd|off`.
- Shown: the pill "≈$100.00 left · $30.00 expires in 30 days", the Usage
  page and panel line "Expires in 30 days ≈$30.00", amber from 7 days;
  TUI and `magpie quota` "($30.00 until Dec 7)". New strings in zh,
  zh-TW, ja and de.

Run (mote):
- go test of internal/provider, internal/gui, internal/cli (with
  TestCoreScriptBudget: the days' lines in app.js are paid for by five
  balance comments cut there, no raise; core 1,533,559 of 1,533,802); the new tests
  again with TZ=UTC and TZ=Pacific/Kiritimati (every clock held);
  gofmt -l clean; GOOS=linux and GOOS=windows go vet of those packages.
- GUI: key-balance-expiring.test.cjs 20/20 (chromium and webkit, 400px,
  en/zh/zh-TW/ja/de), with every balance-*, key-*, i18n-* file: 768
  pass, 6 red, each red the same alone on origin/main 691a10446:
  i18n-keys "a plugin's words are its own" (#5327) and key-replace's
  five webkit 420px cases (#4126, numbers added there).
- A real sandbox (own HOME, -tags nogui binary, ports 3591/3592): set
  $70 + $30 until +30d and ¥40 + ¥5 for +3d through the CLI, then
  through the pill's menu in the real page (¥8 for +6d, then removed);
  a past date shows the part no longer counting; retyping in USD dropped
  the CNY part; `magpie quota` shows the split. No page errors.

Broken by hand, each red:
- Go (TestTypedBalanceExpires): part not spent first; end taken in UTC
  (red under Kiritimati); part kept after its end; part kept across a
  currency change.
- GUI (key-balance-expiring): no soon class; soon only from 2 days; a
  past day accepted; the other currency's sign accepted.

Not tried: a real vendor's spend priced against the part; the GUI on
Windows or Linux. The full Go and GUI suites were queued on mote's
suite lock behind other sessions' and had not run when this was pushed.

Reported-by: tenacious_eagle_96548
2026-11-08 13:39:32 +08:00
yetone 5a27348058 providers: a key's balance picks its currency beside the field, the number kept
Changing a key's balance from $ to ¥ meant clearing the balance, switching
Settings' currency, then typing it again (a bare number kept the old
balance's currency). The balance field now has a currency button beside it
(USD/CNY, the app's menu, not a native select). It starts at the balance's
own currency, else Settings' one, which stays the default for new
balances. Picking keeps the typed number and posts nothing; Enter or
leaving the field saves, and the pill then reads ≈¥40.00 left. A typed ¥
or $ flips the button as you type. Nothing is reinterpreted: Settings'
currency still never touches a saved balance, and usage and cost displays
are unchanged. No server or API change; keybalance.js is lazy-loaded, so
app.js and the core budget are untouched.

Run (mote):
- key-own-balance.test.cjs: 20 of 20 ok (chromium + webkit, narrow width,
  every language), with new cases: $40 → CNY picked → Enter posts
  {balance:40,currency:"cny"}; ¥100 → Escape posts nothing; → USD, Tab
  away posts {balance:100}; no row runs past the window.
- Whole GUI suite (earlier run at this change): every file ok except
  i18n-keys "a plugin's words are its own", red on main already and filed
  (#5327, #5332, #5426, #5482).
- Real GUI, sandbox HOME on mote (go build -tags nogui, ports 3591/3592):
  typed 40 → ≈$40.00 left; Enter balance…, picked CNY, field kept 40,
  Enter → ≈¥40.00 left, no page errors; `magpie provider key-balance`
  read ¥40.00 typed. Screenshots taken.

Broken by hand: the old keybalance.js against the new test times out
waiting for the currency button; dropping the blur guard (saving when
focus moves to the button) makes the menu pick time out because the field
saved and redrew under it (chromium and webkit). Both red, restored.

Not run to the end: the full Go and GUI suites are queued under
suite.lock on mote behind ~20 other sessions' suites (~/runs/bc-suite);
no Go file changed. Not tried: the real desktop window, WebKitGTK on
Linux, Windows.

Reported-by: tenacious_eagle_96548
2026-11-08 12:54:13 +08:00
yetone eef99e4bbe redact: a value on both Masked words and Never mask is masked; Never mask still beats the user's rules
TakaNaShi_ShiKi on X asked for a way to keep a value from being masked.
That exists already: Settings › Privacy › When a value is found ›
Never mask (RedactAllow, Options.Allow, since b00c82acf), and a click
on a masked value in a request's masking record adds it there
(/api/masking/allow). It is applied in apply() to every span, whichever
finder found it: magpie's rules, the user's rules, the local model and
known values. Nothing new is wired for it here.

What was undecided was the order between it and the user's own lists.
apply() let a Never mask value go even when the same value was one of
the user's Masked words, and an allowed value hid a masked word inside
it (Masked word "kelvarn", Never mask "team.inbox@kelvarn.io": the
word went out). The value menu already refuses Never mask on a Masked
word ("One of your Masked words"), but the settings list doesn't.

Decided: of two things the user asked for, the one that keeps a value
from the vendor wins. A Masked word is masked even when Never mask
lists it, and a Masked word inside a value Never mask lets go is
masked. Never mask still wins over every finder, the user's own rules
included: a value named there is the exception to the user's pattern
(rule PROJ-\d{4}, Never mask PROJ-0001: PROJ-0001 goes as written,
PROJ-0002 is masked). Matching is unchanged: a whole value, any case.
A user with a value on both lists before this sees it masked from the
next request on.

Test: TestMaskedWordsWinOverAllow (new). Broken by hand (apply()
restored): FAIL "a value on both lists went as written: \"deploy on
build-01, mail team.inbox@kelvarn.io, …\"" and "a masked word inside an
allowed value". Restored: ok. TestAllowLetsAValueGo still passes.

Run (mote-run, at eb7ce732a): gofmt -l internal/redact (empty), go vet
./internal/redact/, go test -count=1 ./internal/redact/... ok.
Not tried: a running magpie; no GUI change, so no GUI run in this
commit.

docs/subsystems/gateway-routing.md says the order beside Never mask.
2026-11-08 11:49:18 +08:00
yetone 2d90c7c565 redact: a hex number (0x and up to 16 hex digits) goes as written, whatever the local model takes it for
TakaNaShi_ShiKi on X: in reverse-engineering notes, an address written
as inline code, `0x004EA5E0`, went to the vendor as {{SECRET_6kkmmxxd}},
and the vendor's model lost the data it was asked about.

Which finder took it: no rule. With Secrets and Personal on and every
kind on, the rules alone mask none of the values in the new test (the
"by the rules" checks in TestHexNumberGoesAsWritten). The local model
did. Asked for real (Privacy Filter and AstrLink Guard from this Mac's
cache, copied to mote, MAGPIE_EVAL_CACHE), on a notes table:
  Privacy Filter: secret 0.679 on 0x0058C210 (beside "密钥表")
  AstrLink Guard: secret 0.625 on the same
  Privacy Filter, "The license check is at `0x004EA5E0`; the key table
  at `0x0058C210`.": account_number 1.000 and 0.995 on both
  Privacy Filter, "key: 0x004EA5E0": secret 0.992
modelFits let them through: hexRe, which holds back a bare hex run
unless a key's name is right before it, asks lower case and no 0x, and
numberLike reads 0x004EA5E0 as a number, so ACCOUNT took it too. That
is the sibling, with the real model's evidence; PHONE did not take one
in the fake-model test, and decimal numbers already have their own
checks (numberNamedSecret), so nothing wider is changed.

Now modelTakes takes no value of any kind that is 0x or 0X and 1 to
16 hex digits (hexLiteral, a 64-bit value: an address, a constant, a
flag). No cue is asked, unlike a bare hex run: the function at an
address is often named for a key (DecryptKey: 0x004EA5E0), and
secretCued would read that as "key:". A longer 0x value (a 64-digit
private key, a 128-bit 0x+32) is masked as before.

Tests:
- TestHexNumberGoesAsWritten (new): the reporter-shaped table row, a
  cued address, 0X upper case, 0xFFFFFFFFFFFFFFFF, a 64-bit x64dbg
  base; none masked by the rules, nor as secret, account_number or
  private_phone from the model; 0x+64 and 0x+32 still masked.
- TestMaskEval: cases hex-addresses and hex-addresses-en, with the real
  models' recordings added (only these two entries; the rest of the
  recordings were left as committed, since re-recording on mote moved
  other cases' scores slightly).
- Broken by hand: the hexLiteral check taken out of modelTakes.
  TestHexNumberGoesAsWritten FAILs with eight masks
  ("0x004EA5E0" as secret: masked "...`{{SECRET_7bm7qoxm}}`...", as
  account_number "{{ACCOUNT_rcgox2br}}", 0xFFFFFFFFFFFFFFFF and
  0x00007ff6a1b20000 as secret), and TestMaskEval/privacy-filter FAILs
  with 'hex-addresses: "0x0058C210" was masked, and should go as
  written' and both hex-addresses-en values. Restored: both pass.

Run (mote-run, at base 4ab1191bc): gofmt -l internal/redact (empty),
go vet ./internal/redact/, go test -count=1 ./internal/redact/... ok.
Not tried: the reporter's own text (not posted in full); a running
magpie with the model on.

docs/subsystems/gateway-routing.md says it beside the EVM address rule.
2026-11-08 11:48:50 +08:00
yetone 9a92fd099b claude: a long auto mode classifier keeps its cache marks as claude -p (#5585, #5655)
With Claude Code's interactive mode on, the classifier was pasted into a
new run each call with none of its marks: Claude Code marks only the last
block of what it is pasted, and the classifier's tail changes every call,
so each call read only Claude Code's own prompt and wrote the whole
transcript again (126K and 132K a call at 1h's 2x in iamnil's rows).
Desktop's header-less classifier lost its marks at parse time
(e5f66f8a6); an opted-in one lost them when pasted.

There is no honest way to make the interactive Claude Code put a mark
mid-message: rewriting its body in tap.js would make the request unlike
Claude Code's and can pass the four-mark limit. So a classifier whose
marks keep 64KB or more of history (marksPrintAt, keptByPrint) runs as
claude -p, which keeps the marks (DISABLE_PROMPT_CACHING, the client's
marks in the first message, the tail through CLAUDE_CODE_EXTRA_BODY).
-p counts about 2x a token; with S Claude Code's prompt, M the marked
transcript and D the new part, interactive ~ 0.1S + 2M a call and -p ~
2(0.1(S+M) + 2D), which meet at M ~ 15-20K tokens. A shorter classifier
and every other request stay interactive; claudePrint names it
"cache-marks". No entrypoint, system prompt or identity text changes.

Run:
- TestClaudeTUIClassifierKeepsLongMarksAsPrint (with and without the
  header; a short classifier as control) is red with keptByPrint forced
  false (the old routing) and green with the fix.
- On mote at 70c10074c: go test -tags nogui -run
  'Claude|Classifier|AutoMode|Cache' ./internal/gateway ok; go vet
  ./internal/gateway for darwin, linux and windows ok; gofmt clean.
- Real account (one Max account, sandbox HOME, its keychain item copied
  to the sandbox's service name and deleted after; port 3481; Claude
  Code 2.1.316; claude-haiku-4-5), two classifier-shaped calls sharing a
  ~244KB prefix, interactive mode on:
    before (4ab1191bc): call 1 read 0 wrote 49,838; call 2 read 0 wrote 49,865
    after:              call 1 read 0 wrote 49,763; call 2 read 49,748 wrote 42
  The gateway logged both after-runs as claude -p with the reason.

Not tried: Claude Desktop's real classifier (the body was built to its
shape), Sonnet, Windows/WSL. Full suite not run at push; queued on mote
under the suite lock.

Reported-by: jerrychoi
Reported-by: iamnil (Discord)
2026-11-08 11:39:44 +08:00
yetone 7880a00ac6 models: a model of a key's provider can be asked on System One
axelburks on Discord: a relay serves its decision model under a name of
its own (an Ark endpoint id). A key's provider with a System One URL
beside a conversation URL can set a model's API to decide (System One
in Model settings' API row, its chip's right-click, or `magpie model
api <pid/model> decide`). The model is then a decision model there:
asked on System One by its own name, offered to routing groups, kept
out of the conversation models, and a turn for it is refused with 400
before the vendor is asked. Auto gives it back. A provider with no
System One URL, with that URL alone, an account, a remote magpie and
Vertex refuse it, saying why. Chat routing (apisAmong) ignores decide.

Broken by hand: removing the decideSet check in DecidesModel turns
TestModelSetToSystemOneIsADecisionModel and
TestModelSetToSystemOneAskedThere red.

Run, on this stack over origin/main 0fc3455e2 (mote's suite lock had
hours of queue, so the suites ran on WSL magpie-desktop under flock):
- go test -timeout 45m ./internal/{provider,gateway,gui,cli,settings,fx}
  on WSL, ok; ./internal/codexcat on mote, ok; gofmt -l clean;
  go vet on mac, GOOS=linux -tags nogui and GOOS=windows on mote, ok;
  TestCoreScriptBudget ok (paid by cutting comments, no raise).
- GUI, both engines, every language, on WSL at the pushed head and at
  0fc3455e2: every touched test file plus the provider-editor files a
  first run found red. No red at head that isn't red at 0fc3455e2. The
  shared reds have issues: i18n-keys #5332, model-chip-steady #4388,
  model-copy-id #4621, models-works-only #4391, plugin-move-unserved
  #4392, provider-fetch-again #5232, provider-levels-save #4394,
  provider-levels-scroll #4395, provider-models-rest #4396,
  provider-picks-stay #4397, provider-typed #4673, remote-magpie #4398,
  zero-priced-free #5262, model-reasonless (webkit de) #4100,
  name-suffix-no-names #1937.
- Rebased on origin/main 4ab1191bc (gateway.go moved under it) and run
  again at the pushed head: gateway and provider ok on WSL, gofmt,
  vet (mac, linux nogui, windows) and the budget ok, i18n-keys,
  model-headers and routing-groups-back with only #5332's red.
Not run at push: the whole GUI suite (1277 files).

Not tried: a real relay's System One endpoint; fake vendors only.

Reported-by: axelburks (Discord)
2026-11-08 11:28:54 +08:00
yetone 7a6211d047 providers: a model's own headers, in Model settings
axelburks on Discord: a vendor routes one model by a header of its own.
A key's provider (built-in or custom) can give each model headers
(settings.ModelHeaders["pid/model"]). They go on that provider's
requests for that model alone, after the provider's headers and after
auth: a name both have is sent once, as the model's, so a user's value
is never overridden by the provider's or magpie's key header. The
gateway names the model (provider.WithModel) on every route that asks
one: chat on each API, translated and streamed, count_tokens, System
One's decision, embeddings, images, videos and the model test. A
fallback provider serving the same model id gets its own headers only.
Accounts and plugins carry their sign-in's headers and take none.

The editor's "Name, price and reasoning level" panel is now "Model
settings" (every language), with + Add header per model, staged and
made with the Save; Restore default takes them away.
The rows being typed are kept out of the draft's
compare, so an untouched editor still closes without asking.

Broken by hand: dropping WithModel from gateway.go turns
TestModelHeadersReachTheirModelOnEveryRoute red; dropping the provider
id check in modelOf turns TestModelHeadersStayWithTheirProvider red.

Run, on this stack over origin/main 0fc3455e2 (mote's suite lock had
hours of queue, so the suites ran on WSL magpie-desktop under flock):
- go test -timeout 45m ./internal/{provider,gateway,gui,cli,settings,fx}
  on WSL, ok; ./internal/codexcat on mote, ok; gofmt -l clean;
  go vet on mac, GOOS=linux -tags nogui and GOOS=windows on mote, ok;
  TestCoreScriptBudget ok (paid by cutting comments, no raise).
- GUI, both engines, every language, on WSL at the pushed head and at
  0fc3455e2: every touched test file plus the provider-editor files a
  first run found red. No red at head that isn't red at 0fc3455e2. The
  shared reds have issues: i18n-keys #5332, model-chip-steady #4388,
  model-copy-id #4621, models-works-only #4391, plugin-move-unserved
  #4392, provider-fetch-again #5232, provider-levels-save #4394,
  provider-levels-scroll #4395, provider-models-rest #4396,
  provider-picks-stay #4397, provider-typed #4673, remote-magpie #4398,
  zero-priced-free #5262, model-reasonless (webkit de) #4100,
  name-suffix-no-names #1937.
- Rebased on origin/main 4ab1191bc (gateway.go moved under it) and run
  again at the pushed head: gateway and provider ok on WSL, gofmt,
  vet (mac, linux nogui, windows) and the budget ok, i18n-keys,
  model-headers and routing-groups-back with only #5332's red.
Not run at push: the whole GUI suite (1277 files).

Not tried: a real vendor that routes by header (Ark); fake vendors only.

Reported-by: axelburks (Discord)
2026-11-08 11:28:54 +08:00
yetone ae58ec9b44 providers: a key's provider can have its model list off
axelburks on Discord: Ark's pay-as-you-go list names models that can't
be asked for, and each one is asked by an endpoint id the user made. A
key's provider can now have its list off (Provider.ListOff): nothing
asks its vendor for a list (Fetch, Refetch, List, RefreshLists, a test,
a new key's prefill, a resting key's probe), a list fetched before and
models.dev's are not read, and only the ids added by hand are served.
The editor shows it as "Fetch the model list", ticked by default;
unticked, Fetch models and Forget go. A save that doesn't name listOff
keeps it. CLI: `magpie provider set <id> list=off`. Accounts and plugins
list as their sign-in does, so they don't take it.

Broken by hand: ListAsks returning false for a list-off provider turns
TestListOffAsksNoListAndServesTheIDsAdded red; dropping the keep in the
save turns TestProviderSaveListOff red.

Run, on this stack over origin/main 0fc3455e2 (mote's suite lock had
hours of queue, so the suites ran on WSL magpie-desktop under flock):
- go test -timeout 45m ./internal/{provider,gateway,gui,cli,settings,fx}
  on WSL, ok; ./internal/codexcat on mote, ok; gofmt -l clean;
  go vet on mac, GOOS=linux -tags nogui and GOOS=windows on mote, ok;
  TestCoreScriptBudget ok (paid by cutting comments, no raise).
- GUI, both engines, every language, on WSL at the pushed head and at
  0fc3455e2: every touched test file plus the provider-editor files a
  first run found red. No red at head that isn't red at 0fc3455e2. The
  shared reds have issues: i18n-keys #5332, model-chip-steady #4388,
  model-copy-id #4621, models-works-only #4391, plugin-move-unserved
  #4392, provider-fetch-again #5232, provider-levels-save #4394,
  provider-levels-scroll #4395, provider-models-rest #4396,
  provider-picks-stay #4397, provider-typed #4673, remote-magpie #4398,
  zero-priced-free #5262, model-reasonless (webkit de) #4100,
  name-suffix-no-names #1937.
- Rebased on origin/main 4ab1191bc (gateway.go moved under it) and run
  again at the pushed head: gateway and provider ok on WSL, gofmt,
  vet (mac, linux nogui, windows) and the budget ok, i18n-keys,
  model-headers and routing-groups-back with only #5332's red.
Not run at push: the whole GUI suite (1277 files).

Not tried: a real Ark account; the switch was checked against fake
vendors only.

Reported-by: axelburks (Discord)
2026-11-08 11:28:54 +08:00
yetone 4ab1191bc9 routing: Routing groups opened from Routing lead back to it
Since Routing groups became a page of their own, a group chip on a
request (or Routing's "Routing groups ›") switched to the groups page
with nothing leading back. Without the sidebar the only way out was the
tab bar, and the request you came from was gone from view.

The groups toolbar now starts with "‹ Routing" (gBack). It goes back to
Routing through window.show, so a dirty draft is still asked about, and
focus returns to the chip or button the page was opened from. Esc does
the same, except while an editor, Import, Select or a modal is open, or
focus is in a text field. With the sidebar the back control shows only
when the page was opened from Routing (.rt-gfrom); from the sidebar's own
Groups tab the page is top level and has none. No other drill-in page in
app.js binds Cmd-[, so neither does this. The label follows the language
on every draw. No new layout, no accent stripe.

Run (mote, playwright 1.62.0):
- routing-groups-back.test.cjs (new): 30/30, Chromium and WebKit x
  en/zh/zh-TW/ja/de x 1280 window, 640 window, 420 web. Red on
  origin/main's assets (MAGPIE_ROUTING_ASSETS): no visible .rt-gback.
- Broken by hand: Escape handler off -> red (chromium en 1280); the
  side-nav hide rule off -> red (webkit en 1280, "no back from the
  sidebar's own tab").
- Every routing*, sidebar*, group-*, i18n-keys, i18n-en-no-cjk,
  old-webkit and settings-groups file at 2d66e9f23 (main 0fc3455e2 +
  this): 3548 tests, 3526 pass, 22 red. The same files at origin/main
  cdf734757 alone: the same 18 red, all filed: i18n-keys (#5332, #5426,
  #5482), routing-intent-entry 8/8 (#5392), routing-context-fold webkit
  (#5586), routing-row-swap (#3799), routing-story-shrinks webkit
  (#3954). The other 4 (routing-busy chromium zh, routing-many-keys
  chromium en, routing-pace-expiry chromium de, routing-rule-drag webkit
  ja) passed whole, with routing-groups-back, at this commit on
  cdf734757 (70/70); filed #5665, #5664, seen in #4082, #3789.
- Whole GUI suite and ./...: queued on mote, not run at push; results to
  follow.

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

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

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

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

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

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

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

Reported-by: maxleebeta (Discord)
2026-11-08 10:55:49 +08:00
yetone 06324e99e8 automode: say that Claude Code may have no local check behind a gateway
chenxiang0010 saw "Auto mode can't check actions in this session ...
your requests go through 127.0.0.1:3425, which doesn't pass it
through". magpie's comments and the gateway-routing and agent-wiring
pages said that Claude Code, finding no safeguard_results, classifies
locally. Claude Code 2.1.312 to 2.1.316 (read from their bundles) turn
that local classifier off behind a non-Anthropic base URL when
Anthropic's per-account flag tengu_bright_dragonfly is "all"
(PA(), bbt(): auto_mode_side_calls_retired, localClassifierSwitchedOff).
A call with no server verdict then gets "No classifier runs for this
session", and each action the check would judge asks for approval.
2.1.314 adds the text for CLAUDE_CODE_AUTO_MODE_SERVER=0: "Claude Code
no longer has a check of its own to use instead".

So on a route only Anthropic doesn't answer (another vendor's model,
another subscription's Claude, a translated route, a relay that drops
the fields), auto mode has no check at all for such an account. magpie
can't answer one on Anthropic's behalf. The reviewed routes (Anthropic's
API, a relay passing the fields, the Claude subscription bridge) still
carry the beta, safeguards and safeguard_results as before. Comments and
docs only, no change in behaviour.

Not changed: answering 400 naming safeguards on an unreviewed route, as
Claude Code's gateway spec allows. It sets a refused latch for the
session, so a later /model to a reviewed Claude stays unchecked, while
the strip loses nothing.

Run: gofmt -l internal (clean); go vet -tags nogui ./internal/gateway
./internal/agent on mote (ok).
Not tried: a real Claude Code run, since the flag is Anthropic's per
account and the reporter's route is unknown.

Reported-by: chenxiang0010 (Discord)
2026-11-08 10:55:10 +08:00
yetone 00198b26e0 gateway: a session's side call goes on the account its main conversation is on (#5655)
With two Claude accounts, Claude Desktop's own Sonnet calls beside an
Opus chat (desktop-beside), and Claude Code's auto mode classifier, ran
on account B while the chat was on A. Each model's conversation is kept
under its own scope (p.ID/model), so the side call was routed as a
session of its own: leastHeld, or Smart's order once its cache was cold,
put it on the account the fewest others held, and B's 5 hours drained on
calls the user never made there.

Decided (product call delegated): one session goes on one account. The
user picked one, the vendor sees one client, and the cost is one cache
write of the side call where the session goes on reading it.

withSession (affinity.go) puts first, for a request whose session a
header names, the key or account of that session's largest conversation
under another model's scope (answered within heldFor, at least
cacheWorth kept, larger than this one's own). It acts for Why first,
gone, cold, no-cache, cache and session; never mid-turn, under Strict,
for a subagent (withLead), past a rest, reserve, credits or a fallback
routing put first, nor to an account that isn't readyForNew. The trace
says Why "lead" with LeadModel, and the Routing page says "Put on
{first}, where this session's {model} is: one session goes on one
account." in en, zh, zh-TW, ja and de. docs/subsystems/gateway-routing.md
says the same.

Not fixed here: the classifier's ~110-130K cache write per call. That one
is ours too: in Claude Code's interactive mode the bridge pastes the
classifier's transcript as one block without the client's marks
(claudetui userPieces, clientCache.pasted), so only the fixed prefix
(Claude Code's system plus the appended rules, the 68,925) is read and
the rest is written again on every call. The cause and a candidate fix
are on #5585. It changes what a real Claude Code sends and can't be
checked without a real account.

Run (mote, through mote-run), at this head (aeeeed54a's tree, origin/main
0fc3455e2 unchanged after a fresh fetch):
- go test ./internal/gateway ./internal/gui -count=1 -timeout 45m: ok (964s, 157s).
- TestSessionSide*, TestGroupAccountsHoldEveryRoute,
  TestPluginFactoryStandardOnlyCaps, TestWholeSession*, TestBusyModel*,
  TestInOrderKeeps* -count=2: ok.
- gofmt -l: clean. go vet ./internal/gateway for darwin, linux, windows: ok.
- node --test routing-affinity-lead (new), routing-affinity-order,
  routing-affinity-cache-write, i18n-keys, i18n-en-no-cjk: 67/68
  (Chromium + WebKit, 1100 and 420, en/zh/zh-TW/ja/de). The one red is
  i18n-keys "a plugin's words are its own", red on main for strings this
  change doesn't touch (#5327/#5332, #5426, #5482).
- The first package run of this change failed TestGroupAccountsHoldEveryRoute
  and TestPluginFactoryStandardOnlyCaps/auto (both green at 0fc3455e2):
  without a session header the id is the opening's hash, so two
  conversations that opened with "hi" were one session, and a main with
  nothing cached led. Both are excluded now, each with a subtest.
- The full go test ./... under the suite lock was queued behind four
  other sessions' suites and had not started when this was pushed.

Broken by hand, each red: the withSession call removed (both new tests;
"the session's m2 call went to k2 while its chat is on k1"); the named
session check removed (no session named); the cacheWorth bar removed
(main holds no cache, and TestPluginFactoryStandardOnlyCaps).

Not tried: real Claude accounts, real Claude Desktop. A session already
split before this release moves its side call at the side call's next
turn, writing its cache once on the main's account.

Reported-by: jerrychoi
Reported-by: iamnil (Discord)
2026-11-08 10:40:22 +08:00
yetone 0fc3455e2a providers: a key's typed balance may be in yuan and refill each month or week
tenacious_eagle_96548 asked, after v0.1.3281's typed balance, to type it
in RMB and to have it refill (e.g. $10 a month, on the 1st).

- A balance may be typed in yuan ("¥100", "100元", or a bare number while
  Settings shows costs in CNY). What magpie counts spent stays in USD and
  is turned into yuan at fx.Known(): the rate internal/fx last fetched
  (cached 12h, fetched again in the background, never on a request).
  fx.Known never returns fx.Fallback, so with no rate fetched and
  something spent, what is left is unknown (left null; the card says
  why), not a guess.
- An optional refill: monthly on day 1-31 (past a month's end, its last
  day) or weekly on a weekday, at midnight in the user's local time.
  Nothing is stored on a refill: the spend counts from the last boundary
  after the balance was typed. Typing the amount again keeps the refill.
- GUI: the pill's menu gains Refills each month… (a day, in place),
  Refills each week… (the app's menu of weekdays) and Never refills;
  provider/keybalancerefill; keyownbalance takes currency cny. CLI:
  magpie provider key-balance <id> <key> [usd|¥cny|off]
  [--refill monthly[:day]|weekly[:mon…sun]|off]. Strings in zh, zh-TW,
  ja, de. docs/subsystems/providers-accounts.md updated.

Run on mote at this tree (base origin/main 350599a0f):
- go test -tags nogui -count=1 -timeout 45m ./internal/fx ./internal/provider
  ./internal/cli ./internal/gui ./internal/usage: all ok (suite lock).
- GOOS=linux go vet -tags nogui ./... ok; GOOS=windows go vet ./... ok;
  gofmt -l clean.
- key-own-balance.test.cjs 20/20 (chromium + webkit, en zh zh-TW ja de,
  900 and 400px): yuan typed posts currency cny, monthly day (40
  refused), weekly Friday, never. i18n-keys, i18n-en-no-cjk, old-webkit ok.
- Broken by hand, each red: Known returning Fallback
  (TestKnownIsNeverAGuess); refill days taken in UTC
  (TestTypedBalanceRefills, TestRefillDays); refill dropped on retype
  (TestTypedBalanceRefills).
- Full GUI suite still running at push: 3502 ok, 6 red so far, none in a
  file this touches: webkit By weight; webkit de 1100/420 Codex resets
  used by themselves; chromium en named caller keys; chromium zh-TW 420
  a key's several limits; webkit en gateway key held to its models.
  They are run on origin/main next and filed if red there.

Not tried: a live rate fetch (tests stay offline), the real app window,
WebKitGTK.

Reported-by: tenacious_eagle_96548 (Discord)
2026-11-08 09:03:00 +08:00
yetone 350599a0f1 gateway: a held request's route is done before its 504 goes (#4200)
TestUnroutedRequestShownThenAnswered went red on ubuntu CI under -race
at d4a6e9315: the client had the 504, and the held request's route
still said Done:false, Status:0. Cause: giveUp wrote the answer
(heldWriter.answer) and only then marked the route done, with its
status, error and, after writeHeld, its report's name. A client that
reads the 504 and looks at the Routing page at once (or the GUI's next
poll) could find the request still routing and naming no report. Not a
test-only race.

The class: giveUp is the only path that answers for a held request
(checkMost and checkUnknown both end there). answer is split in two:
claim takes the reply under heldWriter.mu (false if the handler began
one; the handler's writes go nowhere from then), and send writes it.
giveUp now writes the report before taking f.mu again (out of f.mu,
it is a file), claims the writer, marks the route Done/Status/Error/
Millis/Held in one update, and only then sends, all under f.mu as
before so the handler can't return between claim and send. A report
written for a request routed or answered meanwhile is removed. The
#4300 order (report taken before the answer) is kept.

heldAnswered (the tests' hook once the 504 is out) is an
atomic.Pointer now: with the route final before the answer, a test can
end while its giveUp still runs, and -race caught the plain var read
against the test's cleanup. TestUnroutedRequestShownThenAnswered holds
giveUp in that hook until it has read the route, so a route ended after
the answer is seen undone every time; it also checks the route names its
report as it is answered. The subsystem page says the route is final
before the answer.

Run (mote, Go 1.26.8, at base 44b762d50):
- Old giveUp, new test: go test -tags nogui -race -count=5 -run
  'TestUnroutedRequestShownThenAnswered$' ./internal/gateway: 5 of 5
  red, "the held request's route: ... Done:false Status:0" (the issue's
  text).
- This change: the same test -race -count=50: ok.
- Broken by hand (the route update moved back after send and the hook):
  -count=5, 5 of 5 red at unrouted_test.go:420.
- go test -tags nogui -race -count=3 -run 'Unrouted|Held'
  ./internal/gateway: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway (under
  suite.lock): ok (801s).
- go vet -tags nogui ./internal/gateway; GOOS=linux and GOOS=windows go
  vet -tags nogui ./...: clean. gofmt -l: clean.
- Rebased on origin/main 1cb3dc435 (internal/pii only): go test -tags
  nogui -race -count=3 -run 'Unrouted|Held' ./internal/gateway: ok.
Not tried: a real held request in the app; the full ./... suite.

Fixes #4200
2026-11-08 07:20:19 +08:00
yetone 2b08ccc838 routing: the story says why by the keys Smart sorted by (#5646)
The Routing page explained Smart's order from each window's raw reset
(Weighed.Renews), while the gateway sorts by Allowance.Renewal (a credit
pack's end when it runs out before the reset) and breaks hour ties by
Allowance.Lapse. So a WorkBuddy account whose pack ends in 3 days was said
to "renew within the same hour, so the order given stays". The trace now
carries both keys (Weighed.Soon, Weighed.Lapse); renewsBy, cmpRenews,
firstWhy and behindWhy compare them, with two new story lines (credits
expire before the other renews; same hour but its credits expire sooner)
and a row note, in en, zh, zh-TW, ja and de. "Kept in order" is said only
when every key ties. A route from before soon falls back to renews and
restarts. The other keys Smart reads (tier, unreached, learns, balance,
use first) were already in the trace.

Two accounts with one name: logoed() gave only the first its icon. Each
later occurrence of the name now gets the next same-named member's own
icon, so "louis and louis" shows WorkBuddy's and Zhipu's.

Run (mote, via mote-run):
- go test ./internal/gateway -count=1 -timeout 45m: ok (1010s), before the
  rebase onto 0b4cda048 (no gateway trace/routing change between).
- go test ./internal/gui: ok. gofmt -l: clean. GOOS=windows go vet ./...
  and GOOS=linux go vet -tags nogui ./...: ok.
- After the rebase: TestTraceCarriesSmartSortKeys, TestSmartSpends*, and
  node --test of routing-story-credits-expire (62/62, Chromium + WebKit,
  en/zh/zh-TW/ja/de, 1100 and 420), routing-behind-why and every GUI file
  that was red in the full run below.
- Full routing-*.test.cjs + i18n-*.test.cjs at concurrency 4 before the
  rebase: 2955/2978. Rerun at concurrency 1 after it, 18 stay red, and the
  same 18 are red on a plain origin/main b77400826 copy on mote: i18n-keys
  (#5332, #5426), routing-intent-entry (#5392), routing-row-swap (#3799),
  routing-story-shrinks WebKit (#3954), routing-context-fold WebKit (#5586).
  routing-many-keys, routing-order-unknown and routing-steps-cap passed in
  the rerun.

Broken by hand, each red: no Soon in weighed() (Go), no Lapse (Go),
renewsBy ignoring soon (GUI pack case), no lapse tie-break in cmpRenews
(GUI shows the reporter's "保持原顺序"), logoed with one icon only.

Not tried: a real WorkBuddy account's trace; the real Linux app. Two
same-named members of one provider still show the same icon.

Fixes #5646
Reported-by: louisgreen0726
2026-11-08 04:06:22 +08:00
yetone b77400826a usage: the Overview read again keeps its cards and its place, and shows it is reading
jiabubu on Discord: a refresh of the Usage page's Overview showed nothing
while it read, flashed the page and dropped cards for a moment, and
pressing Usage again while on the Overview flashed it or moved its scroll.

- Pressing Usage again (show() calls the plugin's open, loadUsage(true))
  put the skeleton up, which hid the sections, collapsed the page and
  clamped its scrollTop. loadUsage now puts the skeleton up only for a
  first read or another period or zone (usageFor/usageKey); a page that
  already shows that read reads again quietly through refreshUsage, so
  nothing is blanked and the scroll stays.
- The refresh beside the period turns while such a read is out
  (#usageReload.reading, after 200ms), and while every card is read
  (loadQuotas) each card's refresh turns (#subscriptionUsage.reading,
  quotaReading in page.js). A card's own busy turn is left to its own
  animation (:not(.busy)). No turning under reduced motion.
- renderQuotas draws the cards again in one go, as their reset
  countdowns need, but now keeps their logo nodes (keepIcons), and the
  Overview's lists do too: a logo made afresh blinked out while its
  picture loaded.
- app.js stays in its budget: a three-line comment in renderQuotas cut
  to one. Core 1,533,507 of 1,533,802 before the rebase on 0b4cda048.

Tests:
- New usage-quiet-refresh.test.cjs: Usage pressed again at the top,
  halfway and at the foot, with the read held: no skeleton, chart not
  hidden, scrollTop the same, the refresh turning, then the same figure,
  row and logo nodes; and Refresh with the allowances held: every card
  stays, each card's refresh is shown and turning, the logos kept.
  Chromium and WebKit, en and zh, 1180 and 560px. Red on the old assets
  (8 of 8 per part: "nothing blanked while it reads ['skeleton','chart
  hidden']", "the cards' logos are the ones drawn before: false,false,
  false"), green on the new.
- usage-quota-head.test.cjs waited for the skeleton on Agents -> Usage;
  it now waits for the quiet read (the page kept, the refresh turning).
- usage-stale-answer.test.cjs lifts loadUsage out of page.js; it now
  lifts usageFor/usageKey with it and stubs the page's loading state.

Run on mote (mote-run), at the rebased head 344cdcde3: go test -run
TestCoreScriptBudget ./internal/gui ok; gofmt -l clean; the nine usage,
quota and panel files above plus panel-fit-tabs, panel-usage and
panel-quota-refresh: 140 of 140. Before the rebase (at d32a7a70c's base,
same change less the stale-answer stub): go test ./internal/gui ok apart
from TestSettingsSaveKeepsWhatItDoesNotSend, fixed on main by c7c05dcf2;
GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... clean;
every GUI file named usage, quota, allowance, click-scroll, sidebar or
last-page (129 files, 1880 tests): red only in files red on main too or
filed: usage-agents-hide (#2276, #3414, red at d32a7a70c alone),
usage-fold (#3415, red at d32a7a70c alone), usage-ledger's Requests
(#5048), and usage-compact-counts' zh-TW 420px tip under load (#5648,
30 of 30 alone); usage-stale-answer's reds there are fixed here (11 of
11).

Not tried: the whole GUI suite (1,274 files; mote at load 60 to 80
from other sessions), the real app and WebKitGTK, languages beyond en
and zh in the new test (no new strings), and the other pages' re-open
by probe (Sessions, Library, Gateway and Masking were read: none puts a
skeleton up over a page already drawn).

Reported-by: jiabubu (Discord)
2026-11-08 03:57:04 +08:00
yetone 0b4cda048c gui: the tray panel shrinks back to a short tab, gliding there
The tray panel was held at its tallest tab's height (#124): fit()
measured every tab and asked for the largest. Once Routing or Usage had
been opened, Agents sat over empty room under its rows until the panel
was let go (refeccd on Discord, macOS). fit() now lays every tab out
the same way and asks for the height of the tab showing (Agents when
none is set), so the panel shrinks as well as grows. #124's complaint
was the panel jumping bigger on a tab switch, so a tab picked glides
the edge there instead (TAB_GLIDE: 240ms on app.css's --ease-out, as
.nav-hl; a jump under reduced motion). Content fits inside a tab
(rows unrolling, Allowances landing) are unchanged.

Siblings: the Go side already shrinks on every OS. FitPanel takes the
height asked, panelFrame clamps it to panelMin/panelMax/the screen, and
glidePanel animates the Mac's frame with its top under the menu bar and
steps Windows/Linux by the tray icon. All three take their height from
this one fit(), so nothing there changed. The web host has no panel.

panel-fit-tabs.test.cjs gets "the tray panel shrinks back to a short
tab": two agents and Routing's eight requests, Agents -> Routing ->
Agents, with reduced motion and without. Agents' height is asked
again, and the tab's fit carries ms=240 and the ease (none under
reduced motion). Its Routing-skeleton check now picks the Routing tab
first, as that is the tab whose height it is about. panel-usage's
assertion is now the showing tab's height, not the tallest.

Run on mote (mote-run). At this commit, rebased on d32a7a70c: gofmt -l
internal/gui nothing; go test -tags nogui ./internal/gui ok (sandbox
HOME); panel-fit-tabs, panel-usage, panel-fit-order, panel-fold 40/40.
Earlier, at the same change on c7c05dcf2:
- new test on origin/main's app.js: 10 of 10 red, Chromium and WebKit
  x en/zh/zh-TW/ja/de: "reduce: Routing asked no taller a panel than
  two agents: 163 629" (the short tab asked the tallest's 629)
- with the change: panel-fit-tabs + panel-usage 24/24 ok (both
  engines, five languages); again at the rebased head with i18n-keys:
  27/28, the one red is i18n-keys' "a plugin's words are its own",
  filed as #5332, #5426, #5482
- the 46 GUI files that read /api/window/fit (at d32a7a70c, before
  the rebase; the change is the same): 1182/1186. Reds, none in the
  panel: images-codex-one (Settings window; red alone on origin/main
  d32a7a70c too, #4618, commented) and view-open-wheel's "wheels
  unheard, usage, en, 1000px" in WebKit (window only, no panel page,
  where fit() returns at once; #4132)
- gofmt -l internal/gui: nothing; go vet, GOOS=linux go vet -tags
  nogui, GOOS=windows go vet ./internal/gui: ok
- go test -tags nogui ./internal/gui (sandbox HOME, pinned caches): ok
  (before trimming, TestCoreScriptBudget was 346 bytes over; the
  comments were cut, the budget not raised)

Not tried: the real app's panel on the Mac, Windows or Linux (no
desktop session driven); the whole GUI suite (mote's suite.lock queue
was full); go test ./... .

Reported-by: refeccd (Discord)
2026-11-08 03:41:23 +08:00
yetone d32a7a70cb remote magpie: once magpie updates, the Remote magpies it uses update too
nnlrl_75403 on Discord: a magpie used as another's Remote magpie stayed on
its old version after the local one updated, and had to be updated by
hand on the other computer. Now nothing needs setting up:

- provider.KeepRemotesUpdated (started by the app's updater and by
  magpie serve) runs UpdateRemotes 30 s after start and hourly. A
  released build with automatic updates on reads each Remote magpie's
  version (GET /v1) and, when it is older, asks it through
  POST /v1/magpie/update?version=<v> with the provider's key, at most
  once in six hours per version. Off here, or a dev build: nothing asked.
- The remote updates as its own automatic update would: the app
  downloads and restarts once idle (updater.updateAsked → download,
  waitIdle); magpie serve puts the latest in where it runs from, one at
  a time, never elevated, and serveFollow restarts into it. Automatic
  updates or downloads off there: it answers "off" and stays.
- A copy that can't replace itself says why: a container (docker pull
  ghcr.io/yetone/magpie:latest), a package manager's (its command), a
  folder it can't write, a build from source. A magpie from before the
  route answers 404 ("too old"), a read-only or held key is "refused".
  The provider's row on the Providers page adds a short status to its
  line ("updating to v…" for 30 min, or "can't update itself" etc.),
  with the reason and the command in its tooltip. en/zh/zh-TW/ja/de.
- The route replaces the program, so it takes the Codex reset's
  admission: another machine only while shared, never a browser page,
  an enabled key with full access from loopback too (401 without one),
  read-only 403 gateway_key_read_only, held 403 gateway_key_held. It is
  in readOnlyRefused and the CORS route list.

App.js stays under TestCoreScriptBudget by cutting two comments; the
budget is not raised.

Run (on mote, at the tree committed here):
- gofmt -l internal/: clean. go vet of gateway, gui, cli, provider for
  darwin, GOOS=linux and GOOS=windows: ok.
- go test -count=1 ./internal/gui ./internal/cli ./internal/provider
  ./internal/gateway: gui and cli ok but for #5644's two settings tests
  (red on main since 6b7ee4a98, owned); provider and gateway were
  still running at the push, and go in the full run after it.
- Rebased on origin/main c7c05dcf2, again: gofmt, vet, the new tests,
  ReadOnlyKeyEveryRoute, CORS, TestCoreScriptBudget (not raised) and
  both GUI files 32 of 32: ok.
- New: TestRemoteUpdateNeedsAFullKey (no key from loopback, Origin null,
  an app scheme, *.localhost, a rebound Host, a foreign page with and
  without the full key, another machine with none or a wrong key,
  read-only and held keys, then not shared; the updater is never
  called until a full key asks, from LAN and loopback),
  TestRemoteMagpieAskedToFollow (UpdateRemotes against a real gateway:
  dev build, same and newer remote, NoAutoUpdate here, asked once per
  version, container answer kept, read-only key refused, a 404 magpie
  "old"), TestUpdateAskedByAnotherMagpie, TestRemoteUpdateNote,
  TestServeUpdateAsked.
- GUI: remote-update.test.cjs (new) and remote-self.test.cjs, Chromium
  and WebKit, 1100 and 420 wide, en/zh/ja/de: 32 of 32 ok, with every
  key checked in zh, zh-TW, ja and de. i18n-en-no-cjk ok. i18n-keys'
  "a plugin's words are its own" is red, the same on origin/main
  f8525323d (#5327/#5332, #5426, #5482); its other cases ok.

Broken by hand, each red, then put back: the handler's key check
(loopback without a key got 200 updating), its held-key check, the
route itself (404 = the old code), asking a remote that is current,
ignoring NoAutoUpdate here, asking again for the same version, the
app ignoring automatic updates off, the app never waiting to restart,
serve's single flight (2 downloads), serve's container answer.
The handler's own Origin and not-shared checks stay green when removed:
corsGuard and lanGuard refuse those first; they are kept as the Codex
reset keeps them.

Not tried: a real update of a real remote (a Docker magpie and an app
on another Mac) end to end; Windows and Linux runs of the new tests
(vet only); the full suite (run after the push).

Reported-by: nnlrl_75403
2026-11-08 03:13:15 +08:00
yetone f8525323dd providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL,
no relay query found), so their keys showed none. Now the user types what
the vendor's page says is left, on the key's row in the provider editor
(Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`.
The key's card shows that less what magpie's usage priced the calls it
sent on the key since it was typed (usage.KeySpent, the spend caps'
count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its
title saying what was typed, when, and what was counted since. Typing it
again counts from then; No balance takes it off.

A balance the vendor tells always wins: a provider with a Balance URL, a
plan source, Cline's or OpenCode Zen's card takes none typed, and a relay
whose query is found shows its own; when the probe finds none
(errNoBalance) the typed one is shown. A typed balance stays saved as the
user left it: the editor's save keeps it, a key's replaced value carries
it. An estimate is never kept in the balance history and tells routing
nothing (the routing allowances cache is left alone).

keybalance.js is loaded by keyspend.js (itself loaded when the editor
draws a key) for a provider that takes one, so app.js and the core's
script budget are unchanged. Words in zh, zh-TW, ja and de.

Run at this tree (mote):
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of
  gui, provider, cli and usage;
- go test -tags nogui -count=1 ./internal/gui ./internal/provider
  ./internal/cli ./internal/usage: provider and usage ok; gui and cli
  red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main)
- the provider tests under -race -count=3;
- GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de,
  900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de,
  gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk:
  104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the
  same on origin/main 7a2946caf (#5327, #5332, #5482, #5426).

Broken by hand, each went red:
- estimates kept in the balance history: TestTypedBalanceCountsDown;
- no fallback to the typed balance on errNoBalance:
  TestToldBalanceWinsOverTyped;
- the editor's save dropping KeyOwnBalances: TestKeyOwnBalanceRoutes.

Red on main, not this change: TestSettingsSaveKeepsWhatItDoesNotSend
and TestSettingsCLISetsWhatTheWindowSaves (groupSink, groupFirstToken,
groupPatience from 6b7ee4a98), filed as #5644.

Not tried: a real relay account with no balance URL (the cost counted is
magpie's own estimate, so a vendor pricing differently drifts until the
balance is typed again); the full Go and GUI suites before the push (run
after it, under the suite lock); the GUI in the real Windows and Linux
apps; routing does not use the estimate.

Reported-by: tenacious_eagle (Discord)
2026-11-08 02:54:25 +08:00
yetone 0ec4e84ebd gateway: a Remote magpie's cards carry their whole-window estimate
The computer reading a Docker magpie as a Remote magpie showed no estimate
for ChatGPT Pro's week: /v1/magpie/quotas/cards never sent Holds, and that
computer has none of the remote's calls to reckon them. writeCards now
reckons them for the owner or a key with no limits on what it sees; a held
key gets none, as /v1/magpie/quotas does.

Run (mote): go test ./internal/gateway -run TestRemoteMagpie ok; vet both
OSes and gofmt clean.
Broken by hand: on the old code the office/bal card's windows are [].
Not tried: a real Pro card through a real remote; past-cycle holds on
remote cards; the full suite (mote rebooted mid-run).

Reported-by: linkaww on Discord
2026-11-08 02:37:09 +08:00
yetone f78d6b0d95 tune: gateway mode leaves Tuned for you out
/api/tune replays this computer's Claude Code and Codex files, and a
~/.claude folder alone makes a Claude Code card. In gateway mode the agents
are on other computers, so the card said Claude Code made 0 requests while
the harness card counted the gateway's. /api/tune now says gateway: true
with no agents, Use and Undo answer 409, and context.js draws no section.

Run (mote): go test ./internal/gui -run 'TestTune|TestGatewayMode' ok;
node --test context-tune-gateway, context-tune, context-tune-shapes 334/334
(Chromium and WebKit, en and zh, 900 and 420 wide); vet both OSes and gofmt
clean.
Broken by hand: with the ownSessionsOff checks taken out the Go test shows
the reported Claude card with 0 calls; the GUI test fails 20 of 30 (every
gateway-mode case) on the old context.js.
Not tried: a real Docker magpie; the full suite (mote rebooted mid-run).

Reported-by: linkaww on Discord
2026-11-08 02:37:09 +08:00
yetone 371b2b63a0 sessions: gateway mode lists the sessions the gateway counted
Usage › Sessions lists only the stats' keys, and the keys named only the
agent files this computer reads. A Docker magpie in gateway mode reads none,
so the sessions that came through the gateway were counted and not listed.
MergeExternalStats now puts them in the keys too, in the list's order.

Run (mote): go test ./internal/sessions ./internal/gui -run
'TestGatewayStats|TestGatewayMode' ok; GOOS=linux go vet -tags nogui ./...
and GOOS=windows go vet ./... clean, gofmt -l clean.
Broken by hand: on the old code the unit test's keys are [claude:a] and the
gui test's [] (gateway mode off, days=0).
Not tried: a real Docker magpie; the full suite (mote rebooted mid-run).

Reported-by: linkaww on Discord
2026-11-08 02:37:09 +08:00
yetone 2b3f76d880 gateway: a held request's report is taken before its 504, so a client that closes on it can't let its wait go first (#4300)
TestUnroutedHeldReportSaved was red in full gateway runs and on CI
with the report's image description wait no longer "(under way)".
Cause: giveUp answered the 504 first and took the report after. The
answer says Connection: close, so the client reads it and closes; the
server's background read then ends the request's context, the
description wait (describeKeyed's select on ctx.Done) returns, and the
noteWait ends. When that happened before heldReport ran, the report
said the wait had ended and its stacks showed the request let go. Not a
test-only race: a real held request's report could name no wait under
way in the same way.

giveUp now checks under f.mu, lets go of it, takes the report (waits,
body, stacks), takes f.mu again and checks again that nothing routed,
answered or let the request go meanwhile, and only then answers. The
log line uses the same snapshot of the waits. The dump stays out of
f.mu. heldAnswered (nil outside tests) is called once the 504 is out;
the test holds giveUp there until the request's context has ended and
the description wait has let go, so the ordering is forced, not timed.
The subsystem page says the report is taken before the answer.

Run (mote, Go 1.26.8):
- Old giveUp plus only the heldAnswered call, with the new test:
  go test -tags nogui -race -count=5 -run 'TestUnroutedHeldReportSaved$'
  ./internal/gateway: 5 of 5 red, "the report doesn't say
  "(under way)"" (the same text as the issue).
- This change, same command: ok (5 of 5).
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
  (875s), at base bb33142ea.
- Rebased on origin/main 46b10af87 (no change there to unrouted.go,
  held_report*.go): go test -tags nogui -race -count=3 -run
  'Unrouted|Held' ./internal/gateway: ok; go build ./...: ok.
- go vet ./internal/gateway, GOOS=windows and GOOS=linux go vet
  ./internal/gateway, gofmt -l: clean.
Not tried: a real held request in the app; the full ./... suite.
2026-11-08 02:36:04 +08:00
yetone 7a2946caf4 gateway: a Codex side call to magpie's own API goes on the conversation's model
With magpie as Codex's provider, the Codex app asks a new conversation's
title on a model it chooses itself, not the one picked for the
conversation: ephemeralGenerationModel, and when the provider's model
list lacks it (magpie's always does), the list's default model, else the
first visible one that takes low effort (app.asar's oX). magpie wrote
the title on that model as asked, so with the conversation on A/dsf4.1
the title went to B/qwen3.7, another provider (tenacious_eagle_96548).
Now a title, description, summary or prediction that reaches /v1/responses
goes on the session's model (codexSideSession, as the ChatGPT route
already did; it waits for the conversation's turn like it does there),
and on the model asked only when no session's model is known.
settings.CodexTitles, when set, still writes every title.

TestCodexOwnTitleFollowsThePickNotTheAppsChoice: the title on third/
(the app's choice) before the turn on fourth/, then a description and a
summary on third/ in that conversation. Red on the old gateway.go (the
app's choice got the requests), green on the new.

Run (mote, at this commit's tree):
go build ./..., go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./...: clean. gofmt -l: clean.
go test -count=1 -run Codex ./internal/gateway/: ok (172s).
Full suite (go test -tags nogui -timeout 45m ./..., through the suite
lock) was still queued/running at push; any red it shows gets an issue.
After a rebase onto 6b7ee4a98 (its routing commits touch gateway.go
and the routing doc too), go build, the three vets and
go test -run 'Codex|Routing|Group' ./internal/gateway/ ran again at
that tree. Then rebased onto 9451ad59f (two gateway commits touching
none of this change's files); go vet ./internal/gateway/ there only.

Not tried: the real Codex app was not run; the oX choice was read from
its app.asar. No real provider accounts. Windows and Linux: vet only.

Reported-by: tenacious_eagle_96548 on Discord
2026-11-08 02:16:48 +08:00
yetone 6c7cedece8 gateway: the first Codex title after magpie starts waits for the turn, not the config's model
Codex signed in to ChatGPT, its config's model one provider's (B/qwen3.7),
the conversation put on another provider's (A/dsf4.1) in the Codex app:
the first new conversation's title was written by B. The app asks for a
title on a temporary thread with no link to the conversation, sent as
the first message is, so it can reach magpie before that conversation's
first turn. codexLeads.sideOf waits for that turn when the key's last
turn is old, but when the key had no turn at all (nothing through magpie
since it started) it returned at once with nothing, and servedSession
fell back to CodexSideModel, the config's model. Now such a call waits
the same way (codexSideWait, 5s, or its cancellation) and takes the
turn's model; the config's model only when no turn comes. A memory call
before any turn (Codex consolidating as it starts, no turn on the way)
still takes the config's model at once. A model set for titles in
magpie's settings (settings.CodexTitles) still wins, as before.

TestCodexFirstTitleFollowsThePickNotTheConfig: fresh server, config on
third/, the title sent, then the conversation's turn on fourth/. Red on
the old codex_follow.go ("the config's model got 1 requests, the title
among them"), green on the new. TestCodexSideTurnsOnThePickedModel sends
side turns with no turn ever: it sets codexSideWait to 0 so it doesn't
wait 5s on each.

Run (mote, at this commit's tree):
go build ./..., go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./...: clean. gofmt -l: clean.
go test -count=1 -run Codex ./internal/gateway/: ok (172s).
Full suite (go test -tags nogui -timeout 45m ./..., through the suite
lock) was still queued/running at push; any red it shows gets an issue.
After a rebase onto 6b7ee4a98 (its routing commits touch gateway.go
and the routing doc too), go build, the three vets and
go test -run 'Codex|Routing|Group' ./internal/gateway/ ran again at
that tree. Then rebased onto 9451ad59f (two gateway commits touching
none of this change's files); go vet ./internal/gateway/ there only.

Not tried: the real Codex app was not run; its title model choice was
read from its app.asar. The Codex 0.165.0 TUI with magpie-style config
(model B, -m A, fake Responses server) sends its title on A, so the TUI
was never affected. No real provider accounts. Windows and Linux: vet
only. The same report on the /v1 route (magpie as Codex's provider) is
the next commit.

Reported-by: tenacious_eagle_96548 on Discord
2026-11-08 02:16:48 +08:00
yetone a7113d5c92 gateway: a Mac's Claude Code cache pick reaches the remote magpie's relay (linkaww)
linkaww's chain: Claude Code on a Mac (API-key mode) -> the Mac's
magpie -> a Docker magpie whose Claude provider is the relay. Two rules
asked for: a 5m pick on the Mac never writes an hour's cache; with
nothing picked, the relay keeps Claude Code's subscription default, an
hour.

Claude Code 2.1.316 marks five minutes with no ttl, whether its user
picked them or it is its default off a subscription (the marker names a
ttl only for 1h). So since v0.1.3256 the relay, which followed the marks,
wrote 5m with nothing picked, and an unmarked side call (Haiku's title,
the classifier) fell to the Docker computer's own pick, an hour, under a
5m pick.

Now the Mac's magpie names the pick: X-Magpie-Claude-Cache-TTL
(ClaudeCacheTTLHeader), "5m", "1h" or "default", set by passOnCaller
for a request from Claude Code on this computer (its token or its
claude-cli/ User-Agent from loopback, never Claude Desktop's) and passed
on as it came through further magpies. It is read as claudeRunTTL reads
the pick (claudePickedTTL); a settings.json that can't be read or parsed
names none (claudeSettingsKnown), and the marks decide as before. The
far magpie takes it from a magpie/ request alone (callerFrom) and takes
it off what comes in (withCaller), so no vendor sees it; native
passthrough already drops X-Magpie-*. runTTLFor: forced 5m; marks that
name an hour; else the pick (Request.pickedTTL), "default" giving
claudeRunTTL (that computer's pick or an hour); else the marks; else
claudeRunTTL. Claude Code on the relay's own computer gets the same
rule from its local pick. A Claude Code that goes straight to a remote
magpie sends no header and keeps today's marks-first behaviour. Nothing
sent to Anthropic changes beyond the run's CLAUDE_CODE_PROMPT_CACHE_TTL.

Known limits, in the bridge doc: a pick made only in Claude Code's shell
env or a project's .claude/settings.json isn't seen by magpie, so it
goes as "default" (an hour unless the marks name one);
subagentPromptCacheTtl is not told apart.

Tests: TestClaudeRunKeepsTheUsersCacheTTL gains 11 cases (the Mac's
5m/1h/default, marked and unmarked, against this computer's settings,
forced, marks naming 1h, Claude Code here, unreadable settings);
TestClaudeCacheTTLFromAMagpieOnly; TestClaudeCacheTTLOf;
TestClaudeCacheTTLReachesTheRemoteMagpie (two real handlers: 5m,
default, unreadable -> none, another agent -> none, vendor sees no
X-Magpie-* header).

Run (on mote, at this tree rebased on 3b541a7f3 = origin/main just fetched;
the targeted tests and vet again there):
- go test -count=1 -run 'TestClaudeCacheTTL|TestClaudeRunKeepsTheUsersCacheTTL|TestRemoteMagpieAgent|TestAskedCacheTTL|TestClaudeInstructionsCachedApart' ./internal/gateway: ok
- go vet ./internal/gateway, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet: ok; gofmt -l internal/: nothing
- full go test -count=1 -timeout 45m ./... through suite.lock: still
  running at push (started at base bb33142ea) (owner's rule: no verified commit waits on it); any
  red it shows gets its own issue.

Broken by hand: runTTLFor ignoring pickedTTL -> 5 table cases red
(unmarked 5m, marked 1h, default, Claude Code here); the header taken
from a non-magpie -> FromAMagpieOnly red; passOnCaller not setting it ->
ReachesTheRemoteMagpie red ("told \"\""); claudeSettingsKnown always
true -> TestClaudeCacheTTLOf "here, unreadable" and the table's
unreadable case red.

Not tried: a real Claude subscription, a real Docker magpie, or
linkaww's own Mac; cache writes were checked by the run's environment,
not by Anthropic's usage numbers.

Reported-by: linkaww on Discord
2026-11-08 02:10:17 +08:00
yetone 6b7ee4a984 routing: every group follows a default for rate limits, slow starts and busy members unless it sets its own
jiezhengj on Discord asked to set the per-group policies once instead of
in each group. The Routing groups page's Settings card, under the list,
now has three rows: Rate limited (keeps its place / goes to the back),
Slow to start (wait / 30 s ... 4 min) and Every member busy (off / 1 min
... 4 min). They are saved in settings.json as groupSink, groupFirstToken
and groupPatience (settings.SetGroupDefaults, POST /api/groups/defaults).

A group follows the default for each value it leaves unset, and its own
value always wins:
- Sinks() is the group's Sink, or else the default unless NoSink, a new
  field for an explicit "Keeps its place".
- FirstTokenOr() is the group's own FirstToken (-1, FirstTokenWait, is an
  explicit Wait), or else the default. The gateway reads it where it
  reads a group's first-token time.
- Waits() reads the default when Patience is 0. 60 is an explicit 1 min.
Groups saved before have 0 and no NoSink, so they follow the default,
which starts at magpie's own (keep its place, wait, 60s). Nothing a user
set changes. The group editor's three rows gain a Default option, on for
a group that sets none, and its hint names the value it follows. Segments
only, with no native select.

Run on mote, at 06b2daeff rebased on origin/main 2dac9b84e:
- go test on the new tests TestGroupDefaultsUnlessItsOwn,
  TestGroupFirstTokenFollowsTheDefault, TestGroupSinkFollowsTheDefault
  and TestGroupDefaultsSaved, plus TestKeysAreWhatTheSaveWrites and the
  existing first-token and sink tests: ok.
- Broken by hand (Waits, FirstTokenOr and Sinks ignoring settings): the
  three provider/gateway tests went red.
- GUI: group-defaults (new), group-patience, group-first-token,
  group-found-off and rate-limited-sink, in Chromium and WebKit, in en,
  zh, zh-TW, ja and de, at 1100 and 420: 56/56 pass. With the old
  client.js and routing.css, group-defaults, group-patience and
  group-first-token fail 44 of 44.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...:
  clean. gofmt -l: clean.

Still running when this was pushed (owner: never hold a verified commit
behind the suite): go test -timeout 45m on internal/provider,
internal/gateway, internal/gui, internal/settings and
internal/settingsapi, then the whole GUI suite under suite.lock. Any red
they show gets its own issue.

Not tried: the real app with real groups under real rate limits. Only
the gateway tests' fakes exercise the default sink and first-token paths.

Reported-by: jiezhengj on Discord
2026-11-08 02:08:30 +08:00
yetone 3b541a7f36 routing: Smart ranks an account by its week once its month can't be used up before it renews (#5639)
Smart ranked a Volcengine Agent Plan (5 hours 2,000, week 7,000, month
20,000) by its month, the biggest window, so it always stood behind
accounts renewing weekly, and its month could reach a point where it
could no longer be used up before it renewed.

The rule keeps #1778's reasoning: a month holding less than its weeks add
up to is the real cap while the weeks can still carry it. Once what the
biggest window has left is more than the next window (a day or longer,
same unit, counts known) can let through between its own reset and the
biggest one's (Of x time between / Span), what the week leaves at its
reset is lost, and the week ranks the account.

- provider: Allowance.Unreached counts the biggest windows to pass over.
  Renewal and Seat.Soon are unchanged for other strategies and plugins.
- routes: Seat.Unreached; Smart compares Soon past it.
- gateway: weighRouted fills it; the trace's Weighed carries `unreached`.
- GUI Routing: renewsBy skips those windows, and a new story line says the
  shorter window decides. The Smart header and the group hint say so in
  en, zh, zh-TW, ja and de.
- docs: reference.md (How magpie picks an account) and
  subsystems/gateway-routing.md.

With the issue's numbers as reported (month 696 h away, 18,372 left),
four weeks carry 28,017, so the order is unchanged. Two weeks before the
month renews, 14,017 < 18,372, and the plan goes first, ahead of the
point where a week's leftover is lost.

Run on mote at this tree (base 2dac9b84e; origin/main bb33142ea touches
none of these files):
- go test -tags nogui ./internal/provider ./internal/routes: ok
- go test of TestMonthOutOfReachRanksByWeek,
  TestSmartSpendsAWeekTheMonthCantWait, TestSmartPassesAnUnreachedWindow
  and the Smart/Renewal/Weighed tests in provider, routes, gateway: ok
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok
- gofmt -l internal/: clean
- node --test routing-key-windows.test.cjs: 52/52 in Chromium and WebKit,
  en/zh/ja/de, the new #5639 scene included

Broken by hand:
- Unreached returning 0: TestMonthOutOfReachRanksByWeek ("two weeks to
  go", "the last week") and TestSmartSpendsAWeekTheMonthCantWait went red.
- Smart comparing a.Soon, b.Soon whole: TestSmartPassesAnUnreachedWindow
  and TestSmartSpendsAWeekTheMonthCantWait went red.
- client.js without the slice and the story line: the #5639 GUI case went
  red (Chromium en).

Still running when pushed (the owner's rule not to hold a verified commit
behind the suite): the full internal/gateway package; all routing-*,
panel-routing*, gui-zh-tw/ja/de and i18n GUI files in both engines; and
the full go test ./... -timeout 45m. Any red they show gets its own issue.

Not tried: a real Volcengine Agent Plan account. Ark replies that send
only Percent carry no counts, so the rule can't apply to them. Not
changed: Use before expiry (Pace) still ranks this plan by its month;
filed as #5641.

Reported-by: louisgreen0726
Refs #5639
2026-11-08 02:08:08 +08:00
yetone bb33142eae gateway: a relayed Claude run cut from a busy, forked or side-questioned session keeps its 5m cache (linkaww)
The relay's runs keep the cache lifetime of the session they go on from
(savedSession.cachePrefix). Three of the four places that make a
savedSession left it out: branch (a fork's turn), retryBranch (a turn
sent again while its run is busy) and branchAt (the turn after the
interactive mode's side question). cachePrefix.runTTL() reads an empty
ttl as an hour, so each such run was started with
CLAUDE_CODE_PROMPT_CACHE_TTL=1h under a 5m pick, and wrote 1h cache
entries. Each now carries its run's cachePrefix, as shelve did.

Tests: the fork, busy-retry and side question harnesses log each run's
CLAUDE_CODE_PROMPT_CACHE_TTL; with promptCacheTtl 5m picked
(pickFiveMinutes), everyRunKept5m requires every resumed run to have 5m.

Run (on mote, at this commit, base 2dac9b84e = origin/main just fetched):
- go test -count=1 -run of the side question, busy retry, fork and
  TestClaudeRunKeepsTheUsersCacheTTL tests ./internal/gateway: ok
- go test -count=1 -timeout 45m ./... through suite.lock: every package
  ok (88), exit 0
- gofmt -l internal/: nothing
- go vet ./internal/gateway, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet: ok

Broken by hand: the three cachePrefix carries taken out, the busy-retry
test (print and interactive), the fork test (print and interactive) and
the side question test each fail "a branch's run, want a 5m cache as its
parent's".

Not tried: a real Claude subscription, and linkaww's Mac -> Docker
magpie chain. The second half of the report (a 5m pick and an unmarked
side call, and no pick at all) is the next commit.

Reported-by: linkaww on Discord
2026-11-08 02:03:17 +08:00
yetone 7f2706e7fb gateway: a System One request is masked, at /v1/systemone and from /v1/decisions
With Settings' masking on, a /v1/systemone request went to the decision
model's vendor as the agent wrote it: serveSystemOneBody and
serveDecideTries never called the masker, so a secret or a name in the
state or a question's instructions left unmasked. c7810ea5c then sent a
/v1/decisions request for a System One model down that same path, where
before it went through serveRetrieval, which masks, or was refused.

serveDecideTries, which every System One request reaches (one provider,
a decision group, a translated Decisions request), now masks the body
once before its tries (redactedHits), unless every try goes where the
user set requests to go unmasked (SkipsRedaction), as embeddings do. A
masker that fails, or is wanted and missing, sends nothing (maskStatus).
The answer is restored on its way back, the mask is recorded as
"systemone" in Settings › Privacy and on the route, and Recent calls
keeps the body as it went. systemOneByDecisions still masks in
serveRetrieval, before this point, so nothing is masked twice.

Run (mote, at c7810ea5c + this change):
- go test -timeout 45m ./internal/gateway ./internal/redact ./internal/maskrec: ok (gateway 811s)
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok
- gofmt -l: clean
Broken by hand: with the decide_group.go change stashed,
TestSystemOneMasked/systemone and /decisions fail (secret sent whole);
the two unmasked cases pass on both.
Not tried: a real decision vendor (Bailian, Jev) with masking on.
2026-11-08 01:07:44 +08:00
yetone c7810ea5cc gateway: /v1/decisions asks a System One decision model, and /v1/systemone a Decisions-only one (wudi_boy)
wudi_boy on Discord: a Decisions request (Python-urllib) to the Qwen
decision model, decision-model-preview, was refused, while the same
model answered on /v1/systemone. canDecide sent Decisions only to an
OpenAI key, Azure or another magpie, and nothing translated between the
two APIs.

Now a Decisions request whose model answers System One (Qwen's, Ark's,
a Jev, a Clef, a plugin's, or a decision group whose members do, none
of them a provider that serves Decisions itself) is asked there
(decisions_systemone.go): predicate -> noul, choice -> criteria map
(boolean values as "true"/"false", typed back on the answer), score ->
criteria list "label: description" least first, an unnamed question ->
question_N answered with a null name, input -> state (a string as it
is, items as {"messages":[{role, content, refusal}]}, input_json as its
JSON text). The answer comes back in the Decisions shape in the
questions' order, a missing answer as refusal, with input and output
tokens. prompt_cache_key/options and safety_identifier change no answer
and are left out. Everything with no counterpart is a 400 naming it,
before the vendor is asked: an image unless every target is a Clef or
another magpie, an http image, function/custom tool calls and outputs,
an image or refusal in a question, any other field or question type.
The reverse: /v1/systemone whose model no System One provider has but
the Decisions API serves (openai/gpt-6-luna) goes through
serveRetrieval as /v1/decisions does, and is answered as System One.
A vendor's error passes through as it was said.

Tests, against fakes with the real shapes (Ark's 2026-11-01 System One
answer, Cloudflare's result envelope, openai-python's Decision):
TestDecisionsAskSystemOne, TestDecisionsMessagesAsSystemOneState,
TestDecisionsUntranslatableRefused, TestDecisionsImagesToClef,
TestSystemOneAsksDecisions.

Run on mote (mote-run) at this change on d4712e131: go test -count=1
-timeout 45m ./internal/gateway ok (777s); go vet ./internal/gateway
for darwin, linux and windows clean; gofmt -l clean. Full suite queued
under the suite lock, not run.
Broken by hand, each red: the decide branch taken out (the qwen tests
400 "no OpenAI-style API"); the reverse call in serveSystemOne off
(404 "no Jev provider"); an image to a text-only model and a
function_call dropped silently instead of refused (200 instead of 400).
Not tried: a real Qwen or Ark key, or a real OpenAI Decisions call; a
plugin's decision model through the translation.

Reported-by: wudi_boy
2026-11-08 00:45:30 +08:00
yetoneandRuijia Zhang 04aabf3a01 sessions: read Antigravity Insiders conversations (#5634)
Antigravity - Insiders keeps its conversations in a separate store,
~/.gemini/antigravity-insiders/conversations/<id>.db, with its own
conversation_summaries.db beside it. Only the stable store was scanned,
so Insiders sessions and their token use never reached Sessions or Usage.

Both stores are now read under the existing antigravity agent and its
session-reading choice. An Insiders-only install shows up in Found, and
Dirs lists each store that exists. Each file takes its title and folder
from its own store's summaries. Insiders session ids carry an
"insiders-" prefix in magpie, so a UUID present in both stores stays two
sessions with separate call ids; stable ids are unchanged and nothing on
disk is renamed. Nothing maps a session id back to a path, so the prefix
can't send a reader to the wrong file.

Ported from BUKOWSKIREAL's branch (926d4fe50), unchanged.

Ran (mote, at this head):
- TestAntigravityInsidersSessions: green; red with the three source files
  put back (Insiders missing from Found, Dirs and List).
- go test -count=1 ./internal/sessions ./internal/usage ./internal/usageapi
  ok; go vet ./internal/sessions for darwin, linux and windows ok; gofmt
  clean.
- The author's own run: 42 real Insiders databases read in an isolated
  copy, 2,293 calls, each model's tokens matching an independent decoder.
Not tried: a real Insiders install on our machines; the full suite.

Co-authored-by: Ruijia Zhang <ruijiazhang76@gmail.com>
Reported-by: zhang9083 (Discord #feedback)
2026-11-08 00:33:08 +08:00
yetone dca338f3a3 gateway: a relayed Claude run keeps its cache as long as the request's own marks ask (Linka)
v0.1.3247 (dbc74414b) gave a bridge run the prompt-cache TTL of the
user's pick, but read it only on the machine the relay runs on: its env,
settings.json's env, then promptCacheTtl. A Docker magpie has none of
them, so it fell back to 1h while the Mac it serves was set to 5m. The
Mac's pick reaches the remote only as the cache marks its Claude Code
puts on the request.

A new run's TTL is now picked by runTTLFor:
1. FORCE_PROMPT_CACHING_5M on this computer: 5m, as Claude Code does.
2. The request's own marks: the longest TTL on its tools, system,
   messages or the request itself (askedCacheTTL, Request.askedTTL).
3. claudeRunTTL: this computer's CLAUDE_CODE_PROMPT_CACHE_TTL or
   promptCacheTtl.
4. 1h, only for a request with no marks (Chat, Responses clients).

The run started from a saved transcript (replaySession) follows it too.
Warmup and usage runs have no request and keep claudeRunTTL
(cleanClaudeEnv). Linka's FORCE_PROMPT_CACHING_5M=1 workaround keeps
working. Docs: claude-subscription-bridge.md.

Tests: four new cases in TestClaudeRunKeepsTheUsersCacheTTL (the child's
env and the first message's marks): client 5m with nothing set here;
client 5m over this computer's 1h; client 1h over its 5m; forced 5m over
client 1h. New TestAskedCacheTTL with bodies shaped like Claude Code's
(billing line, marked system blocks, the last message marked).

Run on mote: go vet ./internal/gateway for darwin, linux and windows;
gofmt clean; go test -count=1 -timeout 45m ./internal/gateway: ok (958.9s), at base 578053d6a.
Broken by hand: startRun back on claudeRunTTL(os.Environ()), three of
the four new cases red (client 5m, 5m over 1h, 1h over 5m); the forced
case passes on the old code too, as it should.

Not tried: a real request through a real Docker magpie. Linka's other
ask, a settings UI for the remote's built-in Claude Code and the Agents
page not detecting it, is not addressed here.

Reported-by: Linka
2026-11-07 23:25:10 +08:00
yetone 970a86ff30 gateway: a vendor thinking for minutes is not pinged into GOAWAY too_many_pings
zdevoz (Discord, Windows, 0.1.3249): gemini-4-argon at effort high
through Antigravity waited ~235s for its first byte and then failed with
"http2: server sent GOAWAY and closed the connection; LastStreamID=3,
ErrCode=ENHANCE_YOUR_CALM, debug=\"too_many_pings\"". magpie logged a 502
and sent the whole turn again, so one turn took 421s.

Cause: the gateway's transports used Go's HTTP/2 health check
(netproxy.HTTP2Health, SendPingTimeout 10s). Go's client resets its
read-idle timer on every frame it reads, the ping's own ACK included
(h2_bundle.go readLoop / healthCheck), so a silent connection is pinged
every 10s for as long as the silence lasts, about 24 pings in four
minutes. Google's front end holds clients to gRPC's ping policy
(keepalive.md: a ping within MIN_RECV_PING_INTERVAL_WITHOUT_DATA, 5
minutes, of the last with no HEADERS or DATA sent between is a strike;
past MAX_PING_STRIKES, 2, the server sends GOAWAY ENHANCE_YOUR_CALM
"too_many_pings").

Fix: netproxy.CalmHTTP2 gives the gateway's vendor transports
(vendorTransport, so upstreamTransport and each Dispatch clone) an
HTTP/2 health check of magpie's own, on x/net/http2 with a ConnPool that
never dials (net/http dials through the proxy and hands the connection
over in TLSNextProto). The first ping of a silence still goes at
PingAfter (10s) and a lost one still drops the connection after
PingWait, in Go's words ("http2: client connection lost", which lostPing
reads), so #2843 and #4936 are found as fast as before. A silence starts
at the vendor's last HEADERS/DATA/CONTINUATION frame (read from the
frame headers as they come) or at the request handed to the connection.
After an answered ping the next waits PingAgain, 5 minutes, so a 4-minute
silence has one ping. A Dispatch clone gets its own pool (Clone copies
TLSNextProto, not RegisterProtocol), and t.CloseIdleConnections reaches
the calm pool through net/http's altProto lookup, so the proxy-move and
region drops (#4523, #5182) still close the connections.
uploadTransport stays on Go's HTTP/2 with no ping (#3909), and
http.DefaultTransport keeps HTTP2Health: its requests are short, and it
is cloned at 8 sites that would share one calm pool across proxies.

Retry after a GOAWAY: the retry the reporter saw is still made. With the
pings gone it should not be needed. When a GOAWAY does come, the
connection can't take a new request and the pool drops it, so the next
try dials anew (TestTryAfterGoawayDialsAnew).

Tests (no network):
- TestLongSilenceIsNotPingedIntoGoaway: a raw x/net Framer HTTP/2 vendor
  that enforces gRPC's ping policy (minimum gap scaled to 600ms, GOAWAY
  ENHANCE_YOUR_CALM too_many_pings past 2 strikes) and answers after a
  2.5s silence, reached through upstreamTransport with pings scaled to
  100ms/1s/1s.
- TestTryAfterGoawayDialsAnew.
- TestRequestOnAHoledConnectionFailsAtThePing now runs for HTTP2Health
  and CalmHTTP2, and the calm run must fail with "client connection lost".
- TestCalmFindsAPathDeadLaterInTheSilence: a path that dies after the
  first ping was answered is found at the PingAgain ping.
- TestCalmIdleConnectionsCloseAndClonesKeepTheirOwn.

Run (mote, Go 1.26.8):
- go vet -tags nogui ./internal/netproxy ./internal/gateway, plus
  GOOS=windows and GOOS=linux vet; gofmt -l clean.
- go test -race -count=1 ./internal/netproxy: ok.
- go test -count=1 -run
  "H2|HTTP2|Silent|Upload|Uplink|Region|Proxy|Goaway|LongSilence|Unsent|Replay|Fresh|LargeBody|Codex|Antigravity|CodeAssist"
  ./internal/gateway: ok (131s).
- win-run (xiaomi-gpu, Windows 11): go test ./internal/netproxy ok, and
  the gateway's Goaway/LongSilence/SilentHTTP2/Unsent/Upload/LargeBody
  tests ok.
- Again at the pushed head, rebased on 784113472: vet, gofmt,
  ./internal/netproxy and the gateway subset above (with TokenWall and
  Fallback, which the rebase brought in): ok.
- The full go test -timeout 45m ./... runs after the push under the
  suite lock; any red is filed as an issue with its output.

Broken by hand:
- vendorTransport back on HTTP2Health: TestLongSilenceIsNotPingedIntoGoaway
  red in 0.46s with the reporter's exact error: "http2: server sent GOAWAY
  and closed the connection; LastStreamID=1, ErrCode=ENHANCE_YOUR_CALM,
  debug=\"too_many_pings\"" (4 pings, 1 GOAWAY).
- watch with PingAgain = 1h: TestCalmFindsAPathDeadLaterInTheSilence red
  (context deadline at 20s).
- watch with PingAfter = 1h: TestRequestOnAHoledConnectionFailsAtThePing/
  CalmHTTP2 red (20s, the dead path not found).
- Dispatch not re-calming its clones: base's request went on the clone's
  connection, red.
- calmPool.CloseIdleConnections a no-op: the idle connection never
  closed, red.

Not tried: a real Antigravity or Google request (no real account was
used, and Google's exact tolerance is unknown: the report suggests about
22 pings at 10s). Not tried with a real proxy between. Go 1.27 moves
x/net's Transport onto net/http's (transport_wrap.go); ConnPool is still
honoured there, but this has not been run on it.

Reported-by: zdevoz (Discord)
2026-11-07 22:18:28 +08:00
yetone ea1a8ae809 routing: a folded fold of accounts on one plan says what they have left together
chen2652 (Discord #help): a provider with several accounts on one plan
should show, when its group is folded, one bar and what is left in all;
opened, each account's own quota as now.

A Routing account fold (3+ adjacent accounts of one provider and model),
when folded, now writes its tightest shared window before its status
("5 hours 40% used · …") and a bar under it, from quotaall.js's
mergeQuotas over the accounts' Usage cards. Its tip lists every window,
how they were put together (the mean of n accounts on one plan, added up,
or unlimited on each) and when the first of them starts again. Only when
every account has a card, all on one plan, none free; with different
plans, a card missing, the fold open, or the day view, nothing changes.
An open fold shows only each account's own row, as before. No new words:
every string is already in i18n.js in every language. routing.css is
unchanged (the account rows' bar grid). foldQuota in plugins/routing/
client.js; documented in docs/subsystems/gui-shell.md.

Run:
- routing-fold-accounts-together.test.cjs (new): 5 languages x 1100/420px
  x Chromium/WebKit, 22/22 on mote. Folded: figure, 40% fill, tip in each
  language, no email in the figure; mixed plans: no bar; open: no bar;
  nothing overflows.
- At this tree (rebased on origin/main 999ba6a00), on mote: the new test,
  routing-fold-all, routing-folder and i18n-keys: 66 tests, 65 pass. The
  one red is i18n-keys "a plugin's words are its own" (plugins/library and
  plugins/routing "No session ID"), filed as #5327/#5332/#5426/#5482, not
  a string of this change.
- Earlier, on WSL at d7b298dec vs base 56f095604: every routing GUI file
  plus i18n-keys, provider-at-once and quota-all, 2942 tests; the same
  WebKit/load reds at the base (36 there, 38 here). The one head-only red,
  provider-at-once "webkit en: accounts at once are typed and saved" (a
  Providers editor timeout), passed 60/60 with the new test on a rerun.
- Screenshots of every language at both widths (WebKit) looked at.

Broken by hand, each red in the new test:
- the old client.js;
- combining while the fold is open (no !f.open): "an open fold has no
  bar of its own";
- no one-plan check: the mixed-plan fold drew a bar.

Not tried: the whole GUI suite and the Go suite before the tag (run after
it); the real app with the reporter's real accounts on one plan.

Reported-by: chen2652
2026-11-07 22:03:32 +08:00
999ba6a00e claudetui: a replayed history keeps its words when one of its lines names an image file and an image follows (#5548)
#5548, Suge8 (magpie 0.1.3106, Claude Code 2.1.318, macOS, interactive
mode, Pi over OpenAI Chat): a compacted Pi conversation told whole to a
new Claude Code reached it as its four images and the closing notes
only; the history, which had `ls` output naming screenshots (a.jpg, …),
came into the next prompt, out of order.

Cause: send pasted a message's text piece and, without waiting for it
to show, the image after it; only the last text piece was waited for.
Claude Code 2.1.318 tries each pasted line ending in .png, .jpg, .jpeg,
.gif or .webp as an image file before it takes the words in (for a
relative name it asks the clipboard through osascript, about 0.45s),
and keeps one "pasting" mark for every paste. The image's read ended
first and cleared it, so the Enter after the closing notes sent the
prompt without the words.

Fix:
- send waits for every text piece to show before the next piece, not
  only the last one.
- shown counts a "[Pasted text #N" only with N past the paste before
  it, else the words' own last line: images and pasted text share
  Claude Code's numbering, so send keeps one number for both, and the
  prompt drawn again shows the earlier "[Pasted text #1". An inline
  paste (800 bytes and 2 line breaks at most) takes no number in
  2.1.318, so the number stays exact. A paste not shown within
  shownWait is still gone past, as before.
- Every paste goes through send, the WSL and queued (busy) messages
  too; a message of an image alone has no text to wait for, and one of
  text alone was already waited for.

Tests: the fake Claude Code now does what 2.1.318 does here: it draws a
long paste as "[Pasted text #N +B lines]" numbered with the images,
draws the prompt again as a paste starts, takes words naming an image
file in after 1s, and keeps one pasting mark (an Enter while it is set
is lost). TestShimWaitsForWordsNamingImages sends [words naming foo.png,
image, an ls naming bar.png and baz.png, image, closing notes], and the
same naming .txt files. TestShimPastesImages now expects its second
image as #3: the "and" between two images is 4 line breaks, pasted text
as 2.1.318 numbers it.

Run, at this tree on 9e6687e3, and again after a rebase on 30ae0e3f
(go vet and go test ./internal/claudetui/ ok, the new test red on its
old tui.go):
- 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.
- go test ./internal/claudetui/: ok (115s); with -race: ok (118s);
  the two image tests -race -count=10: ok.
- go test -tags nogui ./...: claudetui and the gateway's Claude tests
  ok. TestAlmaProvidersSeenDecodeOnce (agent), TestMarshalRawIsEncodingJSON,
  TestMarshalSizedIsJSONMarshal, FuzzMarshalRaw,
  TestServeWSLListensBesideLoopback (gateway) and TestPluginSOCKSProxy
  (plugin) fail on this machine (go1.27.3, HTTPS_PROXY set) at 9e6687e3
  without this change too; not looked into here.
- Real Claude Code 2.1.318 (claude-haiku-5-5) through a helper built
  from this tree, the issue's message driven straight into
  claude-tui-helper, in a sandbox CLAUDE_CONFIG_DIR: s-png (a line
  "foo.png") 3/3 and s-txt ("foo.txt") 2/2 recorded the whole prompt,
  807 chars, the words first and the image as [Image #2]. The old
  helper in the same setup, s-png 4/4: the words came after the image
  and the closing notes ("[Image #1] (The images…" first,
  imagePasteIds [1]); not lost this time, as the clipboard answered
  sooner than in the report.

Broken by hand:
- The old tui.go: TestShimWaitsForWordsNamingImages/.png fails, "Claude
  Code was sent "echo: [Image #1:red][Image #2:blue]\n\n(The images
  above are the tool's results.)\nReply with the codeword."", the
  words missing; /.txt passes.
- Each piece waited for, but shown taking any "[Pasted text #": both
  cases fail: the second image is missing, and with .png the ls too.

Taken from Suge8's own branch commit 15b05052 (byte-identical tui.go code
to the patch ggbdpq rebased on #5548; this one also carries the
subsystem doc and the fake's 2.1.318 numbering). The patch's
replay_image_test.go and its FAKE_SLOW_PASTE fake mode are left out:
they cover the same case as TestShimWaitsForWordsNamingImages with a
second fake.

Review run at this tree on origin/main 9700dd7cd (wsl-run,
magpie-desktop, Go 1.26.8):
- gofmt -l internal/claudetui, go vet ./internal/claudetui: clean
- go test -count=1 ./internal/claudetui/: ok (119s)
- -race -count=3 TestShimWaitsForWordsNamingImages|TestShimPastesImages: ok
Broken by hand: main's tui.go: TestShimWaitsForWordsNamingImages/.png
red, the words missing ("echo: [Image #1:red][Image #2:blue]...").
Known edge (Suge8's): the words' tail can match early when a piece's
last line equals an earlier piece's; it then goes on as before the fix.

Reported-by: Suge8
Co-authored-by: Suge8 <nnyless@foxmail.com>
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-07 21:59:28 +08:00
yetone c8eb7b3877 search: a search API's keys are a list, each switched off, moved and removed on its own
Web search took one key per API in one field (辰林鸭~ on Discord: only one
Tavily key). Settings › Models › Web search now lists an API's keys under
it as a provider's accounts are: each masked on its own row with a tick
(off / on), Show, Copy and Remove; several pasted at once (commas,
semicolons, lines), the reply saying how many were new and how many it
had; the order changed by dragging or Alt+↑/↓. A resting key says why and
until when on its row ("asked last until 14:05: rate limited"), from the
gateway's rest (SearchKeyRest, SearchQuota.Ref); rotation on 401/403,
402/432/433 and 429 (#1477) is unchanged.

provider.SearchAPI keeps Key as the keys on, comma-joined, so the gateway
and an older magpie never ask one switched off; keyList is written only
while a key is off. A Key that differs from the list (an older magpie, a
sync) wins, its keys on in its order, the list's off keys after. The last
key on can't be switched off or removed. The GUI names a key by
SearchKeyRef (a hash): POST /api/settings/search-keys (add, ref+on,
ref+remove, arrange) and /api/settings/search-key with ref. Saving an API
with no key keeps its keys, off ones too. Backup and WebDAV sync carry
the off keys, or leave them out with the rest. `magpie search` says
"+N off". docs/subsystems/gateway-routing.md has "The keys as a list".

Run (mote, at this tree, base 3441035a2):
- go test -count=1 ./internal/gui ./internal/provider ./internal/backup
  ./internal/davsync ./internal/cli: ok but gui's
  TestPanelHiddenByWailsMarksPageOutOfSight (#5322, mote, untouched) and
  cli's TestEveryRouteHasACommandOrIsNamed, then fixed (search-keys named
  S2) and run again: ok. ./internal/gateway search tests ok earlier.
- node --test search-key-list, search-keys, search-api, search-signs-in,
  search-order: 84/84, Chromium and WebKit, en/zh/zh-TW/ja/de, 1100 and
  420px (search-api/order at their own widths). i18n-keys: only "a
  plugin's words are its own" red, as on main (#5332, #5426, #5482).
- go build ./..., go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok. gofmt -l: clean.

Broken by hand, each red then restored:
- SetSearchAPI drops KeyList: provider and gui tests red.
- backup clears Key only / davsync merges Key only: their tests red.
- off keys still put in Key: provider, gui, backup and gateway red.
- the whole key in /api/state: TestSearchKeyListFromSettings red.
- no last-key-on check: TestSearchKeyList red.
- settings.js at HEAD: search-key-list.test.cjs red.

Not tried: a real Tavily account with several keys (the vendor is faked;
no test reaches the network); the real app window (the GUI ran in
Playwright only); Windows and Linux runs of the tests (vet only). The
full Go and GUI suites run after the push, under mote's suite lock.

Reported-by: 辰林鸭~ (Discord)
2026-11-07 21:21:48 +08:00
yetone 9072e2b888 settings: Sync's backup versions fold under Versions, its count and newest in sight (chen2652)
Settings › Sync › Back up by itself listed every kept version, each a row
with Restore…, and the list grows with Versions kept (up to 30). Now the
Versions row folds them: its name carries a chevron (turned down while
open), its name or the line under it opens and folds the list in place,
and the fold is kept over Sync's redraws for the window's life (closed at
first). The keyboard's focus stays on the fold over the redraw. Restore…,
Back up now and the restore's report are as before.

That line, "{n} backups · newest {when}", was one of the hint lines
Settings hides on a hover screen since 11-02, so on a desktop the count
and newest showed nowhere; it is a state, so it carries .say and stays in
sight. No new strings (the fold's text is Versions). Chevron turns in
.15s ease-out, none under reduced motion; no select, borders or gradients.
docs/subsystems/sync-backup.md says it.

Run on mote:
- auto-backup.test.cjs and sync-signins.test.cjs: 42 of 42 pass
  (Chromium and WebKit, 1100 and 420px, en zh zh-TW ja de). The new
  checks: the Versions line is in sight, the list folded at first, opened
  by its line with the page not moving (view scrollTop and the row's top
  the same 300ms on), folded by the chevron, opened by Enter with focus
  kept.
- Broken by hand: origin/main's autobackup.js and app.css under the new
  test: 11 of 11 red in Chromium (the line is a 1x1 hint, no fold).
- Full GUI suite, go vet ./... and go test -timeout 45m ./... (under
  lockf ~/suite.lock): not a valid run. mote's disk filled during it
  (138MiB free, 22GB in its temp folder): 8,673 ENOSPC failures, vet and
  go test could not write their builds. The reds that weren't ENOSPC are
  in files this change doesn't touch: account-eye, codex-auto-reset,
  gateway-caller-keys, gateway-key-models, header-centre, i18n-keys ("a
  plugin's words are its own": three plugin words also in Go files) and
  key-replace; not checked on origin/main, as mote had no room.

Not tried: the real app, a touch screen (where hints aren't hidden), the
full suites (above).

Reported-by: chen2652 (Discord)
2026-11-07 21:02:36 +08:00
yetone dbc74414bb claude: a relayed run keeps its prompt cache as long as the user picked, not always an hour
linkaww (Discord #feedback, server v0.1.3237 in Docker, Claude Code
2.1.319) set the Agents page's prompt cache for the main conversation and
subagents to 5 minutes, and settings.json had "5m", but 237 of 241
relayed requests since 11-01 wrote an hour's cache. cleanClaudeEnv took
CLAUDE_CODE_PROMPT_CACHE_TTL out of the run's environment and put back
"1h" every time (17363b7e3, #626), for every run, warm-up and model test
the bridge starts, -p and the interactive helper alike. Claude Code reads
the variable before the setting, and a saved account's Claude Code reads
its own folder's settings.json anyway, so the pick never reached it.

The hour was pinned because magpie marks the caller's instructions (or
the history's last whole chunk) in the run's first message, and
Anthropic refuses a 1h mark after a 5m one. That reasoning stays: the
run's lifetime and magpie's mark are now one value.

- claudeRunTTL resolves the user's pick as Claude Code 2.1.316 does:
  FORCE_PROMPT_CACHING_5M, then CLAUDE_CODE_PROMPT_CACHE_TTL (in magpie's
  environment or settings.json's env), then settings.json's
  promptCacheTtl. Nothing set (or a value Claude Code doesn't take) is
  an hour, as before.
- cleanClaudeEnvTTL gives the run that value; FORCE_PROMPT_CACHING_5M
  is now blocked too, since it is folded into the value (before, a user
  with it set got a 5m Claude Code under magpie's 1h mark).
- Request.cacheTTL / runMark: magpie's mark in the first message has
  the same lifetime.
- cachePrefix.ttl: a run going on from a saved session keeps the
  lifetime it started with, so an old 1h mark never sits under a newer
  5m pick (an older session with none is an hour's). A replayed session
  has no marks and takes the pick.
- The incoming request's ttl is not followed for ordinary requests:
  Claude Code 2.1.316 sends ttl "5m" explicitly as its default for a
  non-subscription endpoint (MTe: {ttl:"5m",reason:"default"}), so a
  5m mark can't tell a pick from the default, and following it would
  turn the hour off for everyone. Opted-in client marks
  (X-Magpie-Cache-Marks) already run with Claude Code's caching off and
  are unchanged.

Run (mote, at this tree on origin/main 9ed0f1fa4):
- go test ./internal/gateway/ (-count=1, 45m): ok, 980s.
- go vet ./internal/gateway/ on darwin, GOOS=linux, GOOS=windows: ok.
- gofmt -l internal/: clean.
- TestClaudeRunKeepsTheUsersCacheTTL: six cases (nothing picked, Agents
  page 5m and 1h, settings.json env, magpie's env, forced 5m) through the
  bridge with a scripted Claude Code that logs its environment and the
  first message it is told.

Broken by hand:
- "CLAUDE_CODE_PROMPT_CACHE_TTL=1h" put back in cleanClaudeEnvTTL: four
  of the six cases red (each 5m pick).
- runMark always 1h: the same four red on the first message's mark.

Not tried: a real Claude subscription request with 5m picked (no real
run, so the cache_creation split was not read from Anthropic); Docker
web mode; Windows and Linux runs of the test (it uses a shell script and
skips on Windows). The full go test ./... runs under the suite lock on
mote after the push. Idle runs are still kept an hour (idleLongest); with
5m picked that only holds the process longer. Branch sessions (cut
copies) carry no lifetime and take the hour, which is always a valid
order.

Reported-by: linkaww
2026-11-07 20:44:51 +08:00
yetone 21a89fa4e8 liveagent: a model or provider of magpie's deleted in LiveAgent stays out
zero2sin on Discord: every LiveAgent restart brought back magpie's three
providers as magpie wrote them (one Anthropic model, two OpenAI providers
of twenty or thirty models each) over what they had edited in LiveAgent.
LiveAgent's developer pointed at magpie, rightly: SyncCatalog runs at
magpie's start and on every catalog change, and LiveAgent's Sync wrote
every model of magpie's into magpie, magpie-responses and
magpie-anthropic each time. A model the user deleted, or a whole provider
of magpie's, came back on the next sync, and LiveAgent read it at its
next start. TestLiveAgentProvider even asserted that a model missing from
the file is put back.

magpie now remembers, per config.json, which of its models and providers
LiveAgent has had (liveAgentKept, in the stash). One gone from the file
since is the user's: it stays out until they put it back in LiveAgent, or
turn magpie off and on for LiveAgent. A model new to magpie's list is still
added, once. A provider of magpie's whose models the user all deleted is
left as they have it. The user's own providers were never touched and
still aren't.

LiveAgent's backend writes back what it holds on any settings change, so a
model magpie adds while LiveAgent runs is dropped by its next save without
the user doing anything. Such a model is held as pending under the
LiveAgent/k-brain pids then (liveAgentPIDs, pgrep): missing under the same
pids, or after LiveAgent quit, it is written again; once other pids run
(LiveAgent restarted and read it), it counts as had. Windows can't be asked
what runs, so there each counts as had at once.

Run (wsl-run, magpie-desktop; mote's disk is full, 553MB free): gofmt,
go vet ./internal/agent for linux, windows and darwin, go test
./internal/agent: every test passes but TestGrokInstalled, red on WSL2 at
main too (#3548, Windows binfmt interop takes the fake grok). On mote
before its disk filled: go test -run TestLiveAgent -v ./internal/agent,
all 10 pass.

New tests: TestLiveAgentKeepsWhatTheUserTookOut (the reporter's case:
magpie-anthropic and a Chat model deleted, a provider of their own added;
two syncs leave the file byte for byte; a new magpie model is added once;
a model put back stays; off then on gives everything back),
TestLiveAgentAddedWhileRunning, TestLiveAgentAddedThenQuit.
TestLiveAgentProvider now expects a deleted model to stay out and a model
new to magpie to be added on and last.

Broken by hand: take() returning want unchanged (the old behaviour) turns
TestLiveAgentProvider, TestLiveAgentKeepsWhatTheUserTookOut and
TestLiveAgentAddedWhileRunning red ("sync 0 undid the user's edits");
wrote() marking every added model as had turns
TestLiveAgentAddedWhileRunning and TestLiveAgentAddedThenQuit red.

Not tried: a real LiveAgent; the reporter's own config.json; a LiveAgent
that saves over a pending model and is restarted before any sync (reads
as the user deleting it, documented); baseUrl/apiKey/type edits on
magpie's providers are still magpie's and are written back.

Reported-by: zero2sin
2026-11-07 20:43:28 +08:00
yetone 3441035a2e routing: a group's member maps the reasoning level asked to the one sent
A Routing group that relays one long task across vendors sent every
member the same effort word, but one vendor's high is another's xhigh
(LuckymanJC on Discord). A member that follows the group may now carry
a map from the level asked to the level sent: Group.EffortMaps, json
effortMaps, keyed by the member's id as Members spells it.

- Default: no map, or a level the map doesn't name, goes as asked, so
  every group saved before is unchanged and nothing of the user's is
  overridden. A member fixed at an effort (or with several levels) and
  a rule's UseEffort still win over the map.
- SaveGroup keeps a map only for a plain member of the group (not
  :effort, not :a+b, not group/), drops pairs that send what was
  asked, lowercases, and refuses a word that isn't a reasoning level.
- Carried by member rename (groupfast RenameMember and the all-groups
  rename), provider rename, fold (and its fingerprint), share/import
  and CanonicalRef; on a collision the map already spelled so wins.
- Gateway: the level asked is the suffix's/agent pick, then the turn's
  pick, then the request's own (askedLevel: agentEffort, plus none for
  an Anthropic request with thinking disabled); the target is sent with
  withFixedEffort, fitted to the model's catalog levels unless none, and
  the trace's try records mappedFrom. Per candidate, so fallback and
  retries send each member its own; count_tokens sends no member effort.
- The group lists a mapped member's own levels plus the map's keys to
  agents (mappedLevels in buildGroupEntries).
- GUI: the member's reasoning menu has "Map levels…" (app menus only):
  a level asked, then As asked or one of the model's levels. The chip
  reads "Mapped reasoning", its title the pairs. Follow the group or a
  fixed level drops the map. zh, zh-TW, ja and de.
- docs/subsystems/gateway-routing.md says all of it.

Run (mote, at this tree):
- gofmt -l: clean. go vet (provider, gateway, gui), GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test ./internal/provider/: ok. go test -run
  'Effort|Level|Group|Fallback|Rule|Auto|Fixed' ./internal/gateway/: ok.
- node --test group-member-effort-map (30: chromium + webkit, en zh
  zh-TW ja de, 1100 and 420px) and group-member-levels: pass;
  i18n-en-no-cjk: pass. i18n-keys' "a plugin's words are its own" is
  red only for the three words it is red for on origin/main 922cc0ccf
  (#5332, #5426, #5482); this change's words are its own (two that Go
  source said too were reworded).
- go test -run 'Group|Budget|I18n' ./internal/gui/: ok.

Broken by hand, each red, then restored:
- gateway mappedLevel(nil, in): every TestMemberEffortMap* red.
- mappedLevels left out of buildGroupEntries: both levels tests red.
- group_share's rename left out: the import case red.
- RenameMember's rename left out: its case red.
- SaveGroup's cleanEffortMaps call left out: TestSaveGroupEffortMaps red.
- the editor save without effortMaps: 30 of 30 GUI red; moveTo's map
  cleanup left out: 10 of 30 red.

Not tried: a real cross-vendor relay with real accounts (the mapping is
checked on the request bodies the gateway sends to fake upstreams). The
CLI and TUI keep the map but have no editor for it. The full Go suite
and whole GUI suite run after the push, per the loop rules.

Reported-by: LuckymanJC (Discord)
2026-11-07 20:19:50 +08:00
yetone 922cc0ccf8 library: a plugin's tools hidden from every agent from its Plugins row
chengming0v0 (Discord) keeps a plugin for its providers but doesn't want
the MCP server it brings (minimax_query_video_generation and the rest)
shown to agents, and doesn't want to remove the plugin.

Before: a plugin that gives tools is a Library server of its own
(plugin_tools.go), switched per agent with the row's chips in Library ›
MCP, which held through updates and off/on. Nothing on the Plugins page
said so: its line read "Tools for every agent" whatever the Library had,
and an app at the router's address (/mcp/magpie/hub, agent "") was given
every server, ticked for any agent or none, so taking every chip off
still left the tools there.

Now:
- The plugin's tools line says "Tools for agents" or "Tools, hidden from
  agents", with Hide from agents / Give to agents beside the copy button
  (plugins.js, toolsServer in /api/plugins from library.PluginServers).
- PluginServerOn (servers/plugin-on {name, on}) sets Server.Hidden and
  keeps the agents it had in Paused. Hidden, no agent is given it and
  hubServers leaves it out for the router's address too. Give to agents
  gives the kept agents back; with none kept, the router's agents
  (hubAgents), or else every shown agent that can take it.
- It holds through a plugin update, the plugin off and on, an edit in the
  Library editor (SaveServer keeps it) and an agent's "every server"
  (serversAgents with no names skips a hidden one). Ticking an agent for
  it in Library › MCP shows it again (save clears Hidden).
- Library › MCP tags the server "Plugin", its tooltip pointing at Plugins.
- /mcp/magpie/tools (every plugin's tools, wired by hand) is unchanged.
- Docs: plugin-tools.md, mcp-router.md, site docs plugins (en, zh, ja).
- The core script budget is not raised: two plugins.js comments cut, the
  button's tooltips and status lines left out.

Run on mote at this tree (before the site docs, html only):
- go build ./..., go vet ./internal/library ./internal/gui, GOOS=windows
  go vet of both, GOOS=linux go vet ./internal/library: ok.
- go test -count=1 ./internal/library/: ok (187s).
- go test -count=1 ./internal/gui/ -run 'Plugin|Library|Budget|Script':
  ok (TestCoreScriptBudget 1,533,514 of 1,533,802).
- node --test plugin-tools.test.cjs (new: the line's words, Hide and Give
  posting {name, on}, the button inside its row at 980 and 420, all five
  languages, Chromium and WebKit): ok; builtins, every library-mcp-* and
  mcp-* file: ok.
- i18n-keys "a plugin's words are its own": red, the same three words on
  origin/main 61394481c (#5327/#5332, #5426, #5482); nothing of mine.
- library-mcp-first-click: one 1500ms wait red per run (chromium en 1100
  once, webkit zh-TW 1100 once) with several files at once; green alone on
  origin/main 61394481c. Not filed yet; the whole GUI suite comes next.
- site/worker.test.mjs: ok.

Broken by hand: without `!s.Hidden` in hubServers, TestPluginToolsHidden
is red ("hidden: still listed"); without the every-server skip, red at
"every server given to claude".

Not tried: a real MiniMax plugin or the real app; the whole GUI suite and
go test ./... (queued under the suite lock on mote after the push); a Go
test of toolsServer in pluginsState (the GUI test fakes /api/plugins);
Windows and Linux runs.

Reported-by: chengming0v0 (Discord)
2026-11-07 20:14:49 +08:00
yetone a2b552a34b library: a session-start hook can be narrowed to some starts (#5604)
A Library hook on "When a session starts" can now carry a matcher of
starts: one or more of startup, resume, clear, compact and fork (Claude
Code's words, library.HookStarts), joined by "|". NEKO-CwC's case is a
hook that re-injects a file after compaction alone; written whole, it
also ran at startup and once for every subagent fork.

Each agent's format was read from its own source:
- Claude Code 2.1.316 tests the matcher against source, which has all
  five starts. Its entry is written as given.
- Codex (codex-rs/hooks, rust-v0.165.0): SessionStartSource has the
  same five, and a "|" list is read as exact names. Written as given.
- Gemini CLI 0.63.0 has startup, resume and clear only, and its
  matchesTrigger compares the matcher whole. It takes one of those.
- Grok 1.0.67 tells only "new" (fresh, /new, /clear) from "load"
  (resumed). It takes a set that is exactly one of those groups.
- Cursor (cursor-agent 2026.10.01) takes no matcher: its Claude-hooks
  importer warns that a SessionStart trigger matcher "is not supported
  in Cursor, hooks will fire for all triggers".

startMatcher keeps the chosen starts that the agent has. With none
left, the agent is refused; with every one it has, it gets the hook
whole. An agent that can't run the hook at exactly the starts picked is
refused with why, and its chip is greyed, as for any other per-agent
limit. This is the least surprising choice. Widening the hook to every
start would run it at the very starts the user excluded (the fork runs
the issue is about), and a matcher the agent never matches would do
nothing without saying so. SomeHooksAgents (Select) gives a narrowed
hook only to the agents that can run it.

Tool-event validation is unchanged: only tool events take shell or
edit, and only session-start takes starts. check() refuses an unknown
start, a start named twice, an empty part and a wrong case. The matcher
as written is recorded in Applied.Hooks, so an agent's own edit of the
entry is still theirs, and is kept when the hook changes or is removed.

GUI: the editor shows an "At which starts" app menu for session-start
(openProtoMenu, no <select>), with Any start, A fresh session, A
resumed session, After /clear, After the context is compacted, A
forked session and Any start but a fork. HookAgentView.Starts and
StartSources tell the page which matchers each agent takes. A chip that
can't take the matcher greys with one of three reasons, in the editor
and on the row, and save leaves it out. Every new string is in zh,
zh-TW, ja and de. docs/subsystems/library.md's Hooks row says all this.

Run, at 7f60927fd (origin/main 61394481c + this), all on mote:
- go test -tags nogui -count=1 ./internal/library ./internal/backup
  ./internal/davsync: ok.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...:
  ok. gofmt -l: clean.
- node --test --test-concurrency=4 library-*.test.cjs (57 files)
  i18n-keys.test.cjs, both engines: 1183 of 1186 passed.
  - i18n-keys "a plugin's words are its own" is red for three strings
    already filed: #5482, #5426 and #5332/#5327. My "A new session"
    hit that test too (internal/claudetui says it), so it became "A
    fresh session".
  - library-mcp-json chromium "ja 390" timed out once. It passed 11/11
    run alone, twice. Filed as #5613.

Broken by hand:
- With the old hooks.go, TestHookSessionStartNarrowed and
  TestHookMatcherKeptToItsEvent fail ("session-start can't be narrowed
  to compact").
- With entry() writing no matcher and the sync check skipped, 17
  assertions fail: Claude and Codex are given matcher "", Gemini,
  Cursor and Grok get the hook whole, and no problems are shown.
- With the old client.js, library-hooks.test.cjs fails in every
  language, waiting for .lib-hookstart.

Not tried:
- No real agent ran a narrowed hook. The formats come from each
  agent's source and docs, not from a live session start.
- Old data: a hook saved before this has no matcher and is unchanged.
  A narrowed hook carried in a backup or sync to an older magpie is
  written whole there, because that magpie's sync doesn't check the
  matcher.
- The full go test ./... and the whole GUI suite run after the push,
  as agent-rules.md orders.

Reported-by: NEKO-CwC
2026-11-07 20:14:25 +08:00
yetone dec791f849 gateway: a Codex conversation's next turn goes on its kept socket as a delta
rem_thank on X: Codex sends a turn on its kept WebSocket as only its new
input after previous_response_id, while magpie opened a socket per turn
to chatgpt.com and sent the whole conversation, which a long one meets as
1009 (message too big).

A conversation's socket is now kept between turns (codex_socket_keep.go),
as codex-rs's WebsocketSession and get_incremental_items do it:
- kept for a turn that names its conversation (session-id/thread-id, else
  prompt_cache_key) and ended response.completed with an id, under a key
  of host, path, a digest of Authorization and chatgpt-account-id, the
  conversation ids and the subagent headers, so another account's turn
  never finds the socket nor names its response;
- taken out of the pool by the next turn, so two turns at once each have a
  socket and the last to end is kept;
- let go after 10 min idle, at 55 min from the handshake (the backend ends
  at 60), and the oldest past 32; the closes run outside the pool's lock,
  and no lock is held across a read;
- the turn goes as a delta when every field but input, client_metadata and
  stream_options is as the last turn sent it and its input starts with the
  last input and then that turn's output_item.done items (compared without
  id, status, nulls, empty lists, annotations, logprobs); anything else
  goes whole on the kept socket. It is compared on the body as it goes,
  after masking, so a turn masked otherwise goes whole;
- a kept socket that fails before the reply is handed on (closed while
  kept, the write fails, an error frame first such as
  previous_response_not_found or the connection limit) is closed and the
  turn goes whole on a new socket, and from there over HTTP as before.
The socket's dial context is detached from the request (the handshake
alone ends with it) and cancelled when the socket closes. The gateway's
tests drain the pool in socketOn's cleanup.

Tests (codex_socket_keep_test.go): the delta on one socket and an edited
history or another model whole on it; previous_response_not_found asked
again whole on a new socket; a socket closed meanwhile; another account
gets its own socket; idle let-go and no keep without a conversation; two
turns at once take the kept socket once; a turn after another reply goes
whole.

Run (first at origin/main 2683123c7, gateway and vets again after rebasing on 61394481c, the pushed parent):
- mote: gofmt -l internal (clean), go vet ./..., GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./..., go build ./... all ok
- mote: go test ./internal/gateway -run 'CodexSocket|CodexKept|
  CodexTurnGoesOverWebSocket' -count=3 -race: ok
- mote: go test ./internal/gateway -timeout 45m -count=1: ok (944s at
  2683123c7, 924s at 61394481c), with the Linux and Windows vet of
  internal/gateway again: ok
- Real account, sandbox HOME, dev build of this tree, through a counting
  CONNECT proxy: two turns of gpt-6-sol on the owner's Codex sign-in
  (passed through), the first with 40 KB of random hex. Both answered
  (ping, then pong) on one chatgpt.com connection; the first sent ~22 KB
  on the wire after the handshake, the second 395 bytes.

Broken by hand:
- delta always refused: SendsTheDelta, LostResponseGoesWhole and
  TakenOnce red
- the fields check off: SendsTheDelta red
- the input-prefix check off: SendsTheDelta red (edited history went as a
  delta)
- the output-prefix check off: OtherReplyGoesWhole red

Not tried: a real conversation long enough to have hit 1009 before; a
real previous_response_not_found (only the fake's); Codex itself driving
magpie's gateway over many turns with tool calls; Windows and Linux runs
of the tests (vet only).
2026-11-07 20:13:23 +08:00
yetone 61394481c7 agent: DeepSeek Harness Desktop is found on Linux (AUR, .deb, AppImage entry)
xianhongtao (magpie 0.1.3232, Arch Linux) has DeepSeek Harness Desktop
from the AUR (deepseek-harness-desktop 0.2.2rc.1-1) and no dsh CLI.
magpie knew the app on macOS and Windows only, so it said "DeepSeek
Harness CLI not found ~/.dsh/profiles/web/cordis.patch.yml".

HasApp for dsh now also finds the Linux app (linuxApp, desktopapp_xdg.go):
- a folder holding the Electron executable deepseek-harness with
  resources/app.asar beside it: /usr/lib/deepseek-harness-desktop (the
  AUR's) or /opt/DeepSeek Harness (electron-builder's .deb/.rpm);
- or the app's desktop entry in the XDG data dirs (XDG_DATA_HOME first,
  then XDG_DATA_DIRS, the first file of a name wins, Hidden=true hides
  it): Name=DeepSeek Harness, Type Application, MimeType holding
  x-scheme-handler/dsh, and its Exec program there (on PATH, or an
  absolute executable file: an AppImage anywhere). Scans of a folder are
  kept by its mtime, trusted only when read over a second after it
  changed and for a minute at most.
Linux only; macOS and Windows keep their own checks.

Siblings: everything reading HasApp for dsh follows: the profile a fresh
~/.dsh gets (profiles/desktop), the desktop lead and notices, cliHeld and
CLIMissing (so the GUI's and the CLI's "CLI not found" go away). The
"running" check for noticeDsh2 also knows deepseek-harness, the app's
Linux executable. With both profiles present (the reporter's case) Path
stays profiles/web as on macOS; the desktop lead picks the model shown.

Run (mote, through mote-run):
- go test -count=1 -race -run 'TestDshLinux|TestDshDesktop|TestCodexLinux|Lody' ./internal/agent/: ok
- go test -count=1 ./internal/agent/ ./internal/gui/ ./internal/cli/: ok
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; GOOS=linux/windows go build: ok
Run (wsl-run, magpie-desktop, Ubuntu 24.04): the TestDshLinux tests
-count=3: ok. The first WSL run caught a stale scan of a folder made
again within the same mtime tick; the 1s rule fixes it.

Broken by hand (mote), each red, then restored:
- installed() without onLinux: all three new tests red ("the AUR's app:
  app false, CLI missing true", "the AUR's entry, its program on PATH,
  not found", the profile = profiles/web, want profiles/desktop);
- no scheme check: "another app's entry taken for DeepSeek Harness's";
- no Hidden check: "an entry the user hid still counts".

Not tried: a real AUR, .deb or AppImage install of DeepSeek Harness
Desktop (the fixtures are the AUR PKGBUILD's entry and layout as the
reporter gave them, and AppImageLauncher's entry shape); the GUI suite
(no GUI file changed). The full suite runs after the push.

Reported-by: xianhongtao (Discord)
2026-11-07 19:48:49 +08:00
yetone e9bde2520d codex: OpenAI's threads follow Codex onto magpie from a provider of the user's, and a move the budget stopped asks for the next sync (Lice9735 on X)
Lice9735 on X, Windows, magpie 0.1.3233, Codex app 26.1104: an old chat
(10-13) answered "模型提供商不匹配 — 此聊天使用的是 OpenAI,但你当前
的提供商是 magpie。请切换至 OpenAI 以继续", only a new chat worked,
after d620ff6b5 and d2c29abe7. Their config.toml has a provider table
of their own, openai-http.

Cause. The banner is the app-server's modelProviderMismatch on
thread/resume (app 26.1103: providerBlock is set only from that error;
codex 0.167 load_for_resume compares the stored thread's provider, the
row for a paginated thread, the rollout's session_meta for a legacy
one, with config.toml's). With Codex on a provider of the user's at the
takeover, the stash's codex.provider is that provider, and bringOver
moved only its threads: OpenAI's stayed on openai by design ("whose
threads bringBack would hand them to"). The Codex app lists them and
refuses each one on magpie. A second gap on the same path: the
rewriting moves (MovePackedCodexThreads, MoveRecentCodexThreads) go
128 MB a sync, newest first, and the rest waited for a sync nothing
asked for, which can be hours away.

- bringOver, with Codex on a provider of the user's before magpie (not
  OpenAI, magpie or cc-switch-official, and no profile naming OpenAI),
  moves OpenAI's threads to magpie too: in place, a paginated one by its
  row, the last 30 days rewritten. They are recorded in codex.lent with
  that provider as To, as lendOwn records its own: the Disconnect gives
  every magpie thread to that provider (bringBack), where Codex resumes
  them, and giveLent gives these back to OpenAI once Codex is on OpenAI
  again. One the app holds open waits (codexThreadsLater on openai).
- MovePackedCodexThreads and MoveRecentCodexThreads say more when the
  budget stopped them with a thread left, and bringOver, bringBeside and
  lendOwn ask for the next sync at once (codexThreadsAgain). The three
  share one mover now (codexOnto); bringBeside also waits on a held
  thread as the other two do. packedBudget is a var, for the test.
- Tests: TestCodexOpenAIThreadsFollowMagpieFromOwnProvider (new: an
  openai-http table named "OpenAI", a plain and a packed OpenAI thread,
  moved, lent, to openai-http at the Disconnect, back to OpenAI after;
  none while a profile names openai), TestCodexThreadsLeftByTheBudgetAskAgain
  (new), TestMovePackedCodexThreads checks more. TestCodexThreadsFollowMagpieIn's
  two user-provider subtests now expect OpenAI's thread on magpie, then
  on that provider after the Disconnect.
- docs/subsystems/agent-wiring.md says so.

Run:
- Real codex-cli 0.166.0 on mote, sandbox HOME and CODEX_HOME, a fake
  Responses server: a thread started on the built-in openai (API key,
  openai_base_url), a second after switching to model_provider
  openai-http (name "OpenAI"); both paginated. On openai-http the first
  was refused ("This chat uses openai, but your current provider is
  openai-http"). A throwaway test (not committed) ran magpie's takeover
  (Set fake/m1, Sync) on a copy of that home: with origin/main's code
  the openai row stayed and `codex exec resume` on magpie (the copy's
  base URLs pointed at the fake) failed with exactly "This chat uses
  openai, but your current provider is magpie"
  (modelProviderMismatch); with this change the row was magpie,
  codex.lent {"to":"openai-http",...}, and the resume answered.
- New and changed tests red on origin/main 191f3c0af (the openai thread
  on "openai", want "magpie"; after the Disconnect "openai", want the
  user's provider).
- Broken by hand: bringOver's `if more` dropped ->
  TestCodexThreadsLeftByTheBudgetAskAgain red ("0 sync(s) asked for");
  `more = true` turned false -> TestMovePackedCodexThreads red.
- mote: gofmt -l clean; GOOS=windows go vet and GOOS=linux go vet
  -tags nogui of internal/agent and internal/sessions ok;
  go test ./internal/sessions ./internal/agent ok at this head
  (this change on e6cdeac9c; rebased after onto 5dbdfc1bd, which
  changes internal/provider only), agent 292.2s, sessions 47.4s. Pushed and tagged
  without waiting for the full `go test -timeout 45m ./...`, per the
  owner's rule to ship each verified fix at once; it runs on mote after
  another session's suite, and a red it shows is filed or fixed in a
  follow-up.
- win-run (xiaomi-gpu), go test ./internal/sessions ./internal/agent
  (at the commit's parent before a rebase onto abe7b0063, which touches
  neither package): every test this change adds or touches passes; 29
  reds, 28 of them red the same at origin/main 191f3c0af run alone
  there. The 29th, TestHermesProfilesFollowMagpieModel, passes alone
  3/3 on this tree and is in #4115.

Not tried: the Codex app itself (the CLI's app-server gives the same
error the app shows); Windows with a real Codex; a legacy (non-paginated)
thread with a real Codex, covered by the unit tests only; a history
over 128 MB with real files. The chat the app has loaded at the switch
goes on once the app lets it go: fully quit the Codex app and reopen it
after magpie updates.
2026-11-07 18:08:39 +08:00