Commit Graph
1989 Commits
Author SHA1 Message Date
yetone 3fc6ee4111 site: release files from Cloudflare R2, GitHub behind them
Updates and the installer downloaded every file from github.com, which
answered 504 for every release file for hours on 2026-11-08. The site now
keeps a copy on R2 (bucket magpie-releases, binding RELEASES):

- A five-minute cron copies the newest release and the Stable one from
  github.com (or, when that fails, GitHub's API) into R2. R2's put takes a
  file only with the SHA-256 the release's SHA256SUMS gives. A run starts
  no copy after 4 minutes; the feeds' tags and the 4 newest besides are
  kept, older ones deleted.
- /files/<tag>/<file> serves R2's copy, Range and conditional asks
  included; a file R2 doesn't hold, or a failing R2, is a 302 to
  github.com.
- /api/latest (both channels) and /download name /files only for a file
  R2 holds under the release's hash, and give every file's github.com
  address as `github`, which the previous commit's clients fall back to.
  Older clients only mirror a github.com address, so a mirror never goes
  in front of the site's.
- start (en, zh, ja), privacy (en, zh, ja) and reference.md say where
  files come from.

Run (mote): node --test site/*.test.mjs 104/104, with files.test.mjs
(R2 stood in for by r2stub.mjs) and new worker tests for the feed,
/download, /files and the cron. wrangler deploy --dry-run binds RELEASES.

Broken by hand: onR2 taking any held file regardless of hash, two tests
red (the feed test and "bytes R2 holds under another hash").

Not tried yet: the real cron run and R2 serving (after deploy).
2026-11-09 05:48:23 +08:00
yetone 82ca554be9 routing: a provider's accounts routed In order give a conversation back to the first
CryptoSarom on X: with a provider's accounts set to In order, a
conversation that had moved to the second account (the first was
resting) stayed on the second once the first was ready again. Only a
group's members went back to the first; a provider's own accounts never
did, because inOrder was read from the group's routing alone.

- gateway.go: inOrder comes from the provider's routing, or the group's
  when the request is to a group.
- affinity.go: backToFirst compares accounts (who()) for a provider's
  own accounts. For a provider it overrides only a cache that would have
  kept the conversation (cacheHolds: worth keeping and still warm), so a
  cold or empty cache keeps its own "cold"/"new" label.
- plugin_factory_cap_test.go: "auto, cached on B" pinned the old
  stay-on-B behaviour; it now expects A, the first account, on purpose.
- GUI: the Routing affinity line for "order" without a group says the
  provider goes in order and the first is ready again (all languages).
- docs/subsystems/gateway-routing.md: the In order bullet covers a
  provider's own accounts.

Run on mote at this tree on aa3d11d5b; rebased onto c6702f462, which changes only context.css and its own GUI test: gofmt -l clean,
GOOS=linux and GOOS=windows go vet ./internal/gateway ok, go test
./internal/gateway -count=1 -timeout 45m ok (985s).
GUI: routing-affinity-order (new accounts case) and i18n ok in both
engines. i18n-keys "a plugin's words are its own" is red from three
strings not in this change, filed as #5332, #5426, #5482.

Broken by hand: inOrder := false turns
TestOrderedAccountsGiveTheConversationToTheFirst red (k1 k1 k1 k1, why
"cache"). Without cacheHolds TestForeignSealedItemsAfterAColdSwitch went
red (why "order" for a cold switch).

Not tried: a real account pair in the live app.
2026-11-09 05:42:44 +08:00
yetone c6bdc172a0 netguard: a fake-IP resolver's own AAAA beside its fake A is left out, not refused
jiezhengj (Discord, 11-08): under Clash Verge Rev's TUN (mihomo
1.19.33, enhanced-mode fake-ip, fake-ip-range 198.18.0.1/16) every
web_fetch of `magpie mcp search` answered "it is at a private address".
#2593 already lets a name whose every answer is in 198.18.0.0/15 through,
so that wasn't it. Clash Verge Rev writes dns.ipv6: true and
fake-ip-range6: fdfe:dcba:9876::1/64 into its default config (and fills
in 2001:2::/64 when IPv6 is on without one), and mihomo then answers
AAAA from that pool too (dns/middleware.go withFakeIP, read at
v1.19.33). The resolver's answer was 198.18.x.y beside fdfe:dcba:9876::z,
the ULA is private, a fake answer beside a private one is refused, so
every name failed.

netguard.FakePaired names that AAAA: an IPv6 address in fc00::/7 or
2001:2::/48 while the same answer holds an IPv4 one in 198.18.0.0/15.
It is dropped where Loon's paired AAAA is dropped (dropLoon in the
gateway's publicTransport, iconIPs for a provider's icon, the two
places that share netguard), and the fake A is judged and pinned in its
place. 2001:2::/48 (RFC 5180 benchmarking) joins Public's special ranges;
it wasn't covered by 2001::/32 and passed as public.

Why this opens nothing new: the AAAA is never dialled. What is dialled
is the fake A, exactly as when the resolver answered the A alone, which
#2593 already allows: an address in 198.18.0.0/15, which no host on a
normal network uses, so without a TUN it goes to the default route and
reaches the internet or nothing. A hostile DNS that pairs 198.18.0.9
with fd00::<a LAN host> gets the 198.18 address dialled, never the LAN
one. Through a proxy on this computer the proxy gets the name, as for a
pure fake answer; a hostile resolver could already give a proxy another
answer for that name than it gave magpie, so the pairing adds no route.
What stays refused (tests below): a ULA or 2001:2:: alone or beside a
real A, a fake pair beside 10.0.0.1 or ::1, a fake A beside a public
address, and ULA / 2001:2:: / 198.18 address literals.

Ran (on mote; whole packages at base f1a4b5751, the -run set, vet and
gofmt again after the rebase onto the next main):
- go test ./internal/netguard ./internal/provider ./internal/gateway
  -run 'FakePaired|FakeIP|Loon|Icon|Public|Fetch|Guard|Private': ok
- go test -timeout 45m ./internal/netguard ./internal/provider
  ./internal/gateway (whole packages): ok (netguard 0.2s, provider
  130s, gateway 838s)
- go vet for darwin, GOOS=linux and GOOS=windows on those packages,
  gofmt -l internal cmd: clean

Broken by hand: with netguard.go, image_fetch_guard.go and icon.go back
at origin/main, TestFakeIPWithItsIPv6Answer fails with the reporter's
own message ("couldn't fetch http://example.com/: it is at a private
address ..."), TestFakeIPRefusesTheRest lets http://[2001:2::7]/
through, and TestIconIPsLoon refuses fdfe:dcba:9876::5 + 198.18.0.5 and
keeps 2001:2::5. Green with the fix.

Not tried: a real Clash Verge Rev / mihomo TUN on mote or the Mac (the
answers are a fake resolver in the tests, nothing reaches the network);
sing-box's inet6_range is covered only as far as it is a ULA. Not run:
the full ./... suite (mote's suite.lock had five full runs queued).

Reported-by: jiezhengj (Discord)
2026-11-08 22:55:09 +08:00
yetone 7a56c83e72 gateway: a compaction Copilot sealed stays out of Codex's auto-review
echo_ts (Discord #feedback) runs Codex Desktop's turns on GitHub Copilot
through magpie, with Copilot's native compaction on, and Codex's
auto-review on its built-in codex-auto-review through the ChatGPT
sign-in. The guardian's review carries the conversation's history, so
after the first compaction it carried Copilot's sealed compaction item
too. A request for one of Codex's own models with no magpie Codex
account to route it is relayed to the sign-in as it came, and
codexInputAs keeps any non-magpie1: compaction ("OpenAI's own, for
OpenAI"), so OpenAI was sent Copilot's ciphertext and refused every
review: 400 invalid_encrypted_content "The encrypted content P4ih...bDU
could not be verified". After the next compaction, the new ciphertext.

The siblings: a side call routed through magpie (the auto-review set to
a magpie model, a subagent or a title on another provider's model)
met checkpointReaders, found no writer among its candidates and was
refused with checkpointError, so the review failed there too. A turn or
a /responses/compact on one of Codex's own models relayed to the sign-in
sent the seal to OpenAI to be refused (sealedCompact took a Copilot
writer for the sign-in's own and relayed it).

Now:
- compactionAside names the calls Codex makes beside the conversation
  with its history in them: the guardian (or anything asked on
  codex-auto-review), memory, subagent, title, description, thread
  summary, prediction and suggestion. In serve, when the writer of the
  sealed compaction isn't among such a call's candidates, it goes on
  without the compaction item (withoutCompaction, body and plain);
  instructions, developer/user messages, the turns since and their tool
  calls and outputs stay. The conversation's own turns are still held
  to the writer or refused saying why (#1099), unchanged.
- foreignToSignin: on the relay to Codex's own sign-in (codexBackend), a
  compaction magpie recorded as sealed by a provider other than the
  Codex subscription is never relayed. A side call goes without it; a
  turn or a /responses/compact is answered checkpointError, magpie's
  own explanation, with nothing sent to OpenAI. A seal with no record
  (OpenAI's own, compacted on the sign-in), one the codex provider
  sealed, and one whose provider can't be read are left as before.
No portable plaintext summary exists for a native compaction (only the
writer can read it), so the side call goes without it rather than with
a summary.

Run (on mote, through mote-run, at 9730e0199 + this change):
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/usage/: ok (gateway 926s, usage 35s)
- go test -run 'TestForeignCompaction|TestNativeCompaction|TestCodex'
  ./internal/gateway: ok, again after rebasing onto f1a4b5751
  (which changed internal/gateway: trace.go and others)
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  ./internal/gateway; GOOS=linux go build -tags nogui, GOOS=windows go
  build: clean; gofmt -l internal: clean

Broken by hand: with the three non-test files at 9730e0199,
TestForeignCompactionLeftOutOfAutoReview is red in 4 subtests: the
review through the sign-in gets the reporter's exact 400 ("The
encrypted content P4ih...bDU could not be verified ...
invalid_encrypted_content"), the review and a subagent on another
provider's model are refused "compacted natively by copilot@student",
and a gpt-5.5 turn and its /responses/compact sent Copilot's seal to
OpenAI.

Not tried: the reporter's real Codex Desktop, Copilot or ChatGPT
account; the shape is from their report (Copilot compaction item with
encrypted_content, guardian on codex-auto-review). A Copilot compaction
magpie has no record of (made before compactions.json, or older than
30 days) still goes to the sign-in as before. No full ./... run: mote's
suite lock has had full suites queued for 4h; the change is confined
to internal/gateway.

Reported-by: echo_ts
2026-11-08 22:33:12 +08:00
yetone f1a4b57511 agent: Claude Science goes back on magpie after its app starts its own daemon
shuitunlulu_ on Discord: after magpie connected Claude Science, it went
back off magpie. The daemon reads the gateway only from its environment's
ANTHROPIC_BASE_URL. The 0.1.72 app (Electron) attaches its window to a
daemon running; with none it starts its own (`serve --stdio
--adopt-install`, launch_context app-child) in its own environment, which
has no such variable. Its "let the app run it instead", and the offer it
makes once it updated past the daemon, stop magpie's daemon to do the
same. The keeper only started a daemon when none ran, so the app's stayed.

KeepClaudeScience now puts magpie's daemon back on the port the other was
on (stop, serve --detached with the variable) in three cases: a daemon
magpie didn't start, one started for the gateway's old address, or its
own older than the program installed (`--version`, asked again only when
the file changed). It does this only when status says no session runs
(active_frames and active_conversations 0; a status without them counts
as busy). It never touches one launchd or systemd keeps, and does it at
most three times an hour. It reads operon.lock every 10s and asks status
when the lock's pid changed or a minute went by.

Run:
- go test ./internal/agent (mote): ok 261s
- gofmt -l, go vet for darwin, linux and windows (mote): clean
- Real Claude Science 0.1.72 on mote, the keeper driven through a
  throwaway test (not committed) against the real claude-science:
  - App attached to a terminal daemon: status parsed (idle, terminal),
    the daemon was replaced on port 18481 and the new one has
    ANTHROPIC_BASE_URL. shell.log says "adopted daemon restarted
    (45446 → 89598) — following the successor", so the window carried on.
  - App opened with no daemon: it started its own (app-child, port 8000,
    no ANTHROPIC_BASE_URL in ps -E). The keeper replaced it on 8000 with
    the variable, and the app showed its "stopped from the command line"
    screen. Reopening the app attached it to magpie's daemon
    (ADOPT-RUNNING).
- Broken by hand, each red: no idle check (the busy and unknown-status
  cases), no retake cap, no version skew, no lock-pid trigger.

Not tried:
- The screen's "start it again in the app" button (read in main.js:
  runInvariant adopts the daemon running; reopening the app did the
  same).
- A daemon with a session running: one would need a Claude sign-in.
  The fake covers it.
- The Windows attach shell, and Linux.

Reported-by: shuitunlulu_
2026-11-08 22:30:07 +08:00
yetone 9bef67d420 gateway: Claude Code's and Codex's requests reach a Remote magpie as magpie's, so it takes X-Magpie-*
linkaww (Discord #feedback, Mac v0.1.3315 to a Docker remote v0.1.3288):
a capture showed X-Magpie-Claude-Cache-TTL reaching the remote on a
request whose User-Agent was claude-cli/2.1.319, not magpie/. The
remote takes X-Magpie-* only from a magpie's request (magpieAsks), so it
dropped the cache lifetime (Opus still 5m, Haiku 1h), the agent, the
computer (X-Magpie-Via), X-Magpie-User-Agent, and X-Magpie-Hops, the
guard that answers 508 when two magpies are each other's remote.

Cause: forwardOnce sets magpie's User-Agent for a Remote magpie
(userAgentFor, OwnClient), then #179's copy of Claude Code's headers
(p.Account == nil) put claude-cli/... back over it. Codex had the same
hole: its copy (codexClientHeader) puts codex_cli_rs/... on too, which
keepTurnAsks had already worked around.

Fix, on the sending side: after every copy, a request to a Remote magpie
goes with magpie/<Version> (forwardOnce). Decision, retrieval, image and
video requests already set it at their call sites and copy no client
header. On the receiving side, so a relay behind the remote that serves
only Claude Code or Codex still gets their headers: the remote knows
Claude Code by the User-Agent the near magpie named (claudeCodeAsks,
agentUA) for #179's copy, ?beta=true, the test-as record and Desktop's
move, and both copies put on the agent's User-Agent (agentUA), not the
magpie/ one that came in. Codex is known there by its originator, as
before. A key+URL provider that is not a magpie still gets Claude Code's
and Codex's own User-Agent (TestClaudeCodeHeadersReachAnthropicRelay,
TestRemoteMagpieClientHeaders).

The reporter's guess that this empties the remote's Usage > Sessions is
not borne out: with the bug the remote still recorded each call's
session id (x-claude-code-session-id was copied), only under agent
"claude-cli" with no via. Filed separately.

Run (on mote, mote-run, at this tree):
- TestRemoteMagpieTakesClientsHeaders (new): Claude Code and Codex
  through two in-process gateways to a relay. The remote is asked as
  magpie/, with X-Magpie-User-Agent; callerFrom on what it got reads agent,
  via, hops 1, the relayed UA and the TTL 5m picked in settings.json; the
  relay gets the agent's UA, originator, x-app and ?beta=true and no
  X-Magpie-*; the remote's record names the agent and a via.
  Red on the old gateway.go: UA claude-cli/codex_cli_rs at the remote,
  agent "claude-cli", via "", hops 0, ttl "".
- go test -tags nogui ./internal/gateway -run
  'Remote|ClaudeCode|Codex.*Header|UserAgent|ClaudeCacheTTL|Desktop|SawClient|TestAs|Hops|Loop': ok.
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway: clean.
Broken by hand:
- the magpie UA reset taken out: the new test red in both subtests
  (remote sent claude-cli/codex UA, nothing taken).
- the remote-side detection put back to fromClaudeCode(in) and the copies'
  UA left as it came: the new test red (x-app and ?beta=true lost,
  relay sent magpie/dev) and TestRemoteMagpieClientHeaders' three Codex
  cases red 403.
Not tried: a real Docker remote or a real Claude Code; the full suite was
not run at push (run after). The remote must update too for its relays
to send them as the agent: an older remote, asked as magpie/, copies no
Claude Code x-app, X-Stainless-* or ?beta=true to its relay, and puts
magpie/ over Codex's User-Agent there (it is known by its originator), so
a relay behind it that serves only Claude Code or Codex refuses until it
updates. The TTL, agent, via and hops need only this (sending) side.

Reported-by: linkaww
2026-11-08 19:10:30 +08:00
yetone d1f8d8aae7 agent: Cherry Studio adds magpie through its providers link (plugins#865)
Cherry Studio (CherryHQ) shows on the Agents page, and with
`magpie cherrystudio`, on macOS, Windows and Linux. Its row is the link
its main process takes, cherrystudio://providers/api-keys?v=1&data=, with
the gateway at <gw>/v1 as an OpenAI-compatible provider named magpie and
the named key agentKeyAt("cherrystudio"). Cherry Studio asks the user to
confirm it. magpie writes nothing into its store. "Added" is read
untouched from its 2.x database (Data/cherrystudio.sqlite, user_provider),
in the default userData and every one boot-config.json moved it to. A
database or boot-config that can't be read, or a 1.x userData (Local
Storage, no database), is unknown. The data is standard base64, because
Cherry Studio swaps raw + and / before parsing and back after. /api/open
lets that link through. aionui's database status is generalized into
dbStatus{has} so both apps share it. Icon: Cherry Studio's own logo, not
cherryin-color (a different product).

Run (mote, at this change on origin/main c66cdbea9; then rebased on
0f04dca6e and run again: vet of agent/gui/cli, Windows vet of agent/gui,
and the Cherry, AionUi, gateway-key and import-link tests, ok):
- gofmt -l clean; go vet ./internal/agent ./internal/gui ./internal/cli;
  GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- go test -tags nogui -count=1 ./internal/agent ./internal/gui
  ./internal/cli: agent and cli ok; gui ok but TestCoreScriptBudget, red the
  same on a clean c66cdbea9 (#4526, 1533856 > 1533802)
- node --test import-row.test.cjs i18n-keys.test.cjs: import-row 20/20,
  chromium and webkit, en/zh/zh-TW/ja/de, and 420px wide; i18n-keys red
  only on "a plugin's words are its own", the same on clean c66cdbea9
  (#5332, #5426, #5482). No new strings.
- TestCherryStudioLinkParsedAs2_1_10 runs the link through 2.1.10's own
  parser (copied into testdata) and the renderer's zod checks, with
  gateways whose base64 spells + and /.
- Real try on mote (macOS 27.2, arm64): released Cherry Studio 2.1.10 in a
  sandbox HOME and --user-data-dir, with a sandbox magpie of this tree on
  127.0.0.1:3561 and a fake upstream. `magpie cherrystudio add` opened the
  dialog with base URL http://127.0.0.1:3561/v1 and the key
  magpie-cherrystudio. Add saved it, turned off as every Cherry provider
  is. `magpie cherrystudio` then said added, read while the app ran (WAL).
  Sync models listed fake/fake-1 from the gateway, and adding it turned
  the provider on. A chat got the fake upstream's reply, and magpie usage
  counted it as Cherry Studio's. A link sent while the first-run welcome
  page was up showed no dialog; after "set up later" it did.

Broken by hand, each red, then restored:
- URL-safe base64: TestCherryStudioLinkParsedAs2_1_10 (baseUrl decoded as
  /x~>/v1 and /xy\x7f?/v1)
- no closing quote/slash on the address match: TestCherryStudioHas
  (another port's provider counted)
- the /api/open prefix dropped: TestCherryStudioImportRow
- Cherry Studio dropped from /api/open's app case:
  TestImportLinkNothingOpens

Not tried: a real run on Windows or Linux (detection is unit tests
only); Cherry Studio 1.x, which reads as unknown; a real vendor upstream
(the try used a fake). Full suite not run at push.

Reported-by: mysterysqwq
2026-11-08 19:09:21 +08:00
yetone c66cdbea97 update: a release file github.com won't serve comes through GitHub's API
On 2026-11-08 github.com answered 504 for every file of
yetone/magpie-releases (…/releases/download/<tag>/<file>) for hours, while
api.github.com/repos/yetone/magpie-releases/releases/assets/<id>, asked
with Accept: application/octet-stream, redirected to the same bytes.
Every self-update and the install script failed (kurutodenzeru, wjbdx,
isee1_1 on Discord). Retrying the same address (a46190e1f) can't help.
The site's feed was stuck at 0.1.3318 too: its SHA256SUMS read went to
the same address.

- internal/update: download() goes to the API route at the first busy
  status (5xx/429), or for the last try after connection errors. The
  feed's new per-asset `api` is used as it is; without it the address is
  looked up from the release's tag (apiroute.go). The file is checked
  exactly as before: the feed's SHA-256, and Stage's signing-team check on
  the Mac. A mirror the user set keeps precedence: through one, no API
  route is tried (its whole point is that GitHub isn't reachable). This is
  the one download every caller uses: the app's update, the CLI's
  `magpie update` and serve's auto-update.
- site/public/install.sh: when the feed's github.com URL fails and no
  mirror is set, it downloads through the feed's `api` (else looks it up
  with curl+sed, no jq), and checks the same SHA-256.
- site/worker.js: the feed lists `api` per asset. SHA256SUMS is read
  through the API when github.com fails. While it does, each file's `url`
  is usemagpie.ai/dl/<tag>/<file>, which 302s to the address GitHub's API
  gives (only *.githubusercontent.com or github.com, https), so an older
  magpie, which follows `url` only, updates too, still checked against the
  feed's SHA-256. That feed is cached 60s instead of 300s, so it goes
  back to github.com's URLs soon after github.com recovers.
- docs/reference.md: the API route, and that a mirror keeps precedence.

Run:
- mote: go test -tags nogui -count=1 ./internal/update (ok 20.3s).
- mote: node --test site/install.test.mjs site/worker.test.mjs
  site/stable.test.mjs: 76 pass.
- gofmt -l internal/update: clean. mote: GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet -tags nogui ./..., GOOS=windows go vet
  ./internal/update ./internal/cli ./internal/gui: clean.
- Real, on the Linux box (wsl-run, magpie-desktop) at 10:50Z: a nogui
  build stamped 0.1.3000, `magpie update` in a sandbox HOME
  (MAGPIE_ADDR=127.0.0.1:9). MAGPIE_UPDATE_FEED was a local feed whose
  magpie-cli-linux-amd64 url answered 504, with the real `api` of
  v0.1.3319 and the sha256 from the real SHA256SUMS. The download address
  was asked once and got 504. The file came through api.github.com, and
  the binary was replaced with exactly 89fff184… and reports 0.1.3319.
- Real: install.sh's apiroute sed against api.github.com's full
  v0.1.3319 description found the right asset id for 5 files
  (723602745 for magpie-cli-linux-amd64, the same as Go's lookup).
- Full suite: not run at push; it runs after.

Broken by hand:
- No switch to the API route in download(): 3 of the 4 new Go tests red
  ("504 Gateway Timeout, on every try").
- Mirror check and the octet-stream Accept removed:
  TestMirrorKeepsPrecedenceOverTheAPIRoute red, and
  TestDownloadGoesThroughTheAPIWhenGitHubIsBusy red (checksum: GitHub's
  JSON description instead of the file).
- worker: no API read of SHA256SUMS, no /dl location cache, and no check
  of the redirect's host: each red.
- install.sh: no API fallback, then no mirror guard: each new install
  test red.

Not tried:
- The real outage itself: github.com had recovered (302, slowly) by the
  real run, so the 504 was a local server's and the API route was real.
- An old magpie through the deployed /dl route against a failing
  github.com; it is covered by the worker test only.
- install.sh end to end against the real API (only its lookup); the Mac
  app's Stage through the API route (only the fake tests, which keep the
  signing-team check unchanged).
2026-11-08 18:52:32 +08:00
yetone b0926e81a2 import: a link can say where its key's balance is read (balance=, balance_path=, balance_method=)
A relay's "Add to magpie" link can now name the URL that tells a key its
balance, where the amount sits in the reply, and GET or POST. magpie
takes it only on the host of one of the link's own base URLs, over
https, with no userinfo or fragment, so a link can't send the key
anywhere its requests don't already go; anything else refuses the whole
link. balance_path or balance_method without balance is an error. No
header or token is taken from a link: an account-wide token is worth
more than a key, and a URL stays in browser history.

- provider.ParseImport: linkBalance checks and sets BalanceURL,
  BalancePath and BalanceMethod.
- CLI: the import preview shows the balance URL and doesn't ask it
  before yes (showProviderAsking).
- GUI: the import dialog shows method, URL and field (.imp-bal).
- Docs: docs/import in en, zh and ja (table rows, a note on headers,
  the builder's three fields with the same host check, a security
  bullet); docs/reference.md's parameter table.

Run on mote at this tree (rebased on 8fa3c60f8):
- go test -count=1 ./internal/provider ./internal/gui: ok
  (TestParseImportBalance, TestCoreScriptBudget in it).
- go test ./internal/cli: ok but TestEveryRouteHasACommandOrIsNamed,
  red on main since f418edffc (GET /api/context/session); fixed in the
  next commit, and ok there with -run 'TestEveryRoute…|Import'
  (TestImportPreviewAsksNoBalance).
- GUI import-link-balance, import-link-gemini, i18n-keys: 43/44. The
  red is i18n-keys "a plugin's words are its own", the same three
  strings on an origin/main 8fa3c60f8 copy (#5327, #5426, #5482).
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of provider,
  cli, gui: ok. gofmt -l: clean.

Not tried: a real link with balance= imported into the app and read
against a real relay's balance endpoint.
2026-11-08 18:37:41 +08:00
yetone 8fa3c60f80 claude: an interactive run takes many images between words (#5654)
Chapin2018's message of nineteen images between words (the issue's
script, Claude Code 2.1.319, claude-fable-5-1) ended the interactive
helper "after 13s (exit status 1)" and the client got a 502, while -p
answered. The cause is how the helper saw a paste taken. It looked for
"[Image #N]" and "[Pasted text #N" only in what Claude Code drew after
the paste. Once the prompt runs past a row, Claude Code draws it again
only where it changed and moves the cursor past cells that are already
right. After the 33rd piece the drawing held "\r\x1b[16C\x1b[1B3": one
digit of "[Image #33]". The helper waited out pasteWait (10s) and ended.
Text marks came out in part too ("[Pasted t xt #16"), so several word
pieces each sat out their own 10s before that. There is no limit in
Claude Code's TUI: the same paste is on its screen whole, so no -p
fallback is needed.

Each check now also reads the prompt as the 200x50 screen grid shows
it: the rows between its last two rules, words one space apart (a mark
can wrap onto the next row). The mark that ends it counts (lastMark),
an image's [Image #N] or a whole [Pasted text #N +k lines], numbered
past the piece before, and so do words the prompt ends with. The
stream check stays first.

Run:
- Real, macOS arm64, this Mac, sandbox HOME and CLAUDE_CONFIG_DIR
  (token by env, nothing rotated, DISABLE_AUTOUPDATER=1), the issue's
  script unchanged, --images 19, Claude Code 2.1.319:
  - origin/main a46190e1f: exit 1 after ~32s, stderr as reported.
    2.1.316 failed the same way. -p: success, 5.8s.
  - This change: exit 0 in 5.3 to 12.1s on 5 runs, subtype success.
    The transcript's user row has all 19 image blocks and the words in
    order, and the model answered. The script's answer_ok stays false
    because the helper's result line has no "result" text (-p's does).
    The gateway reads the assistant events, not that field.
- TestShimSeesPastesOnAPromptDrawnInPart feeds the real run's bytes
  (testdata/paste-images-2.1.319.bin, folder name replaced at the same
  length). Each of the 33 pastes must be seen taken.
- Broken by hand: drop the prompt checks from imageTaken and textTaken
  and it goes red on text 12, text 22 and image 33, the pieces whose
  marks were drawn in part.
- WSL magpie-desktop (Ubuntu 24.04 amd64, go1.26.8), because mote is
  down:
  - gofmt -l . is clean.
  - go vet -tags nogui ./... and GOOS=windows go vet ./... pass. Plain
    vet there lacks gtk4 headers.
  - go test ./internal/claudetui/ is ok (120s).
  - The darwin build used for the real runs above.

Not tried: Linux arm64 (the reporter's system) with a real account, the
gateway's /v1/messages path end to end with 19 images, and the full
suite (not run at push).

Refs #5654: kept open for the reporter to confirm.

Reported-by: Chapin2018
2026-11-08 18:24:16 +08:00
yetone f418edffc3 sessions: a session's details show how full its context was, request by request
liang_yongxiang on Discord: Routing tells how full one request's context
window was; does Sessions have the same, each turn's share?

A session's details on the Sessions page (and in Usage's Sessions list,
which draws the same details) get a Context line when the gateway sent
calls of it (s.via): the Context tab's spark of its prompts, request by
request against its window, and the fullest one's share beside it, toned
as the tab tones it. A point's tip says "Request 2: 80K of 200K (40%)" (the
tab's spark says it too now, where the window is known); a point clicked
opens that request in Routing with its card. A session the gateway never
saw asks nothing; one it kept no prompt of shows no line.

The data is the routing history the Context tab already reads. A new
GET /api/context/session?agent=&id=&from=&to= reads only the days from the
session's first to its last (30 at most), through the tab's per-day cache
(daysRecsLocked, split out of contextRecsLocked, so the tab's cached days
are not evicted), and keeps that one session (contextOfRecsFor), with up
to 1000 of its requests. The tab keeps the latest 80 sessions and would
leave an older one out. Subagent and side calls are left out as the tab
leaves them out; the same id under another agent is that agent's.

The line's code is in plugins/usage/page.js (sessCtxLine). context.js only
exports spark and health, and pays for its tip by cutting comments, so
the core's scripts are 10 bytes under main's, no budget raise.

Run at this head (rebased on e215d335a), on WSL (magpie-desktop, Linux;
mote rebooted mid-run):
- gofmt -l clean; go test -tags nogui -run
  'TestContextSessionLine|TestCoreScriptBudget|TestContext' ./internal/gui/: ok
  (also ok on mote at this head).
- node --test sessions-context-line (new: Chromium and WebKit, en zh zh-TW
  ja de, 1100 and 420 wide) and context-window: 44 of 44.
Run on mote before the rebase, at 627fd1a3b:
- the whole internal/gui package: its one red, TestCoreScriptBudget
  (1,536,110 > 1,533,802), is why the line moved into the plugin.
- sessions-context-line: 20 of 20.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- i18n-keys: "a plugin's words are its own" red, the same on origin/main
  e215d335a (#5327, #5332, #5426, #5482); the new strings pass its other
  checks.

Broken by hand:
- the one-session filter dropped: TestContextSessionLine red ("its
  requests' prompts: [21000]", another session's line).
- the tip back to "Request {n}: {tokens} tokens": sessions-context-line red
  in de ("Anfrage 2: 80K Token" for "Anfrage 2: 80K von 200K (40%)").
- the details line turned off: sessions-context-line red in en and zh.

Not tried: the whole GUI suite (it was running under mote's suite lock
when mote rebooted; not run at push); a real magpie with real routing history (the GUI test stubs
/api/context/session; the Go test reads real history files in a sandbox
config); the Linux app's WebKitGTK.

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

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

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

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

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

Reported-by: young02036 (Discord)
2026-11-08 17:52:09 +08:00
yetone 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