Commit Graph
805 Commits
Author SHA1 Message Date
yetone ebf3f48f7f usage: a reported call takes first_text_ms and flow_ms, so a reasoning reply tells its speed and a burst is held (#2637)
POST /v1/magpie/usage/requests turned away first_text_ms and flow_ms as
"not a field a reported record takes", so a reported reasoning reply was
timed from its first reasoning token and a burst-at-the-end reply was
never held. The ingest now takes both, validated like ttft_ms (whole
milliseconds, 0..ingestMaxMillis, null = unset), and checks:
- first_text_ms <= ms, and first_text_ms >= ttft_ms when both are set
  (the first text is content too);
- flow_ms <= ms*10/8+1, since the gateway's flow is the tenth-to-nine-
  tenths span scaled by 10/8 and can exceed ms.
The fields reach usage.jsonl through the Record, so DecodeOf, Row.Decode
(ThinkPace, HeldShare) and the Reported totals read them as they do the
gateway's own rows. docs/reference.md and gateway-sessions.md say so.

Tests: TestUsageIngestTellsSpeed posts the reporter's literal repro
(grok-4.7, out 307, reasoning 129, ms 5035, ttft 4632, first_text 4700:
178 tokens over 335ms), a burst held by flow_ms, an even reply told, and
a ThinkPace hold, and checks the totals. TestUsageIngestTimesChecked
covers each bound, its edge, null and absent fields.

Broken by hand: old code fails both tests (field refused); dropping
FirstText tells repro-1 0; dropping Flow tells the burst 601/4035;
removing the ttft check accepts first_text 299 < ttft 300; bounding flow
by ms rejects the valid 1501.

Run at 8bb9375e7 + this diff: gofmt -l clean; go vet ./... on darwin,
GOOS=linux and GOOS=windows -tags nogui clean; set -o pipefail; go test
-timeout 45m ./... exit 0 (66 ok, gateway 1192s) under a sandbox HOME and
private GOCACHE (an earlier run against the shared cache had build
errors from cache files removed mid-run, not code). Machine load ~250.
Not tried with a real reporting client.
2026-10-17 10:14:03 +08:00
yetone 333c167575 routing: a rule can set the reasoning its model is asked for (#2633)
dengtongcai asked for a routing rule that picks both the model and the
reasoning it is asked for (a quick question goes to a cheap model at low).
A rule now has an output field, useEffort (low|medium|high|xhigh|max). When
the rule matches, its member is asked for that effort. A member's own fixed
effort still wins. Otherwise the rule beats the model's suffix, the turn's
pick and the agent's pick. The existing effort condition is unchanged.

- The value is fitted to the model's levels (max -> high on a model that
  tops out at high). A model with no Efforts is sent what the agent asked,
  untouched. Unset changes nothing. Failover members are not affected.
- The trace records it: Rule.UseEffort and the try's RuleEffort (the second
  Try construction in the candidate loop was missing it).
- Saving a group rejects an unknown value or one on a pause (cleanRules).
  The CLI takes use-effort=; the TUI and CLI lists show " at <effort>".
- GUI: a chip after the rule's model, picked from the app menu (pickFrom,
  no native select), set/changed from the rule's menu. A pause clears it.
  Strings in zh, zh-TW, ja, de.
- A Gemini-protocol client is left unchanged, as with every effort magpie
  sets.
- Docs: docs/subsystems/gateway-routing.md; site docs intent and start (en,
  zh, ja).

What was run, at d4c03a2c5 (rebased on d4a1b9baa) unless said:
- gofmt -l: none. go vet ./... (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./...: clean.
- go test -count=1 ./internal/gateway ./internal/provider ./internal/cli
  ./internal/tui: ok.
- The full go test -timeout 45m ./... under pipefail, before the rebase at
  6f950653f: every package ok except internal/gui. There, 8 real-window
  darwin tests were killed at their deadlines with the load average at
  150-300. Four passed on a rerun. TestMainWindowCorners,
  TestMainWindowRightToLeft, TestTrayCellClickReleasedPanel and
  TestCoveredWindowStaysUp fail the same way on a clean 6f950653f checkout
  (added to #1936). This change has no Go in internal/gui.
- Broken by hand: ruleEffort returning "" turns the four gateway tests red
  (Chat member, intent rule, failover member, Anthropic member). Returning
  the raw value for a model with no levels turns the unset/no-levels test
  red. Dropping the cleanRules checks turns TestCleanRulesUseEffort red.
  routing-rule-effort.test.cjs against the 6f950653f routing client.js and
  i18n.js is red.
- GUI: routing-rule-effort.test.cjs passes 18/18 in chromium and webkit
  (en, zh, zh-TW, ja, de; 1100 and 420 wide). The 140 GUI files that open
  the Routing view ran 560 tests before the run stopped with no summary.
  Two of the 560 were red: group-from-model-add (#2388) and
  name-suffix-where-named (filed #2640, a skeleton-row race). Both pass
  alone. The whole 791-file suite was not finished. At a load near 280 it
  covered about 20 files in 40 minutes. The reds it showed were in
  account-* files, and account-models passes 12/12 alone.
- Then rebased onto 8bb9375e7 (#2635, internal/library only) and
  go build ./... at the final head.
2026-10-17 10:04:39 +08:00
yetone df3734b959 proc: the login shell's variables count only when exported, and Codex's proxy detail names the variable it read (#2627)
ReneXiong: Codex showed the "proxied" drift, "through the proxy at
http://127.0.0.1:7890, set in HTTP_PROXY", while Codex went direct. The
value was fish's universal http_proxy from an old Clash setup, never
exported (`set -S` says "unexported"), so no program fish starts has it.
shellEnv asks fish beside the login shell (zsh), and shellProbe printed
"$http_proxy" in the shell itself, which expands unexported variables too;
mergeShellEnv then filled zsh's empty value with fish's.

Fix at the shared reader: every shell is now asked to run
/bin/sh -c 'printf ... "$PATH" "$CODEX_HOME" ...', the form nushell already
used (still with its ^). A child sees only exported variables, so each
value is what an agent started from that shell gets. This covers every
reader of the probe: Codex's proxy (codexEnv), Claude Code's provider
switches (claudeShellEnv), and agentenv.Vars such as CODEX_HOME and
CLAUDE_CONFIG_DIR that magpie takes into its own environment; an
unexported zsh or bash variable no longer counts either, which matches what
an agent run from that terminal sees. Proxy variables are still merged from
fish when the login shell has none: a fish user who exports one runs Codex
with it from fish, so taking proxies from the login shell only (the
report's other suggestion) would miss that case.

codexProxyFor named HTTP_PROXY (or HTTPS_PROXY, ALL_PROXY) for a value in
the lowercase variable. It now names the one it read, in both the reqwest
and respect_system_proxy paths, and the detail's NO_PROXY advice matches a
lowercase name too (and not "the system's proxy settings").

Other proxy readers checked: the daemon's carried env, wslrun's proxyVars,
netproxy and the plugin host read magpie's own environment, not a shell;
the WSL probe scripts ask for no proxy variable.

Tests: TestLoginEnvUnexportedNotCounted, a login shell with the reporter's
literal values unexported beside an exported NO_PROXY; TestShellEnvRealFish
now writes the reporter's literal fish_variables lines and checks that
http_proxy, https_proxy and all_proxy read empty;
TestCodexProxyNamesItsVariable. Broken by hand, each went red: the old
in-shell printf (unexported values read back, in the fake shell and in real
fish 3.7.1), and env() naming keys[0].

Run: go test ./internal/proc and the codex proxy tests on darwin;
TestShellEnvRealFish, TestShellEnvFishLogin and
TestLoginEnvUnexportedNotCounted on real fish 3.7.1 in an alpine container
(linux/arm64), green with the fix and red without it; gofmt -l clean; go vet
-tags nogui ./... for darwin, linux and windows; the full go test -tags
nogui -timeout 45m ./... under pipefail, both fixes together on
origin/main ec6454395: exit 0, 66 packages ok, no FAIL.

Not tried: the reporter's Mac with fish itself, and nushell (not installed
here; TestShellEnvNushell's real-nu part skipped, its probe-shape check
passes).
2026-10-17 05:35:45 +08:00
yetoneandggbdpq ed0335f75c gateway: an assistant turn cut off before it said anything is left out of what a Chat upstream is sent (#2599)
timonwong (#2599): after the user stops a reply while the model is still
thinking, the agent keeps a turn with no text and no calls and sends it
again on every later turn. Translated (buildChat) or relayed, it reached
the Chat upstream as {"role":"assistant","content":""} (reasoning_content
alone, on DeepSeek), and DeepSeek and Kimi turned every request of the
conversation away: "Invalid assistant message: content or tool_calls must
be set".

One rule, withoutSilentAssistants (chat.go), runs on both Chat routes:
buildChat before pairToolMessages (Claude Code, Codex and Gemini clients,
and the plugins fed by buildChat), and silentAssistantsOut in passthrough
next to developerAsSystem (a Chat client's own body). An assistant
message with no content or only blank text parts, and no tool_calls or
function_call, is left out; the user messages it stood between join into
one (texts with a blank line, else their parts in order), so no two user
messages stand in a row. A prefill (prefix, partial, a Resume), a legacy
function_call, a refusal and an audio reply stay. A relayed body without
such a turn goes byte for byte. TestChatThinkingOnlyAssistantKeptOutside-
Exchange pinned the old pass-through; it now expects the joined message.

Built on ggbdpq's patch (cb438ebb on their fork) and its fake upstream,
written again because the review found it missed shapes the issue names:
- after a tool result it kept the empty turn ("a strict template wants the
  reply behind its tool message"), so the interruption mid tool loop still
  sent content "" and still got the 400. tool then user is what any agent
  sends when the user writes after a tool result; it is now left out.
- the relay dropped an assistant with a legacy function_call or a refusal
  and empty content, and a client's own prefix/partial prefill;
  kept blank text-part arrays (still refused); joined only string users;
  re-marshalled with HTML escaping.
- its Resume check compared a joinSplitCalls turn index with
  len(r.Messages)-1.

Verified (sandbox HOME, pinned caches, go1.26.8 darwin/arm64, base
origin/main 72d6103e2):
- The fake upstream refuses with the issue's literal 400 body any
  assistant without content or tool_calls, plus DeepSeek's #1462/#1822
  reasoning rule. On main's product code 18 subtests of the new tests go
  red with that 400 (Claude Code: thinking, redacted, empty text,
  thinking+empty text, [], "", after a tool result; Codex: lone reasoning,
  empty output_text, no content; Gemini thought-only; relay: "", null, no
  content, blank parts, after a tool result; relay keeps-what-speaks), and
  TestChatThinkingOnlyAssistantLeftOutOutsideExchange. With ggbdpq's
  product files instead, after-a-tool-result (both routes), blank parts
  and TestChatRelaySilentAssistantsOnly are red. With this change all
  pass; TestChatResumeEmptyPrefillKept is a guard, green before and after.
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux, windows:
  ok. Full suite with both this and the #2575 test change in the tree,
  set -o pipefail; go test -tags nogui -timeout 45m ./... : 66 packages
  ok, none failed (internal/gateway 825s, internal/provider 266s).
- Rebased onto origin/main ec6454395 (claude_subscription, ir.go):
  gofmt clean, vet darwin/linux/windows on internal/gateway and
  internal/settings ok; go test -tags nogui -timeout 45m
  ./internal/gateway ./internal/settings: ok (gateway 668s).
- Not tried against real DeepSeek or Kimi (the fake answers with the
  issue's bytes). Gemini and Responses upstreams are not changed; the
  Messages build already drops an empty turn and merges same-role
  neighbours (anthropicBody's push).

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
2026-10-17 05:15:16 +08:00
yetone ec64543952 claude: a switch gives a Claude subscription's run the agent's instructions as its system prompt, in place of Claude Code's
Every request through a Claude subscription is answered by the real
Claude Code, which sends its own system prompt, with the agent's
instructions in the run's first user message. Settings › Replies › Short
Claude system prompt (claudeLeanPrompt, off by default) starts the run
with --system-prompt-file holding the agent's instructions instead
(without a client Claude Code's billing line, plus the tool-choice
line), and the first message holds the conversation alone. The file is
under the distro's mount in WSL. A request with client cache marks
(#1717) is never lean. The mode is part of the run's identity, so a run
started in one mode never takes the other's turns. The row says the
risk: requests look less like Claude Code's own.

Measured with a real Claude subscription, Sonnet 5.5, Claude Code
2.1.301, off then on:
- chat client, ~600-token prompt, 2 tools, 3 turns: 10,048 -> 6,580
  input tokens (-35%)
- claude -p as the client, Read and Bash, 4 requests: 85,453/85,471 ->
  81,948/81,977 (-4%)
A fixed ~0.9-1.2K tokens a request.

Run at this head (rebased on 72d6103e2):
- go test -tags nogui -timeout 45m -count=1 ./...: all 66 packages ok
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./... ok
- TestClaudeLeanPrompt*: 4 pass; each guard broken by hand goes red
  (cacheIdentity's lean bytes, the tool-results mode check, the
  client-cache exclusion, the WSL path)
- whole GUI suite (before the rebase, machine load ~300-430): the 23 red
  files were rerun alone here and on origin/main. mobile-web's settings
  screenshot differed from main because of the new row; it now takes
  the row out until BASE_REF has it, as it does for other new parts,
  and passes with claude-lean-prompt-setting (4 languages, 1100/420,
  chromium and webkit). The rest are red on main too or under load and
  already filed: usage-agents-hide (#2276, #2399), routing-bodies
  (#2559), routing-model-rest (#2115), sidebar-overlay-scrollbar
  (#1863); plugin-other-ways passed alone.
2026-10-17 04:39:59 +08:00
yetone 72d6103e28 gateway: a Chat tool in MCP's or another API's shape goes upstream as a Chat function tool (#2622)
jinyue806 (#2622): ZCode sends its tools on /v1/chat/completions in MCP's
shape, {"name","description","inputSchema"}, with no type and no function
object. magpie relayed them as they came, and SenseNova turned every request
with tools away ("field Tools[0].Type invalid, should be set"; a flat
{"type":"function","name":…} got "function cannot be empty"). A missing
type is invalid Chat Completions for every upstream, not SenseNova only, and
the translated routes were broken too: parseChat read no name from such a
tool, so Messages and Responses upstreams were offered a tool named "".

shapeChatTools puts a tool with its name at the top (no type, or type
"function" without a function object) into {"type":"function","function":
{name, description, parameters, strict}}, parameters taken from
parameters, inputSchema or input_schema; other fields stay beside it. It
runs right after liftMessageTools at the same two choke points: handle, for
every Chat body before routing (relay, schema fixers, redaction, plugins),
and parseChat, for a body that never came through handle. A tool that has
its function, a hosted tool (any other type) and one with no name are left
alone, and a request with nothing to shape is relayed byte for byte.

Verified:
- TestChatToolInAnotherShapeIsShaped sends the reporter's curl body with
  each of the four tool shapes from the report through the Chat relay,
  Messages and Responses. With shapeChatTools made a no-op by hand all 12
  subtests FAIL: relayed as {"name":"f","inputSchema":{…}} as it came, and
  translated as {"name":"",…}. TestShapeChatToolsLeavesChatShape (byte for
  byte on Chat-shaped/hosted/nameless tools; strict and cache_control kept)
  FAILs on the same break. Both pass restored.
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux, windows: ok.
- Full suite at 81313b912 + this change, sandbox HOME, pinned caches:
  set -o pipefail; go test -tags nogui -timeout 45m ./... : 59 packages ok
  (internal/gateway 1134s, internal/provider 548s). 7 packages failed only
  on "no space left on device" while the disk filled mid-run (cli
  TestModelDisableCmd, library TestAgentMCPFiles, sessions
  TestCodexTitleEvidenceBound, settings TestSaveConcurrent, and gui, tui,
  usage which printed PASS but couldn't write testlog.txt). Rerun once
  space was back (30G free): cli, gui, library, sessions, settings, tui,
  usage all ok.
- Rebased onto origin/main a69cd0707 (#2611's chat call ids, chattidy):
  gofmt clean, vet darwin/linux/windows on internal/gateway ok,
  go test -tags nogui -timeout 45m ./internal/gateway ./internal/source:
  ok (gateway 510s). No other package changed between the two bases.
- Not tried against the real SenseNova (no key here); the reporter's own
  table shows {"type":"function","function":{…}} answered 200.

The "inference request is invalid ... reason=unknown retryable=false" text
in the report is not magpie's (no such string in the repo); it is the
client's wrapper of the upstream error, so nothing changed there.
2026-10-17 04:07:25 +08:00
yetone a69cd07075 gateway: a Chat tool call kept with an empty id goes with one made from its place (#2611, RunMintOn)
RunMintOn's session held an assistant turn whose tool call had "id":""
and a tool result with "tool_call_id":"". magpie relayed it unchanged on
Chat->Chat, and WorkBuddy AI turned the whole request away (400, 11133).
Chat->Messages sent tool_use id "" and Chat->Responses gave the call a
random id while its result kept "".

- chatCallIDs (chat_call_ids.go) runs in attempt for every Chat request,
  before the relay, the translation and a plugin's fetch alike (a moved
  WorkBuddy AI goes through the plugin, so the edit must come first). An
  empty, null or missing call id gets "call_" + a hash of the call's
  message index, position, name and arguments: the same on every resend,
  so the prompt-cache prefix holds. A result with an empty tool_call_id
  takes the turn's unanswered calls in order. A body that already has its
  ids comes back byte-identical.
- chatTidy gives a stream's first fragment of each (choice, index) call an
  id when the upstream sent none, and drops an empty id on later ones;
  chatWhole fills a whole reply's empty ids.
- docs/subsystems/gateway-routing.md says so.

Tests (chat_call_ids_test.go), fixtures from the issue's literal bytes,
against a fake that refuses as WorkBuddy AI does:
- TestEmptyCallIDRelayedWithOne, TestEmptyCallIDReachesPluginWithOne
  (movedFake workbuddy-ai), TestEmptyCallIDTranslatedWithOne (messages,
  responses), TestChatCallIDsLeavesWhatHasIDs, TestStreamedCallGivenAnID,
  TestWholeReplyCallGivenAnID.
- Broken by hand, each watched red: edit removed (relay and plugin get
  the 400; translations send an empty or unpaired id); a random id in
  place of the placed one ("the made id changed between requests");
  stream mend off (first fragments' ids ""); whole mend off ("id":"").

Run at this change on origin/main 81313b912:
- gofmt -l: nothing. go vet -tags nogui ./... on darwin, GOOS=linux and
  GOOS=windows: nothing.
- go test -tags nogui -timeout 45m ./...: 64 packages ok; internal/agent
  and internal/gateway failed on "no space left on device" (the disk
  filled under other sessions' runs: agent's testlog.txt write after
  PASS, gateway's TestRotateSpreadsABurstOfNewConversations renaming
  providers.json). Rerun with space free: internal/agent ok 652.9s,
  internal/gateway ok 732.9s.
- Not tried against a real WorkBuddy AI account (no live configs).
2026-10-17 03:53:40 +08:00
yetone 9228bd443f library: skills are grouped by source when the skills CLI keeps its lock under $XDG_STATE_HOME (@_yukirock on X)
skills 1.7 writes its global lock to $XDG_STATE_HOME/skills/.skill-lock.json
when that variable is set, and only to ~/.agents/.skill-lock.json otherwise.
The Library read only the ~/.agents one, so with XDG_STATE_HOME set every
`npx skills add` skill had no repository and the "By source" view could not
group them. Both locks are now read, the XDG one winning per skill, since a
lock written before the variable was set still names older skills.

XDG_STATE_HOME joins agentenv.Vars, so the desktop app takes it from the
login shell like the other folder variables (TestFolderVarsAreListed).

Not handled: a project install's ./skills-lock.json.

Run (worktree at origin/main 1eba266a9 plus this change):
- TestSkillRepoFromXDGLock: red on the old lock() (grill-me "", tdd
  "stale/repo"), green after.
- go test -p 2 -tags nogui -count=1 -timeout 45m ./...: 66 packages ok.
  The first run had TestFolderVarsAreListed red (fixed here) and
  TestMaxRPMWaitsForRoomInTheMinute red under load, the open #1791; the
  rerun had both green.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet clean.
2026-10-17 01:22:21 +08:00
yetone 1978eabe58 agent: Codex's background compaction is turned on from Settings › Long conversations (#2490, #2493)
Codex 0.163 can compact a long conversation in the background while a
turn goes on ([features.async_compaction]). A new row under Long
conversations turns it on, with the share of the window it starts at
(empty: Codex's own 65%). magpie writes it into each Codex config it
routes (codex_async.go):

- [features.async_compaction] enabled = true and
  model_async_compact_threshold_percent. Codex reads the threshold only
  in that table; one at the top level is ignored (tried).
- capabilities = { remote_compaction = "v2" } on [model_providers.magpie].
  Codex starts a background compaction only on a provider with v2, which
  it gives OpenAI and Azure alone. Tried with Codex 0.163 against a
  sandbox gateway and a fake upstream reporting 70% use: without the
  capability, no compaction in a whole turn; with it, compaction_trigger
  requests ran beside the turn's steps and the next step's input held
  the summary. The capability is written for a feature the user turned
  on by hand too (#2493 asked whether magpie supports it: it didn't).
  putProvider carries the table's capabilities over when a model switch
  writes it again.
- What magpie wrote is in the stash (codex.async). A value the user set,
  or changed since, is never written over and stays when the switch is
  turned off; a bare async_compaction = true, an inline or a dotted
  table is the user's as written. A config that doesn't parse is not
  written to.

Not tried: Codex signed in with ChatGPT (openai_base_url to magpie on
the built-in provider, v2 by default), only the custom provider path.

Tests: TestCodexAsyncCompactionWritten, ...KeepsTheUsers and
...KeepsUsersCapability (internal/agent), each red with the matching
part removed by hand (no writing; no capability carry-over; no
ownership check on enabled). codex-async-compact.test.cjs: Chromium and
WebKit, en/zh/zh-TW/ja/de, red with the 1-100 check removed;
compact-at, i18n-keys, settings-general, settings-search pass.
TestSettingsSaveKeepsWhatItDoesNotSend holds the two new fields.
gofmt clean; go vet -tags nogui on darwin, linux, windows.
Full suite: go test -tags nogui -timeout 45m ./... (pipefail, suite-lock) at the four #2494/#2504/#2505/#2490 commits on origin/main a751f5282: 65 packages ok, among them internal/agent (2124s), internal/gateway (1845s) and internal/sessions (148s). internal/gui was red on TestSetAnswersWhileDevinAndProvidersHang alone (the state after a set took 11.5s at load ~250; #1375); internal/gui run again alone: ok (206s).
2026-10-17 00:39:37 +08:00
yetone a2c4aab1ba gateway: DSH's session header and compaction mark are recorded, also through a remote magpie (#2505)
h4rk8s asked that the Requests list tell DSH's context compactions apart
and attribute usage per DSH session, also when the call goes through
Remote Magpie, from the headers DSH sends and never from the prompt.

- x-deepseek-harness-session-id joins sessionHeaders, after the others:
  sessionOf / nativeSessionOf / conversationID take it, so usage, the
  Routing page and affinity see DSH's session, and passOnCaller already
  sends a native session header on to a remote magpie.
- x-deepseek-harness-compact set (any value but "", 0, false, no, off)
  makes callKind "compact", which PurposeOf groups as Compaction. Only
  display reads that kind; routing is unchanged.
- withCaller keeps the mark on the caller and passOnCaller sends it on to
  a remote magpie, so the other magpie records the call as a compaction
  too. Neither header reaches a vendor (the request to it is built fresh).
- docs/subsystems/gateway-sessions.md says so.

Run:
- TestDshMarksSessionAndCompaction: direct and through a remote magpie
  (two gateways over httptest), marked and unmarked with a summarizing
  system prompt. Red on the old gateway.go/codex_backend.go/
  remote_magpie.go (session "", kind "", remote sent neither header),
  green now; asserts the vendor saw no x-deepseek-harness-* header.
- TestRemoteMagpieKeepsTheSession still green.
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows.
Full suite: go test -tags nogui -timeout 45m ./... (pipefail, suite-lock) at the four #2494/#2504/#2505/#2490 commits on origin/main a751f5282: 65 packages ok, among them internal/agent (2124s), internal/gateway (1845s) and internal/sessions (148s). internal/gui was red on TestSetAnswersWhileDevinAndProvidersHang alone (the state after a set took 11.5s at load ~250; #1375); internal/gui run again alone: ok (206s).
2026-10-17 00:39:36 +08:00
yetone 7d7dba31ae provider: removing or turning off a moved subscription's plugin moves nothing back
The built-ins are being retired (the owner, 10-16: 陆续把内置Provider下线掉),
so the last way back to one is gone. MoveBack, moveBack and releasePlugin
are removed, with the Left flag they set.

- SetPluginOff only turns the plugin off. A moved subscription stays
  moved, off with it.
- RemovePlugin records the moved ids as the new state "removed". The
  record keeps its accounts, which plugin.Remove leaves in the plugin's
  auth store. Nothing moves or installs it by itself: MoveRetiring
  skips it and keepMovedCurrent reads only "plugin".
- HandOver turns a removed record whose plugin is installed and current
  back into "plugin", record and all. So does Adopt (the editor's Move).
- MoveRetiring moves an old "back" record again, whatever Left said.
- Plugins page, rm/off confirms: "{names} stops working until the plugin
  is installed again. Its accounts are kept." / "... while the plugin
  is off." The status after removing no longer says it is back on the
  built-in.
- Strings: five old strings dropped ("Moving back…" among them), three
  new ones in zh, zh-TW, ja and de.
- `magpie plugins rm`/`off` say the same in their output.
- Docs: provider-plugins.md (the states table, the Move-back paragraph)
  and AGENTS.md.

Tests:
- TestNoWayBack is new. It covers a "back" record moved again, the
  plugin turned off (still moved, accounts kept), removed (removed, not
  reinstalled by keepMovedCurrent or MoveRetiring), installed again
  (HandOver), and removed again then Adopt.
- TestReleasePlugin and TestMoveBackKeepsLapse asserted the way back
  and are deleted.
- TestMove, TestHandOver, TestMoveTidiesItsPlugin and
  TestAdoptBeforeSigningIn no longer call MoveBack. TestKeepMovedCurrent
  uses the removed state.
- plugin-release.test.cjs checks the new asks and that the status names
  no built-in.

Run:
- Broken by hand:
  - With HEAD's migrate.go, TestNoWayBack is red at "turning the plugin
    off moved it back".
  - With HandOver's removed branch disabled, it is red at "installed
    again: map[], moved false".
- go test -tags nogui ./internal/provider -run
  'TestMove|TestNoWayBack|TestHandOver|TestKeepMovedCurrent|TestAdopt|TestInstallPlugin|TestWorkBuddyCheckin|Plugin|Migrat':
  ok.
- GUI (NODE_PATH playwright, --test-concurrency=1): plugin-release,
  plugin-move and i18n-keys, chromium and webkit: 17/17.
- gofmt -l clean; GOOS=linux and windows go vet of provider, gui and cli.
- Full suite: go test -tags nogui ./... -count=1 -timeout 90m at this commit rebased on 9b04c4e20 (with the TestFailOpen fix after it): 66 packages ok, none red. Before that fix, at bff7cbd24, 65 ok and internal/middleware TestFailOpen red under load (fixed at its cause in the next commit).
2026-10-16 22:58:41 +08:00
yetone f9ceac1628 provider: a move onto the plugin takes every account, and no model holds it back
The built-ins are retired (the owner, 10-16: 一定要下线完毕), so a move
can't be held back by something only the built-in could fix. Before, a
move failed when every account was lapsed, when one account's check
failed (the vendor unreachable through the plugin), when the vendor
refused every account, or when a model in use wasn't in the plugin's
list. Each of those left the user on a built-in that is going away.

Now Move installs the plugin and imports every account:
- one the vendor refuses goes along marked lapsed, as before;
- one already lapsed, or whose check fails otherwise, goes along untried
  and unmarked, for the plugin's own reads to judge, and is logged;
- no model is checked against the plugin's list.

Only an install failure, the plugin not serving the id, or a sign-in the
plugin won't import fails the move, which puts everything back and is
tried again after moveRetry. The movers' served (Devin, Cursor) and
builtin (ZCode) hooks, modelsInUse, modelNames, lapsedAll and devinBase
had no other use and are gone, with the tests of the hooks. The page still
translates an older magpie's lapsed, unserved and account whys, which
migrations.json can hold.

Tests:
- TestMoveEveryAccountLapsed and TestMoveTriesEachAccount are new, and
  TestMoveToPlugin's first case is now a refused account that moves.
  importAuth is a seam: the fake mover's "r-noimport" sign-in fails part
  way, so TestMoveToPlugin, TestMoveTidiesItsPlugin and TestMoveCutShort
  still test putting back.
- TestMoveCutShort's cut-short record now carries the sent sign-in's
  hash, as a real move writes it. Without it putBack took the built-in's
  sign-in as renewed. The old test passed only because the check renewed
  the token a second time.
- Broken by hand: with a failed check or a refusal returning an error
  again, TestMoveToPlugin and TestMoveTriesEachAccount go red.

What was run:
- go test -tags nogui ./internal/provider -run
  'Move|HandOver|Lapse|PutBack|Retir|Adopt|KeepMoved|ReleasePlugin|
  ZCodeStartPlan|Devin|Cursor' passes.
- go vet passes and gofmt -l is clean.
- At ab7b28510 on ba132d68b: go test -tags nogui ./... -count=1
  -timeout 90m, 66 packages ok, no FAIL; GOOS=linux and windows go vet
  of provider, gui and cli pass.
- Rebased onto origin/main with the next commit; the suite at that head
  is in its body.
2026-10-16 22:58:41 +08:00
yetone 9fcf6a6e7f provider: every deprecated built-in moves onto its plugin, and there's no way back
The owner, 10-16: 陆续把内置Provider下线掉…一定要下线完毕. The plugins now do
what the built-ins did (the parity batch up to 53009f81a), so the built-ins
are retired:

- MoveRetiring moves every subscription with a mover (retiring is
  MovableIDs, the list was empty) that still has built-in accounts, from
  the gateway's hourly loop, six hours after a failed try as before.
- A user who moved back is moved again. Only a move back made by removing
  or turning off the plugin (Migration.Left) is left as it is.
- There is no move back from the GUI or the CLI. provider/moveback and
  `magpie plugins move-back` answer that the built-ins are retired. A
  moved subscription's editor says it stays on its plugin and shows no
  button, and the success line no longer offers to go back. New strings
  in zh, zh-TW, ja and de; the three unused ones are gone ("Moving back…"
  stays, for removing a plugin).
- AGENTS.md and docs/subsystems/provider-plugins.md say so.

Tests:
- TestMoveRetiring's subtests check that a moved-back subscription is
  moved again and an off or removed plugin's is not.
- TestMoveBackRefused goes red on the old handler.
- plugin-move.test.cjs checks that a moved Zed has no button and says it
  stays.

What was run, at 63be47717 with this change:
- go test -tags nogui ./... -count=1 -timeout 90m: 65 packages ok. The
  gateway was red on TestUsageKeepsTimeToFirstToken (#2575, new) and
  TestVisionWaitIsntTheDescribersTime (#2444) at load ~260. Neither file
  is touched here, and both pass alone with -count=3.
- gofmt -l is clean; GOOS=linux and GOOS=windows go vet of provider, gui
  and cli pass.
- GUI, both engines: plugin-move, plugin-move-unserved and i18n-keys pass
  23 of 23.
- The other plugin-*.test.cjs files go red under parallel load as they do
  on untouched main (#1544, commented with the runs). Serially, then alone,
  they pass 28 of 28.
2026-10-16 22:58:40 +08:00
yetone 2c72563dd1 usage: Requests splits and filters by gateway key, with "No gateway key" for the calls none made (#2521)
MauriceCarlo asked for two things on Usage → Requests.

1. The gateway-key filter should show even when one key has calls. The
   picker hides itself under two options, and with one key it had one,
   so calls made with that key couldn't be told from calls made with no
   key. A "No gateway key" choice (callerKey=none) now sits beside the
   keys whenever the period has calls with no key, or it is the current
   pick. A single key's picker therefore shows and separates the two.
   The hidden condition itself is left to #2499, which another session
   has.
2. The trend chart and the ranking can split by gateway key. LED_SPLITS
   gains "Gateway key". It's offered only while the period has a key's
   calls, and it falls back to Model otherwise. A click on a rank row
   picks that key, or none, and a second click lets go, as the other
   splits do.

Server:
- usage.Dimensions gains "callerKey". A row's key is its CallerKeyID, or
  NoCallerKey ("none") when it has none, and the filter takes "none" as
  calls without a key.
- Filter.Without(d) is the one place that clears a dimension's own pick,
  so the by-split lists every value. RequestPage's fast and slow paths
  both use it now; they each had their own switch.
- usageapi names the split's shares from the key labels: "No gateway key"
  for none, the ID if a key was deleted.
- OwnPage keeps a held key's view to its own share in by and in the
  chart's split, so one key never learns another's name or numbers. The
  series was already only its own rows.
- docs/reference.md documents callerKey=none and by.callerKey.

"No gateway key" goes into the core i18n.js. The gateway keys page says
"No gateway keys yet", and i18n-keys' "a plugin's words are its own"
matches on substrings.

Tests:
- TestCallerKeySplitAndNone runs the fast and the slow path over {},
  one key, none, and none+an agent, and checks by.callerKey. Broken by
  hand, it goes red: once with the none clause in the filter removed, and
  once with Without's callerKey case removed.
- TestUsageOverGateway: on loopback the split names both keys. A held
  key's by.callerKey is only its own. With the OwnPage scrub skipped, it
  goes red (another key's name leaked).
- usage-ledger-key-split is new, in both engines, all five languages, and
  1400 and 760 px. It checks:
  - the picker's options with the none choice;
  - filtering on none;
  - the split's rows, and a click picking and letting go;
  - no sideways scroll;
  - that a period with no key's calls shows neither the picker nor the
    pill.
  32/32 pass. With the none option removed by hand, 11 go red.

Run on origin/main d9b943555 (head 663db0ecf), with the #2517,
#2521 and #2522 changes, load ~240:
- gofmt -l clean; go vet -tags nogui for darwin, linux and windows: ok.
- go test -timeout 120m -count=1 ./... (pipefail): exit 0, every package
  ok (gateway 1416.8s, agent 1535.5s). Before the rebase, on 63be47717:
  - The 45m run had agent and gateway past 45m (#2544, #2108).
  - TestMainWindowCorners was killed at its deadline (#1936).
  - TestSkillRelinkKeepsUnreadableCopy failed (#2555; it passes alone).
  - gateway alone with 120m was ok.
- GUI, the 41 Requests/Usage files in serial, both engines, before the
  rebase: 493 pass, 3 fail. The 3 were usage-refresh "not yet 2 !== 1",
  the same on 63be47717 alone (1 of 3); seen again on #2184.
- Rebased, these all pass, 102/102: i18n-keys, usage-ledger-ttft,
  usage-ledger-key-split, usage-ledger, usage-speed, usage-ledger-detail,
  gui-ja, gui-de and gui-zh-tw.
- Rebased again onto 9b04c4e20, which touches ledger.go, request_page.go
  and gateway.go:
  - vet ×3: ok.
  - internal/usage, internal/usageapi and internal/cli: ok.
  - internal/gateway -run 'NativeCompaction|UsageOverGateway|Capped|Cap':
    ok.
  - usage-ledger-ttft, usage-ledger-key-split, usage-ledger and
    usage-speed: 86 pass. i18n-keys was red from main's own words (#2586,
    fixed in the next commit).
2026-10-16 21:59:33 +08:00
yetone 440f66701f gateway: a 429 for native compaction's one account says the compaction pinned it, not that every account is capped (#2517)
When a conversation was compacted natively, only the key or account that
sealed the compaction can read it (#1099), so checkpointReaders keeps the
candidates to that one. When that account was at its usage cap, the 429
and the call record said "every account that serves X is held at the
usage cap", although the other accounts were never candidates. That sent
lm0711 looking at routing modes, which can't change it.

checkpointHeld tells this case apart: the plan held only the sealer's
account(s), and others were left out for the checkpoint. The error then
names the account and its window, says the compaction it sealed is what
keeps the conversation there, that routing mode and stays don't change
that, and to raise the cap / spend credits or start a new conversation.
The record reads "native compaction's account at its usage cap" (or its
credits / both variants). cappedError and cappedRecord are unchanged for
every other 429; their text is split into heldReasons and heldAdvice so
both share it. docs/subsystems/gateway-routing.md says so.

Test: TestNativeCompactionWriterAtItsCap seals a checkpoint on one
account, caps it, and checks the 429 body and the record. Broken by hand
(checkpointHeld returning nil), it fails with the old "every account"
text.

Run on origin/main d9b943555 (head 663db0ecf), with the #2517,
#2521 and #2522 changes, load ~240:
- gofmt -l clean; go vet -tags nogui for darwin, linux and windows: ok.
- go test -timeout 120m -count=1 ./... (pipefail): exit 0, every package
  ok (gateway 1416.8s, agent 1535.5s). Before the rebase, on 63be47717:
  - The 45m run had agent and gateway past 45m (#2544, #2108).
  - TestMainWindowCorners was killed at its deadline (#1936).
  - TestSkillRelinkKeepsUnreadableCopy failed (#2555; it passes alone).
  - gateway alone with 120m was ok.
- GUI, the 41 Requests/Usage files in serial, both engines, before the
  rebase: 493 pass, 3 fail. The 3 were usage-refresh "not yet 2 !== 1",
  the same on 63be47717 alone (1 of 3); seen again on #2184.
- Rebased, these all pass, 102/102: i18n-keys, usage-ledger-ttft,
  usage-ledger-key-split, usage-ledger, usage-speed, usage-ledger-detail,
  gui-ja, gui-de and gui-zh-tw.
- Rebased again onto 9b04c4e20, which touches ledger.go, request_page.go
  and gateway.go:
  - vet ×3: ok.
  - internal/usage, internal/usageapi and internal/cli: ok.
  - internal/gateway -run 'NativeCompaction|UsageOverGateway|Capped|Cap':
    ok.
  - usage-ledger-ttft, usage-ledger-key-split, usage-ledger and
    usage-speed: 86 pass. i18n-keys was red from main's own words (#2586,
    fixed in the next commit).
2026-10-16 21:59:32 +08:00
yetoneandTsukikage7 9b04c4e20f plugin: async gateway request hooks, run in Bun before routing and after the reply (#2118)
A package's magpie.hooks entry (or a *.hooks.{js,mjs,ts,mts} file) exports
`async onRequest(body, ctx)` and an optional `onResponse(reply, ctx)`. They
run in the Bun plugin host, so a hook can await I/O, for example a context
service like PowerContext, which the sync moejs middleware can't. The
gateway still makes one model request per client request. A hook adds
context to the body; it doesn't register tools or run a loop, so magpie
doesn't become an agent runtime.

Ported from Tsukikage7/magpie#1. Changes from the fork:
- The entry name is magpie.hooks / *.hooks.*. The fork's magpie.gateway /
  *.gateway.mjs is already the middleware's alias, so a hook importing
  node:fs was also loaded as moejs middleware and failed there.
  TestGatewayHookNamesApartFromMiddleware fails if the two sets overlap.
- onRequest is rolled back, and counts as failed with no onResponse, when
  it throws, times out, returns non-JSON, or changes tools, tool_choice,
  function_call, functions, toolConfig, model or stream.
- onResponse gets the client-facing reply, merged through the gateway's own
  stream decoder, collector and renderer (no second merger).
- Codex's native passthrough (/backend-api/codex) runs the hooks too,
  without the sync middleware.
- The run ends with the request handler, not the client connection. Codex
  hangs up on response.completed, and the reply it got is still captured
  as a success. TestGatewayHookSeesReplyAfterClientHangsUp is red on the
  old `r.Context().Err()` check and green with -count=3.
- ctx.origin is host-derived (local / gateway-key / remote). Headers, keys
  and peer addresses never reach the hook.
- Plugins page: a hook package shows a "Request hook" chip, a diagnostics
  line (outcome code, calls, avg ms, bytes, failures; no content), and
  Options. Strings are in en, zh, zh-TW, ja and de.

Docs: docs/subsystems/gateway-request-hooks.md (new), provider-plugins.md,
gateway-middleware.md, and site docs plugins.html in en, zh and ja.

Real use, sandbox HOME on 127.0.0.1:3486 with the owner's real Codex Pro
sign-in. The probe hook adds a codename note and logs both callbacks:
- /v1/responses, /v1/messages, Gemini generateContent: stream and
  non-stream. onRequest's note reached the model (the answer had the
  codename), and onResponse got success=true and the whole reply.
- /v1/chat/completions: with the probe also changing `model`, the change
  was rolled back (the reply came from the asked model) and no onResponse
  ran. Without that change, earlier: stream and non-stream success.
- The real Codex CLI 0.162.1 `codex exec` through openai_base_url ->
  /backend-api/codex: the hook saw origin=local, agent=codex and the
  query; the answer had the codename; onResponse success=true (before the
  hang-up fix it never ran: the context was already cancelled).
- `magpie plugin list` shows only "async gateway hook onRequest" for the
  hook package, no failed middleware.

Tests (base origin/main 63be47717, macbook at load avg 220-340 from other
sessions' suites):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. go build and GOOS=linux -tags nogui
  build: ok.
- go test ./... -timeout 45m: every package ok except:
  - agent, gateway and library timed out at 45m under the load;
  - gui's TestSetAnswersWhileDevinAndProvidersHang (#1375, also red on a
    clean 63be47717 run alone; commented there);
  - library's TestSkillRelinkKeepsUnreadableCopy, which passes -count=2 alone.
  Rerun at -timeout 150m: agent ok (4524s), library ok (2581s). gateway was
  ok except TestVisionWaitIsntTheDescribersTime's 300ms limit (#2444,
  commented), which passes -count=5 alone on this tree and on 63be47717.
- internal/plugin and internal/gateway hook tests: ok.
- GUI (chromium+webkit; en, zh, zh-TW, ja, de): plugin-gateway 12/12 twice.
  It failed earlier at load ~340, chromium only, on page.goto's 5s (#2542).
  All 43 plugin-*.test.cjs files and mobile-web are green except:
  - plugin-move: red on a clean 63be47717 too (#2399, commented);
  - plugin-moved-signin: one 5s waitFor under load, then 6/6 twice.

Rebased onto ea3dee96a (21 commits; main touched host.go, host.js, i18n.js and
the plugin docs; clean rebase), then rerun at the rebased head:
- gofmt, vet (darwin, linux nogui, windows) and build: clean.
- go test: plugin ok, cli ok, gateway -run 'Hook|Middleware|Codex|Plugin' ok.
  gui ok except TestMainWindowCorners, which was killed under load (#1936)
  and passes alone.
- GUI: plugin-gateway 12/12, plugin-middleware 24/24, plugin-tools 22/22,
  plugin-agent 22/22.
- Real account with the rebased binary: every protocol and the real Codex
  CLI gave the same results as above (codename answered, success=true,
  chat's model change rolled back).

Co-authored-by: Tsukikage7 <65526564+Tsukikage7@users.noreply.github.com>
2026-10-16 20:48:51 +08:00
yetone ea3dee96a8 gateway: a URL magpie didn't choose is downloaded from public addresses only, wherever the request came from
5241de909 held an image URL a caller names to public addresses. This
carries the same guarantee to every URL magpie downloads that isn't its
own fixed vendor endpoint, and drops where the request came from as a
reason to reach a private address.

What is downloaded through the one restricted client now (every resolved
address checked and pinned, the dialled address checked again, each of up
to 5 redirects checked the same; loopback, RFC 1918, fc00::/7, link-local
with metadata, CGNAT, multicast, unspecified, documentation/reserved,
IPv4-mapped, NAT64/6to4/Teredo forms all refused):
- a caller's reference image (fetchPicture, draw.go), as before;
- web_fetch's page (search_fetch.go), as before;
- an image a vendor answers by URL, downloaded for a b64_json caller
  (draw.go) - was the gateway's unrestricted client;
- /v1/videos/{id}/content's video URL from the vendor's status
  (video.go) - was the gateway's unrestricted client;
- generate_image's own download of the gateway's image URL
  (internal/imagemcp) - was http.DefaultClient.
A vendor's answer can be steered by what the model is asked to do, so
its URLs are treated as a caller's.

Policy: a request from this computer gets nothing more. The exemption for
a loopback request that wasn't from a web page or through a forwarding
header (withPrivateFetch/privateFetchAllowed) is gone: a reverse proxy or
relay on the same host makes every request it carries arrive that way.
Two explicit allowances remain:
- settings.json "fetchPrivate" (settings.FetchPrivate): names, name:port,
  IPs and CIDR ranges the user lets magpie download from. None by
  default, no Settings page, per-machine (KeepOwn, kept across a GUI
  save). A settings.json that can't be read lets nothing extra in.
- for a vendor's URL only, the host:port of that provider's own
  configured endpoints (a LAN or local provider serving its own images).
The refusal says to send the image itself or name the host in
fetchPrivate. A vendor image that can't be downloaded is still answered
by its URL; a video is a 502.

Audited and left alone: kiro, codex_search, codex_backend and the
catalog/provider http.DefaultClient uses (fixed vendor endpoints);
remoteVideoURL (p.Do to the provider); the MCP proxy and mcpauth (URLs
the user configured); community plugins (only fixed vendor endpoints,
nothing a request names).

Docs: docs/subsystems/gateway-routing.md (the guard paragraph, web_fetch,
test command), docs/subsystems/sync-backup.md (FetchPrivate stays on
each computer).

Tests (new or rewritten): TestEditImageURLFromThisComputer (loopback,
[::1], and loopback with X-Forwarded-For as a same-host reverse proxy:
400 naming fetchPrivate, the private server never asked; with
fetchPrivate ["127.0.0.1"] it is fetched, a non-image still refused),
TestFetchPrivateEntries, TestVendorImageURLAtPrivateAddressNotFetched
(127.0.0.1, a name resolving to it, ::ffff:127.0.0.1; the vendor's own
host:port still fetched), TestVideoContentAtPrivateAddressNotFetched,
imagemcp TestVendorImageAtPrivateAddressNotFetched. gui's
TestSettingsSaveKeepsWhatItDoesNotSend sets FetchPrivate. The two imagemcp
download tests and TestImageByURLIsFetchedForB64Caller now name their
local file server in fetchPrivate / resolve files.test to a public
address.

Broken by hand, each red, restored:
- draw.go inline fetch on s.client -> TestVendorImageURLAtPrivateAddressNotFetched red
- video.go on s.client -> TestVideoContentAtPrivateAddressNotFetched red
- imagemcp on http.DefaultClient -> its TestVendorImageAtPrivateAddressNotFetched red
- fetchPicture unrestricted (the old local bypass) -> TestEditImageURLFromThisComputer red
- fetchPrivate ignored -> TestEditImageURLFromThisComputer, TestFetchPrivateEntries red
Not distinguished: settings.Load in place of LoadChecked passes too (an
unparsable file with no last good generation gives no list either way).
Not tried: a real reverse proxy (nginx/caddy) in front of a running
magpie; the X-Forwarded-For loopback request stands in for it. Not tried
against a real vendor's image or video URL.

gofmt -l clean; go vet -tags nogui darwin, GOOS=linux, GOOS=windows clean.
Full suite: go test -tags nogui -timeout 45m ./... at 8b84dc902 plus this
change: every package ok except agent and gateway (timed out at 45m at
load average ~370, no test failed before the timeout) and gui
(TestSettingsSaveKeepsWhatItDoesNotSend, fixed here by adding
FetchPrivate; TestSetAnswersWhileDevinAndProvidersHang 12.4s under load,
(4726s) with -timeout 150m at load ~220.

Rebased onto ba132d68b (17 commits; only the doc test line conflicted).
At the rebased head: gofmt clean, vet darwin/linux/windows clean, and
the Image/Draw/Video/Fetch/Edit/Private/Public tests in gateway, imagemcp,
gui and settings ok.
2026-10-16 20:12:05 +08:00
yetone c5f15cae7c provider: Amazon Bedrock's Mantle endpoint (@marktoown on X)
"添加 AmazonBedrock 的时候,API 还是旧的 Bedrock-runtime 节点,不支持最新的
Bedrock-mantle 节点". The reporter wanted to add Amazon Bedrock at its
Mantle endpoint, but magpie only offered bedrock-runtime.

What it does:
- A new vendor preset, bedrock-mantle ("Amazon Bedrock (Mantle)"), takes
  the same Bedrock API key as the runtime.
  - It has 17 regions of its own (mantleRegions): the
    bedrock-mantle.{region}.api.aws hosts that answered on 2026-10-16.
    The runtime's eu-west-3 has no Mantle host.
  - Chat completions and Responses go to /v1, and Messages to
    /anthropic.
  - Unlike the runtime, its models are listed from GET /v1/models.
    NoList stays on the runtime preset only.
- Mantle serves each OpenAI-style model under one prefix.
  - OpenAI's closed GPTs and xAI's Grok are under /openai/v1. Every
    other model is under /v1. Asking at the wrong prefix gets "model `x`
    isn't supported on this route".
  - provider.MantleBase picks the prefix from the model id. The
    gateway's forwardOnce and the provider test's tinyBody both use it.
  - For a model whose maker the rule doesn't know, the gateway asks
    again once at the other prefix when Mantle refuses it for its route
    (internal/gateway/mantle.go).
  - When the second prefix takes it, the gateway remembers that prefix
    in unfit. When both refuse, the client gets the first refusal and
    nothing is remembered.
- IsBedrockMantle is true for the preset and for any provider added at a
  Mantle host. IsBedrock includes it, so the shared Bedrock rules apply
  to Mantle too:
  - Claude goes on Messages only.
  - The key is sent as x-api-key alone, which is what Mantle's own
    examples send.
  - max_completion_tokens is used, and metadata is stripped.
  - Beta renames and refusals apply.
  - There is no Priority.
  - GPTs go to Responses first.
- I checked every other IsBedrock caller. None is runtime-only except
  the legacy /openai/v1 -> Responses migration in normalize, which is
  harmless for Mantle.
- A provider added by its Mantle address gets the APIs it wasn't given
  (mantleEndpoints, in normalize). A chat or Responses URL given at
  /openai/v1 is moved to /v1, because /openai/v1/models is a 404 and the
  list lives at /v1/models.
- GUI: the editor's Key header row is hidden for a Mantle Anthropic
  address, as it already was for the runtime's.
- Docs: README (en, zh) preset lists, docs/reference.md,
  providers-accounts.md (a new row) and gateway-routing.md (a new row,
  plus a test command).

What was run, in the worktree at e72b6a332 (origin/main):
- New tests: TestBedrockMantlePreset, TestBedrockMantleByAddress,
  TestMantleBase (internal/provider) and TestBedrockMantleRoutes
  (internal/gateway, against a fake Mantle that serves each model at
  one prefix only and refuses the other with Mantle's words). All pass.
- Each was broken by hand and went red:
  - The reroute call removed: newmaker got a 400.
  - The prefix pick turned off: gpt-5.5 got a 400.
  - mantleEndpoints made a no-op: the endpoints were not filled in.
  - mantleHost made false: the provider was not taken for Mantle.
  - On the old source, the gateway test fails with 'no preset
    "bedrock-mantle"' and the provider tests don't compile.
- GUI: I added a Mantle case to provider-auth-header.test.cjs.
  - It passes 20/20 in chromium and webkit, en and zh.
  - Against the old app.js, chromium fails 2 of 10 on the new
    assertion.
  - add-sheet 6/6, tencent-cloud 12/12, strip-scrollbar 2/2,
    zhipu-team 12/12 and volc-access-key 12/12 pass in both engines.
- gofmt -l prints nothing.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  -tags nogui ./... and GOOS=windows go vet ./... all exit 0.
- go build, GOOS=linux go build -tags nogui and GOOS=windows go build
  all exit 0.
- Full suite: go test -p 2 -tags nogui -count=1 -timeout 45m ./...
  (sandbox HOME).
  - 64 packages ok.
  - internal/agent and internal/gateway hit the 45m timeout with no
    test failing. Load average was 260-380 from other sessions, with
    about 68 other test binaries running.
  - A second 45m run of those two timed out the same way, again with no
    test failing, and different tests were running at the timeout each
    time.
  - The two were run again with -timeout 150m (-p 2, the same load):
    internal/agent ok in 2988.8s and internal/gateway ok in 2972.4s,
    both just past 45 minutes.

What was not tried:
- The real Mantle API. The owner has no Bedrock key (no Bedrock
  provider in providers.json, and AWS_BEARER_TOKEN_BEDROCK is unset).
  The only real-API evidence is unauthenticated probes of the hosts and
  the routes they answer on.
- The per-model prefix rule, /v1/models, Messages with x-api-key, and
  the "isn't supported on this route" refusal come from AWS's docs and
  model cards, not from a signed request.
- The Mantle Anthropic base's own model list (/anthropic/v1/models) was
  not checked. The list is taken from /v1/models.
- The GUI was not tried in the real desktop app.
- The gui-zh-tw, gui-ja and gui-de suites were not run, since no string
  was added.

Rebased onto origin/main e243937ca (no conflicts). At the rebased head:
go test -run 'Mantle|Bedrock' ./internal/provider ./internal/gateway ok,
gofmt -l of the changed files empty, GOOS=linux and GOOS=windows go vet
-tags nogui of both packages exit 0. The full suite above ran at
e72b6a332, not again at the rebased head.
2026-10-16 19:30:42 +08:00
yetone e243937ca3 gateway: a fast pick can be sent as Ultrafast where the account offers it (#1954)
zhenghaowen0967 asked for an agent's fast pick of a ChatGPT model to go as
Codex's Ultrafast without the client asking for it. settings.UltraPicks
holds the agent's fast picks that are set to Ultrafast; each one is in
FastPicks too.

- The gateway marks those candidates `ultra` in fastPick.
  - On Chat and Responses, a try sends service_tier "ultrafast".
  - From Messages, a try carries withUltra to forwardTranslated, which
    sets Request.Ultrafast for the ChatGPT backend.
  - In every case, the #1784 check decides the account. One whose list
    doesn't offer Ultrafast goes after a mate that does (tierMate). With
    no mate left, it is sent priority.
  - That check now covers Chat as well as Responses.
- Sibling fix: chat.go dropped a Chat client's own service_tier
  "ultrafast" (Fast was false, Ultrafast unset). It now parses as
  Responses does.
- provider: SetFastTier (""/priority/ultrafast) behind SetFastPick.
  CanUltra and UltraModels say whether one of Codex's accounts lists
  Ultrafast on the model. UltraPicks follow a provider rename
  (renameModelPrefs) and survive a GUI settings save.
- GUI: an option gets ultraOk/ultra. Where ultraOk is set, the bolt in
  the picker steps usual -> Fast -> Ultrafast -> usual, as a camera's
  flash button steps its modes. Ultrafast shows two overlapped bolts, in
  the row and after the field's model. Tooltips and the status line are
  in en, zh, zh-TW, ja and de. POST /api/agent-fast takes `ultra`.
- No `:ultrafast` suffix for routing groups yet.

Tests, each broken by hand and seen red:
- TestUltraPickSentUltrafast covers omp/Responses with no tier asked
  (acct-pro:ultrafast), the Pro account out (then acct-plus:priority),
  another agent unchanged, opencode/Chat and claude/Messages picks, a
  Chat client's own ultrafast, and switching back to Fast or off.
  - Red with ultra forced false (4 cases).
  - Red without withUltra (claude went priority).
  - Red without the chat.go parse (2 cases).
- TestSetFastPick: red without UltraPicks in renameModelPrefs.
- TestSettingsSaveKeepsWhatItDoesNotSend: red without the api.go carry.
- fast-ultra.test.cjs (en zh ja de, window and 440px panel): red (9/9)
  without the Ultrafast step.

Run (vet, gofmt, GUI and full suite at base 8b84dc902; the reruns
below at a rebase onto 6b3ee5a03 and then onto 63be47717 origin/main):
- gofmt -l: clean.
- go vet -tags nogui ./... for darwin, linux and windows: clean.
- GUI, chromium + webkit: fast-ultra, fast-pick, group-member-fast,
  i18n-keys, model-pick and 14 other agent-model/picker files. 197/197
  pass.
- Full suite: set -o pipefail; go test -timeout 45m ./... (sandbox
  HOME, macOS, 3 other sessions' suites running at the same time):
  every package ok except two.
  - internal/gateway: TestMaxRPMGroupPrefersMemberWithRoom hit its fixed
    1s bar (1.126s) under load. It passes 5/5 alone (-count=5). Filed
    as #2520.
  - internal/gui: TestPanelJoinsFullScreenSpaces, red on macOS 26.2 on
    main already, filed as #2450.
- Rerun of internal/gateway and internal/library after the rebase onto
  6b3ee5a03 (both packages changed upstream), -timeout 60m, load
  average ~290: library ok. gateway hit the 60m timeout (the test
  running, TestPauseByFolder, was 13s in) and
  TestQueueRefusalIsInTheUsageLedger saw b's 1s queue timeout as a
  second 429. Filed as #2541. TestQueueRefusalIsInTheUsageLedger,
  TestPauseByFolder and TestUltraPickSentUltrafast, -count=5 at this
  head: ok.
- At the 63be47717 rebase: gofmt clean; vet darwin/linux/windows clean.
  internal/provider ok, internal/settings ok. internal/agent hit the
  45m timeout under load ~295 (in TestCursorLocalEffort, at 0s), so
  this is not a green for that package. Its -run
  "Fast|Option|Models|Picker|Cursor|Codex" subset, run through the
  shared 3-slot queue, was ok in 794s. The whole package is left to
  CI's Test run.

Not tried: a real Pro account's Ultrafast. The fake ChatGPT backend's
model lists offer it on one account only.
2026-10-16 19:14:52 +08:00
yetone e733b0722e plugins: a provider plugin says which service tiers a model serves, and Codex offers them (#2514)
Lovest on Discord (#general, v0.1.1267): a provider plugin had no way to
say a model is served at Fast or Ultrafast, so Codex never offered them for
plugin models, and the host dropped the field anyway.

- host.js keeps m.serviceTiers (tiersOf: string ids or {id} objects,
  trimmed, de-duplicated, anything else dropped) as plugin.Model.ServiceTiers.
- pluginCatalog puts them on catalog.Model.Tiers; CodexTiers offers a
  plugin's tiers when it declares any, so codexcat writes service_tiers
  (priority named Fast) into Codex's catalog and /v1/models.
- forwardTranslated keeps service_tier (OwnTier) for a plugin provider only
  when the request is translated to its Chat or Responses and the tier is
  one the model declares (provider.PluginTiers). A request relayed in its
  own protocol was already sent as the client wrote it; unchanged. Cursor's
  fast flag and #1954's ChatGPT tiers are untouched (#1954 not on main yet).
- Docs: serviceTiers in site/public/docs plugins (en, zh, ja) and a
  "service tiers" section in docs/subsystems/provider-plugins.md.

Tests (internal/gateway/plugin_tiers_test.go, fake plugin FAKE_TIERS):
TestPluginModelServiceTiersListed (fake-1 priority=Fast + ultrafast,
fake-resp ultrafast, fake-claude none) and TestPluginServiceTierReachesFetch
(Responses→plugin Chat and Chat→plugin Responses send a declared tier,
drop an undeclared one; same-protocol relays as before).
Broken by hand: OwnTier branch forced false → 3 translated cases red;
CodexTiers without IsPlugin → listed test red; host.js serviceTiers: [] →
listed test red. Restored → green.

gofmt -l clean; go vet -tags nogui with GOOS=darwin, linux, windows clean.
Not tried with a real vendor plugin that serves ultrafast.
Full suite: go test -timeout 45m ./... at af9e0d6b2 (sandbox HOME, load
average ~408 from other sessions): every package ok except agent and
gateway, which timed out at 45m with no failed test (rerun whole: timed
out again, 0 failures), gui (TestMainWindowCorners killed, #1936),
TestVendorThatStopsMidAnswerIsSaid (filed #2535) and
TestSetAnswersWhileDevinAndProvidersHang (#1375). The reds and the tests
running at each timeout (TestCodexKeptOnChatGPT, TestReplyNamesMember)
pass rerun alone, except TestMainWindowCorners (#1936). CI is the gate.
2026-10-16 18:13:15 +08:00
deephbz d9e87eb328 gateway: clients opt into Claude subscription cache marks and TTLs (#1717)
Problem:
Messages clients need control of cache boundaries and TTLs when a Claude
subscription answers. Ordinary clients must retain their run identity,
prompt and environment. A routing group's API-key member keeps its marks
and must not report the subscription bridge's drops.

Change:
Select client-owned marks only with X-Magpie-Cache-Marks: client. Map system
and fresh-history boundaries and the request tail, default missing TTLs to
5m, validate slot and TTL order, and separate opted-in run identities.
Retain prefix constraints across live and saved runs. Report unmappable
marks only for the Claude subscription try. Bound its selection hold to
two seconds and clear the report and hold for a non-Claude fallback.
Check ordinary identity bytes without a version-specific hash golden.

What was run:
Sandbox HOME, nogui: go vet ./... on darwin; gateway vet with GOOS=linux
and GOOS=windows; full gateway tests; focused cache and usage tests with
-race. gofmt and git diff --check passed. The group probe failed before
the fix with tools:1 on the API-key reply in both routing orders and both
stream modes. Hand-broken candidate scoping, stale report clearing,
keepalive holds and ordinary identity bytes each failed behavior tests.
Live, Claude Code on a Claude subscription and an Anthropic API key,
through a recording proxy: in a group whose API-key member answers, in
either order and both stream modes, the reply has no dropped-mark header
and upstream receives the tool mark; a Claude answer reports tools:1; a
failed Claude try followed by an API-key answer leaves no report. With a
delayed API-key reply, the group's first keepalive came 0.85 s after a
direct request's. Without the header, the outgoing request equals one
from a gateway built at the same base. No GUI or real Linux/Windows
execution.
2026-10-16 14:16:51 +08:00
yetone a15e576564 agent: OpenPencil uses magpie's models (@JC_be_better on X)
OpenPencil (ZSeven-W/openpencil, the openpencil-desktop app) keeps the
builtin agents its chat runs on in settings.json under Rust's
dirs::config_dir()/openpencil (read from its settings_io.rs and
settings_payload.rs). magpie adds one builtin_agents entry, id "magpie",
kind openai-compat at the gateway's /v1 with the magpie-openpencil key,
preset custom, the picked models as OpenPencil writes a list: the first
as `model`, `models` only for two or more, at most 64. The user's other
entries and settings stay, and so do the display_name and enabled they
give magpie's entry; a sync with nothing to change doesn't write. A file
magpie makes gets "version": 1 (OpenPencil sets a file without it aside
as corrupt); a file with another version, or none, is left alone.
Disconnect takes the entry out, and the file when nothing else is left.
OpenPencil reads the file once at start and writes it all back when it
quits, so a change is refused while openpencil-desktop runs (Windows
can't be asked, so the notice says to quit it first). Notice translated
in zh-CN, zh-TW, ja and de. README (en, zh-CN), docs/reference.md and
docs/subsystems/agent-wiring.md list it.

open-pencil/open-pencil, the other app of the name, keeps its providers
in its webview's localStorage, so it gets no row.

Run, under a scratchpad HOME with GOCACHE/GOMODCACHE pinned:
- go test -p 2 -tags nogui -count=1 -timeout 45m ./...: ok, 66 packages
  ok, 18 with no test files
- gofmt -l: clean; GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean
- go test ./internal/agent -run '^TestOpenPencil': ok
- node --test agent-notice-lang, i18n-keys, header-relang (Chromium and
  WebKit, every language, wide and narrow): 37/37 pass
Broken by hand, each went red: the running check, the 64 cap, the
version check, keeping the user's display_name, the no-op sync, and
writing the version into a new file.

Real use: OpenPencil v0.8.4 (latest release, arm64, sha256 checked against
its SHA256SUMS) under a sandbox HOME, started on a settings.json magpie
wrote with the user's own Anthropic entry beside it. It started and ran
15s with the file intact and no .corrupt copy. v0.8.4 has no `models`
field, so it lists only the first magpie model; main lists them all.

Not tried: a chat request through OpenPencil's UI; its exit save (it
didn't quit on an AppleEvent and was stopped with TERM, so the write-back
wasn't seen); Linux and Windows; a build of OpenPencil's main.
2026-10-16 11:43:51 +08:00
yetone 7597c13237 gui: a curl example pasted into a provider's editor fills it in (@mark_li21 on X)
@mark_li21 asked: 能支持通过curl例子直接导入provider不? A curl example
from a vendor's docs, pasted into a custom provider's Base URL or API key,
now fills in the editor instead of being pasted as text.

curlOf (app.js) is one pure function. It reads the paste the way a shell
would: lines joined by \, cmd's ^ or PowerShell's backtick; curl.exe;
quotes and escapes. From that it takes:

- the API that the URL's endpoint names: /chat/completions is Chat,
  /messages is Anthropic and /responses is Responses;
- the base URL before that endpoint, spelled by respellURL the way the
  editor already wants it;
- the key from Authorization: Bearer, x-api-key or api-key;
- the model in the JSON body.

A key that is only a placeholder ($X, ${X}, %X%, <token>, YOUR_API_KEY)
is not taken. The key box is left empty and focused instead. A new
provider adds the model to its models. A saved provider's picks are left
alone, because adding to an empty list would narrow what it serves. A
preset's editor only takes the key.

A note in the editor says what was filled in. It also points out a
placeholder left in the URL, such as {WorkspaceId}, and a URL with no
known endpoint. Its four strings are translated into zh, zh-TW, ja and
de. Text that isn't curl pastes as before, including several keys at
once.

Found along the way: url.onpaste = fromCurl cancelled every plain paste
into the Base URL, because an on-handler that returns false cancels the
event. The handler is now wrapped. The test fails on the unwrapped one.

Fixtures, in internal/gui/tests/fixtures/curl, are the docs' own bytes:
- OpenAI chat (API reference) and Responses (quickstart);
- Anthropic Messages;
- DeepSeek, Zhipu, Moonshot and OpenRouter quick starts;
- Alibaba Bailian's Windows cmd example (^ and \"-escaped JSON);
- SAP AI Core's PowerShell one-liner (curl.exe, <Deployment_url>);
- Unsloth Studio's PowerShell example, with backtick continuations, as
  its usage panel renders the template. This one is not copied from a
  static doc page.

The doc row is "A pasted curl command" in
docs/subsystems/providers-accounts.md.

Run at 674b6ca28 (origin/main) plus this change:
- provider-curl-paste.test.cjs (new): 10/10. It covers Chromium and
  WebKit; curlOf on every fixture, with LF and CRLF line ends; and the
  editor in en and zh at 900px and 440px. The editor checks are the
  filled form, the focused key, the note's text, plain and many-key
  pastes, the saved body, no sideways scroll, no <select> and no page
  errors.
- Related GUI files, run together with the new one, 112/112:
  gui-de, gui-ja, gui-zh-tw, i18n-keys, key-import, nokey-editor,
  provider-add-gemini, provider-base-api, provider-many-keys,
  provider-many-keys-proxy, provider-url-each-api and vertex-editor.
- Broken by hand, the new test goes red:
  - fromCurl taking nothing: 8 of 10 fail (the editor runs);
  - the endpoint not cut from the base URL: 10 of 10 fail;
  - url.onpaste = fromCurl unwrapped: the plain-paste check fails.
- gofmt -l: none. GOOS=linux and GOOS=windows go vet -tags nogui ./...: ok.
- go test -tags nogui -count=1 -timeout 45m ./... in a sandbox HOME:
  exit 0, 66 packages ok, no FAIL.

Not tried:
- the real app (Wails) on macOS, or WebKitGTK on Linux;
- Windows;
- a pasted command used to reach a real vendor with a real key.
2026-10-16 11:01:24 +08:00
yetone 674b6ca288 gui: a provider's per-key proxy lines fold past eight keys (@NetRozee on X)
@NetRozee on X: a custom endpoint given a thousand keys froze magpie.

Cause. The editor's Advanced > Proxy drew a line for every key, each
with a Provider's proxy | Direct | Custom control. Each control, once in
the page, looked up its place among every .segs in the editor and slid
its thumb (segsPlace, slide): quadratic, with a layout read each. The
Accounts list above it already folded (keyFold); this list didn't.

Fix. proxyLines folds a provider's keys as keyFold does: past KEYS_FOLD,
the first KEYS_FIRST and those with a proxy of their own, then All N
keys; opened, a filter (keyMatches, as the Accounts list's) over
KEYS_PAGE lines and how many more, and Show fewer. Typing draws the
lines again under the filter, which stays in the page (#1055). A key not
drawn keeps its proxy: Save posts every key's own, drawn or not.
Subscription accounts' lines are unchanged. No new strings.

Measured (Playwright, the editor opened on a provider of N keys):
                1000 keys          5000 keys
  Chromium      1067ms -> 100ms    55.6s -> 93ms
  WebKit        4809ms -> 68ms     203s -> 81ms
  DOM           9388 -> 434 nodes  45388 -> 434 nodes

Tests: provider-many-keys-proxy.test.cjs (new, en and zh, Chromium and
WebKit): fails in all four on the old app.js (no All 300 keys). With
account-proxy, provider-many-keys, filter-ime, usage-keys-fold,
i18n-keys, click-scroll, provider-proxy, proxy-own-wording,
routing-proxy, plugin-proxy-page, signin-proxy and proxy-test: 221 of
221 pass in both engines.

Run: gofmt -l (clean); GOOS=linux and GOOS=windows go vet -tags nogui
./... (clean); go test -tags nogui -count=1 -timeout 45m ./... in a sandbox HOME (GOCACHE, GOMODCACHE pinned) on af601541e with this series: 66 packages ok, 18 without tests, no FAIL (gateway 468.5s, provider 215.9s, gui 122.8s).
provider-many-keys-proxy.test.cjs rerun after the suite: 4 of 4.
2026-10-16 08:43:02 +08:00
yetone af601541ef routing: a request opens to its request and response (Fate on Discord)
Fate asked on Discord to see what a single request on the Routing page sent
and got back, such as a Codex prediction. The bodies were captured already,
in the Gateway page's 40 recent calls and the opt-in request archive, but
nothing led there from a Routing request.

- gateway: a Call carries the Routing request it was (Call.Route = the
  trace's Route.ID), set where serve, the Codex backend and a refused title
  record it. Server.RouteCall finds it in the ring. A route id is not a
  call id. A route names its archive copy (Route.Archive =
  call.archiveName()), set only when the archive was on, so it reaches the
  saved history too.
- gui: GET /api/gateway/call takes ?route= besides ?id=. It is the same
  handler, the same no-store, the same key guard and the same 404 once the
  ring has let the call go.
- Routing page: the story's head has "Request and response". It fetches
  only when pressed, and shows the masked bodies through callBodyPanel (an
  SSE reply reads as its events). A request the ring no longer has shows
  the archive's copy through archivePanel when the route names one.
  Otherwise it says the last 40 are kept until magpie quits and how to turn
  the archive on. Nothing more is captured or kept than before.
- The head now wraps. At narrow widths its buttons ran past the story
  ("Back to live" was cut off at 440px).
- The two button words live in i18n.js: i18n-keys' "a plugin's words are
  its own" found them inside core strings.
- docs/subsystems/gui-shell.md says how a route reaches its bodies.

Tests:
- TestRoutingRequestOpensItsBodies (new): each of two routes gets its own
  bodies; route 0 and an unknown route get 404. Red without
  `call.Route = tr.ID` ("route …: 404").
- TestArchiveWholeBodies now checks that the route names the archive. Red
  without the t.Archive line (`route names archive ""`).
- routing-bodies.test.cjs (new), chromium and webkit at 440px, en, zh,
  zh-TW, ja and de, 10/10. It covers the ring's copy read only when asked,
  hiding, another request closing it, the archive's copy, the
  how-to-keep note, nothing past the story and no left border.
  - Red with the client asking ?id= and with the head's wrap removed.
- routing-request-metrics.test.cjs: with the head wrapped, its 480px
  picker clicks in WebKit landed on the footer. Playwright's WebKit places
  elements in the scrolled view hundreds of px lower than
  getBoundingClientRect, which elementFromPoint agrees with. The test now
  clicks where the page shows them. 5 runs of both engines, 20/20.

Run in a sandbox HOME at f1c91a99c plus this change:
- gofmt -l: clean. go vet -tags nogui: darwin, linux and windows ok.
- GUI: routing-*, panel-routing*, recent-call*, i18n-keys and
  header-relang in both engines: 1079 tests, 1079 pass (a first run had
  2 reds, both fixed above).
- go test ./internal/gui after the i18n move (TestPanelJoinsFullScreenSpaces
  skipped): ok.

Full suite: `go test -timeout 45m ./...` gave 65 ok, 1 FAIL. The FAIL is
internal/gui TestPanelJoinsFullScreenSpaces ("the panel shown doesn't take
the keyboard"), red 3/3 alone here and red the same on origin/main
1d227a7eb just fetched. It is filed as #2450.
2026-10-16 07:23:55 +08:00
yetone ba17c4f90d provider: a Command Code plan key's card shows the month's credits as a meter (#2451)
tianxia3111 runs Command Code on the keyed preset with a plan's key. Its
card showed the 5-hour and weekly windows as meters, but the month's
credits only as dollars left ($5.27), with no share of the month. The
cause: billing/credits leaves out the planId, so the key's card couldn't
know the plan's monthly pool. The signed-in subscription's card gets
that pool from billing/subscriptions.

The key's card (planKeyWindows -> cmdKeyWindows) now asks
billing/subscriptions with the same key for the plan. It then makes the
month a "Credits" window beside the other two, through the same
cmdQuotaOf the subscription's card uses ("$4.78 / $10.00" on a Go plan).

- The plan id is kept per key for ten minutes, since
  billing/subscriptions takes 15-20 s at times.
- The id read before still counts while the plan can't be read.
- A key whose plan was never read keeps its two windows alone.
- A pay-as-you-go key, with no windows, still gets no card.

planWindows' request and status handling move into planBody, so that
cmdKeyWindows can decode the reply itself; other vendors are unchanged.

Run:
- New TestCommandCodeKeyCardHasCredits uses the reporter's own
  billing/credits reply. Its billing/subscriptions reply has the shape
  the other Command Code tests use (individual-go-monthly), because the
  reporter's plan id isn't known.
- With the new branch disabled by hand, the test went red: two windows,
  no plan. With it, green.
- TestKeyQuotasKeepLast now answers billing/subscriptions with 503 and
  still sees its two windows.
- gofmt; go vet -tags nogui for darwin, linux and windows.
- Not tried against Command Code's real API: there is no plan key here.
- Full suite (go test -timeout 45m ./..., at f1c91a99c plus this change):
  every package ok except internal/gui, red only on
  TestPanelJoinsFullScreenSpaces, which is #2450 (macOS 26.2, red on
  main before this change).
2026-10-16 06:32:41 +08:00
yetone 97f264c7fb gateway: a 413 on the OpenAI routes says request_too_large, so pi compacts (@wilsonxuuuu on X)
@wilsonxuuuu's pi, on gpt-6.1 through magpie, stopped on
"magpie API error (413): {...,"type":"api_error"}" at 114k of a 1M
window and never auto-compacted. The vendor's 413 was a body byte cap.
pi's overflow table (pi-ai utils/overflow.ts) knows a byte cap only as
request_too_large, Anthropic's type, which magpie already gave on the
Anthropic route but not on chat/responses. writeErrorSaid now types
every 413 request_too_large (Gemini keeps its own status shape). The
status stays 413 and the byte-limit hint stays; it is not turned into
context_length_exceeded, so Codex and Claude Code read it as before
(Codex reads code, not type). pi compacts once and retries once
(_overflowRecoveryAttempted), so a body that is still too big after
compacting stops instead of looping.

Run:
- pi 1.1.0's own isContextOverflow on the reporter's body: api_error
  false, request_too_large true.
- TestPayloadTooLargeSaysRequestTooLargeToPi (an nginx 413 page from a
  chat upstream) and the new Chat/Responses rows of
  TestBodyRejectionErrorShapes fail with the gateway.go change reverted
  by hand, pass with it.
- go test -tags nogui -count=1 -timeout 45m ./... under a sandbox HOME:
  every package ok. gofmt clean; GOOS=linux and windows go vet of
  internal/gateway clean.
Not tried: a real pi session hitting a real vendor 413.
2026-10-16 06:09:50 +08:00
yetone 6641e1b0ac provider: a plugin sign-in drops what a request holds at once (#2449)
TestPluginLoginInstallsItsCLIFirst went red on macOS CI (run
38798393584) with "not signed in after the install: []". cli's run()
sets catalog.Changed = agent.SyncCatalog, and a sync left going from an
earlier step holds the catalog (provider.Hold), plugins and their
sign-ins among it, for up to a second. The host's "auth" event dropped
that only through catalog.Touched, told in the background, so on a busy
runner provider.Logins right after the sign-in read the snapshot taken
before it.

plugin.OnChangeNow registers hooks run before changed() or listed()
returns, i.e. before the host's reply after the event is read; provider
registers dropHeld there. Changed() is filememo.Forget + dropHeld.

Reproduced by injecting a pause where SyncCatalog holds (patch kept
outside the tree): without the fix red 3/3 with the CI message; with it
ok -count=5. TestHeldGoesWithAPluginChange: red without the fix ("held
from before the change: built 1 times, want 2"), green with it, also
-race -count=20.

Run: -count=20 -run TestPluginLoginInstallsItsCLIFirst ./internal/cli
ok; internal/cli, internal/plugin, internal/provider whole ok; gofmt -l
clean; go vet -tags nogui for darwin, linux, windows on the three ok.
Full suite: go test -tags nogui -timeout 45m ./... at 7fefbc614 with both #2449 commits (this one and the Settle fix after it) (sandbox HOME, macOS): exit 0, 66 ok, 18 no test files, 0 FAIL.
2026-10-16 05:29:20 +08:00
yetone bbf901570e provider: a WorkBuddy account's spent credits leave its free models counted out, as the plugin does (plugins#138)
hheei (magpie-community/plugins#138): an account at 560 / 560 credits
was ranked spent for deepseek-v4.1-flash too, which WorkBuddy serves at
x0.00 and which draws no credits. The plugin was fixed in 0.1.23
(notModels) and the mover min is 0.1.24 already; the built-in, which
users who haven't moved still run, had the same fault. wbQuota's
personal Credits window and the enterprise window now pass through
wbSpareFree, which scopes them (QuotaWindow.matches) to the models not
marked Free in the provider's last fetched list (catalog.Live). With no
list read, every model counts, as before. The 14018 "Credits exhausted"
rest already rests only the paid model (PaidBesideFree).

Run:
- TestWorkBuddyCreditsSpareFreeModels (new): with no live list the free
  model reads 100%; with one, deepseek-v4.1-flash (either case) reads 0
  while -sg (x0.03) and gpt-5.5 read 100. Broken by hand (wbSpareFree
  returning early): red, "deepseek-v4.1-flash: 100% used, want 0".
- gofmt -l clean; go vet -tags nogui ./... for darwin, linux, windows: 0.
- Full suite: go test -timeout 45m ./... in a sandbox HOME, twice: every
  package ok except internal/gui's TestPanelJoinsFullScreenSpaces ("the
  panel shown doesn't take the keyboard"), which is red the same way
  alone on a fresh origin/main be1030ece worktree; filed as #2450.
2026-10-16 05:21:09 +08:00
yetone a80bc30092 agents: the Cursor editor's ~/.cursor is no Cursor CLI
The editor makes ~/.cursor on its own, so the folder alone says nothing
of cursor-agent (dirShared): cli-config.json or the command finds Cursor
CLI. The Library still writes the MCP servers and skills the editor reads
there when only the editor is here (SharedHere).

Run at this head before the rebase onto 0f391a7a7: go test -tags nogui -count=1 -timeout 45m ./... under a sandbox HOME, every package ok; gofmt -l clean; go vet clean for darwin, linux (nogui) and windows; GUI files agent*, i18n*, gui-*, getting-started, library*, sess* and import-row in both engines: 1638/1638.
2026-10-16 05:10:43 +08:00
yetone 486ea82378 agents: cursor-agent's row is Cursor CLI (@G_Z_Y on X)
@G_Z_Y looked for Cursor CLI on the Agents page and took the "Cursor" row
for the editor. The row is cursor-agent, so it is named Cursor CLI. What
it keeps in ~/.cursor is the Cursor editor's too (MCP servers, skills,
chats), so the Library and Sessions name it Cursor there (SharedName).

Run at this head before the rebase onto 0f391a7a7: go test -tags nogui -count=1 -timeout 45m ./... under a sandbox HOME, every package ok; gofmt -l clean; go vet clean for darwin, linux (nogui) and windows; GUI files agent*, i18n*, gui-*, getting-started, library*, sess* and import-row in both engines: 1638/1638.
2026-10-16 05:10:43 +08:00
yetone 7fefbc614e gateway: a relay's cap on one request's input fails over in a group (#2445)
B.ai answered a 380K request, under the model's 1M window, with 400
"Input token exceed the limit (request id: …)". No pattern in tooLongRe
matched it, and quotaWords wants "exceeded", so retryable() was false and
group/top's other three members were never asked (worksyang).

tooLongRe now also matches "input token(s) (count) exceed(s|ed) (the)
(max|maximum) limit". The refusal is taken as an overflow, so the chat
loop's existing #700 path asks the next member that may hold the request
(withRoom, failOverflow). Nobody rests, another account of the same model
isn't asked, and with no member left the agent is told it overflowed, to
compact. paceWords still keeps rate limits worded with input tokens out,
and a plain bad request still isn't asked of anyone else. System One's
decision groups (decide_group.go, which the report cites) are unchanged:
their requests are short decision text.

Test: TestRelayInputCapGoesToTheNextMember uses the reporter's message
verbatim. The JSON around it is not the reporter's; the issue shows only
the message. Docs: gateway-routing.md failure paragraph + verification.

Run:
- Broken by hand, the new test went red each time:
  - pattern removed: group answered 400, member 2 never asked;
  - paceWords check removed: two rate phrasings taken as overflow;
  - retryable true for every 400: the plain bad request reached member 2.
- TestRelayInputCap, TestEveryVendorsOverflow, TestOverflow*,
  TestContextOverflow*, TestOutOfBudget*: ok.
- gofmt -l: clean. go vet -tags nogui ./... on darwin, linux, windows: ok.

Full suite: go test -tags nogui -timeout 45m ./... at 0cad76cd9 + this
change, sandbox HOME: 66 packages ok, 0 FAIL (internal/gateway 1768s).
2026-10-16 04:58:32 +08:00
yetoneandggbdpq 7e4336e719 gateway: an event magpie appends to a cut stream begins after a blank line (#2446)
A passthrough stream cut mid-line got its error event written onto the
half-written line, so the client read "event: error" as more of that
line's data and never saw the error as an event. ggbdpq's patch (#2446)
tracks whether the last write ended a line (passthrough's write, and
holdWriter.atLine for cutLoop) and puts a blank line, two newlines when
mid-line, before the appended event.

The same join could happen to the other event passthrough appends: the
finish_reason filled in for a Gemini OpenAI-compatible reply that ended
done (a6f908ba5). It now goes through the same separator (apart). The
truncated pending event is still dispatched; SSE can't take it back, but
the error now arrives as an event of its own.

holdWriter's other appends (release, failTo) only follow keepalive
comment lines, so they already start on a line.

Tests: TestPassthroughStreamCutMidLine, TestPassthroughStreamEndsOnLineEnd,
TestLoopCutMidLine (ggbdpq), TestGeminiCompatFinishAfterPartialLine.
Broken by hand: apart returning "\n" always -> CutMidLine and
GeminiCompatFinishAfterPartialLine red; the Gemini fill-in without the
separator -> GeminiCompatFinishAfterPartialLine red; cutLoop's "\n\n" as
"\n" -> TestLoopCutMidLine red. Restored, all green.

gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui ./... clean.
Full suite: go test -tags nogui -timeout 45m ./... at base 0cad76cd9, 66 packages ok, 0 FAIL (gateway 1869s, provider 445s; sandbox HOME)

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
2026-10-16 04:56:34 +08:00
yetone 056cfe3323 provider: Codex's keychain read waits for the user, tells a refusal from no answer, and is kept while the item is unchanged (#2367)
Dony2050 (#2367) runs Codex with cli_auth_credentials_store = "auto" and no
auth.json, so magpie reads "Codex Auth" through /usr/bin/security. Four
faults:
- One 10s timeout covered both of macOS's prompts and the user typing their
  password. A read they approved after 11-16s still failed.
- A timeout and a refusal gave the same error.
- A read was kept for 10s only. With "Allow" (once), background polls
  prompted again about every 30s.
- Only a restart cleared the 10-minute failure cache.

What changed:
- Reading the secret is one ask per item at a time (askCodexKeychain). It
  runs in its own goroutine for up to 2 minutes (keychainAsk), outside
  codexKeychainMu, so no `security` run happens under a lock a reader needs.
  A reader waits at most 5s from when the ask started (keychainHold), then
  gets errKeychainWaiting. A request or a page never waits out the prompt.
  The ask's answer is kept when it lands, unless magpie kept a newer one
  after it started.
- Each failure says what happened:
  - exit 44: no item.
  - exit 51 (errSecAuthFailed) or 128 (errSecUserCanceled): denied or
    cancelled (errKeychainRefused). Checked against SecBase.h. Exit 44 was
    also checked on a throwaway keychain in the scratchpad.
  - the 2 minutes ran out: no answer (errKeychainNoAnswer).
  - anything else: errKeychainUnread.
  None of them counts as signed out.
- A successful read is kept while the item is unchanged. After 10s a reader
  runs Stat (find-generic-password without -w), which shows no prompt and
  returns only the item's mdat. The secret is read again only when the mdat
  changed.
  - Every write of the credential re-derives the cache:
    - codexStore.write keeps the date of what it wrote (keepCodexKeychain).
    - Switch, sign-out (deleteCodexLogin) and refresh forget a read
      (forgetCodexKeychain), so the next read checks the date.
  - forget keeps a refusal for its 10 minutes (#2408).
  - resetCodexKeychain clears everything. Only tests use it.
- The saved accounts' line in the GUI has a "Try again" link beside Remove
  when a read was refused, got no answer or is waiting (Exclusion.Retry).
  It posts /api/provider/keychain-retry, and RetryCodexKeychain reads once
  past the refusal.
  - The reason now says "Always Allow" lets /usr/bin/security read the item,
    so macOS stops asking each time Codex changes it.
  - Two new strings in zh, zh-TW, ja and de.
- docs/subsystems/providers-accounts.md: the "Codex's credential store" row
  describes the above.

Tests:
- TestCodexKeychainAskedSeldom (rewritten) covers:
  - an unchanged item over aged and forgotten rounds asks once;
  - a changed item asks again;
  - a gone item is not found without asking;
  - a refusal is kept through forget.
- TestCodexKeychainPromptWaitedFor: a held prompt gives "waiting" to the
  first and to 8 concurrent readers without blocking. Once answered, the
  read succeeds with one ask.
- TestCodexKeychainRetry: Retry and Why for refused, no answer and no item,
  and RetryCodexKeychain.
- TestSecurityKeychainExits (codex_keychain_ask_unix_test.go): a fake
  `security` built with testenv.Program covers:
  - a 2s answer with keychainWait = 1s succeeds;
  - Stat parses the mdat;
  - exits 44, 51, 128 and 1 map as above;
  - a hang gives no answer.
- signedout_test: Retry is set only for an unread item.
- GUI keychain-retry.test.cjs runs in chromium and webkit, in en and zh:
  - order Try again, Remove;
  - the POST body;
  - the line leaves after a click;
  - no link without retry.

Broken by hand (each restored after):
- Find bounded by keychainWait again: TestSecurityKeychainExits red ("a read
  the user answered late ... no answer in time").
- exit 51 not classed as refused: TestSecurityKeychainExits red ("Find,
  denied").
- Readers wait on the ask (no hold): TestCodexKeychainPromptWaitedFor hangs;
  the package timed out.
- forget clears every read: TestCodexKeychainAskedSeldom red (4 asks).
- mdat match ignored: AskedSeldom red (7 asks).
- Cache never re-checked: AskedSeldom red (the changed item wasn't seen).
- RetryCodexKeychain also deleting the failure cache: still green, because
  a fresh read asks past a refusal. That loop was removed as redundant.

Not tried:
- A real macOS prompt, or an item Codex itself wrote. Every test uses a fake
  `security`; the real keychain and ~/.codex were not touched.
- Put and Remove are still bounded at 10s.

Run at this head, rebased on origin/main 1a16fc0b5:
- gofmt -l: clean.
- go vet -tags nogui ./...: ok for GOOS darwin, linux and windows.
- go test -race -count=2 on the keychain, signed-out and Codex sign-in tests
  in internal/provider: ok.
- GUI (node --test, NODE_PATH playwright 1.62.0): keychain-retry, i18n-keys,
  saved-signedout-remove, gui-de, gui-ja, gui-zh-tw: 24/24 pass.

Then rebased on origin/main 167df7055 (TestSecurityKeychainAnswers' fake is
a testenv.Program; no overlap in hunks): go vet -tags nogui for darwin, linux
and windows on provider and gui, and go test -race ./internal/provider: ok.

Full suite: go test -timeout 45m ./... in a sandbox HOME, set -o pipefail, at
this tree on origin/main 1a16fc0b5: exit 0, 66 packages ok, no FAIL (gateway
1588s, agent 1497s, provider 510s).

Rebased onto origin/main a6f908ba5 (#2440, #2437 Gemini finish_reason; no overlap): go test -tags nogui ./internal/provider ./internal/gui ok.
2026-10-16 03:46:15 +08:00
yetone a6f908ba58 gateway: a Gemini OpenAI-compatible stream that lost its finish_reason is ended by usage, or cut
Linka (Discord #feedback): Gemini's OpenAI-compatible API sends a whole
function call (its thought signature, the usage) in one chunk and the
finish_reason in the next. When the upstream hung up between the two,
magpie relayed a stream that ended with neither, and Pi threw the
complete call away ("Stream ended without finish_reason") and asked the
whole 160k turn again. On a Chat upstream only a failed read was a cut,
so a clean EOF there went on as a stream with no end.

That API counts the usage only on the generation's last chunk(s): the
Vertex fixture (testdata/vertex_openai_thoughts.sse) has it only beside
finish_reason, Linka's frames have it on the call chunk and the finish
chunk, and Google's forum and third-party docs say the same; no Google
doc states it. So for a Chat upstream that is Gemini's (geminiCompat,
saysItsEnd) and ended without a finish_reason:
- its last chunk carried usage: the generation was done and only the
  finish_reason was lost. It is filled in (chatTail), "tool_calls" after
  a call and "stop" otherwise: relayed, as one chunk before [DONE]
  (written only if [DONE] hadn't gone); translated, as the reply's normal
  end (tool_use for Claude Code), streamed and unstreamed. Recorded ok.
- no usage at its end: the reply was cut, and the client gets "the reply
  ended before it was complete" (errEndedShort), as a Gemini stream's
  finishReason is told (#1643, #1644): the relay's error chunk, the
  translated stream's error, an unstreamed 502.
A failed read keeps its own "connection lost mid-reply". Other vendors'
Chat streams are unchanged.

Tests (gemini_compat_cut_test.go, Linka's frames): relayed, the call
with usage ends with finish_reason tool_calls then [DONE], text with
usage with stop, the call without usage with the error and no
finish_reason; a whole reply with or without [DONE] goes as it came
with one finish_reason; kimi-k3 with and without usage unchanged.
Translated: with usage one message_stop with stop_reason tool_use and
no error, streamed, and a 200 tool_use unstreamed; without usage one
error and no message_stop, and a 502 unstreamed.
Broken by hand, each red: the relay fill off (relay test: no
finish_reason), the streamed fill off (0 stops, 1 error), the
unstreamed fill off (502), usage ignored in chatTail.finish (every
no-usage case ended as whole, unstreamed 200).

Run: gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui ./...
ok; go test -run 'TestGeminiCompat|EndedShort|TestStreamCut|
TestWellFormed|Sniff' ./internal/gateway ok.
Docs: gateway-routing.md says when the finish_reason is filled in.
Full suite: go test -tags nogui -timeout 45m ./... at base a61a6f954 + this, EXIT 1: 65 packages ok, internal/gateway red only in TestVisionWaitIsntTheDescribersTime (300ms describer limit under load, unrelated; passes -count=5 alone; filed #2444). Rebased onto 1a16fc0b5, internal/gateway whole: ok.
2026-10-16 03:41:49 +08:00
yetone db8b791797 plugin: tools-, page- and agent- packages take their short name without the prefix
@magpie-community/tools-calc served its tools as tools-calc_eval and its
page under "tools-calc" because ShortName only dropped middleware- and
opencode-. It now drops tools-, page- and agent- too, so the calc example
serves calc_eval/calc_convert/calc_date as its README and the docs say.
`magpie plugin options` / SetOptions find a plugin by its short name or by
its bare package name (plugin.Called), so "agent-aider" keeps working
beside "aider".

Run at 1a16fc0b5:
- go test ./internal/plugin ./internal/cli ./internal/middleware, and
  gateway -run 'Tool|MCP', gui -run Page: ok.
- Broken by hand: ShortName without the new prefixes -> the new
  TestShortName cases red; Called without bareName -> the
  SetOptions("agent-aider") case red. Both green after restoring.
- Sandbox HOME: magpie plugin add @magpie-community/tools-calc listed
  tools calc_convert, calc_date, calc_eval.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: 0.
- go test -timeout 45m ./... : ok (load ~130).
2026-10-16 03:41:22 +08:00
yetone a0a4d55ef7 gateway: a passed-through reply whose reasoning loops before it says anything is asked again once, and its tries counted (#2436)
lqisgod's five looped replies (pi → WorkBuddy, Chat in and out) each
ended at once with empty tries and status 200. The once-only re-ask of a
reasoning loop (loopReasks) lived only in streamTranslated's onLoop, so a
same-protocol passthrough had holdWriter.reask nil and cutLoop ran on the
first trip. A re-ask that did happen in place wasn't counted in the usage
record's tries either (tries came from route.Tries alone).

Now holdWriter lets such a try go (mayReloop/letGoLoop) when its
reasoning looped, nothing has spoken (loopGuard.spoke: no text or call),
the request has its re-ask left and its context is alive, and either
nothing of the try reached the agent (held bytes dropped, any protocol)
or the agent speaks Chat (bytes written up to the end of the tripping
event, the next try's chunks follow). The fallback loop records the try
as failLoop with reloopedError and asks the same provider again after
retryPause. In-place re-asks add to tries too. An Anthropic or Responses
stream whose reasoning already reached the agent still ends with the
loop error: a second message_start/response.created can't follow. The
plugin host's fetch goes through the same holdWriter
(TestLoopEndsWorkBuddysReply's plugin subtests).

Tests: loop_guard_test.go's chat case now expects 2 asks and an answer;
every passed-through `data:` line is valid JSON; the usage record has
Tries == asks and no error. docs/subsystems/gateway-routing.md updated.

Broken by hand, each red:
- hw.reloop = false (old behaviour): TestLoopEndsTheReplyOnEveryProtocol,
  TestLoopEndsWorkBuddysReply, TestReasoningLoopIsAskedAgain fail.
- reasked not added to tries: the same three fail with "usage record's
  tries 0, the vendor asked 2 times".
- spoke never set: TestLoopAfterTextIsNotAskedAgain fails.

Run: gofmt -l clean; go vet -tags nogui ./internal/gateway ./internal/usage
with GOOS=darwin, linux, windows ok; go test -run Loop ./internal/gateway ok.
Not tried: a real WorkBuddy account looping (the loop can't be forced).

Full suite: go test -tags nogui -count=1 -timeout 45m ./... on base
b03031738, every package ok, no FAIL line.
2026-10-16 01:55:47 +08:00
yetone b6533893a7 plugins: Discover lists tools and page plugins, and the intro links to the plugin docs
Every kind of plugin magpie runs now has its place on the Plugins page, so
someone looking to extend magpie finds what exists and how to write one:

- Discover has "Tools for agents" (market kind "tools") and "Pages" (kind
  "page") sections beside Subscriptions, Gateway middleware and Agents,
  each card with its own chip (a new Tools chip, the Page chip). Before,
  both kinds fell under Subscriptions as Providers.
- A GitHub repository tagged magpie-plugin whose package.json has
  magpie.page.file is a Page, and that file must be committed, as a
  provider's entry must (TaggedRepos).
- An installed plugin that only gives tools wears the Tools chip.
- The intro says what a plugin can be (provider, gateway middleware,
  routing strategy, tools, an agent, a page) and its "Write a plugin" link
  opens usemagpie.ai/docs/plugins in the window's language (zh and zh-TW
  to zh/, ja to ja/), outside the window.
- The docs' Publishing section lists the "tools", "page" and "agent"
  registry kinds and the community package names for each, in en, zh, ja.

Run at the reviewed head (on origin/main cf21b71ff):
- go test ./internal/plugin: ok. Broken by hand: without the page case,
  and with the page's entry not checked, TestTaggedRepos goes red.
- plugin-kinds-discover.test.cjs (new): 5 languages x 980/420 x chromium
  and webkit, green. Broken by hand, each red: the old plugins.js (11/11
  fail), no "tools" kind (11/11), no ja/zh-TW docs link (3), no Tools chip
  on an installed row (11/11).
- plugin-middleware.test.cjs's intro test now checks the new copy and link;
  it still checks the click scrolls nothing.
- Every plugin*.test.cjs and i18n*.test.cjs, both engines: 505 pass, 0 fail.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: 0.
- go test -timeout 45m ./...: all 66 packages ok (full=0).
2026-10-16 01:48:45 +08:00
ggbdpq abc9006819 gateway: a rule naming a group in the group keeps the group's own routing's order (#2407)
What changed
ruleFirst ranked the candidates of a rule's member by the group's flattened
member order, so a rule that names a group in the group erased whatever that
group's own routing had planned: a rotate group's turn advanced underneath,
but every request the rule put first was served by its first member again.
The rule's own member that is a group in the group is one member now — its
models rank as the group's block, in the order the group's routing planned
them; the members the rules after it name keep their own ranks, so a model
the rule names that the group has too still leads over them (#625,
TestRuleNamesAModelAGroupInItHasToo). TestRuleNamingARotateGroupKeepsItsTurns.

Run
HOME=$(mktemp -d) GOTOOLCHAIN=auto go test -tags nogui -count=1 -p 2 -run 'Rule|Rotate|Nested' ./internal/gateway/ — ok
HOME=$(mktemp -d) GOTOOLCHAIN=auto go test -tags nogui -count=1 -p 2 -timeout 45m ./internal/gateway/ — ok 304s
TestRuleNamingARotateGroupKeepsItsTurns on rules.go at 2e2c8903 (fix stashed): red, "modelA modelA modelA modelA modelA modelA"
gofmt -l clean; go vet -tags nogui (darwin), GOOS=linux -tags nogui, GOOS=windows on ./internal/gateway — clean
go build -o /dev/null . (darwin, known ld warnings only), GOOS=linux -tags nogui, GOOS=windows — ok

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-16 00:46:26 +08:00
ggbdpq a786c51cb0 agent: a magpie-models.json that doesn't parse is kept aside, not written over or removed whole
What changed: #2263 gave magpie's state files whose reader takes an
unparseable file as empty the lastgood.KeepUnparsed copy-aside, and its
sweep named the files it covered. Codex's magpie-models.json was in
neither its covered list nor its cache exemption, and its reader has the
exact missed shape: codexcat.Keep (#1450) returns the new list for a
file it can't parse, and the next sync, model switch or stepping back in
wrote that over the file, ending the keys the user added by hand
(supports_reasoning_summaries and friends) with no copy. Stepping out
was worse: dropList took an unparseable file for one holding nothing of
the user's and removed it outright.

Now the three writers of the list go through writeOwnList, which keeps
an unparsed file aside (magpie-models.json.bad-<time>) before the write
and stops when the copy can't be made, and dropList keeps one aside
before it removes the file.

Run:
- gofmt -l internal/agent: clean.
- go test -tags nogui -p 2 -count=1 -timeout 25m ./internal/agent: ok
  (183s).
- TestUnparsedCodexCatalogKeptAside fails on the code before this ("the
  unparsed list was written over with no copy kept"); the ablation
  replays it against this commit's parent.
- go vet -tags nogui ./... for darwin, linux and windows ok; go build
  for the three ok (reviewer, at the batch head).
Full suite: go test -tags nogui -count=1 -timeout 45m ./... ok, every
  package (reviewer, at the batch head before #2424 was added).

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-16 00:16:43 +08:00
ggbdpq d830d460f0 provider: a refused keychain read is not asked again for ten minutes (#2408)
What changed: copilotCLISecret backs a denied keychain read off (10
minutes, "don't ask again at once"), but the two other readers of the
same family took every failure as an absent item and asked again after
their ordinary 10s TTL. On macOS a denied item prompts again on every
read, so a user who answers Deny once was asked again every 10 seconds
while Cursor's status or Claude's credentials were polled, and every 10
minutes only for Copilot (#2408's report is the Copilot face of this).

Now cursorKeychainToken and readClaudeKeychainItem (through
claudeCredential's cache) treat any `security` failure but 44 — the item
not being there, which asks nobody — as a read that may have shown the
user a dialog, and don't repeat it inside keychainDeniedTTL (10 minutes,
copilot's own pause). A sign-in or out in magpie reads afresh
(forgetCursorStatus, forgetClaudeCredential clear the pause), and a
fresh read in CursorToken is unchanged.

Run:
- gofmt -l internal/provider: clean.
- go test -tags nogui -p 2 -count=1 ./internal/provider: ok (72s).
- TestDeniedCursorKeychainReadIsNotAskedAgain and
  TestDeniedClaudeKeychainReadIsNotAskedAgain fail on the code before
  this (a refused read asked again 11s later).

Not tried: a real macOS keychain dialog answered no (a fake `security`
stands in for it); Copilot's own reader is unchanged.
- go vet -tags nogui ./... for darwin, linux and windows ok; go build
  for the three ok (reviewer, at the batch head).
Full suite: go test -tags nogui -count=1 -timeout 45m ./... ok, every
  package (reviewer, at the batch head before #2424 was added).

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-16 00:16:43 +08:00
yetone 682e4253bf gateway: a Gemini call's thought signature is kept on disk and its id carries a 16-character key, not the signature — ids were 3KB+ and broke a client's PostgreSQL index (#2411, liangxyz)
Since #687 a tool call Gemini signed went to the client with the signature
inside its id (<id>__ts<n>__<base64url>), so the client's next request
brought it back. A Gemini 3 signature is often 2–6KB, so ids were too: LobeHub
stores tool_call_id in a btree index, whose rows are capped near 2.7KB, and
the write failed.

The signature is now written to <settings>/gemini-signatures/<key>, the key
being 12 bytes of its SHA-256 in base64url, and the id carries
__tsk16__<key> (≈36 characters). Coming back, the file is read and its hash
checked against the key; a file gone or changed is no signature, and the
call goes to Gemini with skip_thought_signature_validator, as an id a client
shortened already did. A file is touched when it is read or written again
and pruned 90 days after its last use (at most once an hour, on a write);
temp files from a write cut short go after an hour. When the folder can't
be written, the signature still rides in the id as before. Ids made before
this (__ts<n>__, __tsr<n>__, __ts__) are still read.

Real use: a sandbox HOME magpie serve with the owner's Antigravity account
copied in, antigravity/gemini-3.8-flash-high, a two-turn tool call over Chat
and over /v1/messages: ids came back as call_659137__tsk16__cOTtfB5LubcVSNaX
(36 characters), turn 2 answered from the tool result, and the store file
(584 bytes) was born on turn 1 and touched on turn 2's read.
gemini/gemini-3-flash-preview answered 502 (Gemini CLI no longer
supported), unrelated. Not tried in LobeHub itself; asked on the issue.

Tests: TestFortyCharacterIDThroughGateway now keeps the real signature
through a 40-character id; TestLongSignatureGivesShortID (6.4KB signature,
id ≤ 64, round trip); TestKeptSignatureGoneOrChanged; TestUnkeptSignature-
RidesInTheID; TestOldSignaturesPruned. Broken by hand: keepSignature
disabled fails FortyCharacter and LongSignature; the hash check removed
fails KeptSignatureGoneOrChanged.

Ran: gofmt; go vet -tags nogui ./internal/gateway/ for darwin, linux,
windows; targeted tests -count=3.
Full suite: go test -tags nogui -count=1 ./internal/gateway/ ok (466.9s);
the rest of the suite ran green on the batch this is rebased onto
(386d341e7).
2026-10-16 00:16:43 +08:00
yetone a7a0122027 gui, gateway: the search grip's place is a class, not :has(), and Go no longer says the Routing plugin's words (batch GUI reds)
The full GUI run on this batch had two reds that are real, both from
commits in it:

- old-webkit "the styles hold up in Safari 15.0": 4b69460d1 (#2286)
  placed a search API's grip with `.search-unit:has(> .search-keys)`,
  which Safari before 15.4 can't parse. The unit now gets a with-keys
  class where its keys' row is added, as other rows in app.css do.
- i18n-keys "a plugin's words are its own": 7ff5f595e's test name
  TestArkDrawsUnmarkedOncePerImage and f9ccca71e's comments in active.go
  and left_in_flight_test.go said "Unmarked" and "answering…", which are
  plugins/routing's words. The test is TestArkDrawsWithoutWatermarkOncePerImage
  (the subsystem page renamed with it) and the comments say it in other words.

Run: node --test i18n-keys (3/3), search-order (16/16), old-webkit and
mobile-web alone; gofmt; go vet -tags nogui ./internal/gateway.
Not checked by a test: the grip's top under a unit with keys; the rule
is the same, only its selector changed.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone d6b045a7e7 usage: the Overview's lists fold under their headings and stay folded, the token totals can count the cache, and the Requests Tokens card wraps its cache count instead of cutting it (#2378)
The reporter asked for three things on the Usage page: fold Agents,
Models and Accounts from their titles and remember it (日常看账号维度
较多,都要拉到最底下); an option to count the cache in the token totals;
and the Requests tab's Tokens card cut its cache count off on a wide
window ("缓存 879…").

- Folds: each Overview list's heading (Agents, Models, Accounts, and
  Gateway keys beside them) is a .fold button with its chevron, the
  Gateway page's pattern. A click keeps the page still (backToReader).
  What is folded is kept per viewer in localStorage magpie.usageFolded
  (mountUsageFolds at the plugin's mount, showUsageFolds per render).
- Cache: the tokens tile's label is a pop-up (usageTokensPick, the app
  menu, no <select>) of Without cache / With cache, kept in
  localStorage magpie.usageWithCache. With cache, the tile, the chart,
  and every row's count and share add cache read and written
  (usageTokens), and the tile says the cache's count. Default unchanged.
- Cut count: a token line in parts (the Requests strip's Tokens card,
  the Overview's tokens tile) wraps between its counts and keeps each
  whole (usageParts, .parts); only a count wider than its card on its
  own is cut. The part spans undo .kpi span's label capitals.
- Strings in zh, zh-TW, ja, de. docs/subsystems/gui-shell.md bullet.
- mobile-web.test.cjs: until BASE_REF has mountUsageFolds, the
  desktop Usage comparison puts the new fold buttons and the pop-up
  back to their plain labels and compares the rest as before. That
  comparison caught the tile's line in the label's capitals and 5px
  taller; both fixed, and usage-overview-fold now checks them.

Run at this head (base dd25997a4), BROWSER=chromium and webkit each,
single files:
- usage-overview-fold (new, en/zh/zh-TW/ja/de at 1100 and 420 on the
  Overview, 1500/1100/420 on Requests; the ledger fixture is the
  reporter's numbers, zh in 万/亿 as they read them): 26/26 both.
- usage-accounts, usage-hit-rate, usage-ledger-fit, usage-ledger,
  usage-ledger-agent-middle, own-requests, mobile-web,
  usage-speed-count, usage-sum-whole, usage-head-steady, i18n-keys,
  click-scroll, number-units, gui-zh-tw, gui-ja, gui-de: all pass
  both engines.
- usage-agents-hide: 5 pass, 11 fail in both, "unhiding a row leaves
  the hidden line where it was", identical with this change taken out
  at dd25997a4: #2276, open.
Broken by hand, chromium, each red then restored: the .parts CSS gone
(9 red, among them zh 1500 cut at "缓存 8793.3 万"); folded lists not
hidden (11 red); the cache never counted (11 red, 8.1M vs 568M); the
parts' label-style reset gone (11 red, uppercase/600).
No Go changes, so no gofmt or vet. Not tried in the real app.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone b6fae8efd8 gateway: an advisor magpie leaves out takes its instructions and tool_addition with it, so the model no longer calls a tool it hasn't got (JackChou on Discord)
JackChou: "claude code 使用 advisor 返回找不到对应工具". Claude Code 2.1.300
(its request read from a fake ANTHROPIC_BASE_URL in a sandbox HOME, with
--advisor and a fake key) declares the advisor as the server tool
{"type":"advisor_20260301","name":"advisor","model":…,"defer_loading":true}
and also puts it in the conversation: a {role:"system"} message whose text
ends in "# Advisor Tool … call advisor BEFORE substantive work", and a
{"type":"tool_addition","tool":{"type":"tool_reference","name":"advisor"}}
block.

79f64f028 left the server tool out where the upstream can't run it (a
vendor's model, another provider's advisor) and every translation drops
server tools, but both left the instructions and the tool_addition in place.
The model was told to call advisor() and given no such tool, so it called it
as one of the agent's tools and Claude Code answered "No such tool
available: advisor"; on Messages the tool_addition also named a tool the
request no longer declared.

Where magpie leaves the advisor out, withoutAdvisor (passthrough) drops the
tool_addition/tool_removal/tool_reference naming it, and a message left
empty, and replaces the instructions (up to the end of their reminder or
text) with Claude Code's own "The advisor tool is no longer available;
disregard the earlier advisor instructions." parseAnthropic does the same to
the text on a translation. An advisor that is kept goes as before.

Run: TestAdvisorModelAsTheUpstreamNamesIt (now on the literal 2.1.300 turn
in testdata/claude-code-advisor-turn.json, environment text cut short) and
the new TestAdvisorLeftOutOnTranslation (chat, responses, gemini). Broken by
hand (withoutAdvisor given no names, parseAnthropic not rewriting): both
red, the two left-out passthrough cases and all three translations; green
restored. go test -tags nogui -p 1 -run
'Advisor|Deferred|BillingLine|Shape|Anthropic|ToolSearch|TurnSystem|Passthrough'
./internal/gateway ok. gofmt -l clean; go vet -tags nogui ./internal/gateway
for GOOS darwin, linux, windows.

Not tried: a running magpie with real Claude Code end to end, and a real
vendor upstream; the reporter's provider and model aren't known, so whether
theirs was the passthrough or a translated route is inferred.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone d98e17808b gateway: a refusal that comes as an error ends the try at once, is read across writes after content, and the high-risk message alone is one (#2400, Jichao)
Three gaps Jichao reported, each reproduced on origin/main 4a6bf80f4
with fake upstreams before the change:

1. An HTTP error or stream error event whose message is, whole, "The
   request was rejected because it was considered high risk" with no
   policy code was any failure, not a refusal: no refusal fallback.
   policyRefusal now takes that exact message (trimmed) as a refusal
   (highRiskRefusal). It reads only an error's own message field, so an
   answer that quotes the sentence stays an answer. The vendor that sends
   it isn't known (no wire capture; none of our code or docs has it); it
   says the request was turned away, so it rests nobody and goes to the
   next candidate under RefusalRetries, like every refusal.
2. A policy error event before any content (content_filter, coded) left
   the held try waiting for the upstream's EOF: with the connection kept
   open the request hung until the client gave up. Such an event is now
   eventRefusalError and stops the try as eventError does; a refusal's
   stop/finish marker (eventRefusal) is still read to the end for its
   trailing usage and terminator.
3. After content, refusalAfter skipped a write that didn't look like a
   refusal, so an "event: error" whose name and data came in separate
   writes was never noted (a coded content_filter too). Every write is now
   read; only an unfinished event's bytes are kept, so a reply's content
   isn't copied. refusalSays matches the bare word error for the named
   event. Nothing already sent is replayed.

Reference patch by Jichao (585836c on Jichao/magpie
fix/provider-refusal-errors), reviewed line by line and taken with
changes: refusalAfter no longer appends every write to a buffer, the
message is a named const with why, the doc line is rewritten, and the
split test gains a coded named error (red on main without the message
match). No new retries or fallbacks: everything goes through the
existing refusal path.

Run (darwin, sandbox HOME, -tags nogui -p 1):
- New tests on main without the fix: TestHighRiskErrorMessage,
  TestHighRiskErrorFallsBack, TestRefusalErrorDoesNotWaitForEOF (hung to
  the 10s guard), TestHighRiskErrorWhenRetryStops,
  TestHighRiskTextAndStartedReplyAreNotReplayed,
  TestHighRiskNamedErrorAfterContentRestsNobody,
  TestHighRiskErrorSplitAfterContent all red. With it, ok.
- Broken by hand, each red: no stop on eventRefusalError
  (TestRefusalErrorDoesNotWaitForEOF), the per-write prefilter back
  (TestHighRiskErrorSplitAfterContent), the message case off (the
  TestHighRisk* set).
- -run 'Refus|Refuse|Hold|Fallback|StreamEvent|Late|Policy|Safety' ok;
  -race on 'TestHighRisk|TestRefusalErrorDoesNotWaitForEOF|Refus|
  StreamEvent|Hold' ok.
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows ok.
Not run: the full suite, any real vendor.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone 6e17d58ebf usage: a top session only the gateway saw says "Gateway session", not "(no prompt)" with no folder (#2285)
The reporter's Usage › Sessions card listed seven Pi sessions on
deepseek-v4-pro as "(no prompt)" with no folder, and their routing group
has no DeepSeek. Those rows were gateway projections: Pi asked magpie for
deepseek/deepseek-v4-pro (every served model is in Pi's models.json), most
likely through a pi-subagents child, whose session file is in a temp folder
magpie never reads. The card gave no sign of that, so it read as Pi's own
sessions with an empty prompt, and our first reply took it that way.

The overview's summaries from MergeExternalStats now carry gateway: true,
as MergeExternal's list rows already did. The card shows "Gateway session"
where the folder would be, "(prompt not recorded)" as the title when no
text was kept, and a tooltip pointing to Record gateway conversations.
Strings in zh, zh-TW, ja and de. gateway-sessions.md says it.

Run in this worktree (a1f7b8c13 base):
- go test -tags nogui -p 1 -count=1 -run 'TestTopSessionsMarkWhatOnlyTheGatewaySaw|TestGatewaySession|Overview|Session' ./internal/gui/: ok
- go test -tags nogui -p 1 -count=1 -run 'External|Overview|Stats|Gateway' ./internal/sessions/: ok
- Gateway: true removed by hand: TestTopSessionsMarkWhatOnlyTheGatewaySaw red
  (the Pi record, provider deepseek, came back with cwd "" and title "",
  no gateway field), green with it back.
- sessions-overview.test.cjs: 28/28 in chromium and webkit; with the
  page.js change undone by hand, red in en and zh ("(no prompt)").
- i18n-keys, gui-zh-tw, gui-de, gui-ja (chromium): pass.
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows on
  internal/sessions and internal/gui: ok.
Not run: the full Go suite and the full GUI suite.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetoneandfangzhengjin 3f4186fd8e providers: a provider you added can skip its own host's certificate check, nowhere else (#2383, fangzhengjin)
A vLLM on the LAN, an Ollama behind a self-signed certificate or a
company CA can't be reached over https today. A custom provider now has
"Don't check its certificate" (Certificate, in its editor, shown while an
address is https), with a short risk note, in en/zh/zh-TW/ja/de.

Scope, enforced in Go, not only in the GUI:
- Only a provider the user added with their own base URL takes it
  (TakesInsecureTLS: no preset, no account, no Vertex, no subscription
  id). Save refuses it on anything else, and Via ignores a hand-set flag.
- It reaches the hosts of the provider's own base URLs alone
  (netproxy.WithUncheckedTLS): a redirect elsewhere, a models/balance/
  image URL on another host, and a nested request for another provider
  (With drops it) are still checked.
- Every route: it is set in Provider.Via, which the gateway's attempt and
  forwardOnce (count_tokens too), List, Test, Detect, balance, draw,
  embeddings and video all go through.
- The unchecked host gets its own cloned transport (the route key holds
  the flag), so the leave never reaches another request. An https://
  proxy is refused for it, because its TLS would be dialled with the same
  config and go unchecked too; http:// and socks5:// proxies work.
- The editor shows the saved value, Test/Detect/Fetch carry it before a
  save, and a save that omits it keeps it. Backup, export and WebDAV sync
  carry it (backup.Collect).

Rewritten from fangzhengjin's fork 749e82a25 rather than applied: it had
no Go-side limit to custom providers, set InsecureSkipVerify for every
host the provider's requests reached (redirects, other hosts, nested
requests) and for an https:// proxy's own certificate, never showed the
flag back to the editor (the next save cleared it), and didn't carry it
into Test/Detect/Fetch. Its transport cache key holding the flag is kept.

Run in this worktree (-tags nogui -p 1, sandbox HOME):
- go test -run 'TestUnchecked|TestWith|TestDispatch' ./internal/netproxy ok
- go test -run 'TestInsecureTLS|TestVia|Proxy' ./internal/provider ok
- go test -run TestInsecureTLS ./internal/gateway ok (chat, responses,
  anthropic, count_tokens, gemini against a self-signed server)
- go test -run 'TestProviderSaveInsecureTLS|TestProviderSaveKeeps|Typed'
  ./internal/gui ok
- go test ./internal/backup ok
- GUI provider-insecure-tls.test.cjs: chromium 30/30, webkit 30/30
  (en, zh, zh-TW, ja, de at 1100 and 420)
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows on
  netproxy, provider, gui, gateway, backup clean

Broken by hand, each went red, then restored:
- With not clearing the leave -> TestUncheckedTLSOnlyItsHost
- the https:// proxy guard off -> TestUncheckedTLSStillChecksItsProxy
- TakesInsecureTLS always true -> TestInsecureTLSNotForPresetsOrSubscriptions
- Via not setting it -> TestInsecureTLSOwnProviderOnly and all 5 routes
  of TestInsecureTLSEveryRoute
- backup field tagged json:"-" -> TestRoundTrip
- save not keeping an omitted flag, providerInfo not showing it ->
  TestProviderSaveInsecureTLS
- draftOf/asTyped not carrying it -> 2 of 3 GUI tests (en 1100 chromium)

Not tried: a real vLLM or Ollama behind a self-signed certificate; the
image, video, balance, embeddings and draw routes are covered through
Via, not each by its own test. The full suite was not run.

Co-authored-by: fangzhengjin <12680972+fangzhengjin@users.noreply.github.com>

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone dc8dcc85d1 provider: a custom Balance URL can be asked with POST, for an endpoint that answers only a POST (#2368, yaofeng)
A custom provider's Balance URL was always asked with GET, so a balance
endpoint that takes only a POST answered 405 and the card never showed.

- Provider.BalanceMethod ("" or GET, or POST with no body). It applies to
  the user's own Balance URL only; a vendor magpie knows is asked as
  before. balanceMethodOf refuses any other value before anything is sent.
- CLI: `magpie provider set <id> balance.method=POST` (GET clears it; any
  other value is refused and the saved one kept); `magpie provider <id>`
  shows "from POST <url>".
- GUI: a GET/POST segmented control (segs, not a <select>) beside the
  Balance URL in More endpoints, aria-labelled and titled in en, zh, zh-TW,
  ja and de. Check balance and Save carry it; a preset's save keeps it.
- No vendor preset or name is added. A string amount ("0.94306040") was
  already read by number(), so `$usd_balance` reads as any field does.
- docs/subsystems/providers-accounts.md says it.

Run:
- go test -run TestBalance ./internal/provider/: ok. New TestBalanceMethod:
  a POST-only httptest server, POST (any case) reads $0.94 from a string
  usd_balance, "" and GET are still GET (405 is an error), PUT, DELETE and
  a CRLF value are refused with nothing sent.
- go test -run TestProviderSetBalanceMethod ./internal/cli/: ok.
- Broken by hand: the request always GET turns TestBalanceMethod red
  ("asked GET, want POST"); balanceMethodOf passing any method turns it red
  (PUT and DELETE sent); the CLI taking any value turns
  TestProviderSetBalanceMethod red; the Check balance body without
  balanceMethod turns 20 of 21 balance-method.test.cjs cases red, and
  origin/main's app.js all of them.
- GUI: balance-method.test.cjs 42/42 (Chromium and WebKit, 1100 and 420,
  en, zh, zh-TW, ja, de, saved GET and POST: opens on the saved method,
  named and titled in the language, fits beside the URL with no page
  scroll, the other pick goes in the check and save bodies). Siblings:
  balance-parts, balance-field-default, balance-fix, catalog-hint,
  duplicate-pause, key-balance-card, local-address, provider-base-api,
  provider-auth-header, provider-gemini, provider-search,
  provider-url-each-api, gui-de, gui-ja, gui-zh-tw, i18n-keys: 250/250.
- Real use: the built binary in a sandbox HOME, a custom provider at a
  local server that answers GET 405 and POST {"usd_balance":"0.94306040"}.
  Default: "unavailable 405 Method Not Allowed"; balance.method=post:
  "$0.94 from POST …/api/check-balance $usd_balance", the server saw one
  POST with Content-Length 0 and the Bearer key; balance.method=PATCH
  refused. NanoGPT itself was not asked (no key here).
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.

Suite run here: HOME=<sandbox> go test -tags nogui -timeout 45m ./...: 62
ok, internal/gui FAIL only on TestSetAnswersWhileDevinAndProvidersHang
(a state took 11.97s, load ~180), open as #1375; it passes -count=2 alone.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone afb0ff7720 gateway: a tool Pi adds in a message of its own joins the request's tools on every route, once by name (#2322, deephbz)
Pi 1.2.0 with supportsMidConvoToolAdditions sends a tool it adds
mid-conversation as {"role":"system","tools":[...]} with no content and
keeps top-level tools as they were. parseChat read only top-level tools
and the Chat relay sent the message on as it came, so the tool could be
called on no route, and the tools-only message became an empty part of
the system text ("</cwd>\n\n\n\nUpdated ...").

liftMessageTools (message_tools.go) moves message tools into the
request's tools. handle does it for every Chat body, before serveAgent,
so the Chat relay, schema fixers, redaction, the prompt shown and
routing all see them; parseChat does it too for a body that never came
through handle. Each tool joins once by name and the first definition
wins (top-level, then the earliest message's), as liftAdditionalTools
and a tool_addition in withoutDeferredTools do. A system or developer
message that carried only tools is left out; one with content keeps
its place without tools. Message order is unchanged: the in-place
system message / inline-tools beta part of #2322 is not in this commit.
6312af989 (#2338, inline-only tool_addition joins tools) is not on
origin/main a1f7b8c13, so this builds on neither; the rule matches it.

Tests, from deephbz's literal Pi 1.2.0 request (last comment on #2322):
TestPiAddedToolReachesEveryRoute (Chat relayed to an OpenAI-compatible
upstream, Messages, Responses, Gemini, Codex), TestPiAddedToolOffered-
ToClaudeCode (the Claude subscription bridge's MCP tools.json, a fake
claude; skipped on Windows), TestMessageToolsFirstDefinitionWins.

Run (sandbox HOME, -tags nogui -p 1):
- go test ./internal/gateway -run 'TestPiAddedTool|TestMessageTools|
  Chat|Messages|AdditionalTools|Lite|Deferred|ExtraBody|Gemini|
  CodexAccessPrograms|Developer|ThinkingEffort|Kimi|DeepSeek|ClaudeRun|
  ClaudeSubscription|Strict|Prompt' -count=1: ok (75.8s)
- broken by hand: liftMessageTools a no-op -> every route subtest, the
  bridge test and FirstDefinitionWins red (tools [lookup_pantry], empty
  system relayed, "\n\n\n\n" in the system text); only handle's lift
  removed -> chat relayed red; only parseChat's lift removed -> the
  bridge test and FirstDefinitionWins red.
- gofmt -l internal/gateway: clean; go vet -tags nogui ./internal/gateway
  for GOOS=darwin, linux, windows: clean.
Not run: other packages, the full suite. Not tried with a real Pi or a
real upstream.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00