Commit Graph
511 Commits
Author SHA1 Message Date
yetone 2fbbd16945 gateway, gui: routing history keeps the last two levels of the folder an agent works in, and By session, the stage and the panel name it (#1068, emo172)
Routes now carry Folder: the last two levels of the working directory the
agent states (Claude Code's "Primary working directory", Codex's <cwd>,
Pi, OpenCode), cut by shortFolder before the route is stored, so no full
path reaches the routing history, /api, or the GUI. It is kept in the
routing history for as long as the history itself (30 days / 200 MB).
A request that states no folder (title, side calls) takes the folder its
session (or parent session) last stated; the per-session map is capped
at 512 entries.

GUI: By session headings read "Agent · folder · title", their tooltip
and every request row's tooltip (page and tray panel) name the folder,
the stage's agent subtitle lists the last level of each folder when an
agent works in more than one, and the panel's agent node tooltip lists
them.

Run:
- TestShortFolder (unix, trailing slash, C:\, D:\, UNC, CJK with spaces)
  and TestRouteKeepsItsFolderShort (real Handler, fake upstream: session
  inheritance, a moved Windows path, nothing of the full path in the
  marshalled routes, saveRoute -> History round trip), TestTurnDone.
  Broke it by hand: without the session lookup the title request has no
  folder; with the folder unshortened the full path shows. Both go red.
- routing-session-folder.test.cjs: chromium + webkit x en, zh, zh-TW,
  ja, de x 1100 and 420 px, 20/20. Red on the old routing.js and with
  the stage's live routes left out.
- GUI suites routing-*, panel-routing*, purpose-filter, reasoning-speed,
  gui-de/ja/zh-tw, click-scroll, number-units: 951/951.
- gofmt -l clean; go vet darwin, linux (nogui), windows; builds for all
  three. go test -tags nogui ./...: all ok except internal/gateway, which
  hit go test's default 10m timeout at 611s on a loaded machine (#2108);
  alone with -timeout 30m it passes in 356s.
- Real use: nogui build in a sandbox HOME, fake upstream, real Claude Code
  2.1.299 (claude -p) run from .../workspace/magpie and .../src/dial: the
  day's routing jsonl has folder "workspace/magpie" and "src/dial" and no
  part of the sandbox path above them.

Not tried: title/side requests' inheritance end to end with a real agent
(claude -p made none), Codex, OpenCode and Pi with real binaries, Windows.
2026-10-14 14:03:38 +08:00
yetone d9ca84a2f4 gateway: built-in TLS, magpie serve/web/daemon install --tls-cert --tls-key, reloaded on renewal (RoderickZH)
magpie serve, magpie web and magpie daemon install take --tls-cert <file>
--tls-key <file> (or MAGPIE_TLS_CERT / MAGPIE_TLS_KEY). The gateway and the
web UI on its listener then serve HTTPS to other computers. Without them
nothing changes.

- Half a pair, a file that doesn't parse, or a flag with no value is
  refused at start with a message naming the missing flag.
- The pair is re-read when either file's mtime or size changes (certbot
  renewal), with no restart. A renewal that doesn't parse keeps the
  certificate already served and is logged once.
- Other computers get HTTPS only. Plain HTTP from them gets net/http's
  400 "Client sent an HTTP request to an HTTPS server".
- This computer (loopback, or a peer address equal to the local one) may
  still use plain http on the same port. Its connections are sniffed on
  their own goroutine (a first byte of 0x16 is TLS) for up to 10s, so a
  silent client holds nobody else up. gateway.URL() stays
  http://127.0.0.1:<port>, which agents, MCP servers, ServedBy, the
  healthcheck and daemon status all use, and no certificate covers
  loopback.
- WSL NAT and containers count as other computers.
- ALPN is http/1.1 only (hijacked connections and websockets need it), with
  TLS 1.2 as the minimum.
- Printed links, LAN addresses, publicURL, the serve/web banners and
  daemon install show https:// for other computers' addresses.
- The DNS-rebinding Host checks (foreignPage, rebound, the MCP
  loopbackHost) don't depend on the scheme and are unchanged.
- daemon install carries MAGPIE_TLS_* into the unit or plist. A reinstall
  or `daemon web on` that names no certificate keeps the installed pair,
  and --no-tls removes it.
- Docs: reference.md gets an HTTPS section that names Caddy as the
  alternative, gateway-routing.md gets a TLS row, and docker.html (en,
  zh, ja) gets the env rows.

What was run:
- New tests: internal/gateway/tls_test.go (others HTTPS-only, this
  computer both, a silent local client holds no other, renewed
  certificate served, CheckTLS, addresses, Relisten keeps TLS),
  internal/cli/tls_cli_test.go and daemon TestInstallCarriesTLS (linux
  and darwin, paths with space, %, & and ").
- Each was broken by hand and went red: no wrap in listen, no reload, a
  synchronous sniff, a bad renewal dropping the certificate, http in
  publicURL or the pinned LANURLs, the carried entries removed, and
  keepTLS as a no-op.
- Real use under a sandbox HOME, with a self-signed pair, on
  0.0.0.0:3461:
  - Half a pair, a garbage certificate, a flag with no value, and the
    env set to half a pair each exit 1 with the message.
  - curl -k https://127.0.0.1 and https://<LAN IP>/v1/models with a key:
    200. Plain http on loopback: 200.
  - The cert files were swapped for a second pair while it ran.
    openssl s_client then showed the new CN and serial, and curl
    --cacert with the new pair got 200. A junk key file then kept the
    second pair, logged once.
  - From the Windows box over the LAN: plain http got 400; https with
    the key got 200, and without it 401.
  - magpie web --addr 0.0.0.0:3462: https network links. From Windows,
    http got 400 and https with the key got 303.
- gofmt -l clean. go vet passed on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -tags nogui for ./internal/cli, ./internal/daemon, and the TLS
  tests of ./internal/gateway and ./internal/gui: all pass at the rebased
  head.
- Two reds in the full suite (`go test -tags nogui ./...`) are the same
  on origin/main f074996d9; both are filed:
  - TestGatewayHeldByAContainer failed 2 of 5 there (#2107).
  - The gateway package runs past go test's default 10m under load:
    1208s on main and 1221s here, both passing with -timeout 40m
    (#2108).
2026-10-14 13:36:03 +08:00
yetone 579de3baa0 agent: enabledModels lose a deselected model's entries after the catalog sync (#2055)
misaka9981: models deselected in a provider's editor left magpie's
provider in Pi's models.json, but their magpie/<provider>/<model>
entries stayed in settings.json's enabledModels, and Pi warned "No
models match pattern" for each at every start. Pi's resolver
(model-resolver.js resolveModelScope, 1.1.0) only warns, never prunes.

After the sync writes magpie's provider block, an enabledModels entry
that names one of magpie's models outright (no glob; a thinking level
read off) whose model the block no longer has is taken out. As the
entry may be the user's own, it is remembered in stash.json
(<agent>.scope.gone) and goes back on the list's end once the model is
offered again; a provider rename moves the remembered entries too and a
disconnect forgets them. Globs, entries on other providers and on
models still offered stay, in order, comments kept. A list left with
nothing is removed (never written []) and made again when its entries
come back, with the model picked meanwhile; a list the user removed
isn't made again. When the agent's model list can't be read, nothing
is taken out.

The same holds for the siblings with such a list: OmO and Prime Agent
(piLike), StepCode (config.toml; its wiring state's last scope follows,
so a disconnect still puts the user's list back) and omp (config.yml's
plain entries; folder-scoped entries are left alone).

Run:
- TestPiEnabledModelsLoseDeselected (pi, omo, prime-agent) with the
  reporter's provider and four models, beside the user's own entries
  (another provider at a level, a magpie glob, a model still offered
  at a level): deselect, select again, rename.
  TestPiEnabledModelsEmptiedAndBack: emptied and back; removed by the
  user stays removed; other providers' and globs' file byte for byte;
  an unreadable models.json prunes nothing.
  TestStepCodeAndOmpEnabledModelsLoseDeselected, StepCode's disconnect
  putting the original list back included.
- TestPiEnabledModelsFollowRename and TestStepCodeEnabledModelsFollowRename
  keep a magpie/deepseekx/flash entry to show a rename leaves a name
  sharing a prefix alone; deepseekx is now a real provider there, as the
  sync would otherwise (rightly) take an entry naming nothing out.
- Broken by hand, each red: Pi's, StepCode's and omp's Sync hook off;
  the put-back off; the rename of remembered entries off.
- Real Pi 1.1.0 (@earendil-works/pi-coding-agent) under a sandbox
  HOME, `pi -p`: the stale exact entries gave the reporter's warnings;
  the list as pruned gave none.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows;
  go test -tags nogui ./... green on origin/main 7d15df78a. Rebased again
  over 2eee900dc (omp's Sync now keeps the user's keys, ompProvider(models);
  the conflict is that one line), then vets and ./internal/agent/ and
  ./internal/cli/ again: green but for TestReasonixCLI*, whose fixture
  build read a go1.26.8 toolchain another session was unpacking into the
  shared module cache ("internal/oserror is not in std"); both pass run
  alone right after.

Not tried: the GUI's provider editor end to end with a real Pi session,
real omp and StepCode binaries, WSL. A magpie glob that matches nothing
still gets Pi's warning: it is the user's pattern and stays.
2026-10-14 13:33:28 +08:00
yetone 353464f161 gateway: a translated Anthropic or Responses reply that said nothing and counted no token is asked again, then fails, not completed (#2086, tensornull)
tensornull's Codex turn on an Anthropic-compatible proxy (baseAPI
anthropic, claude-opus-5-5) ended as response.completed after 21s with
no output: the route had status 200, no usage, no served model, no
ttft. Codex took it as its turn's end (last_agent_message null) and
didn't ask again. No usage and no served model mean the proxy never sent
a message_start Claude would have (it counts the prompt and names the
model), yet the stream said it ended (message_stop or a stop_reason), so
320af9858's replyEnds read it as whole and errEndedShort didn't apply.

Now a reply from an Anthropic or Responses upstream (repliesCounted) that
said nothing (no text, call, search or image) and counted no token at all
(uncounted) is the empty reply #667 already handles for Gemini: asked
again in place, then failed with "an empty reply (the model answered
nothing; try again)", which Codex retries. Same in streamTranslated and
the unstreamed translate path, for Responses, Messages and Chat clients.
Claude's own empty end_turn (after a tool's result) counts its prompt and
still completes, as does a Responses reply with usage and no output.

Not changed: a reply passed through in its own protocol (Codex asking a
Responses provider, Claude Code an Anthropic one) isn't read for this;
the passthrough has no empty-reply rule at all, Gemini's included.

Verified:
- New stream_uncounted_test.go. TestUncountedEmptyReplyFails (message_stop
  only; pings then message_stop; message_start with no usage then a
  stop_reason; zero usage), TestUncountedResponsesReplyFails and
  TestUncountedEmptyReplyFailsEveryClient (Chat streamed, Responses and
  Chat unstreamed) all FAIL on the old code ("ended response.completed
  \"completed\", want response.failed", "status 200, want the empty
  reply's failure") and pass with the change. TestCountedEmptyReplyStillCompletes
  and the #1933 tests (TestWellFormedStreamsStillComplete, TestMalformed*)
  pass.
- The full go test -tags nogui ./internal/gateway run failed only
  TestCodexHeadersReachKeyedRelay and TestStandaloneNativeAccounts, whose
  fake Codex backends answered response.completed with output [] and no
  usage, which the real backend never sends; their fakes now count
  tokens, and both pass. Run in a sandbox HOME with pinned
  caches; gofmt -l; go vet ./internal/gateway for darwin,
  GOOS=linux -tags nogui and GOOS=windows; GOOS=linux go build -tags
  nogui and GOOS=windows go build.
- Not tried: the reporter's proxy or its real bytes (the report has none);
  the fixtures are the shapes its route record allows. Not run: the full
  go test ./... (only internal/gateway changed).
2026-10-14 13:26:18 +08:00
yetone e710c5accd gateway: the built-in Kiro tells Kiro where to cache the prompt (magpie-community/plugins#110)
plugins#110 ("kiro cli cache 率为 0"): a Kiro subscription read nothing
from its prompt cache. Kiro's generateAssistantResponse takes Bedrock's
cachePoint {"type":"default"} on a userInputMessage (the CodeWhisperer
streaming model in aws/amazon-q-developer-cli; Kiro CLI 2.27's model list
carries PromptCaching with up to 4 checkpoints), but neither the plugin
nor the built-in ever sent one. The plugin's fix is kiro 0.1.10
(plugins 386a2ba); this is the same for users who haven't moved.

buildKiro now marks the first message when there is a system prompt
(which it folds into that message) and the current message, the two
places buildAnthropic marks for Anthropic. gateway-routing.md says how
each Kiro path places them.

Run: gofmt -l (clean); go vet on darwin, GOOS=linux GOARCH=amd64 -tags
nogui and GOOS=windows for internal/gateway and internal/provider; go
test -count=1 ./internal/gateway ./internal/provider (ok; both isolate
HOME in TestMain). TestBuildKiroMarksTheCache fails with the current
message's mark taken out by hand, and passes with it back.
Not tried: a real Kiro account (none signed in here), so whether Kiro
then reports cache reads is for the reporter to confirm; kirocc#83 notes
Kiro often sends a metadataEvent with no token counts.
2026-10-14 13:20:36 +08:00
yetone 33da86c71a provider: removing a plugin sets its providers' model picks in providers.json aside, and adding it again puts them back (#2057, dawn1095)
A plugin's provider leaves a record in providers.json once the user
picks its models: its id and nothing of its own (OnlyPicks). Removing
the plugin left those records behind. Nothing listed them, `magpie
provider rm` couldn't reach them, and a sync or backup asked for a
sign-in to them on every run.

RemovePlugin now finds the ids the plugin's providers are stored under
(PluginID of each provider plugin.Listed gives for its spec), and moves
the records with those ids that hold only picks into providers.json's
new pluginLeft, under the plugin's package name. Left alone:
- any record with an endpoint or a key (the user's own provider,
  whatever its id);
- a built-in's ids (accountIDs) and "magpie";
- an id another installed plugin serves too;
- everything, when the plugins' listing isn't known (no cache and no
  plugin-providers.json): unknown is not "none is the user's".
provider.AddPlugin (CLI, GUI, backup restore) puts the set-aside
records back, each one whose id has no record now; one the user has
given to a provider since stays aside. plugin.Listed is new: the cached
listing, or plugin-providers.json.

Run:
- plugin_left_test.go, four tests with user-owned records beside the
  plugin's (a user "zap" with an endpoint next to the plugin's
  zap-plugin, a hand-made "mine", a built-in's picks, another plugin's
  and a shared id). Each guarantee broken by hand turned its test red:
  no set-aside, no OnlyPicks check, no other-plugin exclusion, no
  unknown-listing guard, take-back over the user's record, no take-back.
- go test ./... in a sandbox HOME; gofmt -l; go vet darwin, linux
  (-tags nogui), windows.
Not done: records left by plugins removed before this change stay where
they are; turning a plugin off (not removing it) sets nothing aside;
`magpie provider rm` still can't name such a leftover. The move flow
(installPlugin) still adds through plugin.Add, since its own
migration owns those records. Not tried with a real plugin removal in
the GUI.
2026-10-14 13:20:13 +08:00
yetone 3a7d0314a9 usage: a window's Pace as a number on its card, and in the menu bar when asked (fflake33)
fflake33 on Discord asked for the pace as a figure, "+12%" or "−8%"
against an even pace through the window, on the Usage cards and in the
menu bar.

- provider: QuotaWindow.Pace(readAt, now) is the share used (0-100) less
  the share of the window gone by, from Bounds (reset less span; a
  month's window a calendar month); none for an unlimited window, one
  whose span or reset isn't known, or outside it. WithWindowStarts sets
  startsAt on copies of the cards for the GUI (the caches' cards are
  left alone); /api/usage/quotas and its refresh send it.
- Usage page: "Pace +20%" on the reset line after the wait (quotaPace,
  paceLine), its sign turned with the meter in Left mode, amber while
  more is used than an even pace would have, what it means in its
  tooltip. Past cycles and windows with no known start show none.
- Menu bar: Settings > Menu bar pace (settings.TrayPace, off by default;
  hidden on Windows, whose tray shows no text) puts " +12%" beside each
  figure ("42% −14%", at most 10 runes, trayRowMax) and "pace −14%" in
  the tooltip. KeepOwn keeps it device-local like the other tray
  settings; the Settings save keeps it (prefsKeep).
- Strings in en, zh, zh-TW, ja, de. gui-shell.md says it.

Run:
- go test -tags nogui ./internal/provider ./internal/gui ./internal/settings
  ./internal/usage: ok; ./internal/davsync: ok (now covers TrayPace;
  red with TrayPace taken out of KeepOwn). go test ./internal/gui -run
  Tray (darwin, with the tray image tests): ok.
- New TestWindowPace, TestWithWindowStarts (input not mutated),
  TestTrayUsagePace (off unchanged, used and left, rows, tooltip).
- quota-pace.test.cjs, chromium and webkit: 4 pass; cards in en, zh,
  zh-TW, ja, de at 1100 and 420px, used and left, amber, tooltips, no
  sideways scroll, a click moves nothing; the Settings row in all five
  at both widths, On posts trayPace, a currency save keeps it, no
  scroll; hidden with no card and on Windows, shown on Linux. Red with
  paceLine not called, with trayPace out of prefsKeep, and with the
  Left-mode sign not turned.
- gui-de, gui-ja, gui-zh-tw, i18n-keys: 12 pass; tray-bird 6, quota-holds
  2, quota-read-at 4 pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.
Not tried: the real menu bar on a Mac or Linux tray.
2026-10-14 13:02:48 +08:00
yetone f074996d93 provider, gateway, gui: a model with none of its levels ticked is sent no reasoning field, on every route and in a routing group (yuexian7)
yuexian7 on Discord: models.dev lists their model as reasoning, and the
vendor answers any reasoning parameter with 422 while the same request
without it works. In a routing group they couldn't set an effort per
model, and the model editor refused to untick the last level ("Keep at
least one level"). The learned refusals (bed306ae, #1062) don't cover
this: they learn a refusal of reasoning *off* and of Gemini levels, and
optionalFields holds thinking/enable_thinking, not reasoning_effort.

- settings.ModelReasonless, set by provider.SetModelReasonless (the
  provider editor's Names & levels with every level unticked, saved as
  modelPrefs {reasonless: true}; `magpie model efforts <ref> off`).
  Ticking levels again or Restore default clears it (setModelEfforts);
  setting it drops the model's kept levels.
- entryFor and Efforts/Thinks/Levelless: the model offers no levels and
  is Quiet, so agents are given none for it.
- Gateway: the candidate loop strips the body with withoutAnyReasoning
  in the agent's protocol (Chat/Responses reasoning_effort, reasoning,
  thinking, enable_thinking, include's reasoning.encrypted_content;
  Anthropic thinking of any type and output_config.effort; Gemini
  thinkingConfig). The Anthropic relay doesn't add
  thinking:{type:disabled} for it, and forwardTranslated clears Effort,
  ThinkOff and Thinking for its other callers (continuation, search).
- A routing group with it as a member keeps the other members' levels
  (it `continue`s like a member whose levels are unknown, #597), and the
  member that reasons is still sent the effort asked.
- GUI: none ticked shows "No reasoning field sent" beside the levels, in
  zh, zh-TW, ja and de too; a model with one known level now shows its
  picker so it can be unticked. A model whose levels aren't known
  (m.given) keeps none ticked meaning no levels known.

Run (worktree on origin/main 82f3befd2, sandbox HOME, private GOCACHE):
gofmt -l clean; with set -o pipefail go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... all clean; node --check
app.js. go test -count=1 ./internal/provider ./internal/gateway
./internal/settings ./internal/cli: ok. ./internal/gui: ok except
TestMainWindowCorners/macOS_15_SDK killed at its 40s deadline under
load (AppKit window measurement, untouched here; #1936, noted there).
The run caught TestSettingsSaveKeepsWhatItDoesNotSend (ModelReasonless
added to it) and the CLI usage alignment tests (fixed).
New tests and what breaking the change does: TestReasonlessModelSentNoReasoning
(Chat, Chat+enable_thinking, Responses with include, Anthropic->Chat
translated; by name and through group/mix) and TestReasonlessAnthropicRelay
fail with gateway.go/quiet.go reverted; TestGroupReasonlessMemberKeepsLevels
fails with group.go's reasonless branch disabled; TestModelReasonless
needs the new API. model-reasonless.test.cjs in chromium and webkit, at
1100 and 420, in en, zh, zh-TW, ja, de: 20/20; on the old assets all
fail. Related GUI tests 418/418 (one model-copy-id failure on a first
run under load, passed alone; #2066).
Not tried against the reporter's real vendor: the 422 is taken from
their report.
2026-10-14 09:38:12 +08:00
yetone c4f4aaaa97 gateway: Claude's bridge no longer passes hook notices and token counts on as the user's message (#2060)
Through the Claude subscription bridge, the inner Claude Code kept saying
"The user sent a new message while you were working:" followed by a hook's
additional context, a bare <total_tokens>... line or nothing at all. The
outer agent sends these after a tool result, and saidWithResults took every
text block after a result as words the user typed mid-turn and queued them
into the inner session.

Captured from a real Claude Code 2.1.296 with PreToolUse/PostToolUse hooks
against a local mock: after a tool_result it sends a {role:"system"}
message whose one text block joins "PreToolUse:Bash hook additional
context: ...", "PostToolUse:Bash hook additional context: ...", optionally
"The user sent a new message while you were working:\n<words>\n\nThis is how
Claude Code surfaces messages ...", and "<total_tokens>N tokens left
</total_tokens>". Older clients put the same in <system-reminder> blocks;
the reporter's had an empty reminder too, which is why some of their
"messages" were empty.

- saidWithResults takes only the user's words out of a mid-turn block
  (midTurnSaid, up to the client's own tail, a reminder's end, the token
  count or the next hook notice), skips the rest of a system or developer
  message, and drops a text that is an agent notice (agentNotice: empty
  once reminder tags are stripped, a hook notice of the known kinds, a
  token count, or one of the injected leads prompt.go already knows).
- renderParts, the sibling that labels text after a result as
  [user message] in the prompt for a fresh run, closes the result instead
  for an agent notice.
- docs/subsystems/claude-subscription-bridge.md says so.

Run:
- Fixtures are the literal 2.1.296 bytes and the reporter's
  (claude_hook_notice_test.go): nothing queued for hooks and token counts;
  only "also tell me the date" queued when the user did write; the
  rendered prompt has no [user message]. A "Stop hook is broken: fix it"
  typed by the user still goes on.
- With the old condition put back and the renderParts change off, the
  three new tests fail; restored, they pass.
- gofmt -l internal/: clean. go vet ./internal/gateway on darwin,
  GOOS=linux -tags nogui, GOOS=windows (set -o pipefail): clean.
- go test -count=1 -timeout 30m ./internal/gateway: ok (667s).
- Not tried end to end through the bridge with a real Claude subscription.
2026-10-14 09:32:21 +08:00
yetone aa6a0d6b20 library: one skill over 200 MB is left out, not the whole repository (#2062)
mikubaka88/CCFA-Skills couldn't be installed at all: "the skills in ... are
too big to install (over 200 MB)". The repository is over the 200 MB
tarball cap, so fetchSkillFiles fetched it file by file, and that refused
the whole repository once the files summed past 200 MB. One skill,
ccf-paper-writer, is 297 MB on its own (exemplar paper PDFs, llava-4d.pdf
alone 46.8 MB); the other 16 are small.

The 200 MB limit per skill stays: a skill is copied into every agent that
gets one as a copy, and treeOf stops comparing at 256 MB, so a 297 MB skill
can't be told current or edited. What changes is that one such skill no
longer blocks the rest:
- fetchSkillFiles sums each skill's files (the deepest skill folder a file
  is under) and leaves out a skill over maxFetch; its files are never
  asked for. Only when every skill is over it does it fail as before.
- The left-out skills reach ProbeSkills as Probe.Left (path, size), kept
  per temp folder and taken once (tookLeftOut).
- The GUI's probe names each under the list ("{name} is too big to
  install: 283 MB, over the 200 MB a skill may be"), or in place of "No
  skills there" when nothing else is left; zh, zh-TW, ja, de. The TUI says
  it in its flash.
- docs/subsystems/library.md says how a big repository is fetched.

Run:
- Real: probe of mikubaka88/CCFA-Skills under a sandbox HOME lists 16
  skills and leaves out ccf-paper-writer (296736735 bytes). Not installed
  into a real agent.
- gofmt -l internal/: clean. go vet ./internal/gateway ./internal/library
  ./internal/tui on darwin, GOOS=linux -tags nogui, GOOS=windows (set -o
  pipefail): clean.
- go test -count=1 ./internal/library ./internal/tui: ok.
- TestOneSkillTooBigLeavesTheOthers (new): fails with the per-skill
  leave-out turned off by hand, passes with it.
  TestTooBigRepositoryChecksWhatArrives now makes every skill too big.
- skill-too-big.test.cjs (new), chromium and webkit, en 980 and zh,
  zh-TW, ja 440, de 420, plus every-skill-too-big: 14/14; red (0/7 in
  chromium) with client.js at origin/main. skill-*.test.cjs 190/190 and
  library-*.test.cjs 484/484 in both engines.
2026-10-14 09:32:21 +08:00
yetone e855272cf0 gui: a refused allow list names the address magpie sees the page from, with Add <addr> (Mathresearcher)
Settings > Share on local network > Allowed addresses refused a list that
would shut out the page itself with a fixed sentence and no address
(Mathresearcher on Discord). The server already names it (KeepsOut in
gateway/allow.go, "that allow list would shut out <addr>, the address
this page is open from"); allowSays now carries it into the message in
every language, and a one-click "Add <addr>" button saves the list with
it added.

The address is the connection's own (peerAddr: RemoteAddr, unmapped, zone
dropped); X-Forwarded-For and the like are never trusted, and loopback and
the machine's own addresses always pass. Behind Docker Desktop or rootless
Docker every client shows as Docker's own address (192.168.65.x), the host
reaching a container shows as the bridge gateway (172.17.0.1), and a proxy
in another container shows as that container. So the button's tooltip
says that behind Docker or a reverse proxy this is the proxy's address,
and adding it lets in everyone who comes through that proxy.

Run:
- allow-ips.test.cjs, chromium and webkit: 14 pass. The subtest checks
  the refusal names 203.0.113.50, the button's text and tooltip fit,
  a click posts ["172.16.0.0/12","203.0.113.50"], lists the rows, takes
  the button away and doesn't scroll. With the old app.js put back it
  fails (TimeoutError; chromium 5 pass, 2 fail).
- gui-de, gui-ja, gui-zh-tw, i18n-keys: 12 pass.
- gofmt -l (clean), go vet darwin, GOOS=linux -tags nogui, GOOS=windows:
  clean. go test -tags nogui ./internal/gui -run Allow: ok.
Not tried: a real Docker or reverse-proxy setup.
2026-10-14 09:31:01 +08:00
yetone 2eee900dc9 agent: eight more syncs keep what the user set on magpie's block (#2030's siblings)
1e654d8ce fixed T3 Code's sync, which rewrote magpie's provider instance
whole. The same shape lost user-set keys in eight more agents. On every
Sync and every pick, each one rewrote magpie's own block in the agent's
config whole. Each app's schema was taken from its own source, never
guessed:

- Qoder 1.1.70 (@qoder-ai/qodercli bundle): providers.magpie lost routing
  (the compact and subagent models), firstPayloadTimeoutMs,
  streamIdleTimeoutMs, type, authType, anthropic and a displayName.
- fx (vercel-labs/fx configured_provider.zig): reviewer_model was lost,
  and a tool_choice_mode of "omit" went back to "send". auth stays
  magpie's whole, since fx refuses an env beside type none.
- Hermes (hermes_cli/config_providers.py): `hermes model` itself writes
  default_model into providers.magpie. That was lost, as were key_cmd,
  the timeouts, extra_body, a name and extra headers. This held in every
  profile spread() writes.
- omp (models-config-schema-bundle.ts): modelOverrides, discovery,
  disableStrictTools, headers and compat flags were lost. auth and
  apiKey stay magpie's, or go, so a loopback's auth: none never sits
  beside a WSL key.
- Kimi Code (configSection.ts ProviderConfig): SetTOMLTable replaced
  [providers.magpie], losing inline custom_headers, env and
  default_model. Its three keys are now set in place.
- Cline (local-provider-registry.ts): models.json lost the provider's
  other keys, and the per-model overrides that the VS Code model editor
  writes. A model magpie no longer lists still goes.
- Goose (declarative.rs): the custom provider file was rewritten whole,
  losing display_name, timeout_seconds, toolshim, other headers and the
  like. Goose's own editor carries those keys over.
- ZCode (provider-data-schema.ts, strict): the provider rule lost
  providerName, logo, visibility, api.headers and
  access.apiKeyManagementUrl. Only keys already in the file, which ZCode
  accepted, are kept.

Each merge lays magpie's block over what is there. magpie's parts (the
address, the key, the format and the model list) are named, and a key
magpie stops writing goes with them. The JSON ones use theirsKept or
mergeKept. A new yamlKept does the same for Hermes and omp.
agent-wiring.md lists what each one keeps.

Tests: Test{Qoder,Fx,Hermes,Omp,Kimi,Cline,Goose,ZCode}KeepsTheUsersSettings.
Each one:
- connects;
- sets the user's keys the way the app writes them, plus a stale
  address and a stale model;
- adds a provider, then syncs 3 times and picks again;
- checks that the user's keys stay, that magpie's parts are rewritten,
  and that the stale model is gone.

All eight fail on origin/main's agent code (each reports "the user's
settings not kept") and pass with this change.

Run, in a sandbox HOME, with GOCACHE in the scratchpad and Go 1.26.8:
- gofmt -l on the changed files: clean.
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean.
- go test -tags nogui -timeout 45m ./internal/agent: ok, 805s.
- go test -tags nogui -timeout 45m ./...: all ok.

Not tried: none of these apps was run against a real config written by
this change. Their schemas come from their source (Qoder's npm bundle,
fx, Hermes, oh-my-pi, kimi-code, cline, goose and ZCode at their current
heads), not from a live install.
2026-10-14 09:21:18 +08:00
yetone ccffdadb8a gateway: /v1/audio/transcriptions passes speech-to-text through to the provider (#2053, niyoh120)
niyoh120 asked for an OpenAI-style speech-to-text endpoint so a client's
voice input can go through magpie like its chat does. magpie had no
/v1/audio route, so the request 404ed.

What changed:
- POST /v1/audio/transcriptions and /v1/audio/translations (and the
  /audio/... spellings) route through the same core as embeddings and
  rerank. embeddings.go's routing is pulled out into serveRetrieval, so
  disabled models, key access, groups, pause rules, account holds,
  failover, redaction and usage records are shared rather than copied.
- transcribe.go reads the multipart form only to find `model` (as
  provider/model) and `prompt`. The form goes to the provider byte for
  byte; it is rebuilt part by part, under the same boundary, only when
  the model name is rewritten or the prompt was masked. The audio part
  is always copied as sent.
- Only providers with an OpenAI-style base are tried; an Anthropic-only
  provider gets a 400 saying so. A body that isn't multipart, a form with
  no model, or one that doesn't parse gets a 400 and nothing is sent.
- The vendor's answer type passes through (response_format text/srt/vtt
  stays text/plain). Usage records output tokens from usage.output_tokens.
- The 404 message, the info api list, remote magpie's suffix list, the
  CORS and LAN tests, docs/reference.md, gateway-routing.md and the
  remote docs (en, zh, ja) name the new paths.

What was run, at 9c36c3a0 (this change rebased on 10f38770):
- gofmt -l internal/gateway internal/provider: empty
- go vet (darwin); GOOS=linux and GOOS=windows go vet -tags nogui on
  ./internal/gateway ./internal/provider: clean
- go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider:
  ok (1367s, 339s); also green on two earlier bases (b4fe6663, 06fbfd95)
- Rebased again on a0ebe003 (main had moved 5 commits, none in these
  files; routing.go's Factory rest is the nearest): gofmt, vet on darwin,
  linux (nogui) and windows (nogui) clean, and
  go test -tags nogui -run 'Transcri|Embed|Rerank|CORS|LAN|Lan|Factory|
  Retriev|NotFound|Info' ./internal/gateway ok. The full packages were not
  rerun on this last base.

Break-checks, each turned red and restored:
- routes removed (the old code): all 5 new tests fail
- model never rewritten: TestTranscriptionGoesToTheModelsProvider and
  TestTranscriptionPromptRedacted fail
- answer always labelled JSON: TestTranscriptAsTextKeepsItsType fails
- rebuild truncates the audio part: Goes + PromptRedacted fail
- prompt not masked: TestTranscriptionPromptRedacted fails
- output tokens ignored: TestTranscriptionGoesToTheModelsProvider fails

Real use: through magpie's real handler against aihubmix
(https://aihubmix.com/v1) with a `say`-made m4a: whisper-1 json 200
{"text":"Hello from the Magpie Gateway."}, response_format=text 200,
srt 200 text/plain with SRT cues, translations 200.

Not tried: OpenAI direct (the key answers 429 "account is not active"),
Groq, a local vLLM/whisper server, and any real client's voice input.
2026-10-14 09:19:16 +08:00
yetone a0ebe0032d plugin: a listed plugin whose package is gone is installed again, and bun's installs run one at a time (#2002)
anganing (Windows 11, v0.1.1229): after an auto-update, every switched-on
plugin said "no such plugin: …\node_modules\@magpie-community\opencode-grok-auth"
at each start. For the github: plugins the path was the spec itself
(node_modules\github:owner\repo), so package.json no longer listed them.
Removing a plugin and adding it again was the only way out.

- InstallMissing installs again each listed plugin (switched off or not)
  whose package isn't in plugins/, from its own spec. KeepUpdated runs
  it 30s after start and then hourly, before CheckUpdates. Nothing did
  this before: CheckUpdates skips a plugin with no installed version.
- installMu serialises every bun command that changes plugins/: install
  (including the first package.json it writes), reinstall's bun update,
  and Remove's and add's bun remove. At start KeepUpdated (30s) and
  keepMovedCurrent (20s) each run bun add with no lock. On the Windows
  box, three concurrent bun add runs (Bun 1.4.3) in one folder kept only
  one writer's package.json change. A git plugin's dependency dropped
  that way leaves Name() unresolved, which is the reporter's github rows.

The exact sequence that emptied the reporter's node_modules wasn't
reproduced. Bun 1.4.2 -> 1.4.3, magpie v0.1.1205 -> v0.1.1227 with the
same plugins, and a package.json reset all left the folders in place.
So this repairs the state and closes the one race found. It isn't
proven to be the trigger.

Run:
- go test ./internal/plugin ./internal/provider -count=1: ok.
- The new tests -count=3 on macOS, and on the Windows box as a
  cross-built test binary: ok.
- Broke each fix by hand (lock a no-op; InstallMissing returns early):
  TestBunCommandsOneAtATime fails with "another bun is running here",
  and TestMissingPluginsInstalledAgain gets 0, want 2.
- Real use on the Windows box, sandbox HOME, port 3561, real Bun 1.4.3:
  deleted opencode-grok-auth and opencode-qoder-auth from node_modules
  and started serve built from this commit. The host logged the
  reporter's exact "no such plugin" for both. At +30s it logged
  "installed 1 missing plugins again" and both folders were back.
  After the restart, no plugin failed to load.
- gofmt -l internal/: clean. go vet for darwin, linux -tags nogui and
  windows (plugin, provider, gateway), and GOOS=windows go build ./...:
  ok.
2026-10-14 09:17:47 +08:00
yetone 8cb0946fbe gateway: a Factory usage-limit 402 that arrives before the account's windows are read rests only that model once they are (#2036, Ziqi-Cui)
#1979 rests only the model when Factory answers 402 "You've reached your
weekly standard usage limit" and the account's windows say Standard's
pool is the one used up. Before the windows are read (just after a
start, or after a reading failed) nothing tells the pool from the
account, so the whole account rested, Droid Core's models with it,
until the reset the refusal named, often days.

Such a rest now starts narrowWhenRead in the background: it waits for a
reading (provider.AwaitAllowance, up to a minute), and if the reading
says the model's pool is the one used up, moves the rest to the model
alone (restID) with the same end. No reading in time, a reading that
says the whole account, or a rest lifted or made again meanwhile leaves
the account's rest as it is.

CodeAlex52's patch (c623610) waited for the reading inside the request
for up to 10s. That holds the failover the client is waiting on, so the
wait is off the request instead: the request has failed over already,
and the rest's scope only matters to later ones. The gateway's TestMain
turns the wait off so no test's goroutine asks a fake upstream after
the test ends; the tests that need it swap it in and wait on
narrowing.

Run: TestFactoryStandardOutLeavesCore's new unread case (built-in and
plugin windows) and TestResetsInWords' no-reading case; the unread case
fails with the narrowing removed; -race -count=3 on both; full
go test -tags nogui ./internal/gateway in a sandbox HOME; gofmt -l
clean; go vet darwin, linux nogui, windows nogui.
docs/subsystems/gateway-routing.md's 402 paragraph says so.
2026-10-14 09:15:21 +08:00
yetone 2076943915 plugin: a plugin declares its own switches, shown in its provider's editor and read by the plugin (#2038, Vocllum)
Vocllum asked that a plugin can offer the user generic on/off options
without magpie knowing what each one is for. A plugin now declares them
on its auth hook, beside checkin:

  auth.options: [{ key, label, description?, default?, confirm? }]

and reads the user's values through input.magpie.option(provider, key)
or input.magpie.options(provider). Each call reads the current values,
so a change reaches the plugin without a restart. magpie only keeps the
value and hands it over: nothing is scheduled or run when an option
changes. The check-in switch (settings.pluginCheckins) and the check-in
plugins are unchanged.

- host.js: optionsOf keeps a key matching [a-z0-9_-]{1,40} with a
  non-empty label, drops repeats, caps the label at 60 characters and
  the description and confirm at 300, takes default only when it is
  true, and keeps at most 16. The values come at init and through
  setProviderOptions.
- Go: plugin.Option, Provider.Options, OptionOn and SetProviderOptions
  (sent only to a host that is running). settings.PluginOptions is kept
  by the plugin's provider id, then the key. POST
  /api/settings/plugin-option {provider, key, on} checks the key the same
  way and hands the values to the host. The generic settings save keeps
  them, as it keeps PluginCheckins. /api/providers' plugins[].options
  carry each option's resolved `on`.
- GUI: a "Plugin options" field in a plugin provider's editor. Each
  option is a segs Off/On beside the plugin's label and description, put
  in with textContent. A confirm text is asked through confirmAction
  before turning an option on. Changes wait for Save, which posts each
  one before the provider. Strings are added for zh, zh-TW, ja and de.
- Docs: provider-plugins.md (a new section), reference.md, gui-shell.md
  and the tests README.

Run:
- TestPluginOptions (a real host with testdata/options). Red with the
  old host.js (no options listed) and red with setProviderOptions turned
  into a no-op (the plugin still reads the old value).
- TestPluginOptionSetting and TestSettingsSaveKeepsWhatItDoesNotSend.
  Both red with the generic save's PluginOptions line removed.
- plugin-options.test.cjs: 22/22 in Chromium and WebKit, at 1100 and 420
  wide, in en, zh, zh-TW, ja and de. Red on the old app.js (no field).
  The screenshots were looked at: long text wraps and the page has no
  sideways scroll at 420.
- provider-concurrency, plugin-signin, plugin-checkin, provider-price-rate
  and plugin-move-unserved: 68/68.
- go test ./internal/plugin/... ./internal/settings/... ./internal/gui/...
  ./internal/provider/..., gofmt -l, and go vet on darwin, linux
  (-tags nogui) and windows.

Not tried with a real community plugin, since none declares options yet.
The check-in row doesn't take a plugin-declared label or hint; it is
left as it was.
2026-10-14 08:50:41 +08:00
yetone 8da304767a gui: Library is a plugin's page, its script, style and words in plugins/library
P2 of docs/subsystems/plugin-runtime.md, the second page after Sessions.

- library.js and library.css move to assets/plugins/library/ (client.js,
  library.css). The script registers with the kernel
  (magpie.plugin("library")) and adds its page to the "page" slot. Its
  hooks: open and relang load, redraw, close (its modal), dirty, discard.
  What it set up at load (list scroll and resize, the modal's backdrop
  and Escape, beforeunload, the stuck header, a quiet reload on focus)
  runs in mount.
- app.js calls those through magpie.call instead of window.loadLibrary,
  redrawLibrary, closeLibraryModal, libraryDirty and discardLibrary. It
  no longer lists library in its title map, hide loop or OPEN_VIEWS; the
  kernel's pages are in them.
- index.html: <main id="view-library"> goes, the kernel makes it.
  library.css keeps its place in the cascade.
- The 560 strings only Library says move from i18n.js to
  plugins/library/i18n.js (4 languages). i18n.js: 18826 → 16584 lines.
- plugins/library/library.go lists the client files.
- Tests that read i18n.js for a Library string read strings.cjs (i18n.js
  and the plugins'): 8 library tests and mcp-editor-cancel,
  mcp-oauth-app, mcp-signin-health. font-cascade, win-fonts and
  assets_revalidate_test.go name the new paths.
- "Check again" stays in i18n.js: Library said it alone when the words
  were split, and a5d72a095 (Settings' search keys) says it too since.
  i18n-keys has a new test, "a plugin's words are its own": a key in a
  plugin's i18n.js that any file outside the plugin's folder says fails
  it, naming the file. It was red on this key, and search-keys.test.cjs
  said "Check again" had no zh translation.
- docs: library.md, gui-shell.md, plugin-runtime.md.

Run, at this tree:
- 101 GUI test files touching Library, skills, MCP, the plugins, the
  shell and every language (gui-de/ja/zh-tw, i18n-keys, page-width,
  view-no-sideways, mobile-web, text-size, …): Chromium and WebKit, 4 at
  a time, all green but one. text-size's "zh: 100% picked at the foot"
  failed once in Chromium under load ("scrolled from 160 to 109 (max
  115)"); it passed alone, 6 at once here and on origin/main 8f34bbcd1,
  and at 6× and 12× CPU throttling. It's the Settings page, already
  "fixed" by 50dd39104, so I filed it as #2058.
- After rebasing onto origin/main 75cbc7e1e: i18n-keys, search-keys,
  library-mcp-tools, library-all, gui-de, mono-icon-redraw,
  group-first-token, Chromium and WebKit, green.
- go test ./internal/gui/ ./internal/pluginrt/ ./plugins/...; gofmt;
  go vet on darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
2026-10-14 08:33:25 +08:00
yetone 1eaf1e890a gui: Sessions is a plugin's page, its script, styles and words under assets/plugins/sessions (P2)
The first page of P2 to leave app.js's core. sessions.js and sessions.css
move to assets/plugins/sessions/ (client.js, sessions.css). The page
registers through the kernel as magpie.plugin("sessions"): mount takes its
<main>, which the kernel now makes, open and relang read it again, and
reveal is the Usage page's way in. window.loadSessionsPage and
window.openSessionOnPage are gone. app.js reaches the page only through
magpie.call, and show() takes a page's title from its part. The plugin's
manifest lists i18n.js, sessions.css and client.js.

Words: the kernel's magpie.strings(dict) adds a plugin's words to I18N.
A key that is already there is logged and not taken, since the later one
would silently win. The 65 keys only the Sessions page says (own-keys over
every asset, Go and index.html) move, as written, from i18n.js to
plugins/sessions/i18n.js. tests/strings.cjs reads i18n.js and every
plugin's i18n.js as the page has them. gui-de/ja/zh-tw use it, and
i18n-keys now checks that no key is said twice across files and that a
plugin's words are in every language. TestBuiltinClientsLoaded takes a
.css entry as a <link> in <head>, and a script between kernel.js and
app.js.

Docs: plugin-runtime.md (Words, Pages moved out: Sessions), gui-shell.md,
gateway-sessions.md.

Run:
- go test ./internal/gui/ ./internal/pluginrt/ ./internal/gateway/: ok.
- gofmt clean. go vet darwin, GOOS=linux -tags nogui and GOOS=windows on
  gui, pluginrt and plugins: clean.
- GUI, in both chromium and webkit, 40 files, all green:
  - the sessions-* and sess-* tests, session-identity, routing-sessions,
    account-mask-sessions, usage-session*, gateway-conversations;
  - plugin-kernel, the plugin-move* tests, font-cascade, win-fonts;
  - i18n-keys, gui-de, gui-ja, gui-zh-tw.
- session-terminal's red under parallel load is the same on origin/main
  591ed58b5. It is fixed at its cause in the commit before this one.
2026-10-14 08:33:24 +08:00
yetone 2d8f2a86a5 sessions: Kimi Code sessions open as a transcript (#2056)
infinitr0us: a Kimi Code session on the Sessions page had no transcript
to open. HasTranscript now lists kimi, and kimiTranscript reads the
session's main wire.jsonl:
- protocol 1.4/1.5: turn.prompt and turn.steer (a prompt not from the
  user, a skill's activation or a background task's news, is folded as
  context), and the loop events content.part (text, think), tool.call
  and tool.result, a result named for its call. These are there for
  every session, finished or running; agent.message.appended (1.5, only
  at a turn's end) and the timed context.append_message records say the
  same again and are passed over.
- kimi-cli imports (1.0, and the head of a ses_* session Kimi Code
  reopened): the untimed context.append_message records, with an
  assistant's toolCalls in both shapes (name/arguments and OpenAI's
  function.{name,arguments}).
Search and markdown export read the same parts.

Run:
- TestKimiCodeTranscript on the #1607 reporter's wire files in testdata
  (1.4, a cancelled 1.4, an early 1.5 started by a skill, a failed 1.5,
  a kimi-cli import), and TestKimiCodeTranscriptOrder on a synthetic
  file in the same record shapes, exact part order plus SearchSession.
- Broken by hand: kimi out of HasTranscript fails both tests; reading
  the timed context.append_message records fails both (user/text 9,
  not 3).
- A nogui build's `magpie web` under a sandbox HOME, KIMI_CODE_HOME on
  the reporter's whole zip (8 sessions, the July subagent session and
  a reopened ses_* among them): all 8 listed with a transcript;
  /api/sessions/transcript gave 105, 13 and 205 parts for June, the
  reopened ses_* and July; the markdown export worked.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows;
  go test -tags nogui ./internal/sessions/ ./internal/gui/.

Not tried: a live Kimi Code session on this machine (none here; the kimi
installed is kimi-cli 1.52.0), the GUI's look of the transcript, WSL.
A subagent's own wire file isn't shown; the main agent's is.
2026-10-14 08:28:52 +08:00
yetone 75cbc7e1e5 provider: a subscription switched off or removed makes no background requests, no claude auth status every minute (Riko on Discord)
Riko switched Claude off in Providers, and magpie still ran
`claude auth status --json` about every minute. Off only kept the
gateway from routing to it. Every page and request lists accounts,
which re-asked the CLI, and the background loops went on reading
allowances, renewing, switching, warming, checking in and fetching lists.
The same held for each sibling with a CLI or account check: Cursor
(`cursor-agent about`), Devin (`devin auth status`) and the rest.

What changed:
- left_alone.go: leftAlone(id), true for a provider that is Off or
  Hidden (account removed).
- account.go claudeIdentity and cli_identity.go get (Cursor, Devin): the
  CLI isn't asked; what it said last (memory or cli-identity.json) is
  served, so the account stays listed to switch on again.
- subscription_usage.go: claude, cursor and grok are checked as hidden
  before their account is looked up (the look-up ran the CLI).
- login_usage.go loginUsageAt, keepalive.go RenewLogins,
  codex_switch.go NextLogin, codex_warmup.go keepWarm: leftAlone where
  only accountRemoved (or nothing) was checked.
- models.go newDue: a provider that is off has no list fetched.
- checkin.go: each check-in account knows its card's provider; the loop
  skips one that is left alone, a press still checks it in (minimax,
  trae, qoder, workbuddy, plugin check-ins set it).
- docs/subsystems/providers-accounts.md says so.
Not covered: KeepPluginsListed lists every plugin at once in the host. A
Cursor switched off that was never asked who is signed in isn't listed
until switched on.

What was run:
- TestLeftAloneRunsNoCLI: fake claude, cursor-agent and devin on PATH log
  each run; with claude and cursor off and devin removed, All, Hidden,
  fetchSubscriptionUsage, LoginUsage, RenewLogins, SwitchWhenSpent and
  FetchNew run three times over stale caches and no CLI is run; switched
  back on, all three are asked again.
- Break check: with the source changes reverted it fails with
  "switched off or removed, the CLIs were run: [claude_auth_status_--json
  cursor-agent_about_--format_json devin_auth_status ...]"; with only the
  claude gate removed only claude is logged, with only cliIdentity's only
  cursor and devin.
- go test -tags nogui -timeout 45m ./internal/provider ./internal/gateway:
  ok (399s, 1271s).
- gofmt -l: clean. go vet (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean, under set -o pipefail.
2026-10-14 08:28:08 +08:00
yetoneandlu123bing c9af654b26 gateway: Kimi Code takes a Claude Code session that loaded a deferred tool, and DeepSeek one that dropped a tool (#2042, davisjiahao)
Claude Code's deferred tools (ToolSearch, MCP tools that come and go) put
blocks of their own in a message: tool_addition (its tool a
tool_reference naming the tool, or a tool_definition), tool_removal, and
tool_reference. magpie relays an Anthropic body as it is, so they reached
vendors' Anthropic endpoints.

Checked against the real endpoints on 2026-10-14 (a Kimi Code CN key, a
DeepSeek key; shapes read from Claude Code 2.1.296's own builder):
- Kimi Code refuses any of them, in any role and either tool shape, with a
  whole-request 400 "Invalid request Error" that names nothing; a
  tool_reference inside a tool_result passes.
- DeepSeek takes a tool_addition naming a tool, but refuses one defining
  it, a tool_removal and a message's tool_reference: 422 "messages[1].
  content: unknown variant `tool_removal`, expected one of ...".

What changed:
- withoutDeferredTools (anthropic_shapes.go) drops those message blocks
  and a message they leave empty. The tools stay in the request's tools,
  and ToolSearch's answer (a tool_reference inside a tool_result) stays.
- Kimi (isKimi) is never sent them: its 400 says nothing to learn from.
- Any provider that refuses one in DeepSeek's words is marked
  (shapeDeferred, refuseShapes) and asked again at once without them, and
  not sent them again while magpie runs. The shape-retry loop in forward
  now reads a 422 as well as a 400 (refuseShapes and refuseBetas only act
  on wording they recognise).
- Anthropic and every provider that takes them get them as Claude Code
  wrote them. Kimi's bare "Invalid request Error" is not added to
  shapeWords: it names no field, and with the blocks gone there is nothing
  left for it to cover.
- docs/subsystems/gateway-routing.md: a paragraph on the above.

Builds on lu123bing's fork branch (c4a0564), widened from Kimi to the
learned refusal after the DeepSeek check; this keeps a tool_addition
naming a tool for providers that take it.

Run:
- TestKimiIsSentNoDeferredToolBlocks (the reporter's literal body plus
  Claude Code's real shapes, through Handler) and
  TestDeferredToolBlocksRefusedOnceLeftOut (DeepSeek's literal 422,
  learned once; a provider that takes them keeps getting them).
- Break checks, each red: without the Kimi drop, 5 subtests "status 400:
  Kimi Code: Invalid request Error"; with the loop on 400 only, and
  without the mark, "status 422: DeepSeek: ... unknown variant
  `tool_removal`". Restored: green.
- Real use: a nogui build served from a sandbox HOME on 127.0.0.1:35211
  with copies of the Kimi Code CN and DeepSeek providers. The reporter's
  body to kimi-for-coding now reaches Kimi's account check (403, the test
  key's plan has lapsed) instead of the 400; a tool_removal to DeepSeek
  reaches its balance check (402) instead of the 422. A full successful
  Kimi turn wasn't possible on this key.
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on internal/gateway; go test -tags nogui ./internal/gateway/
  in a sandbox HOME: ok (1516s). An earlier run of the same suite, with
  five other gateway.test binaries running on the machine, ended FAIL
  after 1484s; its output was cut to the last 30 lines, which held no
  test name, so the failing test is not known.

Co-authored-by: lu123bing <12312702@mail.sustech.edu.cn>
2026-10-14 08:26:38 +08:00
yetone a5d72a095b gateway, gui, cli: a search API's keys take turns, a refused one rests, and each Tavily key shows what it has used (SlouchyQuill)
SlouchyQuill on Discord asked for a Tavily key pool after
dsh-tavily-pool: several keys, each key's quota shown, keys rotated.
Before this, the comma-separated keys (#1477) always started from the
key that last answered, so one key took every search until it was
refused, a refused key kept no rest of its own, and nothing showed what
a key had left.

What changed:
- Turns (internal/gateway/search_keys.go). Searches take turns over the
  keys by default (round robin, a counter per vendor). pick=order (CLI)
  or In order (Settings) always starts from the first key; the pick is
  saved in SearchAPI.Pick.
- Rests. A refused key rests: 401/403 for 10m ("turned away"), 402 for
  1h ("out of credit"), 429 for its Retry-After held to 30s-10m (1m
  without one). 432/433 count as out of credit from Tavily only; from
  any other vendor they rest as a rate limit. A resting key is asked
  after the others, soonest back first, so failover is kept, and it
  wakes when it answers. Rests are keyed by a hash of the key.
- Quota (internal/gateway/search_quota.go). Each Tavily key's quota is
  read from GET /usage with that key. The fixture is the documented
  reply from docs.tavily.com. The key's own limit is used when it has
  one; otherwise its plan's plan_limit/plan_usage, which the account's
  keys share. A failed read, or a reply missing those fields, says
  unknown and why, never 0. A read is kept 2m unless asked fresh. A key
  found used up with no pay-as-you-go credit rests 1h; a later read
  with credit wakes it.
- Keys never appear in full. The vendor's error has the key masked
  (tvly-…abcd), and errors name "key N (tvly-…abcd)".
- GUI. Settings › Models › Web search adds a "Keys of <API>" row under
  an API with several keys or with Tavily's: In turn / In order, each
  key masked with what it has used and why it is asked last, and Check
  again. There is an API for it (POST /api/settings/search-quota), and
  13 strings in zh, zh-TW, ja and de.
- CLI. `magpie search` lists the pick and each Tavily key's quota, read
  fresh; `magpie search add … pick=turns|order`.
- Docs. gateway-routing.md has a new section "A search API's keys";
  both READMEs have a line on web search.

What was run:
- go test -tags nogui ./internal/gateway ./internal/provider
  ./internal/cli ./internal/gui: ok. After the last rebase, provider
  and cli again, and gateway -race -run Search.
- New tests: TestReadTavilyUsage, TestSearchKeysTakeTurnsRoundRobin,
  TestSearchKeyRefusedRests, TestSearchRestFor, TestSearchQuotas and
  TestSearchKeyNeverInFull. Each guarantee was broken by hand and its
  tests went red:
  - turns pinned to the first key: RoundRobin and RefusedRests;
  - rests ignored: TestSearchAPIKeysTakeTurns, RefusedRests and
    TestSearchQuotas;
  - key masking removed: NeverInFull;
  - a failed read reported as known: TestSearchQuotas.
- gofmt -l; go vet -tags nogui for darwin, linux and windows on the
  four packages.
- GUI: search-keys.test.cjs covers en, zh, zh-TW, ja and de ×
  Chromium and WebKit × 1100 and 420px: 20/20. Without the new
  .search-keys .val wrap rule, de at 420px fails ("Erneut prüfen" went
  past the window's edge).
  - search-api, search-first, search-instead, search-mcp,
    searcher-pick, settings-search, provider-search, gui-de, gui-ja and
    i18n-keys: 56/56 in each engine.
  - Full suite in Chromium (concurrency 6, load ~40): 4498/4504. The
    files that failed (gateway-key-groups, rest-try-now,
    routing-wb-restricted, text-size, usage-sum-whole) were rerun
    alone. All pass except usage-sum-whole, which fails now and then
    on an origin/main worktree too under the same load (#1864, #2023;
    rest-try-now and routing-wb-restricted are #1905). None of them
    touch search.
- Real Tavily API with two invalid keys: /search returns 401
  {"detail":{"error":"Unauthorized: missing or invalid API key."}},
  which counts as a refusal. Both keys rest 10m as turned away, the
  error names them only masked, and both quotas read "unknown · 401".
  Checked through a test and through the nogui CLI binary in a sandbox
  HOME.

Not tried: a valid key's /usage against the real API. No Tavily key
was at hand, so the quota parsing is checked against the documented
bytes only.
2026-10-14 08:24:03 +08:00
yetone 1555cddfa0 agent: with Claude Desktop on magpie, Claude Code runs each model at its own window, not the least of them all (#2025, 6.1sol)
Claude Desktop's Code tab runs Claude Code on ~/.claude/settings.json
with every model Desktop lists. Claude Code takes one window
(CLAUDE_CODE_MAX_CONTEXT_TOKENS) for every model it doesn't know, and
magpie told it the least of Desktop's (#1458), so one small model held
a 500K or 1M one to its 131K.

Now, while Desktop is on magpie, magpie tells Claude Code the largest
window of Desktop's models and of Claude Code's own main and tier
models, and holds each model below it to its own with
modelSettings.<id>.autoCompactWindow (claudePlan, claude_budget.go).
CLAUDE_CODE_AUTO_COMPACT_WINDOW would take precedence over those, so in
this mode magpie's working window goes in the top-level
autoCompactWindow instead, and an entry is written only where a
model's window or threshold differs from what it would run at
without one. Claude models (and groups of them) are left out as
before. magpie's entries and top-level value are stashed and go when
Desktop leaves magpie. The user's own entries, top-level value and
variables are never written over: an entry of theirs past its model's
window (or "auto") holds the largest to that window, and with a
CLAUDE_CODE_AUTO_COMPACT_WINDOW of theirs the least window is told as
before. Desktop off is unchanged.

Verified with real Claude Code 2.1.296 in a sandbox
CLAUDE_CONFIG_DIR, on a settings.json written through magpie's editor:
/context shows 256k for mythos-magpie-2's entry, 131k for
magpie/v/gpt-6.1-sol (dotted key, with and without [1m]), and the
top-level 272k for a model without an entry, under a 1M
MAX_CONTEXT_TOKENS.

Tests: TestClaudePlan and TestBudgetPath (new), and
TestClaudeDesktopContextWindow / TestClaudeDesktopAloneContextWindow
rewritten (largest window, per-model entries, Full window, the user's
entry and top-level kept, Desktop off removing only magpie's). They fail
on the old claude.go (256000 told), and with the skip of the user's
entries removed from claudePlan. Run: go test ./internal/agent (full),
gofmt -l, go vet for darwin, GOOS=linux -tags nogui and GOOS=windows.
2026-10-14 08:17:33 +08:00
yetone f71155591e provider: a provider at a vendor's own endpoint is priced from that endpoint's models.dev catalog (#2052, mengyianx)
A custom provider added by its address alone, with no catalog named, was
priced only by the model's maker. Qwen3.8-27B, whose maker (Alibaba) sells
no such model on any of its seven models.dev catalogs, read "no price is
known for it" even at AMD's own endpoint, where models.dev's amd lists it
at $0, a price.

- catalog: models.dev's provider "api" is read; AtEndpoint names the
  catalogs at a base URL (trailing slash and case ignored).
- provider: EndpointCatalog is the one catalog models.dev lists at one of
  a key's provider's endpoints (an Anthropic base, kept as its root, also
  with /v1), used by ListPrice when the provider has no catalog of its
  own. Never for a subscription's account, never when two catalogs share
  the address (minimax / minimax-coding-plan), never a plan's catalog
  (an id with -plan, or membershipCatalogs), whose $0 is the membership's.
  A user's price and a named catalog still come first; a relay's endpoint
  matches nothing and its model stays unpriced (no reseller guess).
- cli: `magpie model price p/m` with no price gives the two commands that
  set one (p/m and */m); a price from an endpoint's catalog names it.
- gui: the Catalog field's hint says it also sets list prices (en, zh,
  zh-TW, ja, de).
- docs: reference.md's "What a model costs", providers-accounts.md row.

What was run:
- Reporter's exact case, built binary (go build -tags nogui), sandbox
  HOME with a copy of this machine's models.dev cache (2026-10-14, same
  amd entry as the report), providers 001 (relay), 002 and amd at
  https://developer.amd.com.cn/radeon/api/v1:
    001/gpt-5.5      $5/$30, tiers, as before
    001/Qwen3.8-27B  no price, now with the two commands to set one
    002/Qwen3.8-27B  $0/$0, "what models.dev's amd lists at its endpoint"
    amd/Qwen3.8-27B  $0/$0
  The two suggested commands were run and took effect.
- TestEndpointCatalogPrices / TestEndpointCatalogOnlyItsOwn, fixture
  testdata/endpoint_catalog.json trimmed from the real models.dev cache.
  Break checks, each FAILs with the case named:
    ListPrice not using EndpointCatalog -> 002/amd/001 at AMD unpriced,
      EffectivePrice(002, Qwen3.8-27B) unpriced
    plan exclusion removed -> "a plan's endpoint: EndpointCatalog() =
      alibaba-coding-plan", qwen3.5-plus at $0 instead of $0.4/$2.4
    single-match rule removed -> "an endpoint two catalogs share:
      EndpointCatalog() = minimax"
    Account check removed -> "a subscription's account ... = amd"
    Anthropic /v1 match removed -> thinkingmachines unmatched
- GUI: internal/gui/tests/catalog-hint.test.cjs, chromium and webkit, en
  zh zh-TW ja de, widths 1100 and 420: 20/20 pass, plus i18n-keys; with
  the old app.js/i18n.js it fails "one hint names list prices".
- go test -tags nogui -timeout 45m ./internal/catalog ./internal/provider
  ./internal/cli: ok (provider 244s, cli 125s, catalog 3s). gofmt -l
  clean; go vet (darwin), GOOS=linux go vet -tags nogui and GOOS=windows
  go vet -tags nogui on those packages: clean.
2026-10-14 07:51:41 +08:00
fjrtdk 8f34bbcd11 library: Grok Build and Grok App can be given hooks (#1790)
The Hooks tab said "Grok App has no hooks magpie can write" and RTK said
"No rtk hook". RTK stays correct for now (rtk init has no Grok agent), but
the hooks message was wrong: the Grok CLI keeps hooks as [[hooks.<Event>]]
array tables in its config.toml, which Grok App reads from agent-home on a
custom route. Hindsight already ships three hooks into both configs.

Add grok and grok-app to hookAgents with a TOML hook spec. A hook is written
as a [[hooks.<Event>]] table with a [[hooks.<Event>.hooks]] child, the same
find/claim/drop logic as a JSON agent's: the block text is recorded entry by
entry, so only a block still exactly as magpie wrote it is ever taken out,
and the user's own blocks around it stay as they are. Portable events map to
Stop / PostToolUse / PreToolUse / UserPromptSubmit / SessionStart; a tool
matcher uses Grok's own tool names (run_terminal_command, search_replace).
Grok Build and Grok App run the one CLI, so a grok:<Event> own event goes to
both (sameHookFamily).

edit gains WriteTOMLFile and SplitLines so the library can round-trip a
config's lines through the same validating write the other TOML editors use.

Verification (branch grokapp-hooks):
- TestHooksGrokConfigTables fails on the pre-change code with a real FAIL
  ("Grok Build has no hooks magpie can write"); passes with the change.
  Broke the matcher map, the drop and the event map by hand; each break is
  caught by the test.
- go test ./internal/library ./internal/edit: 811 passed (was 828 before the
  two new grok cases and the hookAgents additions).
- gofmt -l clean; go vet on mac, GOOS=linux -tags nogui, and GOOS=windows all
  clean; go build, GOOS=linux go build -tags nogui and GOOS=windows go build
  all succeed.
- go test -tags nogui ./... has three pre-existing failures on base cdb7b5ff
  (internal/gateway TestGrokCallsGiveCodexIntegers, internal/library
  TestRTKCheckLatestDoesNotWaitForThePackageManager, internal/proc
  TestNoCommandBypassesProc); none is in a file this change touches, and each
  reproduces without it.
- Real use: confirmed against the local Grok App 0.2.40 / grok 1.0.55 install
  that agent-home/config.toml already carries Hindsight's [[hooks.*]] tables,
  so the shape matches what magpie now writes. The GUI Hooks tab is driven by
  the backend hookAgents view, which now lists grok and grok-app; the Tauri
  window itself was not clicked through.

Reviewed before landing (fu13-pt, on e297a8ab2 + #1889/#1897/#1900/#1989):
- The shape is Grok's own: grok 1.0.50's binary carries its user guide
  (10-hooks.md), which reads hooks from ~/.grok/config.toml as
  [[hooks.<Event>]] with an optional matcher and an inner hooks array,
  the [[hooks.<Event>.hooks]] form accepted; handler fields type, command,
  url, timeout, env; run_terminal_command and search_replace are its tool
  names (Bash and Edit|Write|MultiEdit are aliases of them).
- A scratch test (not committed) on a config holding a user's inline
  `hooks = [ {...} ]` Stop block, a comment, [mcp_servers.x], a user
  PreToolUse block and [ui]: add (Stop, PreToolUse on shell), edit the
  timeout, remove both. The file parsed as TOML at each step with the
  arrays as Grok reads them, and came back byte for byte. A config with a
  plain [hooks] table (Stop = [...]) is refused as a problem ("key value
  already exists as a Stop, but should be an array table"), file unchanged.
- Drop broken by hand (never drops a block): TestHooksGrokConfigTables and
  TestHooksGrokOwnEventBoth both FAIL with the blocks left; restored, pass.
- Not tried: the Grok App window, and a running grok reading the result.
  Grok App in shared mode reads ~/.grok, not agent-home, as its MCP row
  already does.
2026-10-14 05:43:48 +08:00
yetone 4fbb75c3a8 gateway: Codex's 507 "exceeded request buffer limit" is asked again and told as a 503, not relayed as it came (#2034, sparrowu93)
sparrowu93's pi, on a ChatGPT account, stopped on
"Codex: 507 Insufficient Storage: exceeded request buffer limit while
retrying upstream". That text is Envoy's (ChatGPT's front): its first
try at the backend failed, and the body was more than it buffers to
try again. It is the same backend failure as #1628's 503 "reset before
headers", which magpie already asks again for without resting anybody,
only for a body the front couldn't retry itself. magpie relayed the 507
as it came; pi's _isRetryableError (pi-coding-agent 0.73.0,
agent-session.js) matches 503 but not 507 or these words, so the turn
just ended.

codexDropped now reads that 507 (by Envoy's words alone, any size, since
the 507 itself says the body was large) the way it reads the large
request's 503: the accounts loop asks the next account and the last one
again, nobody rests, and the agent is told a 503 with Envoy's words and
what may help (/compact, fewer or smaller images). The relayed path
(codexUpstreamOn, Codex's own sign-in) asks again the same way: the two
share edgeMayDrop/edgeSaidDrop. A 507 in other words is relayed as it
came. gateway-routing.md says so.

Run:
- New TestCodexUnbufferedAskedAgain, TestCodexUnbufferedTold503,
  TestCodexUnbufferedRelayed, TestCodexOther507Stays, with the
  reporter's literal Envoy text as the fixture. On the old code the first
  three fail: "status 507, want 200 pong: {...\"message\":\"Codex: 507
  Insufficient Storage: exceeded request buffer limit while retrying
  upstream\"...}" (the reporter's message byte for byte), and
  "507 once: 507 ... tried [acct-1]". With edgeSaidDrop matching every
  507, TestCodexOther507Stays fails. Restored, all pass, with #1628's
  TestCodexReset* tests.
- go test -tags nogui ./internal/gateway/ (sandbox HOME, pinned caches),
  gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  (with and without nogui) on internal/gateway.
Not tried: a real 507 from ChatGPT (it needs the backend to fail a
request over Envoy's buffer, which can't be made to happen on purpose).
2026-10-14 05:37:00 +08:00
yetone ea3ea11729 gateway: an image request to a routing group moves on to the next member when one answers 5xx (#2005, tianxia3111)
/v1/images/generations sent to a routing:"order" group only ever drew on
the member the model resolved to; a 502 from it went straight back to the
caller even though the group had other members that could draw.

draw.go: when the asked model names a group (group/<id>, or a bare id
whose group holds the resolved member), drawingTries lists the members in
planGroup's order and the request moves on with chat's retryable rule
(5xx, 429, auth and quota refusals). A request the caller got wrong
(plain 400) still stops at once. Pause rules and a gateway key's model
holds apply per group as in chat. Drawing still rests no account. The
recent call records the skipped members as Fallback, and the final error
says "(tried first: ...)", as embeddings do.

video.go: /v1/videos had the same single-member path. Its start logic
moved into startVideo, and videosCreate walks the same tries; a member
that can't make videos moves on too.

Run: TestImageGroupMovesOnToTheNextMember and
TestVideoGroupMovesOnToTheNextMember go red (502) with either loop forced
to stop after the first member, and the image test goes red with the
retryable check removed. go test -tags nogui ./... (full suite), gofmt -l,
go vet for darwin, GOOS=linux and GOOS=windows on internal/gateway.
Not tried against the reporter's real providers.
2026-10-14 05:32:31 +08:00
NorethSea 56fcd1dc27 usage: each account picks a recorded allowance cycle beside its curve, meters and legend following it (#2009, NorethSea)
Let each account choose completed cycles beside its allowance curve. The
meters, sampling dates, plot and legend follow that cycle. Missing readings
stay unknown, and current account actions and whole-window estimates are
not presented as historical data. Fixed-deadline refills preserve cycle
boundaries alongside natural and early resets.

Keep the upstream whole-window estimate for the current view; no separate
price endpoint or duplicate estimation is added.

Verified on the integrated tree based on origin/main a75de4c2:
- 155 allowance, translation and scroll UI tests pass in Chromium/WebKit.
- Quota history race tests pass with count=3.
- macOS/Linux/Windows vet and builds pass.
- New Go cases fail without the unchanged-deadline refill handling; the UI
  case fails against upstream assets because the picker is absent.
- Real local allowance snapshots confirm cycle and meter switching.
- Full Go suite has one failure: TestPluginModelListThroughAccountProxy
  exceeds its context deadline. Other packages, including provider, usage
  and gui, pass. No release or complete-suite pass is claimed.

Reviewed and landed by yetone's agent from NorethSea's commit 69021d2c8,
cherry-picked onto origin/main (README conflict only: both appends kept).
Run at this head: go test -tags nogui ./internal/provider -run Quota,
-race -count=3 -run QuotaHistory, gofmt, GOOS=linux/windows go vet;
TestQuotaHistoryUnscheduledResets goes red with the refill rule removed.
GUI: quota-*, usage-*, balance-*, panel-usage, tray-*, click-scroll,
i18n-keys, gui-ja/de/zh-tw in Chromium and WebKit: 923/926; the three
reds are usage-sum-whole (also red 3 of 4 runs alone on origin/main
591ed58b5, #1864) and a usage-ledger case that passes alone.
2026-10-14 05:32:03 +08:00
yetone 59a8aec5df agent: Claude Code's /model takes models added in magpie again when the picker magpie wrote has lost its mark (#2046, cjyrainbow)
cjyrainbow's WSL Claude Code (Ubuntu) kept an old /model list: a model
added in magpie was in the gateway's /v1/models but not in modelPicker.
settings.json held the picker magpie wrote (every row "… · via magpie"),
but stash.json had no claude@wsl:Ubuntu.model_picker mark for it, so
writePicker took it for the user's own and never wrote it again. An
older magpie's stash lost keys (concurrent writes / a stash that didn't
parse, fixed in 270b5257), which is the likely way the mark went.

claudeIn's pickerOurs now also counts a picker whose every row has a
model and a description ending "via magpie" (magpiesPicker) as magpie's.
That holds for native and every WSL distro, since all go through
claudeIn with their own place key. Sync rewrites it and marks it again;
Disconnect removes it, as it does a marked one. A picker with any row of
the user's own (another description) stays theirs.

docs/subsystems/agent-wiring.md says when the picker is magpie's.

Verification:
- New TestClaudePickerMagpieWroteIsKeptUpToDateWithoutItsMark, native
  and wsl subtests: the reporter's state (picker written by magpie, mark
  forgotten, a model added, Sync) and a user-written picker after it.
- Broke it by hand: with the old pickerOurs both subtests fail "a model
  added in magpie isn't in /model: [cpa/gpt-6-luna cpa/claude-sonnet-4-6]";
  with the fingerprint ignoring descriptions both fail "the user's own
  picker was written over".
- go test -tags nogui ./internal/agent/ (count=1): ok, 1412s, on
  origin/main 591ed58b5.
- gofmt -l clean; go vet ./internal/agent/ on darwin, GOOS=linux -tags
  nogui and GOOS=windows.
- Not tried against a real WSL distro or the reporter's settings.json.
2026-10-14 05:29:56 +08:00
yetoneandBussanQ 3aa22f9d9c gateway: a translated Responses reply keeps the web search that ran, with its query and sources (#2044, BussanQ)
What changed: responsesEncoder.event gets a KSearch case and
renderResponses a Search case. Both emit a completed web_search_call
item (ws_ id, action.type "search", query plus queries, and the
nonempty source URLs in action.sources) through the shared
responsesSearchItem. The stream adds the item, sends
response.web_search_call.completed {item_id, output_index} and
output_item.done, and the same item stays in the terminal response's
output, in order with text, reasoning and client tool calls.

Why: a search magpie ran for a model that can't search (searchRounds),
or one decoded from an upstream Responses or Anthropic reply, reached
the client only as answer text. Anthropic clients already got
server_tool_use / web_search_tool_result; Responses clients (bqAgent)
had no record that a search ran or what it found. No earlier progress
events or url_citation offsets are invented.

From BussanQ's reference commit b1a4e7b, reviewed line by line and
applied onto origin/main. Added on review:
TestResponsesSearchItemReplayed (the item sent back as the next input,
as Codex does, parses and leaves the turn's messages unchanged) and a
docs line saying so.

What was run (sandbox HOME, pinned caches, go1.26.8):
- go test -tags nogui -count=1 ./internal/gateway -run
  'TestResponsesSearch.*|TestWebSearchForAModelThatCannot|
  TestSearchToldAsAnthropics|TestWebSearchAskedOfEachAPI|
  TestAnthropicServerToolLeftOut|TestParallelToolCallIDs|
  TestResponsesStreamToolThenHiddenThinking': ok
- Break check: origin/main's responses.go put back with the new tests:
  TestResponsesSearchResults "search output lost or reordered: got
  [message message function_call]", TestResponsesSearchDecodedResults
  "decoded provider search missing", TestResponsesSearchFollowedByFailure
  "completed search or subsequent error lost", and
  TestWebSearchForAModelThatCannot "delegated search missing from
  Responses output" all FAIL; pass with the change restored.
- go test -tags nogui ./internal/gateway (whole package)
- gofmt -l; go vet -tags nogui for darwin, GOOS=linux, GOOS=windows
Not run: a live provider; the full repository suite.

Co-authored-by: BussanQ <bussanq@gmail.com>
2026-10-14 05:23:58 +08:00
yetone bf25842714 gateway: a provider's own cap on how long a key that keeps failing rests (#2008, Gaudi-XIX)
A key that keeps failing doubles its rest from a minute up to 10 minutes,
and one rate limited again as soon as its rest is over up to 30; both
caps were fixed, so a free key down for hours was asked again every 10
or 30 minutes all the while.

`magpie provider rest-cap <id> 4h` (Provider.RestCap, minutes, at most
MaxQuotaRest, 8 days) sets where both ladders stop for that provider's
keys and accounts (RestCapOr in restAfterMarked's default branch and in
rateRest); `default` gives back the gateway's own. A time the vendor names
still stands over it. Unset, nothing differs. It is kept by the editor's
save, the account copy and normalize.

Run: go test -tags nogui ./internal/provider ./internal/gateway
./internal/cli ./internal/gui (temp HOME). Broken by hand: both ladders
back on the fixed caps fail TestOwnRestCap (rate-long #6: 30m, want 32m);
the GUI keep removed fails TestSaveKeepsQuotaResetAt. Not tried against a
real vendor's outage.
2026-10-14 05:22:40 +08:00
yetone 064cffdbfd gateway: a key out of a daily allowance rests until the time of day it comes back (#2008, Gaudi-XIX)
A free tier's "You've reached today's free-model token quota" says
nothing of when it is back, so it rested 15 minutes (or the provider's
own quota-rest), and was asked again all day. A vendor Retry-After over
an hour was cut to the hour, and that hour then stood over the user's own
longer rest.

- Provider.QuotaResetAt: "08:00" on this computer's clock, or
  "00:00+08:00" on the vendor's. `magpie provider quota-rest <id> until
  08:00` sets it; a number of minutes set after it replaces it, and
  default clears both. normalize drops one that isn't a time of day.
  It is kept by the editor's save and the account copy.
- restAfterMarked's quota branch rests until its next occurrence
  (OwnQuotaRest). A time the vendor names, or a window's end, still
  stands over it; a Retry-After stands unless it was cut to longestWait
  while the user's own rest is longer.
- Defaults are unchanged: nothing set, nothing differs.

Run: go test -tags nogui ./internal/provider ./internal/gateway
./internal/cli ./internal/gui (temp HOME). Broken by hand, each fails:
OwnQuotaRest replaced by QuotaRestFor (TestQuotaRestsUntilTheTimeOfDaySet,
3 asserts), the Retry-After guard removed (the 7200 case), the GUI keep
removed (TestSaveKeepsQuotaResetAt), default not clearing it
(TestQuotaRestUntil). Not tried against a real free-tier vendor.
2026-10-14 05:22:39 +08:00
yetone 77f90fd84f gateway: a plugin whose config hook says searches: true is sent the client's web_search as sent (#2027, yudaleng)
A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api
relay whose quota the plugin reads) had no way to say its upstream runs
the hosted web search tool: searchesItself returned at once for any
signed-in account, letting only Codex and Grok through, so Claude Code's
WebSearch and Codex's web_search always went through magpie's own search.

Now a plugin's config hook can set `searches: true` on its provider, as
it sets `decide` (#1514). The host passes it through
(plugin.Provider.Searches), pluginProvider sets the provider's Searches,
and searchesItself honours it for a plugin's provider only, on Anthropic
or Responses and only where the plugin has a model on that API, the same
rule a custom provider's "Searches the web by itself" has (#359). Another
sign-in's Searches is never read; Codex and Grok are unchanged. As with a
relay, searchRank leaves it out, so magpie never picks it to search for
other models; Settings can name it by hand.

Documented in docs/subsystems/provider-plugins.md and the plugin guide
(site/public/docs plugins.html, en/zh/ja).

Verified:
- TestPluginSaidToSearch (new, gateway, through the real fake plugin on
  bun and New().Handler()): with FAKE_SEARCHES the plugin's upstream gets
  web_search_20250305; without it, it gets no search tool; Chat doesn't
  search and searchRank is -1 either way.
- Broken by hand, each red: search.go reverted, plugins.go reverted,
  host.js reverted (each "searches by itself on Anthropic: false"); with
  the searchesItself assertion disabled and search.go reverted, the wire
  check fails "said to search true, the plugin was sent []".
- TestMovedGrokSearchesItself, TestGrokPluginSearchesItself,
  TestWebSearch* pass.
- go test -tags nogui ./internal/plugin ./internal/provider ok, and
  ./internal/gateway (see the run noted on #2027) under a sandbox HOME
  with pinned caches; gofmt -l clean; GOOS=linux and GOOS=windows
  go vet -tags nogui on the three packages clean.
- Not tried with a real CPA/sub2api plugin.
2026-10-14 05:17:31 +08:00
ggbdpqandfactory-droid[bot] 1a7aa76b4b mcpauth: an MCP sign-in canceled while its token is being fetched no longer saves the late token or replaces the server's sign-in (#1750, ggbdpq)
Cancel set the flow canceled, but a callback already trading its code
went on to write mcp-signins.json and call Changed when the token came
back, so a sign-in the user had ended was saved, and an existing
sign-in to that server was replaced. The callback's write now happens
under the flow's lock only while the flow is live (flow.keep), so
Cancel or the timeout and the commit can't both win; a commit that wins
still tells the agents before the flow says done.

ggbdpq's patch (46440adc), cherry-picked unchanged.

Run (reviewer): TestCanceledMCPCallbackDoesNotSave (real discovery,
registration, PKCE and loopback callback against mcpauthtest, the token
reply held until Cancel) fails on the old mcpauth.go in both cases
("saved credentials", "redistributed credentials 1 times") and passes
with it, -race -count=5; go test -race ./internal/mcpauth/... ok.
Not tried with a real MCP server's OAuth.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2026-10-14 04:59:08 +08:00
ggbdpqandfactory-droid[bot] 509328ccb0 provider: a Codex reset spent while an allowance read is in flight is never undone by that read, even on Windows' coarse clock (#1754, ggbdpq)
Allowances took time.Now() when its background read began, and
forgetAllowance stamped the reset with time.Now(); a reading was dropped
only when the reset was After the start. On Windows two events in one
clock tick get the same time, so a read begun before a spent reset could
put the account's 100% back right after it. Reads and resets are now
ordered by a generation counter under usedCache's lock.

ggbdpq's patch (e07232ef), cherry-picked unchanged.

Run (reviewer): TestResetAllowanceKnownAtOnce, Windows test binary on
the Windows box (sandbox USERPROFILE/APPDATA), -count=10: old code FAIL
4 of 10 ("routing reads 100 used (known true), want 0"), this change
PASS 10 of 10. macOS -race -count=20 of the Allowance/Renewed tests ok.
Full provider package, gofmt, linux and windows vet: see the push.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2026-10-14 04:59:07 +08:00
yetone 17d4283a5a library, gui: a hook has a description in any language, shown under its name (#2011, emo172)
A hook's name is letters, digits, - and _ (checkName), so a Chinese user
had to translate "auto-format-queue" back in their head; 编辑后格式化 was
refused. Hook now has an optional Description: one line (whitespace and
line breaks folded into single spaces) of at most 200 characters, kept
in library.json only and never written into an agent's hooks file. The
Hooks tab shows it under the name; the editor has a Description field
(maxlength 200) under Name. The library's text fields no longer save or
close on an Enter or Escape that only ends an input method's composition
(isComposing / keyCode 229), which a Chinese description would hit.
Strings in zh, zh-TW, ja and de; docs/subsystems/library.md says it.

The reporter's other option, non-ASCII names, wasn't taken: the
description says more than a name can, and names stay one rule across
servers, skills and hooks.

Run: TestHookDescription (kept through a save, an agents change and a
rename, read by the page, no agent file has it, 201 characters refused,
200 kept) fails with the folding and the length check removed.
library-hooks.test.cjs (a description under the name, none for a hook
without, the field's placeholder and hint, an IME Enter posts nothing,
Save posts the description) fails on the old library.js and with the IME
guard removed. library-*, gui-de, gui-ja, gui-zh-tw, i18n-keys and
click-scroll pass in Chromium and WebKit (263/263 each). go test -tags
nogui ./internal/library ./internal/gui under a temp HOME, gofmt -l,
GOOS=linux and GOOS=windows go vet -tags nogui ./internal/library pass.
2026-10-14 04:18:36 +08:00
yetone 2dcc51417e plugins: the window gets a plugin kernel, and the Gateway page is the first page a plugin draws (P1)
P1 of docs/subsystems/plugin-runtime.md. P0 (3ccbe6bc1) gave built-in
plugins a manifest, plugins.yml and a switch; their pages were still
app.js's own code. Now the window has a kernel a plugin draws its page
through, and the Gateway page moved into plugins/gateway to prove it.

What changed:
- internal/gui/assets/kernel.js (new): window.magpie. A plugin
  registers with magpie.plugin(id, setup); ctx.slots.add("page", part)
  puts its markup where index.html's <template data-slot="page"> is.
  The shell calls its hooks through magpie.call, behind an error
  boundary: a hook that throws, or whose promise fails, is logged and
  its page shows "This page stopped working", what broke and Try
  again, while every other page goes on. ctx.ui is the kit (button,
  switch, the app menu, a settings row) and ui.form draws a plugin's
  settings from their schema. ctx.config / onConfig carry the settings,
  from boot.js before the first paint and from Plugins › Built-in after.
- internal/pluginrt/schema.go (new): a plugin's settings are a Go
  struct (Manifest.Settings); SchemaOf makes the JSON Schema the form
  is drawn from, and Validate is what SetConfig (config.go) takes into
  plugins.yml. Compose drops a hand-edited value the schema refuses.
- plugins/gateway: the Gateway page as a plugin, Essential and in use
  while a gateway key is there. One setting, callsPage (10/20/50/100,
  20 by default). Its client is plugins/gateway/{keys.js,client.js},
  moved out of app.js (and caller-keys.js) unchanged in behaviour.
- internal/gui: builtins.go takes POST {id, config} beside {id, on}
  and lists each plugin's schema and config; boot.js carries
  pluginConfig; /plugins/<id>/… files are served. Plugins › Built-in
  draws a plugin's settings rows under its switch.
- Docs: plugin-runtime.md has "The window's kernel (P1)"; gui-shell.md,
  subsystems/README.md and tests/README.md updated.

What was run:
- go test ./... (sandbox HOME, pinned caches): all packages ok;
  gofmt -l clean; go vet on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- New tests: TestSchemaOf, TestValidate, TestSetConfig,
  TestBuiltinConfig, TestBuiltinClientsLoaded;
  plugin-kernel.test.cjs (a page that throws breaks only itself and
  Try again draws it, at 1100 and 420 in en, zh, zh-TW, ja, de;
  callsPage from boot.js and from Plugins › Built-in), both engines.
- Broken by hand, each turned its test red: the boundary's catch
  removed; Try again not putting the page's markup back; the Gateway
  page's onConfig not re-reading callsPage; boot.js's pluginConfig
  ignored; SetConfig skipping Validate.
- The full GUI suite in Chromium and WebKit (node --test *.test.cjs).
  One red was this change's own. providers-fetching-retry lifts
  providersWhileFetching out of app.js, which now asks providersPage,
  and the lift lacked it. The test now lifts that too, and gains "a poll
  under the Gateway page, a plugin's page that reads with Providers,
  reads". That case goes red with providersPage dropped from the poll's
  guard.
- The reds that were on origin/main a75de4c21 too are fixed in their
  own commits after this one. Two of them came from P0's Built-in tab:
  nav-sub-unroll and plugin-check-github-limit.
2026-10-13 20:39:39 +08:00
yetone a0dc89e5cf agent: a proxy on this machine with a route of its own reaches magpie too, and a pick in Claude Code keeps it (#1985)
ffd077869 took the issue's nginx example (https://ai.corp.example/magpie)
and left loopback out as "magpie on an older port". The reporter's follow-up
on #1985 is the real case: a company-mandated compliance proxy at
http://127.0.0.1:8788/claude-code-anthropic/<route> in front of
127.0.0.1:3425, which every Claude Code request must go through. On
ffd077869 that was still "unwired", Reconnect and a pick wrote 3425 back
(bypassing the proxy), and the sync did too.

- reach.go: proxyBase also takes a loopback address with a path of its own
  (loopbackWithPath). The gateway's own address, and so an older port's,
  has none, so port moves still move those. surelyMagpie: magpie has
  answered there (not merely untried), for writes.
- keptaway.go: the sync keeps such a route where magpie answered or hasn't
  been asked; one where something else answered follows the gateway.
- claude.go: routed() and the written ANTHROPIC_BASE_URL (gwAt) keep a
  proxy where magpie answered, so a model picked in magpie keeps the
  proxy and a tier's own model; before the answer, or at a relay, a pick
  points Claude Code at this magpie as before. claudeStandInAt too.
- codex.go: codexKeptGateway keeps a loopback route as well.

Run (sandbox HOME, worktree at origin/main + this):
- go test -tags nogui ./internal/agent: ok (471s).
- TestReverseProxyIsStillMagpie now runs every agent at the nginx address
  and at the reporter's local route; TestClaudeBehindLocalProxyKeepsIt is
  the reporter's case: no drift, a pick keeps the URL and a tier's own
  model, the sync keeps it, a relay there is told and a pick re-points.
- Broke by hand, each red: proxyBase without loopback (claude,
  claude-desktop... unwired), keptAway's loopback branch (every file back
  on 127.0.0.1:3591), gwAt (pick wrote 127.0.0.1:3425), routed (haiku's
  own model went), codexKeptGateway without loopback.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: the reporter's real proxy daemon; other agents' picks still
point at this magpie (the sync and Reconnect keep the proxy for them).
2026-10-13 18:26:03 +08:00
yetone 47ec2a969f provider: a Sub2API Claude account comes in by its email_address, with its account and organization (#1975)
KKKKKKKEM's Sub2API export of a Claude OAuth account was refused, "the
file doesn't say which Claude account this is": sub2apiEntry read only
credentials.email, and Sub2API keeps a Claude account's email under
Anthropic's own name, email_address. Its CreateAccountModal stores the
token Sub2API was given whole as credentials ({...tokenInfo}: access_token,
refresh_token, expires_at, scope, org_uuid, account_uuid, email_address)
and the uuids and email again in extra (useAccountOAuth's
buildExtraInfo); read in Wei-Shaw/sub2api's source.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Not tried: a real nginx (Host rewriting, auth in front of GET /), the
Windows box, a real CC Switch. No GUI change.
2026-10-13 18:07:03 +08:00
yetone 12ecb6d8e9 gateway: a gateway key held to a budget, models or accounts is told none of this magpie's accounts, only its own limit and routes (#1981)
321sssrt-bit shared magpie on the LAN with a gateway key held to a budget,
and that key still read every account's quota and balance. A held key
(heldKey: a budget, models or accounts) is someone else's to use, so it
now gets 403 with code gateway_key_held (refuseHeld) on
/v1/magpie/quotas, quotas/history, quotas/cards, POST quotas/refresh and
/v1/magpie/concurrency. That holds from loopback as well as the LAN, the
same as usageSummary already did. /v1/magpie/route tells it only the
routes of its own requests. Route.callerKey is set by trace.beginFor at
all five begin sites, so a route begun without it fails closed. It still
reads its own limit at /v1/magpie/limit. Unrestricted keys and the local
owner are unchanged.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Not tried: the real ChatGPT.app's predictions against magpie (the
feature is gated server-side by /wham/predictions/config and isn't on for
the owner's account); the reply shape is from the app's bundle.
2026-10-13 17:23:00 +08:00