88b4c00ea11c8653cada22e11edf20ab1594de43
14
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
1502433978 |
gui: a key's value can be changed in place, keeping its name, place and settings, and its rest is lifted (#1869)
A key rotated at its vendor had to be removed and added again, which lost its name, its place in the order, its weight, protocol, models, proxy and concurrency, and any gateway key restricted to it. As decided on #1869, in multi-key mode the row now has a Change key action, with a double-click on the row as a shortcut. - provider.ReplaceKey(id, ref, key) sets the key's new value and moves what providers.json keys by the key's fingerprint (AccountModels, AccountProxies, AccountConcurrency) to the new one. An empty value, an unknown key and a value another key of the provider already holds are refused. The same value is a no-op. - access.ReplaceAccount moves gateway keys' Accounts entries from provider/old to provider/new, under the caller-keys lock. - gateway.Server.UnrestAll lifts a rest key and every per-model rest under it. The GUI's keys/replace lifts the key's rest (provider#key, and the provider's own rest key when it is the only key on), so the new value is asked from the next request. - app.js: a pencil beside the key's copy button opens a password field in place of the masked value. Enter saves, Escape leaves it, and a double-click on the row away from its controls opens it too. The button has its own class (.key-edit) with the copy button's look. - i18n: four strings in zh, zh-TW, ja and de. - providers-accounts.md: ReplaceKey in the Keys table. Past requests keep the old fingerprint in history, under the same name. A rest is lifted only in the gateway this magpie serves. Run: - go test ./internal/gateway ./internal/provider ./internal/access ./internal/gui -count=1: ok. New TestReplaceKeyKeepsItsPlace, TestKeysReplaceKeepsTheKeyAndLiftsItsRest and TestUnrestAllLiftsAKeysModels each fail with their change taken out. - gofmt -l clean; go vet darwin, linux -tags nogui, windows. - key-replace.test.cjs (new): en/zh/zh-TW/ja/de, chromium and webkit, 1100 and 420px. Checks the post, order, note, no sideways scroll, and no scroll on change or on double-click plus Escape. - With key-copy, rest-try-now and key-import: 96/96. - 72 key*/routing*/rest* GUI files at concurrency 6: 863/871. The 8 reds were key-copy, whose button.copy locator matched the pencil; that's why it has its own class now, and key-copy passes. - Under load, about one run in 300 saw the editor body go back to the top after the copy button's double-click, with no script scrolling it. That is #1504 (findings added there). The test checks scroll before that step. |
||
|
|
5e7efce3bc |
gateway: a key held to some models gets its model list as fast as one held to none, its groups read once a list, not once a group (#1762, LumenXY on X)
LumenXY's /v1/models over Tailscale took 12.4s with a gateway key held to
some models and 1.5s with an unheld one, so apps that list models timed
out and showed an empty list.
Cause (pprof, 1,000 models, 500 found groups): keyAllowed checked each
catalog entry on its own. Each group entry called provider.FindGroup,
which builds a new GroupFinder, so every provider's models were read again
(providerEntries, its files stat'ed and settings loaded) once a group.
That was 96% of the request. Each glob in the key's models was also
compiled to a regexp on every check, and a key held to accounts listed
each provider's accounts (Logins, from disk) once a model.
What changed:
- gateway/key_models.go: keyAllowed weighs a list through a keyList made
for that request alone. It has one GroupFinder and each provider's
AccountIDs read once. entryAllowed and accountServes are the same
checks over them. accountServes(who, p, model) stays for decide.go's
single check.
- access/models.go: globRe keeps each pattern's compiled expression. A
pattern compiles to the same expression whatever key holds it, so
nothing kept goes stale. The map is let go of whole past 4096 patterns.
- gui/groups.go: groupsState (the Routing page) called FindGroup once a
group too, the same class. It now uses one GroupFinder.
Every route that lists models goes through keyAllowed: /v1/models,
/v1/models/{id}, /v1beta/models, /v1/codex/models, Muse's list and the
deciders. The single-model checks (serve, count_tokens, embeddings,
System One, draw, video) ask one group and are unchanged. Nothing is kept
past a request, so a change to a key's models or accounts, a group's
members or an account's own models shows on the next request. No key
limit is loosened. The documented behaviour is unchanged, so no subsystem
page changes.
Tests:
- TestKeyListShowsWhatItDid compares keyAllowed with the old per-entry
check, kept in the test, for 14 keys over a catalog with found groups,
named and nested groups, a no-key provider and an account's own models.
The keys cover exact ids in any case, globs, group/<id>, group/*, a
group inside one named, accounts, and models with accounts.
- TestKeyListSeesChangesNextRequest goes through /v1/models and
/v1beta/models on one server while the key's models, the group's members,
the key's accounts and an account's models change.
- TestModelPatternsKeptCompiled checks each pattern keeps its own
expression and that past the cap works.
- Broken by hand, each went red: the accounts memo shared across providers
(ShowsWhatItDid), the GroupFinder kept across requests
(SeesChangesNextRequest), and the glob cache keyed by the pattern's first
letter (KeptCompiled).
Numbers, BenchmarkHeldKeyListsModels (2 providers x 500 models, 500 found
groups, M4 Pro):
- held to models: 2.36s before, 55ms after
- held to accounts: 2.35s before, 60ms after
- held to none: 43ms either way
Real use: sandbox magpie on 127.0.0.1:3486 with its own HOME, the same
1,500-entry catalog, a key held to 5 patterns, and curl 3x each:
- held key, /v1/models and /v1beta/models: 27.8-28.7s before, 0.18s after
- unheld key: 0.12s either way
- The held list (212 entries) and the unheld one (1500) were
byte-identical between the old and new builds.
- Changing the key's models while the server ran showed on the next
request (10 entries, then 212 again).
Run at origin/main
|
||
|
|
206dc085be |
provider: a magpie run from a terminal that only lists accounts no longer writes logins.json, and every change to it is made under a lock the gateway holds too, so a token the gateway just refreshed is never written back over (#1674, FaintGhost)
Every CLI command that reached Logins() (magpie ls, providers, sessions,
usage) ran rememberLogins, whose 30-second throttle (loginsSeenAt) lives
in the process, so in a new process it never held: each run moved Seen on
for the signed-in Codex and Claude accounts and wrote logins.json back.
loginsMu was an in-process mutex, so that read-modify-write could
interleave with the gateway's renewSavedLogin: the CLI reads, the gateway
writes a refreshed sign-in, the CLI writes what it read. Codex/OpenAI
refresh tokens are single use, so the account would be signed out.
- rememberLogins writes nothing when the only change is Seen and the saved
Seen is less than seenEvery (10 minutes) old (onlySeenMoved, comparing
with what was read, IDs and order normalised as writeLogins writes them;
sortLogins is split out of writeLogins for that).
- internal/filelock (new): davsync's TryLock/Unlock (flock; LockFileEx on
Windows) moved here and davsync uses it; Lock(path, wait) and
filelock.Mutex, a sync.Mutex that also holds the OS lock on a lock file.
A lock another magpie holds is waited for up to filelock.Wait (10s),
then gone on without, as before, so a stuck magpie never hangs others.
- loginsMu is a filelock.Mutex on logins.json.lock, so all 107 existing
Lock sites (every writeLogins is under one) are cross-process with no
change at the call sites. Taking it calls filememo.Look (new), so the
read under it isn't a parse filememo.Hold kept from before another
magpie's write. savedTokenMu holds logins.json.renew.lock the same way:
two magpies never refresh one saved account at once.
- Siblings: caller-keys.json (access.mu: magpie keys from the CLI vs the
window; a lost revoke would bring a key back) and mcp-signins.json
(mcpauth.fileMu, plus mcp-signins.json.renew.lock around renew, since
library's MCP check renews from the CLI too) get the same lock.
plugin-auth.json already has one (plugin-auth.json.lock, shared with
host.js). Not covered: providers.json (33 store sites with no
in-process lock either; user-entered keys, nothing refreshed there),
migrations.json/settings.json (no credentials), and the agents' own
files (~/.codex/auth.json etc.: the agent itself writes them without
any lock of ours, so a magpie-only lock can't make them safe).
Tests:
- TestReadOnlyRunLeavesLogins: Codex and Claude signed in, Seen a minute
old, file time set back; three "new processes" of Logins("")/codex/
claude/All() leave logins.json's bytes and mtime as they were. Seen an
hour old is written; Codex's own refresh is written at once.
- TestLoginsKeepAnotherMagpiesWrite: between this process's read and write
(beforeLoginsWrite hook) a second test process (TestLoginsOtherMagpie,
os.Args[0] -test.run) renews the saved work@ account's refresh token;
both the renewed token and this process's change are in the file.
- TestLoginsReadAfreshUnderLock: with filememo.Hold held, a write
filememo never heard of is seen by a read under loginsMu.
- TestLockAcrossProcesses (filelock): a holder subprocess makes Lock wait
and give up after its wait; killed, the lock is free; a Mutex holds it.
Broken by hand: onlySeenMoved bypassed -> TestReadOnlyRunLeavesLogins
FAIL "a run that only listed the accounts wrote logins.json"; the file
lock taken out of filelock.Mutex.Lock -> TestLoginsKeepAnotherMagpiesWrite
FAIL "the other magpie's renewed sign-in was written over"; Locked hook
emptied -> TestLoginsReadAfreshUnderLock FAIL. Each restored, green.
Ran: gofmt -l (nothing); go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./...; go build, GOOS=linux go build -tags
nogui, GOOS=windows go build; go test -tags nogui -count=1 ./... under a
temp HOME with pinned caches: all ok but internal/provider, whose
TestReadOnlyRunLeavesLogins failed at that point from its own fixture
(two rewrites of one size given the same mtime read as unchanged by
filememo); fixed in the test, then internal/provider, access, mcpauth,
filememo, filelock and davsync -count=1 all ok, and the three new provider
tests -race -count=10 ok.
Not tried: the reporter's Linux arm64 box with a real systemd gateway and
real Codex accounts; Windows (LockFileEx path) only vetted and built, not
run on the Windows box.
|
||
|
|
cec9647a2a |
access: a default gateway key the user removed isn't made again when sharing is turned off and on (#1655, GradientLive)
Turning on Settings -> Share on local network makes a default gateway key named "Magpie". A user who wants only their own, stronger key could remove it from Gateway -> Gateway keys, but configureLAN looked for the default key by LANKeyID, found none, and made a fresh enabled "Magpie" key the next time sharing was turned on. That reads as a default key that is always there. configureLAN now leaves a removed default key removed: when its id is recorded (LANKeyID), or an older magpie dropped the id and kept only the revoked mirror, sharing is turned on with the keys there are. Asking for a new sharing key (newKey / rotate) still makes one, as TestLANSettingSharesCallerKeyStore expects. A disabled default key already stayed disabled; the test now holds that too. First-time sharing is unchanged. docs/reference.md says so. Run: go test ./internal/access ./internal/gui ./internal/agent (ok); TestRemovedDefaultKeyStaysRemovedOnReshare goes red with the new check disabled by hand (a second "Magpie" key appears). gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/access clean. Not tried in the real GUI. |
||
|
|
3541ec2fd5 |
gateway, gui: a gateway key's limit can run every N days, and Reset usage counts it from 0 again (#1509, PennyVibe)
PennyVibe asked for a key limit on a cycle of N days rather than a
calendar day, week or month, and for a way to zero a key's usage by
hand. Both are in.
Every N days (N from 1 to 3650):
- access.Limit gains Days and Since. Since is magpie's own: the
limit-key action always works it out, and a value a client sends is
ignored.
- The cycle starts when the limit is set. Each cycle is N×24h of
absolute time from Since, so a restart, a time-zone change or a DST
shift doesn't move it.
- Changing only the caps or "count cache reads" keeps the cycle.
Changing N or the period, or turning the limit on, starts a new
cycle now.
- A hand-written "days" limit with no Since runs from the Unix epoch.
- The GUI window menu offers "Every N days" with a Days field. The CLI
takes `magpie gateway-key limit <id> 10d`. The refusal and status
name the cycle ("for this 1-day cycle").
Reset usage:
- A new action, reset-limit-key, is on the editor's "Reset usage"
button (after a confirm) and on `magpie gateway-key limit <id> reset`.
- It sets Since to now, so tokens and cost both count from 0 together.
- An N-day key starts a new cycle then.
- A day, week or month key keeps its window's end, so it stays on the
calendar. Only the calls before the reset stop counting.
- The usage log is not touched. Authenticate reloads keys each request,
so the reset takes effect at once.
Keys saved before keep their JSON byte for byte (omitzero, nothing
written on load).
Docs: reference.md documents the cycle and reset rules. The docker page
(en, zh, ja) mentions every-N-days.
Run:
- go test -tags nogui ./... with a temp HOME.
- New Go tests:
- TestLimitDaysCycle covers the NY DST, UTC and UTC+8 boundaries.
- TestLimitCalendarReset.
- TestLimitSetAndReset covers keep/restart, an old key's JSON left
untouched, and errors.
- TestKeyLimitDaysCycleAndReset covers the 429 text and header, a
restart, the cycle boundary, and Reset clearing the token and cost
caps together.
- TestKeyLimitCalendarReset.
- TestGatewayKeyLimitCLI covers 10d, reset and bad args.
- Broken by hand: with reset leaving Since alone,
TestLimitSetAndReset, TestKeyLimitDaysCycleAndReset and
TestKeyLimitCalendarReset go red.
- gofmt -l is clean. GOOS=linux and GOOS=windows go vet -tags nogui
pass on ., access, budget, gateway and gui.
- GUI: the new gateway-key-cycle.test.cjs runs in chromium and webkit ×
en, zh, zh-TW, ja and de, with a narrow-width check. Also run, in both
engines: every test using the caller-keys fixture, i18n-keys,
gui-ja, gui-de and gui-zh-tw (80 pass).
- Real use:
- Sandbox magpie (temp HOME, gateway 127.0.0.1:3691, dev UI 3692)
with a fake OpenAI upstream (300+50 tokens a call).
- `gateway-key limit <id> 1d --tokens 700` allowed 2 calls with curl,
then a 429 "for this 1-day cycle" with X-Magpie-Limit-Reset a day
after it was set.
- Pressed Reset usage in the GUI with Playwright and confirmed. The
badge was no longer spent and showed 0 of 700, and curl passed 2
calls again before the next 429.
|
||
|
|
91581fca27 |
library: a WSL agent under NAT is given a signed-in MCP server with the LAN key, so the gateway no longer answers its every call 401 (#1488, ggbdpq)
A server magpie signed in to (#615) is given to the agents at the gateway's /mcp/<name>, at the address each reaches the gateway at. A WSL distro under NAT reaches it at Windows' address, so its requests come from another machine, and lanGuard refuses such a request without an enabled gateway key with a 401, which an MCP client takes for the server asking it to sign in. through() gave it no key. Its models already carry the LAN sharing key there (keyAt, whqtian on Discord); the relay didn't. The gateway's checks are unchanged: a request from another machine still needs the key, and mcpProxy still lends a sign-in beyond loopback only to a request that carried it (sharedWith). What changed: - agent.KeyAt exports keyAt: the LAN sharing key for an agent that reaches the gateway from another machine while sharing is on, else gateway.Token. - through() gives such an agent Authorization: Bearer <that key>. The gateway takes it in lanGuard, and mcpProxy drops Authorization for magpie's token, so the server never sees it. An agent on loopback, and one in WSL while nothing is shared, stay keyless. - access.LANChanged runs after sharing is turned on or off or its key is made anew; the library syncs again then when it relays any server, so the entry carries the key there is now without a visit to the Library. - docs/subsystems/library.md says so. Run: - TestSignedInServerCarriesKeyBeyondLoopback (library: a FakeWSL distro routed via 172.20.0.1, LAN on) fails on the old through() ("claude@wsl: Ubuntu under NAT is given headers map[X-Team:acme], want the LAN key as its Authorization") and passes now; with the LANChanged call commented out it fails at "after a new key ... is given" the old key. - TestMCPProxyFromWSLWithLANKey (gateway, through lanGuard as the server runs it): 401 without the key and the server not called, 200 with it, the server gets magpie's token and never the key. - go test -tags nogui ./... under a temp HOME; gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui on the touched packages. - Not tried on a real Windows + WSL NAT machine with a real OAuth MCP server; FakeWSL and httptest only. Patch by ggbdpq in #1488; the LANChanged resync added on top. Co-authored-by: ggbdpq <ggbdpq@gmail.com> |
||
|
|
6b6113aa7a |
gateway keys: a key can be created with a value of the user's own, one their clients already send, so moving from another gateway (CLIProxyAPI's api-keys) doesn't mean re-keying every client (love1sbug on X)
Gateway → Gateway keys → Add gateway key has a second field, "Your own key
(optional)"; `magpie gateway-key add <name> --key <value>` (or `--key -`
from stdin) does the same. Left empty, magpie makes a sk-magpie-key- as
before. A value is 8–256 printable ASCII characters with no spaces, can't
start with sk-magpie-, and can't be another key's. The list shows only its
last four characters ("…0042"); rotating it gives a magpie-made key.
From another computer any enabled key was already checked, so an own value
works there as is. From this computer the gateway only identified a request
whose key looked like sk-magpie-…, so an own value would have been let in
unidentified: not counted as the key, nor held to its limit, models or
accounts. managedKey now asks access.Named, which also knows the store's
own values (cached by the file's size and time).
Tested: go test -race . ./internal/access ./internal/gateway ./internal/gui;
-count=20 on the new and LAN guard tests; TestOwnKeyValueIsTheKey fails with
managedKey back on access.Managed. gateway-own-key.test.cjs passes 16/16
(chromium and webkit, en/zh/ja/de, 1000 and 440px), and the gateway-key
suites, i18n-keys, gui-ja and gui-de pass. A built binary in a sandbox HOME
with sharing on: own key from the LAN address 200, a wrong or no key 401,
from 127.0.0.1 200, the old value after rotate 401. GOOS=linux and windows
builds pass.
|
||
|
|
47c2382467 |
gateway: a gateway key can be held to some accounts (#905, LCorleone) — a key could burn any account a provider had: two coding plans of one vendor, and a key given to someone had them both. A key now keeps an optional list of accounts and keys (caller-keys.json "accounts", none = every account, so older files read as before): "<provider>/<account>", an account by its stable id — the login's, set once it is written and kept through renames (logins.json's savedLogin id, written by every write and stood in for by one made of the name until then, so an entry made before stands), a key by its fingerprint — every one a provider has when the list is set, and one gone later (a key rotated, an account signed out) kept as it is, matching nothing, holding the key closer, never wider. The command line and the menu name an account by who is signed in and keep its id. Routing holds a plan to the key's accounts beside its models: a candidate whose account the key may not use is left out — through a routing group the key names no less, for naming a group is not naming its accounts — the plan's order keeping step and its left-out list marking what the key held out (Weighed's held); magpie's own calls for the key — a web search, a picture described, a Codex title — are of the models the user picked, so the models don't hold them, but their spend lands on an account all the same, and the accounts hold them too. When every account or key a model has is one the key may not use, the request is refused with a 403 in the API's own error shape naming the model and the accounts the key may use, logged as a rejected call: after a usage cap's 429 and before an account barred for the model's, itself before the no-member 404. /v1/models and the Anthropic and Gemini lists show the key only the models an account or key it may use serves (a provider's account set not to serve one, #474, is none of the key's); a provider with no account and no key (a local ollama) is one the key names no account of — its models stay listed and its asks pass — while an entry kept after its provider lost its last account or key serves none, holding the key closer. The embeddings, images and videos endpoints hold their candidate to the key's accounts the same way, and counting tokens counts on those alone (the local estimate where it may use none). System One asks its decision model of an account or key the key may use — and sends on that key, of those in use, not the provider's first, which a key held to a later one was spent on; the videos and images keyed paths send on one the key may use too, held to a later key no longer refused for the first alone. Set it in the app's menu the models are picked in — the accounts after the models, an account by who is signed in with their plan in the note, a key by its fingerprint, what the CLI kept that no provider has now kept as "Not signed in now" — or magpie gateway-key accounts <id> codex/me@example.com openai/<key id> (all takes it off); gateway-key list has an ACCOUNTS column. en/zh/ja/de, the German "{n} accounts" main already had left to it rather than written twice. The images API's fan-out over a subscription's accounts is held to the key's accounts as one: one of the key's whose plan refuses to draw no longer hands the pen to an account it may not use, and the second in the order, when it is the key's, draws what the first may not (drawOnAccounts filters the candidates, the account pinned to with the account header told plainly when the key may not use it). The Routing view's left-out list says an account the key held out for what it is, not that its plan lacks the model, in Chinese, Japanese and German too; the key's badge names its accounts by who is signed in, not by the stable ids it keeps. (#932)
|
||
|
|
46f03154ff |
gateway: a gateway key can be held to some models (#882, LCorleone) — a key could reach every model magpie serves. A key now keeps an optional list of models (caller-keys.json "models", none = every model, so older files read as before): <provider>/<model> or <provider>/*, matched against the provider that serves the call, so a bare model name is resolved first and OpenRouter's "anthropic/x" is not Anthropic's. Such a key sees only its models in /v1/models, /v1/models/{id} and the Anthropic (Claude Desktop) and Gemini lists, a routing group only when every member is its; asking for another, by id, bare name or through a group with a member it may not use, is refused before any provider is asked with a 403 in the API's own error shape (permission_error) that names the key and its models, logged as a rejected call like an over-limit key's 429; a fallback it may not use is skipped; embeddings, images and videos it names are held too. magpie's own calls for it (a web search, a picture described, Codex titles with the model Settings name) are marked in their context, not by a User-Agent a client could send, and go on. Set it with the new badge on the key's row in the Gateway page (the app's menu: All models, every model of a provider, each model; sent when the menu closes) or magpie gateway-key models <id> openai/gpt-5 anthropic/* (all takes it off); gateway-key list has a MODELS column. The app's menu, fitting neither below nor above its button, now goes on the roomier side and scrolls instead of running off the window. en/zh/ja/de. TestGatewayKeyModelsHoldAKey (lists, 403s by id, bare name and group, Anthropic shape, fallback skipped, magpie's own call, a free key) fails without the change; TestModelPatterns, TestKeyModelsKept, TestGatewayKeyModelsCLI, TestCallerKeyModelsRoutes pass; gateway-key-models.test.cjs (Chromium and WebKit, en and zh: no native select, menu inside a 420px window, picks sent on close, All models, no scroll, no left border, 560px fits) passes with gateway-connect-keys, gateway-key-limit, gateway-caller-keys and click-scroll. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
|
||
|
|
31626c1543 | agent: an omp in WSL under NAT gets the gateway's network key, and one bun installed is found and asked its version (whqtian on Discord: a WSL omp connected only once auth: none was swapped for the key by hand, and Kimi K3's max still read xhigh) — a distro not in mirrored networking reaches the gateway at Windows' address (172.23.80.1), where a request without a named key is turned away, yet magpie wrote auth: none there too. Its models.yml now carries the key the gateway is shared on the network with (access.LANSecret: the default LAN key, "" while nothing is shared or it is off) in place of auth: none; an omp on loopback stays keyless. The probe asked omp its version only when sh -l found it on PATH, but bun's and nvm's installers put theirs on PATH in ~/.bashrc, which sh -l doesn't read: the version stayed unknown and max was offered as xhigh, as for an omp older than 16.4.0. It now also looks in ~/.bun/bin, ~/.local/bin, ~/.npm-global/bin, ~/.volta/bin, pnpm's, nvm's, mise's and asdf's folders, and runs --version with the command's folder on PATH, where bun's #!/usr/bin/env bun finds bun. TestOmpKeyBeyondLoopback (NAT address shared or not, loopback, localhost) and TestWSLProbeFindsBunOmp (the probe script run with a bun-installed omp off PATH; fails on the old script: no bin, no version). go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass but for TestSavedButSignedOutClaudeServed, which timed out once under load and passes 3 of 3 alone. | ||
|
|
21702d01ff |
Add German translation; harden paths against unset env vars (#770)
* Add German translation and harden paths against unset env vars Add a German locale to the GUI, tray menu, usage alerts and website home page, and refuse to start when the home folder is unset or relative so nothing is written under the working folder; the pi plugin no longer adopts the user's PI_CODING_AGENT_DIR, and an inherited APPIMAGE no longer selects portable mode. Scripts refuse to run from the wrong folder or empty a shared out folder, and a new internal/testenv sandboxes every test package from the user's real files, which also fixes the Claude picker and Termux installer tests on Windows. * Makefile: know magpie's folder by its go.mod, so paths with spaces work The check compared $(CURDIR) with $(dir $(abspath …)), which make splits on spaces, so a checkout under 'My Projects' or 'John Doe' refused every target. It now reads go.mod relative to the working folder and wants magpie's module there: make -C and a symlinked Makefile work, make -f from another folder still stops before any recipe runs. * i18n: German for the strings main added since, with a parity test 75 strings main added (group order, patterns, slow-start wait, usage caps, RTK savings …) get their German, and two that main dropped go. gui-de.test.cjs checks, as gui-ja does, that de has every zh string with its placeholders and tags, and that the window reads in German when picked or on a German system. * appdir: ignore relative folder variables when reading, keep them for children CheckEnv no longer unsets anything. magpie reads the XDG folders, APPDATA/LOCALAPPDATA and every agent's folder variable through appdir.Getenv/LookupEnv, which pass over a relative value; the environment stays as it is, so the agents magpie starts get the variable as the user set it. That covers what proc.UserPath lends from the login shell too, which is set after main's check and reached the desktop app unchecked. On Windows a path rooted on the current drive (\Users\x, Git Bash's /c/x) counts as usable, and magpie version and help answer without a home, before run makes any folder. * Sandbox the tests main added since internal/wslrun gets testenv's TestMain, and four tests main added that set HOME alone set their home with testenv.SetHome, so on Windows they don't read the runner's profile through USERPROFILE. * agentenv: PI_CONFIG_DIR and OPENCODE_DB take relative names on purpose omp puts $PI_CONFIG_DIR under the home and OpenCode a relative $OPENCODE_DB in its data folder, so neither depends on the working folder: appdir no longer passes them over. * i18n: German for the Library's multi-select and System One's decision API The 19 strings main added since (#791's skill multi-select, the decision API snippets) get their German; the one main replaced (four APIs → five APIs) goes. * appdir: tidy the import into magpie's group; say what Go makes of /c/x The appdir import joins the group of magpie's own imports where a file has one. rooted's comment now says that Go takes a Git Bash path like /c/x as \c\x on the current drive, not C:\x. |
||
|
|
0879894af3 | gateway: each gateway key can have its own limit, a token total and/or an estimated cost per day, week or month, and a spent key is refused before any provider is asked (margbug01 on #585, v0.1.671: 每个网关密钥都能设置自己的用量上限) — a gateway key named who called and the Usage page grouped its calls, but nothing held a key to an amount, so one client shared on the network could spend a subscription's whole window. A key now carries limit {period day|week|month, tokens, cost, cacheReads} in caller-keys.json, set with the new "limit-key" change. Windows are calendar ones in local time (from midnight, from Monday, from the 1st) and a call counts in the window it started in. Tokens are a call's uncached input, output and cache writes, plus cache reads when the limit says so; cost is an estimate at the Usage page's effective prices (usage.NewCoster), a call with no known price adding none and counted as unpriced. What a key used is summed from usage.jsonl (usage.Visit), so it survives a restart; the new internal/budget keeps the sums in memory per window and appendUsage writes a key's record through budget.Append, which appends and counts under one lock so a window read meanwhile never counts a call twice. Before a keyed POST reaches the mux, keyLimited reserves for it: its body's size in tokens (4 bytes a token) plus the key's mean output per call this window, at the window's cost per token or the named model's input price; it is let in while used + reserved is under the cap, so requests sent at once overshoot by about one call, and the reservation is released when the request ends, a streamed reply being settled then with the usage its vendor reported. A spent key gets a 429 in its API's error shape (Anthropic, OpenAI chat/responses, Gemini) naming the key, the cap and the reset time, with Retry-After, X-Should-Retry: false and X-Magpie-Limit-Reset, recorded as a rejected call (gateway_key_limit); other keys go on. Requests from this computer without a gateway key are not limited; a key used from this computer is. count_tokens and bridge callbacks are never held. GET /v1/magpie/limit tells a key its own status. Gateway keys rows show a Limit badge (what is used of it, per what, Spent in red) and a line under a limited key (used of limit, left, resets / refused until, in flight; unpriced calls in its title); Limit opens an editor under the row (window, tokens with k/m/万/亿, cost in US$, Count cache reads too, what is counted) staged until Save, marked unsaved, Cancel/Escape dropping it, a bad amount disabling Save, No limit removing it; en and zh; no left-border accent; no click scrolls. The CLI gains magpie gateway-key limit <id> [off | day|week|month --tokens N --cost USD --cache-reads] and a LIMIT column in list. TestKeyLimitRefusesBeforeUpstream (two calls within 700 tokens, the third a 429 the fake upstream never sees, message/type/headers, the rejected record, Anthropic's shape on /v1/messages, another key and a keyless loopback request let in, still refused after budget.Forget as after a restart, a raised and a removed limit let in, /v1/magpie/limit), TestKeyLimitHoldsParallelRequests (20 at once against 2000 tokens: some refused, at most one call over, no reservation left; without the reservation all 20 got in and 7350 were used), TestKeyLimitWindowResets, TestLimitWindow, TestLimitValid and TestGatewayKeyLimitCLI are new; gateway-key-limit.test.cjs (WebKit, en and zh) is new and passes, as do gateway-caller-keys, gateway-connect-keys, api-key-theme and click-scroll (whose request-pick case flaked once under a parallel run and passes alone, as on main). go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass (TestFXInState's known TempDir-cleanup flake aside). | ||
|
|
0361189f9e | test: every package's tests pass on Windows, and none writes outside its sandbox (the user: 把 Windows 上那几个失败的测试修掉) — on a Windows box the suite failed in most packages, and the root package hung for 25 minutes. Tests set HOME, which os.UserHomeDir ignores on Windows (it reads USERPROFILE), so they read and wrote the runner's own home; each now sets USERPROFILE beside HOME, and Devin's, Goose's, Crush's and Claude Desktop's tests set APPDATA/LOCALAPPDATA, where those keep their files there. said() read the command's output only once it returned, and a pipe holds a few KB on Windows, so magpie model --help blocked forever; it reads while the command writes. Unix permission bits (the gateway key store's 0600 too), exec bits and symlinks Windows lacks are checked only off Windows; TOML strings hold Windows paths as literal strings, JSON as marshalled ones; a URL's path is compared as one. The provider and usage packages run in a home of their own (TestMain, as the gateway's already does), since a CLI's identity kept by a refresh still going when its test ended landed in the runner's ~/.config/magpie — and on a Mac in the user's own. Two product fixes came out of it: imagemcp took a file:///C:/… root or image for the path /C:/…, which doesn't exist on Windows, and now makes a Windows path of it (a host for a UNC share); and session discovery could keep a new Cowork session hidden on Linux, where a folder's mtime is a kernel tick and its size doesn't change, so an entry added within the tick of the last listing left both as they were — a listing made within 2s of its folder's last change is read again, as git does for racy files. TestFilePath and TestRacyDirectoryListedAgain fail without the change. On Windows 11 every package passes (32 of 32) and a run of each package in a fresh home leaves nothing in home, APPDATA or LOCALAPPDATA; on Linux (WSL) and macOS go test -tags nogui ./... passes. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build pass. | ||
|
|
bb1aa3acbd |
feat(gateway): named gateway keys with per-client usage (#344)
* feat(gui): show and filter usage for each API key * feat(gateway): issue per-user caller keys and attribute usage * feat(gui): manage gateway users and filter caller-key usage * test: verify caller-key failover and document user management * refactor(gateway): use named caller keys without user accounts * feat(gui): manage named caller keys with existing account styles * fix: remove user breakdown from CLI and leftover gateway styling * fix(usage): drop stale user field from request response * feat(gateway): authenticate LAN calls with named caller keys * fix(gateway): preserve LAN key rotation in the named caller store * fix(gui): retain native LAN key copy and rotation controls * fix(gui): inherit the global theme for API key inputs * fix(usage): show client API keys using the existing terminology * fix(gateway): rotate named keys without changing usage identity * fix(gui): unify gateway keys and selectable connection examples Keep sharing controls in Settings and manage credentials only in Gateway. Refresh the named-key list on navigation, ignore stale reads after key actions, and generate all API examples from the selected address and enabled key. * fix(gui): keep caller key names literal in connection menus * fix(access): use Magpie as default key and drop user migration * refactor(gui): name caller key source and tests consistently * refactor(usage): split provider-key accounting out of caller-key PR * fix(gateway): preserve LAN compatibility and add headless key management * fix(gui): clarify gateway keys and confirm destructive actions * test(gateway): guard caller attribution under 120 concurrent requests * fix(gateway): keep open access, tolerate migration errors and revoke legacy keys * fix(backup): preserve named gateway keys and honor no-keys restores * fix(gui): keep local API-key semantics and disambiguate shared credentials * docs(gateway): keep review scope focused and append browser test documentation * fix(backup): retain existing default keys when old backups lack their store * fix(gateway): attribute video creation usage to the caller key * fix(access): explain default key revocation blocked by read-only settings * test(usage): preserve provider and caller identities after rebase * test(gui): reconcile caller key fixtures with merged main * docs(usage): clarify caller coverage and independent provider accounting * fix(gui): initialize fast members for model-shortcut groups Latest main introduced fast-member arrays but omitted the model shortcut's draft. The existing unlisted-models browser regression fails unchanged on main. Initialize fast to an empty list and assert a standard-speed group is saved, without relaxing existing assertions. * fix(access): retain legacy LAN access when the key store cannot be created Allow only the configured legacy credential before either migration marker exists. Refuse revoked mirrors, disabled matches and unreadable stores; keep the fallback's caller identity stable when migration later succeeds. Cover read-only configuration directories, remote credential transports and revocation. * fix(backup): save settings before replacing gateway credentials Leave the key store untouched when settings validation or writes fail. Restore the previous settings association when the key store refuses its write, and report a rollback failure separately. Cover invalid settings and read-only settings/store failures. * fix(gui): reset missing caller filters and focus key controls without scrolling * test(provider): synchronize Zhipu quota fixture observations |