Commit Graph
1641 Commits
Author SHA1 Message Date
yetone b62fa332f3 provider: Send requests unmasked for subscriptions and plugin providers too (isee1_1)
isee1_1 on Discord uses a community translation plugin as a provider and
asked why "Send requests unmasked" (请求不脱敏) isn't offered for it.
698da36f3 (lc) left a signed-in account, a plugin's provider and another
magpie out because the switch was then for local addresses only, and none
of those is local. 380032cda (AcMilan) made it the user's word at any
address, with a caution while on for one not local, but kept the
exclusion. Nothing still stands behind it for a subscription or a plugin:
the setting lives with the account's model picks, and every route reads
SkipsRedaction. Another magpie stays excluded, as it masks on its own side.

- provider.SkipsRedaction: an account (subscription or plugin) skips when
  set; another magpie never. Save keeps Unredacted in the picks record,
  withPicks applies it (AlsoOn accounts too).
- gateway: serve, count_tokens, embeddings, Jev and the plugin's fetch
  already go by unredactedRoute (every fallback and group member must be
  set too). The Codex relay on a ChatGPT sign-in masked always: it now
  sends the turn whole when the Codex subscription is set
  (codexRouteUnmasked; only for the ChatGPT backend, not the Codex API
  key route), codexMaskRoute stands aside then, and ChatGPT web search
  (alphaSearchOn) goes unmasked only when every provider it is on is set.
  Speech and video stay masked whatever the switch (maskTextHits), as
  before, for every provider.
- GUI: the editor's Redaction row is shared (unmaskRow); a subscription
  or plugin provider has it too, its caution naming the provider while
  on, since its vendor is never local; saved with the account's body.
  Another magpie has none. No new strings; app.js stays in its budget.
- CLI help/show text, gateway-routing.md and the masking docs (en, zh,
  ja) say so.

Run (mote, through mote-run):
- go test ./internal/provider ./internal/cli: ok
- go test -timeout 45m ./internal/gateway: ok (676s)
- go test -run 'Budget|Redact|Unmask|I18n' ./internal/gui: ok
  (TestCoreScriptBudget at +45 bytes)
- GOOS=linux go vet ./internal/gateway ./internal/provider, GOOS=windows
  go vet ./internal/gateway ./internal/provider ./internal/cli: clean
  (GOOS=linux vet of internal/cli fails in wails without cgo, as on main)
- node --test provider-unmasked (chromium): 36/36; i18n-keys: 4/4.
  WebKit on mote can't launch (#4125); WebKit ran through wsl-run:
  the whole file in chromium and webkit, 72/72. At 440 in Linux WebKit
  the list's sticky foot covers the last row (another magpie's), so the
  test clicks that row as an event (#4484).
- gofmt -l: clean

Broken by hand:
- SkipsRedaction's account branch back to false: TestSkipsRedaction
  (an account, a plugin's provider), TestPluginProviderUnmaskedSwitch/set
  and TestCodexSignInUnmaskedSwitch/set go red.
- Unredacted dropped from Save's account whitelist: the plugin test's
  "saved as" goes red.
- codexRouteUnmasked forced off: TestCodexSignInUnmaskedSwitch/set red.
The unset and falls-back-to-a-vendor cases stay masked in each.

Not tried: a real plugin provider or a real Codex/Claude account with
the switch on (fakes only: the fake bun plugin and a fake ChatGPT
backend); the Claude bridge path; the full Go and GUI suites run after
the push.
2026-10-31 02:56:49 +08:00
yetone b78b1de003 library: magpie-image is behind the MCP hub, saving into the calling agent's project
magpie-image was the one MCP server the hub left out, because it saves
what it makes on disk and needs to know whose project that is. The hub
now serves its tools like any other server's and tells it where the
caller works:

1. the hub answers a tools/call as SSE and asks the agent roots/list on
   that stream (3s), as Claude Code answers;
2. else Codex's _meta x-codex-turn-metadata.workspaces (git repos only);
3. else the Codex thread's cwd from its session file
   (sessions.CodexThreadCwd), only with session consent;
4. else none, and the image goes to ~/Pictures/Magpie as before.

The hub passes `magpie/roots` and `magpie/client` in the call's _meta;
imagemcp saves into the first root and names the agent on its usage
row. Its result carries `magpie/model`, which the hub's own usage row
takes, so the row says which image model drew it. A WSL agent keeps
magpie-image as its own entry (the hub can't reach a path inside the
distro). docs/subsystems/mcp-hub.md (mcp-router.md after the next commit), gateway-routing.md and
gateway-sessions.md say so.

It is rebased on #4382 (b889ffe81), which lets the user keep a server
out of the hub (Server.Hub = direct). inHub now asks both: a server
kept direct is out, and magpie-image is in unless the agent is in WSL,
so the user can keep magpie-image direct too; the editor's switch
shows for it like any server, and the hub's line counts it with the
others (mcp-hub-direct.test.cjs follows).

Run at e2583df31 (this stack on 86fef947e), on mote: gofmt -l clean;
go vet for darwin, linux (-tags nogui) and windows; go build ./...;
go test -tags nogui ./... -timeout 45m, 81 packages ok, 0 FAIL;
library, gateway, imagemcp, sessions, cli and gui again alone, ok;
site's node --test, 49 of 49. GUI on xiaomi-gpu (Windows; mote's
browsers crashed under other sessions' suites): library-*, image*,
mcp-hub-direct, i18n-keys, list-sort and plugin-tools, both engines and
every language, 1055 of 1056: i18n-keys found "{name} is given to each
agent directly" dropped from the library's strings in the rebase. Put
back in the first commit; at the pushed head i18n-keys, mcp-hub-direct
and library-mcp-hub are 48 of 48. That is the only difference from
e2583df31.
Broken by hand at e2583df31: imagemcp ignoring magpie/roots fails
TestHubCallSavesInTheCallersProject; the router asking anything but
roots/list fails TestHubAsksTheAgentItsRoots and TestHubRootsUnasked;
inHub leaving magpie-image out fails TestHubGivesMagpieImage.
Real use, sandbox HOME and gateway, at 62421e570 (before the rebase): Claude Code saved into its project
via roots/list; Codex in a git repo via its workspaces _meta; Codex
outside a repo with session consent via the thread's cwd.
At 62421e570 the whole GUI suite ran on WSL magpie-desktop at load 116 to 135 from other
runs: 504 of 15757 red in 118 files, WebKit timeouts, none in a file
this change touches; filed as #4471 with the list.

Rebased once more onto 2570efb5f, which changed library-mcp-hub,
list-sort, mcp-hub-direct and gateway-routing.md. Run at the pushed
head: go build; gateway, library, cli and imagemcp tests ok; the GUI
budget tests ok; on xiaomi-gpu i18n-keys, mcp-hub-direct,
library-mcp-hub and list-sort, 51 of 54. The three reds were WebKit
420px library-mcp-hub cases with no Connect sheet after a reload.
origin/main d77da5bff goes red the same way (de 420px, 9 of 11). In a
second run of library-mcp-hub on WebKit at this head, 11 of 11 passed.
Filed as #4483.
Not tried: Codex outside a git repo without consent (it saves to
~/Pictures/Magpie, #4435); agents on Windows and in WSL with real use.
2026-10-31 02:49:08 +08:00
yetone d77da5bff3 claude bridge: a caller elsewhere whose environment is a message is told the last one given is where tools run
packinggoods on Discord, again after v0.1.2093: a Mac Claude Code
through a Windows magpie's Claude subscription still has its commands
wrapped in PowerShell. The bridge's run is the real Claude Code on the
Windows box, and it puts its own environment (Platform: win32, its
shell, a temp folder) in a <system-reminder> at the start of the run's
first message. 1f03d7546 and 13f9c7fca follow the caller's instructions
with envElsewhereNote: "the environment these instructions describe ...
is the one every tool runs in". But Claude Code 2.1.296 and later, as a
client, don't put their environment in the system prompt: captured from
the real claude 2.1.314 (sandbox HOME, fake key, capture server), it is
a {role: "system"} message after the user's first. So the note pointed at
instructions that describe no environment, and the caller's darwin/zsh
environment came after it as a "Human:" turn, with the gateway's win32
one first.

Now clientNamedWorkPlace says whether the caller's folder was named in a
message (Request.envInTurns). Such a caller gets envTurnsNote, in the
first message's instructions or a lean run's system prompt: of the
environments the conversation gives, the last one is where every tool
runs. The run's own is always first, so the last is the caller's. A
caller naming its folder in its instructions, a run in the caller's own
folder, and a caller naming none are told what they were before. The
note names no app and no vendor.

Test: TestClaudeCallerEnvironmentInAMessageIsTheLastGiven, with the
2.1.314 request shape from a remote address, lean off and on, and a
caller naming its folder in its instructions for the old note. With the
envInTurns case taken out of envNote by hand it is red (told the note 0
times; the old note pointed at the instructions).

Run (mote-run): go test ./internal/gateway -run
'TestClaudeCallerEnvironmentInAMessageIsTheLastGiven|TestClaudeLeanPrompt|WorkDir|RemoteCaller'
ok; go vet ./internal/gateway for darwin, linux (-tags nogui) and
windows ok; gofmt -l clean. go test -timeout 45m ./... was started on
mote and shipped before it finished (owner's ship-at-once rule); its
result goes on an issue if anything is red.
Not tried: a real model turn from a Mac client through a Windows
gateway (no Claude sign-in on xiaomi-gpu), so whether the model now
stops writing PowerShell is not measured; packinggoods's magpie version
is not known.
2026-10-31 02:34:00 +08:00
yetone 2570efb5f7 gateway: an image the picked model can't describe is described by the next model that sees (kelvinjason11 on X)
kelvinjason11 on X: "图片识别好像只支持一个模型识别 没有fallback". When
the describer (Settings' Image recognition model, or AutoVision's pick)
failed, the turn failed with it, though other models that see were there.

Now describeWith asks the pick first, always. When it fails for any reason
but the client's own cancel, magpie asks the next model that sees: the
first ready one of seersRanked, AutoVision's own order (ready, then
Claude account, Codex, API key, other, then cost), leaving out each model
already tried and each one that turned an image away (sightRefused). At
most 3 models (visionTries), and all of them within visionWaitMost
together: each try gets what is left of it, not a fresh visionTimeout.

- The text header names the model that described the image
  ("as other/bigeye describes it"), not the pick.
- The Routing row of the stand-in carries Instead, Why and Picked
  (describingInstead, the same fields web search's searchingInstead
  sets), and the Routing page says in every language that the pick
  couldn't describe it, why, and which model did instead.
- When none answers, the error is the first failure as before, then
  "nor could X, asked in its place: why" for each other model tried.
- Spent/allowance: each try goes through serve as before, so autoSpent
  and spentModel judge every stand-in the same as they judged the pick.
- vision_mcp's describe_image tool gets the same fallback.

Cache (s.sights): a description is kept under the pick and the image,
whichever model described it, with the describer's name beside it. The
same image sent again asks no one, the stand-in's text is reused, and
its header still names the stand-in. A new image asks the pick first
again, so a pick that comes back is used at once. Failures are not kept.

Settings' text ("When the model in use can't see images, this one
describes them to it") is left as it is: the pick is still asked first
for every image.

Tests (internal/gateway/vision_fallback_test.go):
- TestPickedDescriberThatFailsGivesWayToTheNextThatSees
- TestAutoDescriberThatFailsGivesWayToTheNext
- TestNoDescriberAnswersNamesEach
- TestPickedDescriberThatAnswersIsTheOnlyOneAsked
- TestCanceledDescriptionAsksNoOther
TestDescriberThatCantSeeIsntAskedToDescribe now expects the next model
that sees to describe in place of a text-only pick, not a 502.
GUI: internal/gui/tests/vision-instead.test.cjs (every language, 1100
and 520 wide).

Run on mote at 45739f15b (this tree, on origin/main 74f1df869):
- go test -tags nogui ./internal/gateway/ -count=1 -timeout 45m: ok
  (542.988s). An earlier run while mote was at load ~26 failed four
  Antigravity turned-away tests and TestCodexSpentGrokFailingIsTold.
  None of them touches vision, and all passed in this run.
- gofmt -l: nothing.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok.
- GUI, Chromium: vision-instead, search-instead, routing-vision-why,
  vision-mcp, routing-kind and i18n-keys (4/4) pass.

Broken by hand (in a worktree at 0fcb3acb3):
- The old code with the new tests: Picked, Auto and NoDescriberAnswers
  go red. PickedThatAnswers and Canceled pass, as they should on code
  that never falls back.
- The ctx.Err() check removed from describeWith: Canceled goes red (a
  vision row for other/bigeye appears).
- describeWith made to ask the next model after a success:
  PickedThatAnswers goes red ("eye asked 1 times, bigeye 1").

Not tried:
- The GUI files in WebKit. Playwright's WebKit launch timed out at 180s
  while mote was at load ~25 from other suites. To be rerun.
- vision-instead against the old Routing client, to watch it go red.
- No real account: the fallback was run only against fake upstreams.
2026-10-31 02:28:18 +08:00
yetone ef0a5c673a gateway: a web search is left out of a request relayed to a provider that runs none (mxmllln)
mxmllln (Discord #feedback, magpie 0.1.2219, Codex Desktop 0.166.0-alpha.5.1
with remote_compaction_v2): a thread on commandcode/deepseek/deepseek-v4-
flash-vision-exp with 52 function calls and 8 web searches (magpie ran them
for the model through gpt-6.1-sol) failed compaction with Command Code's
400 "An assistant message with 'tool_calls' must be followed by tool
messages responding to each 'tool_call_id'", and every later message too.

Cause: a Responses turn that offers web_search to a provider that runs no
search is translated for magpie's search, and the translation leaves the
web_search_call items out (searchedForIt, searchRoundsBack). A request
that offers no web_search is relayed as Codex sent it, items and all:
magpie's summary request for a compaction_trigger (tools: []), the summary
request Codex makes itself (#1270), a turn with search off. Command Code's
Provider API turns the Responses request into chat for DeepSeek, a
web_search_call becomes an assistant tool call nothing answers, and
DeepSeek refuses it. pairToolItems pairs function and custom calls only.

Fix: the relay of a Responses request leaves the web_search_call items out
when the provider doesn't search for that model (searchesModel), as the
translation does. Kept as they were: a provider that searches itself
(Codex and Copilot accounts, OpenAI, Command Code's gpt-6-luna etc. on
Responses), a relay Codex's turns go to as sent (codexAsSent), and a
native compaction (keepsCompaction). The item holds only the query and the
page URLs, never what the pages said, so there is no result text to pair
it with; the reply after it says what was found.

Other routes checked: the Responses -> Chat and -> Messages translations
already drop the item (or, for Claude's signed thinking, pair it with a
result through searchRoundsBack); Chat and Anthropic clients send no
web_search_call; magpie's plain-text summary retry (plainCompact) reads
no web_search_call. count_tokens is Anthropic-only.

Tests: search_relay_history_test.go. A fake Command Code that refuses a
deepseek request holding a web_search_call with DeepSeek's message, the
history built from searchedHistory (a real ChatGPT backend web_search_call,
2026-10-09) plus a function call and its output: compaction_trigger,
Codex's own summary request and a turn with search off each answer 200,
nothing sent holds a web_search_call, the call and output stay. gpt-6-luna
on the same provider still gets its search. Unit test for
withoutSearchCalls.

Run (mote-run, at this tree):
- go test ./internal/gateway -run 'TestSearchedThread|TestWithoutSearchCalls' -v: ok
- go test ./internal/gateway -run 'Search|Compact|Compaction|Pair|ToolRun|WithoutSearch': ok
- gofmt -l internal/gateway: clean
Broken by hand: with the withoutSearchCalls call taken out of attempt, all
three TestSearchedThreadCompactsOnARelayThatDoesntSearch subtests fail.
Not tried: a real Command Code account (none here), Codex Desktop on
Windows, the reporter's thread. Full suite and Linux/Windows vet run after
the push.
2026-10-31 02:04:22 +08:00
ggbdpq 86fef947e8 gateway: a 200 stream ended with finish_reason "error" fails over (#2471)
What changed: a vendor that ends its 200 stream with finish_reason
"error" - WorkBuddy's and a DeepSeek harness's word for a turn it failed
rather than finished - had the chunk taken for content: the held stream
went to the agent, the try stood as a 200 success, and the group's next
member was never asked. streamEvent now reads the word as the failure it
says, held for the next candidate as an error event before content is;
in the candidate walk the try fails as an empty reply's or a cut-short
summary's does (#1221, #2274): the next is asked, and nobody rests, as
the reply's shape failed, not the account. Content already passed to the
agent can't be taken back, and is not touched.

Run: TestFinishReasonErrorFailsOver (new) red on a15e5765 before the fix
(the reporter's shape: one try, status 200, Fail empty, the second member
never asked), green after; red again with fallback.go and gateway.go
stashed, tests kept. TestStreamErrorBeforeContentFailsOver, the
streamEvent tables, and the stream families (Stream/Finish/Refusal/
Overload/LastOneLeft/GroupFail/Retry, Loop/Hold/Pass/Queue/Patience/
Incomplete/EndedShort/Grok) green. gofmt -l clean; vet on darwin, linux
(nogui) and windows clean; build ok on all three.

Review (magpie): the maintainer's call this waited on is made: the
literal "error" is a failure from any vendor, no vendor sends it for a
finished turn, so it is not keyed per vendor. Alone (no group), the
failure is the last one left's, tried again as a 502 is (15 asks in
the test's clock, the same count a plain 502 gets), then the vendor's
stream goes to the agent as it came. Content already shown is not taken
back. Not covered, still open on #2471: an empty response.completed
and a Chat stream with no finish_reason at all. Run on the Mac mini:
go test ./internal/gateway -count=1 ok. Broken by hand: fallback.go and
gateway.go at the base - TestFinishReasonErrorFailsOver (200, b never
asked) and the streamEvent table red. Not tried: a real WorkBuddy
reply ending so.

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-31 02:00:10 +08:00
ggbdpq d965a239f5 gateway: a litellm relay's "'priority' is not supported for 'service_tier'" is asked again without the tier (#3978)
What changed: refusedOptional's recognizer (unsupportedOptionalField) gains
valueRejectedForField, for a vendor that names the field after the value it
turned away: litellm's "'priority' is not supported for 'service_tier' on
this model", handed to the agent as a plain 400 today, on both shapes the
relay sends — the bare prose (0.1.1330) and the backend's JSON embedded in
litellm's message (0.1.1829, unwrapped by the existing structure-first
walk). The name after "for" is what separates the field's refusal from a
value's ("... is not supported with this model"), which still reaches the
client as it came.

Both readers of refusedOptional take it, so the tier is dropped, the
request is asked again, and the provider isn't sent it again: a relayed
Chat or Responses request that carries the field (#393's path), and the
agent's own request on a provider the user added by its address (OwnTier),
which forwards the tier on purpose (chat.go, responses.go) and asks again
without one that turns the field away.

Run: TestRefusedOptionalNamesOnlyUnsupportedFields gains two rows (the
prose and the JSON-embedded shape, each under the direct, litellm and
openrouter wrappers) and TestServiceTierRefusedForTheValueRetried (a fake
upstream answering the issue's body) fails without the change — turn 1:
400 after 1 calls, want 2 — and passes with it: two tries, the second
without the tier, and the provider marked unfit for it. The value rows
(unsupported-value, tier-value) stay nil/pass. gofmt -l clean; go vet,
GOOS=linux go vet -tags nogui, GOOS=windows go vet ./... pass; go build,
GOOS=linux go build -tags nogui, GOOS=windows go build pass. In
go test -tags nogui ./... every package passes but three tests that fail
the same way on the unmodified base (ba3a7384f) — TestMothX,
TestProxyCheckSaysAProxyPassedBy and TestHostToldTheGatewayAddress, which
are Bun-, proxy- and port-timing-sensitive on this machine; internal/
gateway passes, targeted and in the suite.

Review (magpie): the regex needs a field name after "for", so "is
not supported with this model" still reaches the client as it came
(the table's unsupported-value rows). The tier is remembered unfit for
the provider, every model of it. Run on the Mac mini: go test
./internal/gateway -count=1 ok. Broken by hand: gateway.go at the base
- both litellm rows of TestRefusedOptionalNamesOnlyUnsupportedFields
and TestServiceTierRefusedForTheValueRetried ("400 after 1 calls")
red. Not tried: a real litellm relay.

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-31 02:00:10 +08:00
ggbdpq 460687ff57 gateway: Azure's "invalid encrypted summary" reads as foreign reasoning (#3994)
What changed: a Codex thread the ChatGPT backend served, resumed on a
relay in front of an Azure OpenAI deployment, is refused there with
{"error":{"message":"invalid encrypted summary",...}} - wording the
foreignReasoning table didn't read, so withoutReasoning was never tried
and the 400 reached Codex on every turn of the thread. The refusal is
spelled with spaces, says summary instead of content, and names no item,
so none of the table's branches took it. An alternative
invalid[ _]encrypted[ _](summary|content) now sits beside
invalid_encrypted_content; the named-item reader (unreadableItem) is
untouched, as this refusal names none, which withoutReasoning already
covers by leaving out the whole reasoning set. The ChatGPT-backend
reader (withoutUnreadable) shares the table and takes the same turn.

Run (base f982e46f2, worktree /tmp/magpie-w1d-3994):
- RED (tests kept, internal/gateway/affinity.go reverted to base):
  TestForeignReasoningWords "not matched: {\"error\":{\"message\":
  \"invalid encrypted summary\"...}}"; TestForeignSealAzureSummary
  "first: 400 {\"error\":{\"code\":\"validation_error\",\"message\":
  \"Azure: invalid encrypted summary\"...}}"
- GREEN: go test ./internal/gateway/ -tags nogui -run
  'TestForeignSealAzureSummary|TestForeignReasoningWords|TestForeignSealAcrossGroupMembers|TestForeignSealGrokToCodexAccount'
  -count=1 -> ok (4 tests)
- gofmt -l internal/gateway -> clean; go vet -> ok

Refs #3994

Review (magpie): TestForeignSealAzureSummary now also checks what the
fake deployment was sent - the seal once, then none, and the next turn
one request without it - so "left out up front" is tested, not only
the 200. Run on the Mac mini: go test ./internal/gateway -count=1 ok.
Broken by hand: affinity.go at the base - TestForeignReasoningWords
("not matched") and TestForeignSealAzureSummary ("first: 400") red.
Not tried: a real Azure deployment behind litellm.

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-31 02:00:10 +08:00
yetone 0fcb3acb3f gateway: the 24MB CR test reads a mended line (#4256)
TestCRTidyTwentyFourMBLine's "one call mended" case never mended
anything. Its line ended its output array with a trailing comma, so the
JSON could not be read and crTidy passed it as it came. Its want was
strings.Replace(line, `x\ry`, `xy`), but on the wire the escape is
`x\\ry`, so the Replace changed nothing either. Both sides equalled the
input, and the subtest passed while timing a failed parse.

The fixture now joins its items without the trailing comma. The mended
case reads the output back: the line is still one data line, fc_1's
arguments are {"a":"xy"}, and every text item is there. The healthy case
is still compared byte for byte.

Run on mote (macOS), go test -tags nogui -count=1 -v -run
TestCRTidyTwentyFourMBLine ./internal/gateway/:
- the healthy 24MB line ~25ms, the mended one ~280ms (a whole decode and
  marshal, only on glm-5.3-flash* lines that carry a \r escape);
- with crTidy.responses' item mend turned off by hand, the mended case
  is red ("arguments ... want {"a":"xy"}"); it was green on the old
  fixture.
2026-10-31 01:53:21 +08:00
ggbdpq dd279e9314 gateway: the CR a glm-5.3-flash* replica stitches into tool-call arguments
Yetone's review of the two earlier rounds (#4256): the cure changed
healthy replies and cost the relay hot path. This one keeps to the routes
the defect was seen on, and holds a cut escape the way the encoders do:

- The cure runs only on glm-5.3-flash* routes (glmFlash, the way
  grokModel scopes its rule): a relay installs crTidy for those models
  alone, translate sets Request.CR the way it sets Request.Grok, and the
  encoder wrapper crEncoder and the whole-reply pass crResult hang off
  that flag. Another model's reply goes as it came, healthy or not.
- The relay's mends wait per call (crTidy.calls, by Chat's tool_calls
  index, Messages' block index, Responses' item id), so a \r\n cut
  across two fragments arrives as the pair it is; a \r the next
  fragment does not answer with \n is the defect, and goes. A line's
  end is looked for in the new bytes of a read alone, and a region
  without the escape is said from where it lies: a 24MB line in 32KB
  reads costs a scan (23ms here; the round-2 way took 2.45s).
- The events whose delta is an argument are read from the event's own
  type or shape: a text delta that only mentions the arguments' event
  names stands, \r and all.
- A custom tool's raw input (Codex's apply_patch) is read as bytes: the
  CRLF pair is the line ending it says, a lone CR goes.
- The encoders' dropper is said at a call's end: a lone \r goes, a bare
  \ is said as it came (crEncoder.say).

Refs #4256 (kept open for the reporter)

Run: go test -tags nogui ./internal/gateway/... (ok). The healthy
split-CRLF relays of all three protocols, the custom input's, the text
delta's and the scope's tests fail on the round-2 branch and pass here;
unwiring the flag reds the cure tests again.

Landed by yetone on origin/main e2d7d1f54 with the next commit, run on
mote (macOS) at that tree: go test -tags nogui -count=1 -timeout 45m
./internal/gateway/... ok (506s); GOOS=linux and GOOS=windows go vet
./internal/gateway ok. Rebased onto f45c3c96b (usage and site only)
before the push; there go vet and the 25 CR tests pass again. Broken by hand: glmFlash returning false reds the 13 cure tests
and TestGLMFlashScope; a per-fragment dropCR in place of the per-call
seam reds exactly the four healthy-split tests. Timed on a valid 24MB
response.completed line in 32KB reads: healthy 25ms, text with \r\n
161ms, a call mended 281ms. A model outside glm-5.3-flash* gets no
crTidy and no Request.CR (TestForeignModelStitchedStreamGoesAsItCame).
The 24MB test's mended case was vacuous; the next commit fixes it.

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-31 01:53:21 +08:00
yetone e2d7d1f54a gateway: a body still arriving at the 2m cut-off is answered 408, and its read ends
heatonz on Discord (Hermes Agent to magpie v0.1.2237 in Docker): about
half the requests to a nested group were stopped after 2m0s "without
routing it to any provider". The held report's one wait was "body 2m0s
(under way)", and 7 handler goroutines sat in net/http body.Read under
waitedBody, idleBody and readSized.

The body read has its own idle limit: 60s with no byte, renewed on each
byte (idleBody), which answers 408. That limit never fired, so bytes were
still coming in gaps under 60s, and the time added up to unroutedMost
in the "body" wait. The watch then answered 504 and blamed routing, and the
handler kept reading the body after the answer until the body ended or
went idle.

Now, when the cut-off lands while the body is being read:
- the answer is 408, saying the body was still arriving from the client,
  how much of it had come and when the last byte did; OpenAI's and
  Anthropic's SDKs send a 408 again at once;
- the read ends with the answer (deadline now, waitedBody refuses further
  reads), so the connection closes with it;
- the held report says "stopped it with 408" and has a "body read: X of
  Y, the last Ns ago" line, which tells a trickle from a stall.

Not changed: the 60s idle limit. The report shows it never fired, so a
shorter one would not have been sure to catch this case, and an
upload that keeps progressing is the client's, not magpie's. The 2m bound stays,
so a trickling client can't hold a handler forever.

Run (mote, at this head on 505d9f6a2):
- go test ./internal/gateway -count=1 -timeout 45m: ok (870s)
- go vet ./internal/gateway for darwin, linux and windows: ok
- TestUnroutedTrickledBodyAnswered408 -count=5: ok
- gofmt -l: clean
Broken by hand:
- the case u.inBody() turned off (the old code): red, 504 "without
  routing it to any provider";
- the read deadline and bodyStopped taken out: red, the connection ended
  10.2s after the 408.
Also probed, through s.Front() on a real socket with a 500ms idle limit,
each answered 408 at the idle limit, never held to the cut-off:
- headers then a stalled body;
- Expect: 100-continue and no body (magpie sends the 100, then 408);
- a Content-Length 50 bytes past the body sent;
- a second request on a kept-alive connection, stalled or with Expect.
heatonz says it happens with Hermes and magpie on one machine too, so no
network hop is involved. None of those three shapes holds a read for
2m, so the bytes were trickling from the client.
Not tried: Hermes Agent itself; why it sends its body that slowly is
unknown. The next held report's "body read" line will show it.
2026-10-31 01:32:57 +08:00
yetone 06d36d4142 gateway: Stays: Session spreads new sessions over the accounts (connor_yang)
connor_yang on Discord: three sessions on one provider's three accounts,
Stays: Session (整个会话), ended up on two accounts. Under Smart routing a
conversation nobody had answered yet went wherever routing put first,
whatever other sessions were on; only In turn counted the sessions each
account holds (leastHeld, #946).

Kept for the whole session (Stays: Session or Strict) under a routing that
picks by what is left (Smart, Least used first, Weekly pace;
spreadsSessions), a new conversation now goes to the key, account or
group member the fewest other conversations of the last 30 minutes are on.
It passes over one routing keeps new conversations off (readyForNew:
resting, an aside key, a fallback while the provider's own model leads,
one used past lowShare), counts leads only, and keeps routing's order on a
tie. A Claude Code subagent's first request goes to its lead's account
(withLead), not to another as a session of its own. An answered
conversation is kept as before, and resting, spent and the rest/quota
fallback are unchanged. In order, By weight, Free first, Speed first,
Cheapest, Manual and plugin routings keep their order. Docs: reference,
gateway-routing, site start.html (en, zh, ja).

Run (mote, at this head on 2604d68db): go test ./internal/gateway -run
'TestWholeSession|TestInOrderKeepsNew|TestSpreadsSessionsOnly|
TestRotateSpreads|Affinity|Strict|Subagent|Lone|LoginSwitch|ChatGPT' ok;
GOOS=linux and GOOS=windows go vet ./internal/gateway ok; gofmt clean.
The full Go suite (-timeout 45m) was started at this head after the push.

Broken by hand: spreadsSessions always false (the old code's behaviour):
TestWholeSessionSpreadsNewSessions red, "s2 went to k1, which s1 is on"
for session and strict. Subagent sent through leastHeld instead of
withLead: red, "s2's subagent went to k1, not s2's k2". readyForNew
without the fallback and lowShare checks: TestWholeSessionSpreadLeaves
TheNearlyUsedAndFallbacks red.

Not tried: real subscription accounts (the tests use three API keys on one
provider, the same candidate path); a group of different providers end to
end (leastHeld's group path is the one In turn has used); the reporter's
exact provider and agent; sessions idle more than 30 minutes no longer
count as holding their account.
2026-10-31 01:05:44 +08:00
yetone 380032cda1 providers: Send requests unmasked is the user's switch at any address, with a caution while on for one not local (AcMilan)
AcMilan (Discord) runs a vLLM at http://llm.corp.lan:8000, and the
editor never offered "Send requests unmasked": the switch showed only
for a localhost, *.local or private-IP address. Asked, he said the
choice should be the user's for each provider.

provider.SkipsRedaction is now: Unredacted, no signed-in account, not
another magpie, and at least one address. Nothing is looked up on the
request path. The editor shows the row for every provider but an
account or remote magpie. While it is ticked, an amber caution under it
names an address not on this computer or the local network (awayHost).
A name of the user's own DNS is asked about, only while ticked, through
POST /api/local-hosts (provider.LocalHost -> netproxy.LocalName: every
address loopback, private or link-local, 400ms lookup, kept 1 minute).
That answer only words the caution. CLI help and `provider show` say
the same. The 'away' i18n line is in zh, zh-TW, ja and de. To stay
inside the core script budget, a few nearby editor comments were cut
down (no raise).

Run (logs in the worktree's logs/):
- Full Go suite on mote at base 024393fbb (go test ./... -timeout 45m).
  Every package is ok except internal/gui. Its reds are the AppKit
  window tests (#4125, #2645, #1936, #3949, #3178) and
  TestRestartHandsTheGatewayOver (#4167), plus TestCoreScriptBudget,
  which was mine and is fixed. At the pushed head (rebased on
  995f84a0f): the gui, provider, netproxy, gateway and cli tests for
  this area, with TestCoreScriptBudget and TestI18n: ok.
- GOOS=linux go vet -tags nogui ./internal/... and GOOS=windows go vet
  on the touched packages: ok. gofmt -l is clean.
- provider-unmasked.test.cjs and decide-endpoint-label.test.cjs: 34/34
  in Chromium and 34/34 in WebKit (Linux, wsl-run), on the final app.js.
- The 155 GUI files that open a provider editor, both engines (WebKit
  on Linux, Chromium on mote). Each file red there was rerun on Linux
  beside the base 024393fbb. The one red this change caused was
  decide-endpoint-label: a /api/local-hosts fetch cut off by navigation
  showed as a console error. That is why names are now asked only while
  the switch is on. The rest are red on the base too and have issues
  (#4431 and others). mote's browsers were crashing (#4125), so
  Chromium was compared on Linux.

Broken by hand:
- The old local-only gate put back in SkipsRedaction: TestSkipsRedaction
  (lan name, vendor, public IP, own proxy) and
  TestLANNameUnredactedProvider went red.
- awayHost returning "": 12 caution tests went red.
- The "only while on" guard removed: 4 "nothing is asked while the
  switch is off" tests went red.

Not tried: a real LAN DNS server, or AcMilan's own setup; WebKit on
macOS (mote's WebKit can't launch, #4125); the Windows app; the whole
GUI suite beyond the provider-editor files.
2026-10-31 00:44:59 +08:00
yetone 995f84a0f9 codex: how early an expiring reset is used is a setting
A Codex reset card that would run out unused was spent 30 minutes before
it expired, a fixed resetExpiryLead. Now the lead is codexResetLead in
settings.json (minutes, 15 to 1440). Unset, out of range or unreadable
reads as 30m, never 0, and magpie never writes it unless the user does.

- settings: CodexResetLead and Settings.ResetLead(); the menu's values
  are 15m, 30m (default), 1h, 2h, 3h, 6h, 12h, 24h.
- provider: the spend (expiringResetSpent) and routing
  (Allowance.Restarts, through nextResetLook) read the same resetLead(),
  so they still agree (#717, #718). The "near" look cadence follows it:
  lead + 30m, at least 1h, so a look lands inside a long lead.
- GUI: Settings > Usage, under the Codex auto-use rows, a row "Codex:
  how early before one expires" with an app menu (no <select>), and the
  sub text says spending earlier loses what the windows have left. The
  four "before it expires" strings say the chosen lead. POST
  /api/settings/codex-reset-lead; the general save keeps the field.
  en, zh, zh-TW, ja, de.
- CLI: magpie quota auto-reset lead [30m|3h|<minutes>|default].
- app.js budget: the auto-use rows moved out to lazy autoresetown.js
  (painted in the same draw once loaded), so app.js and the core script
  stay under their budgets with no raise. The button sizes to its widest
  label (a grid of every label), so picking one never rewraps the row.

Run (all on mote through mote-run):
- go vet: darwin, GOOS=linux -tags nogui, GOOS=windows; nogui build.
- go test -tags nogui -timeout 45m ./... at 3955adccf (this change
  before the paint and sizer fixes, which touch only GUI assets): 81 ok.
  go test ./internal/gui at this head: ok.
- GUI, Chromium: codex-reset-lead, codex-auto-reset,
  codex-auto-reset-settings, segs-press-redraw, i18n-keys: 62/62.
  WebKit: every case of those files failed at browserType.launch
  (180s timeout) before a page loaded, both runs; mote's browser
  launches hang under #4125 (load ~26), so WebKit is not run.
- Rebased onto f7f2d75f2 (old-webkit's lazy list now has traywindows.js
  too): go build ./..., go vet -tags nogui ./internal/..., go test
  internal/gui (budgets included), cli, settings, gateway: ok. provider:
  ok but TestQuotaSpanCarriesEveryWindowField, red on main since
  7d4a63148 (#4457, fixed in ccbefe2a2). GUI old-webkit, i18n-keys,
  codex-reset-lead in Chromium: pass.
- Rebased again onto 62a1dcdd7 (clean): go test internal/gui (budgets)
  and internal/provider: ok; i18n-keys and Chromium codex-reset-lead
  12/12 pass; old-webkit 9/10, its Safari 15.0 case a WebKit launch
  timeout (#4125).

Broken by hand, each went red:
- resetLead() pinned to 30m: all 3 provider tests.
- resetExpiryNear pinned to 1h: the long-lead look test.
- ResetLead's range check turned into m == 0: TestResetLeadUnreadIsDefault.
- GUI resetLeadMinutes returning 30: codex-reset-lead in every language.
- The button without the sizer: de at 420px, "no click moved the page".

Not tried: a real Codex account spending a card at a non-default lead;
Windows and Linux runs (vet only). The whole GUI suite in Chromium on
mote has ~45 tests in 31 files crash with "browser has been closed" on
untouched origin/main c84c3e1c0 too (reducedMotion files, #4458).
2026-10-31 00:41:29 +08:00
yetone 4a440560b9 gateway: an image server file link opens without a header, by its own signed token
dhanyqaz on Discord (gateway in Docker on a VPS behind a tunnel, one
gateway key per client): the Image MCP server's file URL
/mcp/magpie/image/files/<name> opened only with the key that made it, so
a link a model relayed to a person was always refused in a browser (no
key 401, another key 404).

The URL handed out now carries ?t=<exp>.<sig> (imageFileToken):
HMAC-SHA256 of the file's name, its expiry (the same hour) and the making
key's id, under a secret made at the first file and kept only in memory,
so a restart, which loses the files, loses the links. It names neither
the key nor its id. lanGuard lets a keyless GET or HEAD of a file path
with a t through (imageTokenAsked), after the allow list and sharing are
judged; imageMCPFile serves it only when the token is that file's,
unexpired, and its key still on (access.On, read outside the store lock).
Anything else is the 401 a keyless request gets; a wrong key with a
token is still 401, a web page's Origin still 403, POST still refused,
the header-key path as before. Rotating a key keeps its id, so its links
stay good for the rest of their hour (they never held the secret);
turning it off or removing it ends them at once. The URL's base is
imageMCPBase as before (MAGPIE_PUBLIC_URL, else the request's host).
Docs: gateway-routing.md's image server section.

Not changed: generate_video's /v1/videos/<id>/content still needs the
key; same class, filed as #4462.

Run at fe3ad3917 on mote: gofmt -l clean; GOOS=linux and GOOS=windows
go vet -tags nogui ./... ok; go test -tags nogui -count=1 ./internal/gateway/
./internal/access/ ok (497s, 2s). New TestImageMCPFileLinkOpensWithoutKey;
TestImageMCPGuarded and the draws test now check the bare URL keeps the
old rules.

Broken by hand (red each): no lanGuard pass-through (no header -> the
reporter's 401); no expiry check (an expired token opened it); no
key-on check (a turned-off key's link opened); key id left out of the
HMAC (another key's token opened it). Dropping the handler's own
sharing check stays green: lanGuard refuses unshared first, so it is
defence in depth only.

Real run (before the rebase, same change) on mote: sandbox HOME, fake
upstream on 3561, magpie serve on 0.0.0.0:3562 with MAGPIE_PUBLIC_URL,
an image made through the MCP generate_image call. The tool gave
https://<public>/mcp/magpie/image/files/<name>.png?t=…, no key in it.
curl to the LAN address and with a tunnel header: link, no header 200
(bytes = upstream's PNG), HEAD 200, another key + link 200; bare URL:
own key 200, no header 401, other key 404; tampered sig, moved expiry,
token on another name, POST, wrong key + link 401; foreign Origin 403;
after `gateway-key remove` 401.

Full suite not run at this head; runs after push.
Not tried: a real browser click, and the reporter's Docker + tunnel
setup itself (the tunnel was a forwarding header).
2026-10-31 00:27:25 +08:00
yetone 4f2d5fc7e0 routing: a group can put its cheapest member first, by each one's price at that hour
liyuanzheng (#general) and lam_em (#feedback) both asked for the same
thing. Off-peak, DeepSeek's own API should come first for deepseek-flash.
At DeepSeek's peak (weekdays 01-04 and 06-10 UTC, billed 2x since
v0.1.2173), another provider should come first, Ollama say. A schedule
editor would make the user copy DeepSeek's hours into magpie. Instead,
a group gets one more routing, "Cheapest first" (`cheap`). Each request
sorts the members by what they cost right then: input + output price per
million, at the peak rate when it is peak hours. A tie goes to the lower
cache-read price. Free models count as 0. A member with no known price
keeps its listed place after the priced ones. Prices come from the same
priceOf the usage ledger bills with, so the user's own ModelPrices,
list prices and maker prices all count, and so does a provider's rate
windows.

- routes: Seat carries Priced/Cost/CacheCost; Strategy.ByPrice; Cheapest
  is a stable sort, so equal prices keep the user's order.
- gateway: weighRouted prices each seat at priceClock() (time.Now; a test
  holds it) through the new provider.PriceAt. The trace's Weighed row
  gets a price (input/output/cacheRead/peak) so Routing can say why.
- It is a group's alone, like Manual. A provider saved with it drops it,
  and `magpie provider set … routing=cheap` refuses it. Groups take it in
  the GUI menu (one more item, no new controls), the TUI and
  `magpie group set <id> routing=cheap` (aliases cheapest, price, cost).
- Routing's mode line says why the first one is first, e.g. "Cheapest
  first: deepseek-v4-flash costs least on ollama-cloud now — $0.150 in,
  $0.600 out a million tokens.", with peak and unpriced variants.
  en/zh/zh-TW/ja/de.
- Docs: gateway-routing, plugin-runtime, reference (it also points at
  Time window and Pause rules for a fixed schedule) and the site's start
  pages (en/zh/ja).

Run, at f7f2d75f2 (this change rebased onto it):
- Red on the old code: TestCheapestFirstGroupFollowsPeakHours (deepseek
  vs ollama with ModelPrices, priceClock held at 14:00 UTC off-peak and
  02:00 UTC peak) and TestCheapestOrdersByPriceNow did not compile
  without Cheapest. TestCheapestFirstIsAGroupsOnly checks that a provider
  drops it and a group keeps it.
- Broken by hand: without `pr = pr.In(at)` the gateway test is red ("at
  DeepSeek's peak ... went to deepseek"). With Cheapest returning the
  order unchanged, both the routes test and the gateway test are red.
  Both were restored.
- Full Go suite on mote (-count=1 -timeout 45m ./..., log kept): every
  package ok except two. internal/provider had
  TestQuotaSpanCarriesEveryWindowField, which is red on origin/main (#4457,
  fixed since in ccbefe2a2). internal/gui had ten AppKit window tests
  killed at their 20-40s deadlines (TestPanelCloseHidesIt,
  TestMainWindowCorners and others). Three of them are red the same way
  on a fresh origin/main f7f2d75f2 copy, under #2645/#4125 (mote has
  several GUI suites running). After the rebase, go vet and the Cheapest,
  SpeedFirstGroup, ParseRouting, ApplyGroupPairs and ProviderRouting tests
  are ok. go vet darwin, GOOS=linux -tags nogui and GOOS=windows are ok,
  and gofmt is clean.
- GUI on WSL (Linux, chromium + webkit): routing-cheapest-first (new,
  3 scenes x en/zh/zh-TW/ja/de x 2 engines), routing-group-strategy,
  builtins, i18n-keys and routing-speed-first gave 95 of 96. The one red,
  routing-group-strategy "webkit en light ... the pick moved nothing", is
  a wheel-scroll timing red. It fails 3 of 3 on origin/main and 1 of 3 here
  (#4459). Core-script budget ok (app.js +9 bytes).
- The whole GUI suite (1025 files) was started on WSL at this tree and
  was still running when this was pushed, at load ~160.

Not tried: real DeepSeek or Ollama accounts, and a real request during
DeepSeek's peak hours. Ollama Cloud's price here is the catalog's, not
checked against a bill.
2026-10-30 23:59:31 +08:00
yetone f7f2d75f2c gateway: nested routing groups share one classifier wait, not one each (heatonz)
heatonz on Discord (v0.1.2215): requests through nested routing groups
often failed after 120s with 504 "magpie held this request for 2m0s
without routing it to any provider". The 2m is the unrouted watch's
bar for known waits, and the wait was the decision model: the top
group's ruleFor and each ruled nested group's (nestedRules) asked its
classifier with a whole classifyTimeout() of its own, one after
another, before the route was begun. With classifiers that don't
answer, N ruled levels held a request N waits (60s x 2 is exactly the
2m). Jason's fix shared one wait across a decision model's key
failover (askDecideTries); the levels were the sibling it missed.

Now a request has one classifier wait, from the first classifier
asked (Server.askWaited), shared by every group it goes through:
- a level asked with time left gets only what's left (askClassifierIn,
  askChat, askDecider/askDecisionGroup/askDecideTries take the wait);
- a level asked once it is spent isn't asked: it goes by its group's
  order at once, as for a classifier that didn't answer, and its
  Classified.Error says "spent by the routing group above";
- a classifier or decision key cut short by the shared wait (waitSpent,
  cutShort) is not rested (classifyRest, decideFailed): it had less
  than its own wait, and nothing says it is down.
docs/subsystems/gateway-routing.md says so.

Nothing from v0.1.2215 to origin/main 2df46e3c8 touched this path.

Tests (new, internal/gateway/nested_classify_wait_test.go):
- TestNestedGroupsShareTheClassifierWait: outer > mid > inner, each
  ruled on intent with its own classifier that never answers,
  classifyUnit 60ms (8s -> 480ms), unrouted most 1.1s. Red on
  origin/main 2df46e3c8: 504 "held this request for 1s without routing
  it" after 1.45s. Green: 200 from a/m, nested levels say "spent",
  only cls1 rests. -count=5 green.
- TestDecisionKeyCutShortIsNotRested: a decision provider's key cut off
  at 50ms of a 200ms wait is asked first again.

Broken by hand, each red then put back:
- askWaited giving each level a whole classifyTimeout(): the 504 again;
- classify resting waitSpent errors: cls2 and cls3 rest;
- askDecideTries without the cut-short case: the key's error is the
  plain "no answer in 50ms", and it is rested.

Run on mote (mote-run), at this tree except a comment moved back onto
askClassifier afterwards:
- go test -timeout 45m ./... : every package ok but internal/gui, whose
  10 real-window AppKit tests (TestMainWindowCorners,
  TestPanelCloseHidesIt, TestDockJoinLeadsCommandTab, ...) were killed
  at their deadlines: mote's AppKit hang, #4125 / #2645. internal/gui
  is not touched here. internal/gateway ok (745s).
- at the final tree: GOOS=linux, GOOS=windows and darwin go vet
  ./internal/gateway, and the Classif|Decide|Decision|Rule|Unrouted
  tests plus the two new ones: ok. gofmt -l clean.

Rebased onto origin/main 59109044c (no internal/gateway change between):
go vet ./internal/gateway and the same targeted tests ok there.

Not tried: heatonz's own groups and settings (their Classifier timeout
and classifiers aren't known; 60s with two ruled levels fits the 2m0s,
and the 30s between rows matches classifyRest), and a real slow
decision model; only fake upstreams. GUI not touched, GUI suite not run.
2026-10-30 23:28:16 +08:00
yetone 2df46e3c87 gateway: Claude's thinking around magpie's search goes back where Claude wrote it (oreoft)
oreoft on Discord: Codex Desktop on a Claude model (Responses translated
to Messages) on a Bedrock-backed line. After a turn with reasoning and a
web_search_call, the next turn got 400 "messages.N.content.1: thinking or
redacted_thinking blocks in the latest assistant message cannot be
modified", Codex retried it ~6 times, then "stream disconnected".

Cause: on a line that doesn't search by itself, magpie runs the search
(searchRounds). Claude writes the reply as two messages: [thinking A,
text, web_search tool_use], then after magpie's tool_result [thinking B,
answer]. Codex keeps only the items: reasoning A, message,
web_search_call, reasoning B, message. parseResponses dropped the
web_search_call, so the next turn sent one message [thinking A, text,
thinking B, answer]. Each block kept its exact text and signature
(claudeseal), but B had moved, which Bedrock checks and direct Anthropic
lets pass.

Fix: parseResponses keeps a web_search_call as a Search part.
searchRoundsBack splits an assistant run that holds Claude's signed (or
redacted) thinking at each search into magpie's web_search call (named as
searchTool names it) and a result with the query and the pages found,
since what the search said was never kept. The latest assistant message
is then [thinking B, answer], as Claude wrote it. A search with no
Claude thinking beside it is left out, as before, and a history with no
web_search_call is untouched (direct Anthropic with valid signatures and
no search: same body as before).

Run:
- TestClaudeThinkingAroundMagpieSearchGoesBackAsWritten (new): a strict
  fake Messages upstream refuses, with Bedrock's words, a latest
  assistant message whose thinking blocks aren't one it wrote at the
  same places. The test runs Codex's two turns through /v1/responses with
  a fake Tavily, streamed and not. TestSearchWithoutClaudeThinkingStaysOut
  (new). Both pass, with the focused Search/Codex tool-loop tests, on mote.
- Broken by hand (claudeSigned always false, i.e. the old drop): red with
  "400 (refused 2) messages.1.content.1: thinking ... cannot be
  modified", the reporter's error, after Codex-style retries.
- Full suite go test -tags nogui -count=1 -timeout 45m ./... on the Linux
  box (mote had three other full suites running): every package ok except
  internal/agent's TestInstalledVersion, TestGrokInstalled,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI and TestOmpDetectedWithPiDir.
  These are #4033 and #3548, red at main on that box, in a package this
  change doesn't touch. After the rebase onto acdc85ac8: internal/gateway
  vet and tests again on the Linux box, ok (1293s). go vet of
  internal/gateway for darwin, linux and windows on mote; gofmt clean.

Not tried: a real Bedrock-backed Claude line or a real Codex Desktop.
Anthropic's search run by the upstream itself (server_tool_use, a relay
told to search) isn't told to Codex as web_search_call, so it isn't
covered here. The rebuilt tool_result holds the query and URLs, not
the page text the model saw.
2026-10-30 22:55:21 +08:00
yetone c84c3e1c03 gateway: a key's holder sees its own usage and setup at /me
zytszone on X runs one magpie's gateway for a whole department, whose
people can't be given the admin's app. Each now opens the gateway's /me
at the address they reach it at, types the gateway key they were given,
and sees that key's own name, limits and what is spent of them, its
usage over today, 7 and 30 days with its most used models, the models
it may use, and copy-ready setup for Claude Code (settings.json env),
Codex (config.toml provider, /v1, responses), any OpenAI-compatible
client and a curl test. The base URL is the address the page was
opened at, never 127.0.0.1; the key is a placeholder until "Put my key
in the setup" is ticked. Strings in en, zh, zh-TW, ja and de.

- GET /me (keypage.html, embedded) is the same bytes for everyone and
  holds no data, so lanGuard serves exactly GET/HEAD /me (no escaped
  path) to another machine without a key, after the allow list, the
  rebinding check and the not-shared 403, which still apply. Its CSP
  loads nothing from elsewhere, posts no form and forbids framing.
- GET /v1/magpie/me (keyInfo) answers access.Caller's own key only. No
  key, a wrong one, one turned off and magpie's own token are 401
  alike; ?key= is refused 400 so a key never sits in an address or a
  log. It names no account, other key, provider or secret; its models
  are /v1/models' for that key (keyAllowed), none for a read-only key.
  The page sends the key as Authorization to its own origin with
  credentials omitted and keeps it in sessionStorage only.
- Both are in readOnlyRoutes, /me in clientPrefixes (magpie web's page
  port), and Gateway -> Gateway keys shows the page's address
  (MAGPIE_PUBLIC_URL, else the LAN address offered) with a Copy, while
  shared and with a key. Docs: gateway-routing.md, reference.md.

Run:
- mote: go build -tags nogui ./...; go vet -tags nogui gateway+gui;
  GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway;
  go test -tags nogui -count=1 ./internal/gateway ./internal/gui: ok
  (gateway 732s). gofmt -l clean. Rebased onto 18b63fe5f after that;
  there: build, vet, and the KeyPage, read-only, client path, page
  port, LAN guard, caller usage and core script budget tests ok.
- Key page Go tests, through the real lanGuard(Handler()) chain, from
  the network and from loopback: the key sees its own name, usage, top
  model, limits and allowed models and nothing of Bob, Bob's secret,
  the upstream key or magpie's token; no key, wrong key, turned-off key
  (Bearer and x-api-key), magpie's Token, ?key=, Origin null, an
  evil.localhost page, a foreign origin with a good key and a rebound
  Host all get nothing; the page opens without a key, not on POST,
  /me/x or /%6De, and not while unshared; a read-only key gets no
  models.
- GUI, key-page.test.cjs: Chromium on mote and WebKit on the Linux box
  (magpie-desktop), 390px, all five languages, 24 of 24; i18n-keys ok.
  The 46 Gateway/caller-key GUI files and i18n-keys on the Linux box,
  both engines: 645 pass, 11 red at concurrency 4. Serially 6 stay red,
  and the same tests are red on origin/main a0cb8b646 there:
  api-key-theme "system", gateway-key-limit webkit en/zh,
  connect-snippet-shell, gateway-key-models (#4120), phone-rows (#4218).
Broken by hand, each red then restored: lanGuard's /me exemption
removed (page 401); the KeyID check removed (no key/wrong/off/Token got
data); keyAllowed dropped (Alice saw plan/m2); the RawPath check dropped
(/%6De served); the ?key refusal dropped (200 with Alice's data).
Not tried: a real Claude Code or Codex pointed at a shared gateway with
the page's snippets; WebKit on macOS (every WebKit launch on mote hangs
right now, for every session, a bare launch included); the whole GUI
suite and a full go test ./... (one suite per machine; mote is running
other sessions' suites).
2026-10-30 22:52:05 +08:00
ggbdpqandyetone e31ccf2307 gateway: a classifier's own cache marks are kept, and a moved mark leaves its old block boundary in place (#3835)
Claude Desktop's auto mode classifier marks its transcript blocks with
native cache_control but sends none of magpie's private headers, so
serveSubscription took the default parse and the marks were dropped.
And even a request that opted in lost its older boundaries:
renderCachedParts ended a block only where a mark still stood, so a
mark that moved on with the conversation's growth let the block it
used to end merge into the next marked one. Anthropic's prefix check
looks back over block boundaries, not into them: the boundary gone,
each classifier turn found none of the last one's write and wrote the
whole transcript again (about 170k tokens a turn at the reporter's
site).

A part that came from one of the client's own content blocks now ends
its rendered block whether or not it still carries a mark; only the
mark's presence adds cache_control. A classifier-shaped Messages body
carrying cache_control is parsed for its marks like an opted-in
client's. Plain-string messages still merge into history chunks, so a
retained prefix reaches as far back as it did.

Changed from ggbdpq's patch: the classifier never asked for its marks
through X-Magpie-Cache-Marks, so a set the bridge can't keep (a TTL
order Anthropic refuses, more than four marks) now goes the default
way, as before, instead of being refused with a 400 that the old code
never gave. TestClaudeClientCacheClassifierBadMarksServedAsBefore
holds it. The bridge doc says so.

Run (mote, macOS):
- Red on origin/main (the reporter's offline repro, renamed beside the
  other client-cache tests): client_marks 6 -> 6 blocks with 307
  reusable bytes, as the issue reports; the classifier's marks dropped
  without the header.
- go test -tags nogui -count=1 -run 'TestClaudeClientCache|TestAudit|
  TestClaude|TestAutoMode|TestServerReview' ./internal/gateway: ok.
- Broken by hand: the fallback removed, the new bad-marks test red
  ("refused before run startup: 400 ... a ttl='1h' cache_control block
  must not come after a ttl='5m'"); restored, green.
- gofmt -l clean. go vet (darwin, GOOS=windows, GOOS=linux) ok on
  gateway and provider. Full suite at b80d1ba7b (this commit, on the
  #2937 one, rebased on ddb1701fe): go test -tags nogui -count=1
  -timeout 45m ./... , 81 packages ok, no FAIL (gateway 755s). Other
  sessions' suites ran on mote at the same time (load ~20 to 30).
- Rebased on 2f65a33aa (gateway.go and providers-accounts.md changed
  upstream, in unrelated lines): gateway, provider, plugin and library
  rerun with -count=1 -timeout 45m, all ok.
- Then rebased on a0cb8b646 (Ark web search, gateway.go): go vet and
  -run 'TestClaude|TestAutoMode|TestExtraBody|TestHeaders|TestAudit|
  TestServerReview|Ark|Search' on gateway and provider at the pushed
  head, ok.

Not tried: a real Claude subscription A/B of the classifier's cache
reads (it would spend ~170k tokens a turn on the owner's live account);
the gain rests on the offline repro's block counts.

Fixes #3835

Co-authored-by: yetone <yetoneful@gmail.com>
2026-10-30 22:48:39 +08:00
yetoneandggbdpq 84a0330f07 gateway: ${subagentId} in a provider's extraBody and headers is the Claude Code subagent, so one conversation's cache key isn't every subagent's (#2937)
Claude Code's subagents send their lead's x-claude-code-session-id, so
an extraBody of {"prompt_cache_key": "${sessionId}"} put every subagent
of a conversation on one key, more traffic than a relay keeps on one
machine: the reporter's subagent turns read 0 or only the shared
~22K system prefix after full hits on the turn before.

${subagentId} is now the request's x-claude-code-agent-id (subOf),
which a subagent's turns send and the conversation's own never do: ""
for the lead. "${sessionId}:${subagentId}" gives the lead one key and
each subagent its own. It is opt-in: a value without it goes out byte
for byte as before, Test and Detect fill it with "", and other agents
get "" (never the literal). Conversation carries it (Session, Thread,
Subagent) and Conversation.expand fills it, so a provider's Headers
take it too, as they take the other two; ggbdpq's patch left a header
naming it to go out as written, which the providers doc says never
happens to a placeholder.

The default prompt_cache_key magpie fills (ownCacheKey, cacheKeyOf)
stays per conversation; the subagent is not folded in. The one
measurement on the default path (tingxueren on this issue: 452 Claude
Code requests, 98.21% weighted hit with a conversation-level key) shows
no overload, the overload was seen on two pooled relays, and folding
would move every default user's keys unasked. The placeholder covers
the reporter's case; the default can be revisited with data.

Patch by ggbdpq (branch hunt50-e-sessionid-cache, b25c8ab82), rebased;
headers added here.

Run (mote, macOS):
- go test -run 'TestExtraBody|TestWithExtraBody|TestHeaders|TestOwnCacheKey|Conversation'
  ./internal/gateway ./internal/provider: ok both.
- Red on origin/main's product code with the new tests:
  TestExtraBodySubagentId "the lead's key \"sess-1:${subagentId}\"",
  TestHeadersCarryTheSubagent "X-Route \"sess-1/${subagentId}\"".
- Broken by hand: Subagent: subOf(in) dropped in forwardOnce,
  TestExtraBodySubagentId red ("a subagent's key \"sess-1:\"").
- gofmt -l clean. go vet (darwin, GOOS=windows, GOOS=linux) ok on
  gateway and provider. Full suite at b80d1ba7b (this commit with the
  #3835 one on top, rebased on ddb1701fe), mote: go test -tags nogui
  -count=1 -timeout 45m ./... , 81 packages ok, no FAIL (gateway 755s,
  provider 253s). Other sessions' suites ran on mote at the same time
  (load ~20 to 30).
- Rebased on 2f65a33aa (gateway.go and providers-accounts.md changed
  upstream, in unrelated lines): gateway, provider, plugin and library
  rerun with -count=1 -timeout 45m, all ok.
- Then rebased on a0cb8b646 (Ark web search, gateway.go): go vet and
  -run 'TestClaude|TestAutoMode|TestExtraBody|TestHeaders|TestAudit|
  TestServerReview|Ark|Search' on gateway and provider at the pushed
  head, ok.

Not tried: a real pooled relay; no GUI hint names ${subagentId} (the
editor's hint text and its translations are unchanged; the providers
doc names it).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-30 22:48:39 +08:00
yetone a0cb8b6466 gateway: Volcengine Ark's Responses API runs Codex's web_search itself
axelburks on Discord: Ark (火山方舟) runs the web_search tool on its
Responses API, but magpie took Codex's web_search out of the body and
gave the model magpie's web_search function instead, so the model said
the tool wasn't there. ark.cn-beijing.volces.com wasn't in searchHosts,
so searchedForIt translated every Codex turn for magpie's search.

Ark's 联网搜索工具 page (docs.volcengine.com/docs/82379/1756990) asks
POST ark.cn-beijing.volces.com/api/v3/responses with
{"type":"web_search"} (sources, limit, max_keyword, user_location), and
its Web Search page (82379/1585128) marks the tool 支持 on Responses and
不支持 on Chat. The host serves the Coding Plan (/api/coding/v3), Agent
Plan (/api/plan/v3) and pay-as-you-go (/api/v3) alike, and the page's
billing names both plans, so the host counts on Responses for all three.

- searchHosts[Responses] gains arkHost. Chat and Anthropic are unchanged.
- forArkSearch (search_ark.go), on the Responses relay after forVendor:
  Ark's web_search keeps only the members Ark's docs name. Codex's
  external_web_access, search_context_size and filters, and a
  location's timezone, are left out; web_search_preview becomes
  web_search. Ark's own shape ({"sources":["doubao"]}) goes as it came.
  Any other host, or an account, is untouched.
- BytePlus ModelArk (ark.ap-southeast.bytepluses.com) is left out: its
  docs name no web_search tool.
- Ark's Messages API (web_search_20250305) and Chat web_search_options,
  which the same page documents, are #4448.

Tests (search_ark_test.go): TestArkSearchesOnResponses (every Ark
region searches on Responses, not on Chat/Anthropic; BytePlus doesn't),
TestArkGetsCodexWebSearch (a Codex body through the real handler to a
fake Ark, Zhipu and relay over a redirected dialer: Ark gets the hosted
tool in its shape, Zhipu gets Codex's as sent, a relay still gets
magpie's function), TestForArkSearchScope.

Run (mote, mote-run):
- gofmt -l on the changed files: nothing.
- go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok.
- go test -run 'TestArk|TestForArkSearch|TestZhipuSearches|
  TestDeepSeekSearches|Search' ./internal/gateway: ok.
- go test -tags nogui -count=1 -timeout 45m ./... at fa427216a + this
  change: every package ok (exit 0; internal/gateway 729s).
- Rebased on 2ec345364 (it changed internal/gateway): vet x3 and builds
  x3 again ok, and the full suite again: every package ok except
  internal/plugin's TestGatewayHookMixedPiPackage, "starting plugins:
  context deadline exceeded" at 267s, which is #2865 (output added
  there); alone at this tree it passes (139.95s). internal/gateway ok
  (807s).
- Rebased again on acdc85ac8 (internal/provider and internal/switch
  only, nothing this change reads): gofmt, vet x3, builds x3 and
  internal/gateway + internal/provider tests again: VET-BUILD-OK,
  internal/gateway ok (652s), internal/provider ok (191s).
- Rebased on 2f65a33aa (a new tools-MCP route in internal/gateway):
  vet x3 of internal/gateway, go build, and -run
  'TestArk|TestForArkSearch|Search|ToolsMCP|Readonly' ok.

Broken by hand:
- arkHost out of searchHosts: TestArkSearchesOnResponses red for all
  three regions, and TestArkGetsCodexWebSearch red with Ark sent
  magpie's web_search function, the reporter's case.
- forArkSearch call removed: TestArkGetsCodexWebSearch red, Ark sent
  external_web_access, search_context_size and the timezone.

Not tried: a real Ark key (none here), so whether Ark turns away
Codex's external_web_access is from the docs, not a reply. Ark says
either search component must be activated in its console first, or the
call errors; a user who hasn't would now get that error on a Codex turn
offering web_search instead of magpie's search. Which models take the
tool is not listed by Ark (its page links a capability table); the
docs' example is doubao-seed-2-1-pro. With no Claude/Codex account, Ark
can now be magpie's automatic searcher for other models too.
2026-10-30 22:41:00 +08:00
yetone 2f65a33aaf library: a tools plugin is a Library server of its own, in the MCP hub (Search1API)
chenxiang0010 (Discord #general) asked for a tools plugin's tools, Search1API's
(@magpie-community/tools-search1api), to be in magpie's aggregated MCP server.
Until now plugin tools were served only at /mcp/magpie/tools, wired by hand;
the hub listed Library servers only.

Now each plugin that is on and gives tools becomes a Library server once the
plugin host has noted its tools (plugin-tools.json, new plugin.ToolsNoted):
- named by the plugin's short name (search1api, search1api-plugin beside a
  user's server of that name), `plugin` set, `local`, its URL the new
  /mcp/magpie/tools/<short> (gateway ToolsMCPOne), which serves that
  plugin's tools alone by their own names;
- added with the hub on, it is on for the agents given the hub's entry, so
  their hub lists search1api__search etc. at once; with the hub off it is on
  for none until switched on. Per agent and per tool it is switched like any
  server;
- the hub lists and runs its tools in process (gateway.PluginToolsOf,
  RunPluginToolOf, under the Plugin tools gate); with the hub off an agent is
  given the per-plugin URL at the address it reaches the gateway (through),
  with a key from another machine;
- offered once (pluginsOffered): removed by the user, it comes back only when
  the plugin is removed and added again. The plugin removed takes the server
  out; turned off it stays and lists nothing; an unreadable plugins.json
  changes nothing (plugin.ReadList). Edited in the Library's editor, which
  doesn't send `plugin`, it stays the plugin's.
Docs: docs/subsystems/plugin-tools.md, mcp-hub.md, site docs plugins (en, zh, ja).

Run (mote; full suite at this change on origin/main 024393fbb, then rebased on
acdc85ac8, whose 5 commits touch internal/plugin/page.go and a gateway test;
library, gateway and plugin focused runs again at the pushed head: ok):
- go test -tags nogui ./internal/library ./internal/gateway ./internal/plugin
  -run 'PluginTool|Hub|ToolsMCP|ServingGates|OwnMCPRejects|Tool': ok.
- TestReadOnlyKeyEveryRoute also covers the new route.
- New tests: TestPluginToolsInHub, TestPluginToolsServerComesAndGoes,
  TestPluginToolsServerThroughAnotherAddress (library), TestToolsMCPOnePlugin
  (gateway).
- go vet (darwin, GOOS=linux, GOOS=windows) on the three packages; go build: ok.
  gofmt -l: clean.
- Full suite, go test -tags nogui -count=1 -timeout 45m ./... (log kept):
  80 packages ok, internal/gateway red on TestReadOnlyKeyEveryRoute: the new
  route wasn't classified for read-only keys. Added to readOnlyRefused's
  list in the test (a read-only key is refused there, as at
  /mcp/magpie/tools); internal/gateway whole package again: ok (846s).
- Real run, sandbox HOME on mote, built binary, MAGPIE_ADDR on a free port:
  `magpie plugin add @magpie-community/tools-search1api` (latest from npm),
  `magpie serve`. library.json got the search1api server (plugin, local,
  url .../mcp/magpie/tools/search1api, pluginsOffered); the per-plugin
  endpoint listed search, news, ask, crawl, sitemap, trending, send_feedback;
  with the hub on, /mcp/magpie/hub listed search1api__search ... and
  search1api__search answered isError "Sign in with `magpie plugin login
  search1api`, configure apiKey ..." from the plugin.

Broken by hand (each red, then restored):
- hub ignoring plugin servers (backend path): TestPluginToolsInHub red
  ("claude's hub tools [fake/a fake/b fake/c]").
- adoptPlugins returning false at once: both library tests red ("no server
  for the plugin").
- through's plugin branch off: TestPluginToolsServerThroughAnotherAddress red.
- the ToolsMCPOne route removed: TestToolsMCPOnePlugin red (404).

Not tried: a signed-in Search1API account (none here), so no search went
through; a real agent (Claude Code, Codex) calling the hub; WSL/remote
agents through another address (unit test only); the GUI's Library page
showing the server (no GUI file changed, GUI suite not run).
2026-10-30 22:33:25 +08:00
yetone ddb1701fe0 codex: a model magpie has no word on is offered low, medium and high
ccdcn on X: in the Codex app, the models of a provider they added
(XJAI's model-code, model-work, model-test) had no reasoning effort to
pick, though the chip said 中. Nothing magpie reads knows those ids, so
their entries in magpie-models.json (and /v1/codex/models) had
supported_reasoning_levels [] and default_reasoning_level null. Codex
then hides the choice but still sends an effort (medium, or
model_reasoning_effort), and the gateway's fitEffort passes an effort on
as asked when a model's levels are unknown, so the effort went out and
couldn't be changed.

provider.CodexEfforts offers low, medium and high for a model whose
levels are wholly unknown. It is used by codexListed (GET
/v1/codex/models, the backend list, spawn models) and by
agent.magpieModels("codex") (the file Codex reads, and magpie's own
Codex effort control). A model known to have no levels keeps none: one
the vendor's catalog or models.dev lists (any provider, any spelling),
one the user marked as taking no reasoning ask, a vendor entry in
Codex's shape, and a routing group.

TestCodexDesktopEfforts' "user's own" now expects medium added to the
user's enabled-reasoning-efforts: its fixture's fake/m1 is such a model.

Run (on mote):
- go test -timeout 45m -count=1 ./internal/provider ./internal/agent
  ./internal/codexcat: ok
- go test -timeout 45m -count=1 ./internal/gateway ./internal/gui:
  gateway ok (615s); gui red only in 10 real-window AppKit tests
  (dock, panel, tray, main window), each killed at its deadline. Four of
  them run alone on origin/main 024393fbb fail the same way on mote:
  #4125 (mote's AppKit/launchd hang). Not run on another Mac.
- GOOS=linux / GOOS=windows go vet ./internal/provider ./internal/agent
  ./internal/gateway: ok; gofmt -l clean
The runs above were at base d99e213f5. Rebased on 024393fbb, which
changed internal/gateway only; at this head the new tests and every
TestCodex.*Effort test in provider, agent and gateway pass again.
Broken by hand: with codex_models.go and route.go stashed, the new
TestCodexOffersLevelsForUnknownModels and
TestCodexCatalogOffersUnknownModelsLevels fail (offered []).
TestCodexPickedEffortReachesUnknownModel checks each offered level
reaches the vendor as reasoning_effort.
Real Codex: codex-cli 0.165.0 app-server (sandbox CODEX_HOME), model/list
on the catalog codexcat writes for xjai/model-test: before,
supportedReasoningEfforts [] / default none; after, low, medium, high /
default medium.

Not tried: the Codex desktop app with a real XJAI vendor. Not changed:
other agents (OpenCode variants etc.), which send no effort for such a
model today, and groups whose members are all unknown.
2026-10-30 21:47:07 +08:00
wrke1990andggbdpq 024393fbb9 gateway: a Codex mode switch keeps its developer role on a translated Responses turn (#2532)
Refs yetone/magpie#2532 (the Responses-to-Responses translation case).
An offered web_search can select translation even for a Responses upstream.
Keep system/developer items in place instead of lifting initial Plan
instructions and demoting a later Default update to a user reminder.
Other APIs and the Claude bridge retain their existing cache mapping.
Update the gateway routing reference and cover search continuation rounds.

Verification on macOS arm64 with Go 1.26.10, isolated HOME and pinned caches:
- New tests on unmodified cc04ce68c1 plus
  test changes fail with real assertions in
  TestResponsesInstructionRolesThroughSearch (developer/system),
  TestResponsesInstructionsOtherAPIsUnchanged and
  TestCodexSearchAnsweredOnResponses.
- Those patched tests, TestCodexLaterDeveloperMessageKeepsTheSystem and
  TestSearchOfferedStaysOnTheClientsAPI pass, also with -race.
- gofmt and diff checks pass.
- Native, Linux/nogui and Windows vet and builds pass.
- go test -tags nogui ./... fails in the unchanged internal/agent package:
  TestRunningNeedsNoPs cannot find its sleep 314.159 process. The complete
  internal/gateway suite passes (427.556s), as do the other packages.
- The patched executable against an isolated local capture upstream keeps
  Plan and Default as developer messages in minimal and full histories
  with web_search offered; real configuration hashes remain unchanged.
Not run: paid real-upstream acceptance, native Linux/Windows runtime tests,
or browser GUI tests (no GUI assets changed).

The unrelated agent failure was traced to macOS pgrep returning exit 3,
"Regular expression evaluation error (illegal byte sequence)", under the
inherited locale. The same local sleep process is found with LC_ALL=C.
TestRunningNeedsNoPs fails 20/20 under -race with the inherited locale and
passes 20/20 with LC_ALL=C (3.848s). No agent code or timeout was changed.
A full-suite recheck with LC_ALL=C is running at commit time; retain the
initial failure and publish as a draft until that recheck completes.

Adapted when landing: a blank line before the next heading in
docs/subsystems/gateway-routing.md. Cherry-picked by ggbdpq (gua2100).

Review and run record (landed by the maintainer's agent; gua2100 brought
both fixes from Discord, rebased onto main):
- External code, read line by line: no network, dependency, workflow or
  credential change; Codex base_instructions/identity untouched.
- Base origin/main d99e213f5. Full checks on mote (macOS, Go 1.26.8,
  sandbox HOME) at 31f025634, whose tree is the one pushed (only messages reworded since): gofmt, go vet darwin, linux,
  windows, builds for all three: rc=0. go test -tags nogui -count=1
  -timeout 45m ./...: 79 packages ok, internal/gateway ok (855s); two reds
  in untouched packages, both filed before: internal/plugin
  TestGatewayHookMixedPiPackage (#2865, "starting plugins: context deadline
  exceeded") and internal/update TestRelaunchOpenTriedAgain (#3881). Run
  alone at the same tree both pass (plugin 97s; update -count=3).
- Broken by hand: the #3739 regex reverted, so both Kimi tests fail (400
  handed back). The #2532 product files reverted (six files), so all three
  tests fail. The mergeTurns role guard removed fails (5 input messages,
  want 7).
- Real binary on mote, sandbox HOME, a fake upstream that records requests:
  at d99e213f5, wrke1990's literal #2532 body sends Plan in instructions
  and Default as a user <system-reminder>; at HEAD both developer items
  keep their role and place. #3739's curl body (and zfsdream96's ZCode
  shape, output_config effort max, no thinking) is a 400 at d99e213f5; at
  HEAD it is a 200 after one retry without thinking, and the next
  request goes without disabled.
- Rebased onto fa427216a (responses.go stream deltas, landed meanwhile;
  no conflict). At the rebased pushed tree: gofmt, go vet and
  go test -count=1 ./internal/gateway ok (580s) on mote. The full suite
  was not rerun after that rebase.
- Not covered: the search reroute's re-parse when a fallback changes
  whether the target is Responses (breaking it leaves the tests green;
  no route found that reaches it). Not tried: the real Kimi Code
  endpoint and its kimi-code-cn preset (a custom Anthropic provider with
  Kimi's literal 400 was used), a real Codex session against a paid
  upstream, Windows/Linux runtime. #3739's second symptom (k3 losing
  thinking when output_config.effort is asked) is not addressed.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-30 21:38:00 +08:00
ggbdpq 72e8d9fa6c gateway: Kimi Code's refusal of thinking turned off is asked again with it left to the model (#3739)
thinkingOffUnlessAsked turns thinking off on a Messages request for a
non-Claude model that doesn't mention it. Kimi Code (China)'s K3.1
(k3.1-pro, k3.1-pro-highspeed) refuses that with 400, "K3.1 Pro does not
support disabled thinking mode. Please enable thinking and try again, or
choose another model.", in a wording neither alwaysThinks,
mandatoryReasoning nor thinkingOffRefused matched, so the 400 went back
to the client on every request that carried no thinking — ZCode's, which
asks for a level as output_config.effort and sends no thinking — and the
session could not start. withoutThinkingOff would have handled it; only
the match missed, as in #1141.

alwaysThinks now matches Kimi's literal sentence. Both retry sites use
it: the relayed Messages path (withoutThinkingOff, gateway.go) and the
translated Chat/Responses path (thinkingBackOn).

Tests: TestAnthropicPassthroughKimiThinkingOffRefused (the reporter's
error body: omitted thinking succeeds after one retry without thinking;
adaptive goes once, as sent; Kimi's own max_tokens 400 and a near wording
"tool use is not supported by this model" are not retried), and
TestTranslatedThinkingOffRefused now runs Kimi's wording. With the regex
change reverted both fail (400 handed back).

Review and run record (landed by the maintainer's agent; gua2100 brought
both fixes from Discord, rebased onto main):
- External code, read line by line: no network, dependency, workflow or
  credential change; Codex base_instructions/identity untouched.
- Base origin/main d99e213f5. Full checks on mote (macOS, Go 1.26.8,
  sandbox HOME) at 31f025634, whose tree is the one pushed (only messages reworded since): gofmt, go vet darwin, linux,
  windows, builds for all three: rc=0. go test -tags nogui -count=1
  -timeout 45m ./...: 79 packages ok, internal/gateway ok (855s); two reds
  in untouched packages, both filed before: internal/plugin
  TestGatewayHookMixedPiPackage (#2865, "starting plugins: context deadline
  exceeded") and internal/update TestRelaunchOpenTriedAgain (#3881). Run
  alone at the same tree both pass (plugin 97s; update -count=3).
- Broken by hand: the #3739 regex reverted, so both Kimi tests fail (400
  handed back). The #2532 product files reverted (six files), so all three
  tests fail. The mergeTurns role guard removed fails (5 input messages,
  want 7).
- Real binary on mote, sandbox HOME, a fake upstream that records requests:
  at d99e213f5, wrke1990's literal #2532 body sends Plan in instructions
  and Default as a user <system-reminder>; at HEAD both developer items
  keep their role and place. #3739's curl body (and zfsdream96's ZCode
  shape, output_config effort max, no thinking) is a 400 at d99e213f5; at
  HEAD it is a 200 after one retry without thinking, and the next
  request goes without disabled.
- Rebased onto fa427216a (responses.go stream deltas, landed meanwhile;
  no conflict). At the rebased pushed tree: gofmt, go vet and
  go test -count=1 ./internal/gateway ok (580s) on mote. The full suite
  was not rerun after that rebase.
- Not covered: the search reroute's re-parse when a fallback changes
  whether the target is Responses (breaking it leaves the tests green;
  no route found that reaches it). Not tried: the real Kimi Code
  endpoint and its kimi-code-cn preset (a custom Anthropic provider with
  Kimi's literal 400 was used), a real Codex session against a paid
  upstream, Windows/Linux runtime. #3739's second symptom (k3 losing
  thinking when output_config.effort is asked) is not addressed.

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-30 21:38:00 +08:00
ggbdpq fa427216a4 gateway: a Responses stream's argument deltas go to the call they name, one call each
JoeyWu-tech (#3985): a Responses upstream that adds two function_call
items before either is argued (output_index 0 and 1, every delta and done
naming its item_id) reached a Chat client as call_1 with no arguments and
call_2 with both calls' run together. responsesDecoder opened a call at
every response.output_item.added and gave every
response.function_call_arguments.delta to the call opened last, never
matching it by the delta's item_id or output_index — the same shape #3945
fixed on Messages and 865df247 fixed on Chat.

The decoder now reads a call by its item: a function_call item added
waits, its lines kept as they came, and goes — start, arguments, done —
at its own first delta or its output_item.done, whichever comes first,
while no other call is open; a call whose item ends while another is open
goes when that one does, and every call still waiting goes before the
reply ends, in output_index order. A delta or done names its call by
item_id, then output_index; one that names nothing at all goes, while no
call is open, to the first waiting one, since a stream whose events name
nothing streams its calls in order — that keeps the call args of such a
stream held and given as before (TestResponsesCallArgsStream and
TestResponsesCallArgsFromDone read them). A stream in Responses' own
order — an item added, argued and done before the next — reads as
before, its start one line later, at its first arguments.

Tests (responses_batched_calls_test.go): the report's stream to a Chat
client, the same with the two calls' arguments by turns, and a stream in
Responses' own order held to the same two calls. The streams are built by
hand from the report, not captured bytes; no real upstream was read.

Run (go1.25.5, darwin/arm64): go test -tags nogui ./internal/gateway -run
'TestResponsesBatchedCalls|TestResponsesOwnOrderUnchanged' — red on
upstream/main (call_1 read_file empty, call_2 read_file {"path":
"a.py"}{"path": "b.py"}, the report's own reading), green here. The full
gateway suite (-tags nogui) was red first at
TestResponsesCallArgsStream, TestResponsesCallArgsFromDone and
TestResponsesToolWithoutReasoningStillTimed, whose streams name no item —
the deltas went out raw with no call open — and green after the
nothing-named fallback; gofmt -l clean; go vet -tags nogui for linux,
windows and darwin; go build -tags nogui for the three; the new tests
with TestRelay*, TestInterleaved* and TestResponsesCallArgs*, -race
-count=5, no race reported.

Generated-by: GLM-5.3-Flash (ZCode)

Review (applied with git am-equivalent cherry-pick of ggbdpq's
edfdf7b97, branch hunt101-ha-3985-responses-delta; the issue's patch
SHA-256 prefix 03728df281142c12 matches the branch's diff), run on mote
at d99e213f5 + this commit:
- The three new tests on origin/main d99e213f5 with responses.go as it
  was: TestResponsesBatchedCallsToChat and
  TestResponsesBatchedCallsByTurnsToChat FAIL ("tool calls: call_1
  read_file" with no args, call_2 with both); TestResponsesOwnOrderUnchanged
  passes there and here. All three pass with the fix.
- Real bytes: Copilot's captured stream (testdata/copilot_rotating_ids.sse,
  item ids rotating every event, output_index steady) translated for a
  Chat client still gives exec_command {"cmd":"go version"} (a review
  probe, not committed); TestCopilotItemKeepsItsID and
  TestResponsesCallArgs* pass.
- Probe: one call whose added names no output_index and whose delta and
  done name another item_id/index still reaches a Messages and a Chat
  client with its args (they come from the item's done).
- Hot path: per event, two more fields decoded and a scan of the waiting
  calls (empty in Responses' own order); a call's added line and first
  delta are decoded twice. Linear, no per-chunk buffering.
- gofmt -l clean; go vet -tags nogui ./..., GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./...; go build, GOOS=linux -tags
  nogui, GOOS=windows: ok. go test -tags nogui -count=1 -timeout 45m
  ./...: 81 packages ok, none failed (internal/gateway 779s).

Not tried: a real upstream that adds two calls before arguing either
(none is known; the report's stream is built by hand). Not handled: a
delta whose item_id and output_index both match no waiting call while
no call is open goes out with no call, as an unnamed one did before;
the call's args still come from its done item.

Refs #3985
2026-10-30 21:25:32 +08:00
yetone da3c5e0c0f gateway: Claude Desktop's connection check is tagged as one on the Routing page (cybercaius on Discord)
Also: the check follows a Desktop model switch made after the last turn.

cybercaius (#help): with gpt-6.1-sol on AnyRouter chosen in the
conversation, the Routing page showed "Claude Desktop requested
deepseek/deepseek-flash" while the answer came from gpt-6.1-sol. The route
was right; the row was not explained.

Those rows are Desktop's own connection check ({"max_tokens":1, content
"."}, app.asar 2.7032 lWt/YT). Desktop names its model itself: the
shortest listed id with haiku, else sonnet, else opus, else the FIRST
listed model. magpie lists no Claude-named ids to it, so the check names
the first one (deepseek-flash), whatever the conversation is on, and
magpie sends it to the model chosen in Desktop's menu (desktopChosen).

- The check is recorded with kind connection_check (KindDesktopCheck,
  usage purposeKinds "Connection check", purposes.js regenerated). The
  Routing page tags the row "Connection check" next to the requested id
  and its story says the id is the one Desktop named from its list, not
  the conversation's model, and where magpie sent it. zh/zh-TW/ja/de.
  The requested id itself stays what Desktop sent.
- desktopChosen: a turn sent after cowork_account_settings.json was last
  written wins over the menus (newer of the two). Before, the last
  session's model came first whenever any menu still held it, so the Code
  tab switched off DeepSeek with Cowork left on it kept the check on
  DeepSeek. desktopPicked now carries when that turn was sent (the
  file's mtime once read).

The two 400s were AnyRouter's own (the reporter says so); not changed.

Run (at 0013f990c, this tree before its rebase on e0ad48641 and the
version stamp v0.1.2208 -> v0.1.2212 in comments/doc):
- mote: go test -tags nogui -timeout 45m -count=1 ./... : 81 ok, exit 0.
- mote: go vet ./internal/gateway ./internal/usage for darwin, linux
  (nogui) and windows: ok. gofmt clean. go generate ./internal/usage
  gives the same purposes.js as committed.
- GUI: routing-desktop-check (new; en, zh, zh-TW, ja, de), routing-kind,
  i18n-keys: chromium on mote ok; WebKit could not launch on mote (90+
  hung pw_run.sh launches from other sessions), so both engines ran on
  the Linux box (wsl-run): 14/14 ok.
- Whole GUI suite (wsl-run, concurrency 4) still running at push; reds
  so far are in account-arrange, account-models and agent-expand-steady,
  files this change does not reach. Checked against main after.
Broken by hand:
- call.Kind = KindDesktopCheck turned off: TestClaudeDesktopProbeAsksNoClassifier
  red ('recorded as kind "" (unmarked)').
- the connection_check story removed from client.js: routing-desktop-check red.
- old desktop.go: the new "Code tab switched off the last session's
  model" case red; the at.After check turned off: red too.
Not tried: a real Claude Desktop. Whether Desktop sends a check on each
model switch, and whether its composer switch writes the menu file, are
read from its bundle, not seen live. AnyRouter's 400s not looked into.
2026-10-30 20:32:25 +08:00
yetone 9c54221814 plugins: origin magpie-key only for the sharing key used from this computer; from elsewhere it stays gateway-key
387e8572a gave a gateway hook origin "magpie-key" for the sharing key
magpie made itself, wherever it came from. But that key isn't only the
owner's agents': Gateway keys lists it (as "Magpie") with a Copy button
(copyCallerKeyBtn in plugins/gateway/keys.js), the connect section
offers it for another computer (selectConnectKey). A friend on the LAN handed it would
have read as "magpie-key", and plugins#526's switch would still have
served them the owner's memories.

Now it is "magpie-key" only from this computer (ownComputer), where
magpie writes it into agents (agent.keyAt): loopback (a WSL distro on
the WSL network is mapped to it by lanGuard), one of this computer's
own addresses (an agent calling MAGPIE_ADDR beyond loopback, ownAddr),
or a WSL distro's NAT network calling this computer's network address
(WSLNets). Never with forwarding headers, a trusted proxy's included,
nor through magpie web's page port. From anywhere else the key reads
"gateway-key", as every other key does.

docs/subsystems/gateway-request-hooks.md says so; plugins#530 and the
#526 comment are corrected to match.

Tests: TestAsyncGatewayOrigin (real Bun host) adds the sharing key from
this computer's own address and a WSL NAT address (magpie-key), and
from 10.0.0.1, through a proxy and through a trusted proxy
(gateway-key); 387e8572a's "magpie-key from 10.0.0.1" case now wants
gateway-key.

Run (on mote, at this tree):
- go test -timeout 45m ./... at 387e8572a plus this change: 80
  packages ok (gateway 662s; access and plugin cached, unchanged since
  387e8572a's full run); internal/gui red only in the same 10 real-window
  AppKit tests as 387e8572a's run, which fail the same way on origin/main
  48edbcb67 on mote: #4125, #2645.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/gateway.

Broken by hand (each subtest red, the rest green): ownComputer dropped
from gatewayOrigin (387e8572a's rule): elsewhere, proxied and
trusted-proxy red; ownAddr dropped: own-address red; the forwarded check
dropped: trusted-proxy red; the WSL-net check dropped: wsl-nat red.

Not tried: a real WSL distro under NAT or a MAGPIE_ADDR beyond loopback
sending the sharing key to a real plugin (the peer addresses are stubbed
through ownAddr and WSLNets); a magpie in a container, whose host's
agents reach it from the container's gateway address and read as
gateway-key.
2026-10-30 20:24:54 +08:00
yetone 387e8572a8 plugins: the sharing key magpie made itself reaches a hook as origin magpie-key, any other gateway key stays gateway-key
A gateway hook's ctx.origin was "gateway-key" both for the sharing key
magpie makes and writes into this computer's own agents (a WSL distro
under NAT, MAGPIE_ADDR beyond loopback) and for a named key the owner
made for a friend. A plugin couldn't tell them apart: plugins PR #526
(nowledge-mem)'s "Agents using a Magpie key" switch would have put the
owner's memories into a friend's requests.

Now access.Authenticate marks the default sharing key (Identity.Default:
the key marked lan, the one LANKeyID names, or an older magpie's
settings-only key, as access.Default tells it), and gatewayOrigin
returns "magpie-key" for it. Every other key, on loopback too, stays
"gateway-key": one the owner made, a value a user brought, or a
sk-magpie- key that didn't authenticate. magpie has no "this named key
is mine" mark, so none of those is treated as the owner's.

Why a new value and not a new field: every consumer in
magpie-community/plugins (agent-office's track.mjs, powercontext, and
#526) compares origin to "local" only, and treats anything else, an
unknown value included, as not local. None compares to "gateway-key" in
code. So "magpie-key" lands in their not-local branch, where the
sharing key already was: no plugin gains or loses a request it serves.
host.js passes the context through untouched. A plugin that wants the
owner's agents checks one value.

docs/subsystems/gateway-request-hooks.md says what each value is. Not
changed: the plugins repo has no type or doc for origin; #526's own
README and switch are its author's to scope (asked on the PR).

Tests:
- TestAuthenticateTellsTheDefaultKey (access): the ConfigureLAN key, a
  key named by LANKeyID only, and the legacy settings key read Default;
  a made key and a user-brought value don't.
- TestAsyncGatewayOrigin (gateway, real Bun host): the sharing key from
  10.0.0.1 and from loopback reaches onRequest and onResponse as
  magpie-key; a friend's own-value key as gateway-key.

Run (on mote, at this tree):
- go test -timeout 45m ./...: 80 packages ok (access, gateway 760s,
  plugin among them); internal/gui red only in its real-window AppKit
  tests (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
  TestMainWindowCorners and 7 more, each killed at its deadline). Three
  of them run at a fresh origin/main 48edbcb67 on mote fail the same
  way: #4125 (mote's AppKit tests hang) and #2645.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of access,
  gateway and plugin.

Broken by hand: origin/main's middleware.go put back, the two magpie-key
subtests red ("request origin=gateway-key, want magpie-key"); Default
forced false in Authenticate, TestAuthenticateTellsTheDefaultKey red in
its first two subtests.

Not tried: a real plugin in the GUI app with a WSL agent sending the
sharing key; npm-published plugins outside magpie-community weren't
searched.
2026-10-30 20:09:09 +08:00
yetone b4cb946f98 gateway: a key out of credit keeps its rest and rung over a restart of magpie
PaulT on Discord: after v0.1.2175's creditLadder (30m, 2h, 8h, 1d, 3d,
7d), a restart of magpie lifted an out-of-credit key's rest and started
its ladder over at 30 minutes, as restingUntil is memory only.

No rest was kept anywhere before (restingUntil, affinity.json and the
provider's served file hold nothing of it), so the ladder's rests now go
to rests.json beside providers.json (rest_store.go):
- saveRests writes every ladder rest (Why credit, By credit, Failures
  > 0) with its until, rung and asking state, through a temp file renamed
  over it, whenever one is set or dropped: restAfterMarked, clearRest
  (an answer), Unrest / UnrestAll (Try now), a probe's lift and a slow
  rest taking an ended ladder rest's place. Unchanged sets aren't
  written again.
- loadRests reads it once per file as ListenAndServe starts. A rest still
  running rests out what is left; an ended one keeps its rung, as it does
  in memory, so the next refusal climbs on; one ended over restsKeep (35
  days) ago starts over; a key no longer in providers.json (id or
  id#keyid) is let go; a rest this process has already wins. A rests.json
  that can't be read or parsed, or a providers.json that can't be read,
  adds no rest; the next change writes the file anew.
The rung decays as at runtime: only an answer or Try now starts it over,
and both now reach the file.

Run (mote-run; first on origin/main 3bce283df, then rebased on 9e73f69af):
- go test -run 'TestKeyCredit|TestKeyOutOfCredit|TestCreditLadder' and
  -run 'Credit|Rest|Quota|Unrest|Afford|Balance' ./internal/gateway: ok.
- go vet ./internal/gateway native, GOOS=linux -tags nogui, GOOS=windows: ok.
- gofmt -l: clean for these files (internal/agent/pi_api_test.go is
  unformatted on origin/main already).
- at 79af00916 (on 9e73f69af), alone on mote: go vet ./... native,
  GOOS=linux -tags nogui and GOOS=windows ok; go test -count=1 -timeout
  45m ./...: 80 packages ok, internal/gateway ok (532s); internal/gui red
  only on its ten real-window AppKit tests, each `signal: killed` at its
  deadline (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
  TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
  TestDockReopenKeepsTheWindowsSpace, TestMainWindowCorners,
  TestMainWindowRightToLeft, TestHandoverLeavesTheMenuBarIconForTheNextMagpie,
  TestTrayCellClickReleasedPanel, TestCoveredWindowStaysUp). The same ten
  are red run alone at origin/main 9e73f69af; #4125 names them.
- rebased on 133493488 (two #2278 commits in internal/sessions and the
  GUI's Sessions, no gateway change): go vet ./internal/gateway
  ./internal/sessions ./internal/gui and go test ./internal/gateway
  ./internal/sessions ok at the pushed head.

Broken by hand, each red:
- loadRests reading nothing: TestKeyCreditRestOutlivesRestart "after a
  restart the key rests no more" (the old behaviour), and
  TestKeyCreditRestFileCorrupt.
- the removed-key check off: TestKeyCreditRestFileForgets "a removed key
  rests after a restart".
- clearRest not saving: "after an answer and a restart: failures 3".

Not tried: a real magpie restart with a real out-of-credit key (the tests
restart by clearing memory and reading the file as ListenAndServe does);
a handover where the old magpie writes after the new one read. Only the
key ladder is kept; other rests (rate limits, quotas, accounts) still end
with the process.
2026-10-30 19:24:31 +08:00
yetone 99ad38b7c8 vertex: Claude models on Anthropic's Messages API at the project
A user on X wanted to spend GCP credit on Claude through Vertex AI. Claude
Code does it with CLAUDE_CODE_USE_VERTEX, ANTHROPIC_VERTEX_PROJECT_ID and
CLOUD_ML_REGION, but magpie's Vertex provider only spoke Gemini. Now a
Vertex provider with just a project and a region serves claude-* ids
(claude-sonnet-5-5, claude-sonnet-4-5@20250929, ...) on every client
protocol: Chat, Responses, Anthropic Messages and Gemini.

The request shape follows the AnthropicVertex SDK bundled in Claude Code
2.1.314 and Google's Vertex docs for Claude:
- a message goes to .../publishers/anthropic/models/{model}:streamRawPredict
  when it streams and :rawPredict when it doesn't, with model taken out of
  the body;
- a count goes to .../publishers/anthropic/models/count-tokens:rawPredict
  with the model kept;
- the body gets anthropic_version "vertex-2023-10-16" when it has none;
- no ?beta=true query; the bearer is the existing Google OAuth token;
- the advanced-tool-use-2025-11-20 beta goes as tool-search-tool-2025-10-19,
  as Claude Code sends it to Vertex (the Bedrock rename table, now for
  Vertex too; Bedrock's refused betas stay Bedrock only).

How:
- provider: VertexClaude(model) and VertexClaudeRequest(path, body).
  Base(Anthropic) is the Vertex project base, so a Vertex provider speaks
  chat, anthropic and gemini; ListedAPIs gives a Claude id Anthropic only,
  so the model id alone picks the publisher. No GUI change.
- gateway: forwardOnce, the one place every Anthropic upstream request
  passes, rewrites path and body for Vertex. Gemini's effort mapping
  (none -> minimal, xhigh -> high) skips Claude. countTokens takes any
  provider with an Anthropic base.
- provider Test stays on Gemini (Claude needs Model Garden enablement);
  TestModels asks a Claude id on rawPredict with max_tokens 16.
- preset lists claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5 and
  claude-fable-5-1 at global. Docs: reference.md, providers-accounts.md,
  gateway-routing.md.

Run (darwin, mote):
- gofmt -l: nothing. go build ./...: ok.
- go vet ./... ok; GOOS=linux go vet -tags nogui ./... ok;
  GOOS=windows go vet ./... ok.
- go test -tags nogui -count=1 -timeout 45m before the rebase:
  internal/provider ok 100s, internal/gateway ok 497s, internal/gui ok 58s,
  internal/cli ok 33s, internal/tui ok 9s.
- After rebasing on origin/main (36 new commits, six in provider/gateway):
  internal/provider ok 112s and internal/gateway ok 578s again, at the
  rebased tree (d53336d9e before this message was written), gofmt clean.
- New tests: TestVertexClaudeModel (gateway, fake Vertex server: chat,
  anthropic, responses streamed and not, two id forms, a Gemini client,
  effort xhigh and none, Claude Code's ?beta=true with the tool-search
  beta, count_tokens, a Gemini model still on streamGenerateContent),
  TestVertexClaudeModels and TestVertexClaudeRequest (provider).
- GUI (no asset changed; files the provider list reaches):
  vertex-editor and i18n-keys in Chromium on mote, 18/18. WebKit on mote
  fails to launch at all (180s launch timeout under load), so WebKit ran
  on the Linux box (wsl-run): vertex-editor 14/14 in four of five
  runs. The first run had 13/14 with one failure whose name was lost
  (log not kept, my fault); three runs with logs kept since were 0 fail,
  so it isn't named or filed. No GUI asset changed here.

Broken by hand, each red, then restored:
- forwardOnce rewrite off: 502 on every Claude request.
- vertexEffort exclusion removed: xhigh reaches Vertex as high.
- beta rename off for Vertex: beta arrives unrenamed.
- countTokens back to c.p.Anthropic: the count goes to streamRawPredict.
- ListedAPIs Claude branch removed: the model is asked on gemini.

Not tried:
- No real GCP project was available: no real Vertex request, no Model
  Garden enablement, no real Claude Code session against Vertex through
  magpie. The shape is checked against the SDK and docs only.
- Claude is listed at global only; regional availability per model isn't
  listed.
- Whether Vertex accepts a 1h cache_control TTL is unverified.
2026-10-30 18:29:45 +08:00
yetone cfcd6648fc gateway: Chinese that says the input is too long is an overflow, Chinese pace words a rate limit (#4420)
A group member answered 400 "内容太长了,请精简输入或开启新对话" once a
turn passed ~730K on a model it declares at 1M. tooLongRe's Chinese only
matched wordings that name 上下文, so the try was filed as a plain
failure that rested the member, and the group's other members were never
asked. Reported by MYCF711 (Discord, issue #4420).

tooLongRe gets a third line for Chinese that names what was sent (内容,
输入, 文本, 提示词/prompt, 问题, 对话, 消息) beside its length: "…太长/过长/
超长", "…超过/超出…长度/token/字数", "输入长度/token…超过", and
"字数太多/过多". Tied to: the reporter's vendor, z.ai's 1261 "Prompt 超长",
iFlytek Spark's 10907 "token数量超过上限。对话历史+问题的字数太多,需要精简
输入". Left out on purpose: bare "超出最大长度" (a field's length), bare
"token数量超过上限" (a day's allowance is said so too), "输出过长" (the
reply), and "请求体过大" (a 413 byte limit, already handled by status).

paceWords gets Chinese pace words (速率, 频繁, 频率, 限流, 并发, 每秒/
分钟/小时/天/日, 稍后再试/重试), so "内容太长,已达到速率限制" is a rate
limit, not a size. rateWords gains 过于频繁/速率 and quotaWords 频繁/速率,
so such a 400 is asked of the next account and such a 429 is failRate.

Tests:
- TestEveryVendorsOverflow: 8 Chinese rows (red on the old code, each).
- TestChineseNotTooLong (new): pace-with-size, a field's length, the
  reply's length, a day's token cap and plain errors aren't overflows; the
  pace 400 is retryable.
- TestChineseInputTooLongGoesToTheNextMember (new): two-member group, the
  reporter's literal words, raw and \u-escaped: member b answers, failOverflow,
  nobody rests (red on the old code: a 1, b 0, 400 to the agent).
- docs/subsystems/gateway-routing.md names the new wordings.

Run (mote, via mote-run, at this tree):
- go test ./internal/gateway -count=1 -timeout 45m: ok 500.9s
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: clean; gofmt -l clean
- Broken by hand: old gateway.go/routing.go/fallback.go with the new
  tests: all three tests red (11 failures). paceWords alone reverted:
  TestChineseNotTooLong red on 4 pace messages and the retryable check.

Not tried: the reporter's real vendor (unknown which member it is), nor a
real z.ai or iFlytek account; the wordings come from their docs. Only
internal/gateway was run, not the whole repo; the change is inside that
package's classifiers.
2026-10-30 17:52:14 +08:00
JoeyWu-tech 497100488a provider, library: a .git is a repository only when git takes it for one (#3675)
TestPluginToldWhereTheAgentWorks was red on any machine with an empty
.git above its temp folder. GitOnDisk took the first .git it met going
up as a repository, and on this box /tmp/.git is an empty folder (owned
by nobody), so every folder under /tmp read "yes". git passes such a
folder over and goes on up: git rev-parse under it says "not a git
repository".

GitOnDisk now reads each .git on the way as git's own search does
(repo_discovery_find_dir in git 2.56's setup.c), through GitAt:
- A folder counts when git takes it for a repository (is_git_directory):
  a HEAD git takes (a link into refs/, "ref: refs/...", or a commit's
  id), and objects and refs folders, in the folder its commondir names
  for a linked worktree. Any other folder, an empty one say, is passed
  over and the walk goes on up.
- A file counts when it is "gitdir: <folder>" naming such a folder,
  relative to the .git's own folder (a linked worktree's, a
  submodule's). Any other file, one over git's 1 MB, or one that is
  neither file nor folder is "no": git stops there with "not a git
  repository" (a worktree whose repository has gone) or "invalid
  gitfile format". (git 2.34 passed a .git that is neither file nor
  folder over; 2.55 and 2.56, CI's, stop at it.)
- A .git it can't read is unknown, and the header is left off. git
  passes such a folder over and stops at such a file, but either way
  it can't tell an empty .git from a repository it isn't let into
  (another user's, through a shared magpie), and a failed read is
  unknown here.
A bare repository kept as a folder's .git (git init --bare .git) is
still "yes": git finds one there, though no work tree. Not mirrored:
the filesystem boundary, GIT_CEILING_DIRECTORIES and safe.directory's
ownership check. Cost: the same one stat per folder on the way up; at
a .git, a read of HEAD (255 bytes at most) and stats of commondir,
objects and refs.

What a user sees: a request to a plugin provider from an agent that
doesn't say whether its folder is a repository (Codex, Pi) was told
"yes" for a project under a stray empty .git, under a worktree whose
repository was deleted, or under a .git file that names nothing. The
community ZCode plugin then tells the model "- <git label>: yes" and
Command Code's sends isGitRepo: true, so the model may run git commands
that fail with "not a git repository". They are now told "no", and
with a .git on the way magpie can't read, nothing (ZCode's plugin
leaves the line out, Command Code's sends false). Claude Code's and
OpenCode's requests say it themselves and are passed on as they say it,
so nothing changes for them; Claude Code 2.1.310's own check takes any
.git, an empty one too.

The only caller of GitOnDisk is tellWorkPlace (workdir.go), which needs
no change. The library's skill groups had the same first-.git walk:
gitRepoOf took the first .git within four folders of a linked skill for
its checkout, so an empty one between a skill and its clone left the
skill in no group, and gave one imported from there no From. gitRepoOf
now asks provider.GitAt, passes such a .git over to the clone's, and
reads the origin from the folder GitAt names (a linked worktree's
common one), which replaces gitdirConfig. gitdirConfig also took
"gitdir:" with no space after it, or with spaces around the line,
which git doesn't take; such a .git now traces to nothing, as git finds
nothing there. Checkouts git made are traced as before; the test's
fake ones had only a config and now have a HEAD, objects and refs.
Every other .git folder in the Go code is one a walk skips when it
copies, hashes or checks a skill (carry.go, skillcheck.go, skills.go,
skill_edits.go), or the one magpie removes from its own fetch of a
skill (skillgit.go), not a decision about a repository. The Claude
bridge's claudeWorkDir takes the temp folder for one in no repository;
Claude Code decides that for itself, and its git status is off for
every run (CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS), so it stays.

TestPluginToldWhereTheAgentWorks gets a real repository for "in a
repository" (HEAD, objects, refs; an empty .git was all it had) and a
case under an empty .git in its own temp folder, so it fails without
this on any machine. Its "not in one" cases, and the new provider
tests' "no" ones, still need no repository above the temp folder, as
the test did before. TestGitOnDiskIsWhatGitFinds lays out each kind of
.git by hand; TestGitOnDiskAgreesWithGit asks git rev-parse
--git-common-dir in each of those folders and in ones git made (init,
worktree add, a worktree whose record was removed, --separate-git-dir,
init --bare .git), for yes or no and where;
TestGitOnDiskUnreadIsUnknown locks a .git folder and a worktree's .git
file. provider-plugins.md and library.md say the same.

What was run (tree 9a4504d9, on origin/main 56602426, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077, git 2.34.1, with
the box's empty /tmp/.git above the tests' temp folders:
- TestPluginToldWhereTheAgentWorks -count=5, Bun 1.4.2: 5 of 5 ok.
  TestGitOnDisk* and TestSkillRepo*, -count=3: 15 of 15 ok. The same
  and TestPluginToldWhereTheAgentWorks, -race -count=2: 12 of 12, no
  race. internal/library and internal/provider whole: ok.
- 56602426's workplace.go and skill_from.go put back under the new
  tests: TestPluginToldWhereTheAgentWorks red 5 of 5, at
  plugin_workdir_test.go:125 both "not in one" and "not in one, under
  an empty .git": the plugin was told git "yes", want "no";
  TestSkillRepoTraced red, "write-a-prd: repo "", want
  "mattpocock/skills"".
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag
  on linux: exit 1 (no libsoup-3.0 or gio-unix-2.0 here).
- go test -tags nogui -count=1 -timeout 45m ./... (Bun 1.4.2, log
  kept; 8m37s, load 32 at its start): 73 packages ok, and 14 tests red
  in 4 packages, none of them this commit's tests or what they cover.
  internal/gateway ran to its end (504s), so
  TestPluginToldWhereTheAgentWorks passed in it; internal/library and
  internal/provider ok. The reds: agent TestCodexDriftReached and
  TestCodexBehindReverseProxy (#3398); TestInstalledVersion,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641: go build's own VCS
  stamping meets the same /tmp/.git, which this doesn't change); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask
  077, #3640); gui TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie (#3649).

This commit is 595b361c rebased: the same internal/ patch-id, and
the same row in docs/subsystems/library.md, put in by git's 3-way
merge, as main's 33ccc618 (#2794) rewrote the Skills row, a line of its
context three rows above. The rest is what was run for 595b361c, at
tree d56bed31 on origin/main 098ac969, the same code (not this tree):
- main's GitOnDisk and gitRepoOf under the new tests (098ac969's
  workplace.go and skill_from.go put back):
  TestPluginToldWhereTheAgentWorks -count=5, Bun 1.4.2: red 5 of 5,
  "not in one" and "not in one, under an empty .git" told git "yes".
  With TMPDIR=/var/tmp/3675-clean, no .git above it: red 5 of 5 on the
  new case alone. TestSkillRepoTraced: red, write-a-prd: repo "", want
  "mattpocock/skills".
- Broken by hand, one at a time in workplace.go, each red in the
  GitOnDisk tests on what it breaks, and green again restored:
    any .git folder taken, main's rule for folders: "yes" under an
      empty .git, a zeroed HEAD and a HEAD alone, and for a locked .git
    a gitfile naming no repository, or not a gitfile, walked past:
      "yes" from the repository above it
    HEAD's content not read: "yes" for the zeroed HEAD; objects and
      refs not looked for: "yes" for a HEAD alone
    a HEAD at a commit not taken, or commondir not read: "no" for both
      linked worktrees; a worktree's own folder named, not its common
      one: the repository at .../worktrees/wt where git finds .../.git
    a HEAD linked into refs/ refused: "no"; a relative gitdir read
      from magpie's folder: "no" for the submodule; no 1 MB cap: "yes"
    ENOTDIR taken for a failed read: unknown for a gitfile naming a
      file; a .git it can't read walked past: "no" for both locked ones

Not tried: CI's git 2.55.0 (ubuntu) and 2.56.0 (macOS, Windows) under
TestGitOnDiskAgreesWithGit, which met git 2.34.1 alone; macOS and
Windows at all (Windows CI only compiles the tests); a real ZCode or
Command Code plugin end to end; a shared magpie told another user's
folder; the Library page itself.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00
JoeyWu-tech 7e7600439a gateway: generateContent with imageConfig asks the Gemini API, not Chat (#3820)
GuoJinguang's relay (#3820) has a Chat URL beside its Gemini one, and
their generateContent asking imageSize 4K went to its chat completions,
which drew 1024x1024. A Gemini client's request asked for one body is
translated (attempt: a Gemini API is always asked streamed), and with
relay off and no ownAPI it goes to the first API usable gives, Chat
where the provider has one. That default is meant (uaSetup in
user_agent_test.go), and the previous commit leaves it: there the
request reaches the Gemini URL only with the model's API set to Gemini.

Now one that asks an image's size or shape, a generationConfig holding
an imageConfig object, sets ownAPI on that rule, as a web search does
and as DashScope's request asked for one body does: it is translated
on the provider's Gemini API, the only one that takes the field, and
the previous commit carries the field there. Every other request
routes as before, so one without imageConfig still goes to Chat at a
provider with both. gateway-routing.md's One try says so.

What moves: a request asked for one body that carries imageConfig, at a
provider with both URLs and the model's API left on Auto, is asked on
its Gemini URL instead of its Chat URL. If that Gemini API turns the
model away in words magpie reads as the wrong API (wrongEndpoint), the
request is asked on Chat and the refusal remembered, as for any
translated request; any other refusal, such as a bare 404 for a model it
doesn't have, goes to the client, as it does today for the same client's
streamed requests, which are relayed there. What a translation drops
(safetySettings, topK and the rest parseGemini doesn't read) is dropped
on Gemini as it was on Chat.

Left as on main, as the previous commit says: a provider with no
Gemini URL has nowhere to send it (#3935), the images API sends
its size to Gemini as an aspect ratio (#3936), and a translated
Gemini request drops the rest of what parseGemini doesn't read
(#3937).

What was run (tree d7ae85a2, on origin/main 0c17aac2, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- TestGeminiImageConfigGoesToTheGeminiAPIBesideChat, new: the previous
  commit's five generationConfigs, generateContent, at a provider with
  both URLs on one fake relay. The three with imageConfig are asked at
  /v1beta/models/gemini-3-pro-image-preview:streamGenerateContent with
  it, the two without at /v1/chat/completions. With
  TestGeminiImageConfigReachesTheGeminiAPI and ReachesCodeAssist,
  -count=5: 15 of 15 pass; -race -count=5: 15 of 15, no race.
- the new test on the previous commit's tree (2b421ece): red, the
  three with imageConfig "the relay was asked at /v1/chat/completions,
  want /v1beta/models/gemini-3-pro-image-preview:streamGenerateContent".
- broken by hand, each alone:
  - the rule never setting ownAPI: the same 3 lines red;
  - the rule setting ownAPI for every request: the two without
    imageConfig red, "the relay was asked at
    /v1beta/models/gemini-3-pro-image-preview:streamGenerateContent,
    want /v1/chat/completions".
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag
  on linux: exit 1 (no libsoup-3.0 or gio-unix-2.0 here).
- go test -tags nogui -count=1 -timeout 45m ./... (Bun 1.4.2, log
  kept; 8m37s, load 34 at its start): 72 packages ok, and 14 tests red
  in 5 packages, none of them this commit's tests or what they cover.
  internal/gateway ran to its end (506s), so the three passed in it.
  The reds: agent
  TestCodexDriftReached (#3398); TestInstalledVersion,
  TestHowInstalled, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask 077,
  #3640); gateway TestPluginToldWhereTheAgentWorks (#3675); gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649).

This commit is 44a63bd5 rebased: the same internal/ patch-id, and the
One try row of docs/subsystems/gateway-routing.md merged by hand, its
sentence unchanged. The rest is what was run for 44a63bd5, at tree
82a169ba on origin/main f8cd964a, the same code (not this tree):
- a probe at that tree, not kept, one server asked twice with
  imageConfig: the Gemini API answering 400 "Model does not support
  this protocol" (a wrongEndpoint wording): asked on Gemini, then on
  Chat, 200 from Chat, and the second ask on Chat alone; answering a
  bare 404 "models/... is not found for API version v1beta": the 404
  to the client both times, Chat not asked, as for a streamed request
  there, with or without imageConfig (relayed, also probed)

Not tried: the reporter's relay, or any real Gemini API; the relay
here is a fake. Not known: whether some relay's Gemini API lacks a
model its Chat API serves, the case where this commit turns a picture
at the default size into that 404.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00
JoeyWu-tech ed9d849a21 gateway: a Gemini client's imageConfig reaches every Gemini upstream (#3820)
GuoJinguang (#3820): a Gemini client's generateContent asking a
gemini-*-image-preview model for generationConfig.imageConfig
{"imageSize":"4K"} drew 1024x1024 through magpie, where the same
request straight to their relay drew 4096x4096. The picture came, at
the model's default size, and nothing said the size had been dropped.

parseGemini didn't read imageConfig, so wherever magpie builds a Gemini
client's request again it was gone: a request asked for one body to a
Gemini API that isn't Vertex AI (always translated, since attempt asks
a Gemini API streamGenerateContent and reads the stream back into one
body), and every request to Code Assist or Antigravity, which go in
their envelope. A streamed request to a Gemini API, and a Gemini
client's request to Vertex AI, streamed or not, is relayed as it came
(passthrough) and kept it.

The reporter's request went to the relay's chat completions instead.
Their provider has a Chat URL beside its Gemini one, and attempt turns
relay off for a Gemini request asked for one body without ownAPI, so
it goes to the first API usable gives: Chat, as Speaks puts a custom
provider's Gemini last. That default is meant (uaSetup in
user_agent_test.go: "Gemini's own wire, which a provider on Chat too
isn't asked on"), and Chat has no field for imageConfig.

Now parseGemini keeps generationConfig.imageConfig as the client sent
it (Request.ImageConfig, raw as Metadata and ClientMetadata are, so
Vertex AI's own fields beside imageSize and aspectRatio go on too), and
buildCodeAssistSent, which every translation to a Gemini API goes
through, writes it into generationConfig: the Gemini API (buildGemini),
Vertex AI (buildVertex), and Code Assist and Antigravity in their
envelope. A request that asked for none is sent none. Chat, Responses
and Messages are left as they were: I found no vendor documenting a
field for it there, so none is made up. gateway-routing.md says where
imageConfig goes.

At a provider with both URLs, a request asked for one body reaches the
Gemini URL, and its imageConfig with it, when the user picks Gemini as
the API the model is asked on in the provider editor (SetModelAPI,
tested below). The next commit sends one that carries imageConfig
there by default.

Left as on main, each in its own issue:
- a Gemini client's image request to a provider with no Gemini URL
  (the Google Gemini preset's OpenAI-compatible endpoint, OpenRouter,
  another magpie, a relay saved with a Chat URL alone) carries no
  imageConfig, asks no modalities, and reads no image back from chat
  (#3935);
- /v1/images/generations and /v1/images/edits send a size to a Gemini
  image model as an aspect ratio only (drawGemini, drawChat), and to
  Code Assist only in words (drawCodeAssist), so nothing above 1K can
  be asked there; a Gemini client's request never takes that path
  (#3936);
- the rest of what a translated Gemini request drops: safetySettings,
  topK, seed, responseModalities, and the newer responseFormat
  (Google's next spelling of the same ask), among the fields
  parseGemini doesn't read (#3937).

This commit's tree (2b421ece, on origin/main 0c17aac2) wasn't run on
its own. It is 85b532c6 rebased, with the same internal/ patch-id and
the same gateway-routing.md line, which applied as is. Its two tests
ran at the next commit's tree, -count=5 and -race -count=5, and in the
full suite there. What was run for 85b532c6, at tree de27856c on
origin/main f8cd964a, the same code (not this tree), with go1.26.8,
linux/amd64, Linux 5.15, outside graftcp, umask 077:
- TestGeminiImageConfigReachesTheGeminiAPI, new: a fake relay records
  each request. Five generationConfigs (imageSize 4K, the reporter's;
  aspectRatio 16:9 and imageSize 2K beside a thinkingConfig; the
  snake_case image_config; none; temperature alone), at a provider
  with the Gemini URL alone (generateContent and streamed), with a Chat
  URL too (streamed), and with a Chat URL too and the model's API set
  to Gemini (generateContent): 4 of 4 subtests ok
- TestGeminiImageConfigReachesCodeAssist, new: the same five to an
  Antigravity sign-in's gemini-3.1-flash-image, generateContent and
  streamed, read in request.generationConfig: ok
- both on f8cd964a, the test file alone: red. The Gemini URL alone and
  the set-to-Gemini subtests, 3 asks each: "asked {...}:
  /v1beta/models/gemini-3-pro-image-preview:streamGenerateContent was
  sent "": ...", no imageConfig; Code Assist, both methods, 3 asks
  each: "sent "": ..."; the two streamed subtests pass, the relay
  having kept it
- broken by hand in a scratch worktree at that tree, each alone:
  - parseGemini not reading it: the same 12 lines red
  - buildCodeAssistSent not writing it: the same 12 lines red
  - buildCodeAssistSent writing it when none was asked: 8 lines red,
    "asked for none: ... was sent null" and "sent null"
- both, -race -count=5: ok
- go test -tags nogui -count=1 -timeout 45m -v ./internal/gateway,
  Bun 1.4.2: 5402 passed with their subtests, 3 skipped, 1 red,
  TestPluginToldWhereTheAgentWorks (#3675)
- tools/vetset.sh: gofmt -l clean; vet for linux, windows and darwin
  with -tags nogui, windows vet, and the three builds exit 0; untagged
  linux vet and build exit 1 at pkg-config (no GTK headers here)
- the full suite ran once, at 44a63bd5's tree; de27856c is covered by
  the gateway package and the vet set above

Not tried: the reporter's relay, or any real Gemini API, Vertex AI or
Antigravity image model; the upstreams are fakes that record the body.
Whether a relay's Gemini API passes imageConfig on to Google is the
relay's.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00
JoeyWu-tech 7ec0769172 gateway: TestStreamingRequestsLetTheirSentBodyGo waits for every answer (#3503)
The test reads the heap once the upstream has written each request's
first chunk: got is sent from its handler right after the Flush. The
gateway lets the body it sent go when forwardOnce returns (#3383),
after the transport has read that reply off the connection and p.Do
has returned it, so the heap can be read while a request still holds
what it sent, and only the two GCs before the read give it time. A
scratch copy of the test, on 23cec6c4, counted the requests whose
first text had reached their agent when the wait ended: -count=30 at
-cpu 1, 2, 4 and 8, it was 8 of 8 in none of the 120 runs (7 in 85,
down to 1), and the held ratio ran from 1.74 to 2.87 against the bar
of 3. In my full suite at 6b556f5a (go test ./..., internal/gateway
441 s beside the other packages) it went over:
  streaming_heap_test.go:96: 8 streaming requests of 4 MB hold 121 MB,
  3.1 times the body each

The test now waits for each request's first text at the agent's end
of its pipe (firstText): the gateway streams it from the reply
forwardOnce returned, so that request's LetGo has run. What the heap
is read for, and the bar, are unchanged.

What was run (this commit on 23cec6c4; go1.26.8, -tags nogui):
  the same count with this wait, -count=30 at -cpu 1, 2, 4 and 8: 8 of
  8 in 120 of 120, the ratio 2.09 to 2.19
  the answers made to reach forwardOnce late, a 300 ms pause after
  p.Do (scratch, not in this commit):
    all 8, -count=10: the old test red 10 of 10, "3.7 times" to "4.0
    times the body each"; this one ok
    the first 3, six runs: the old test red in one, "8 streaming
    requests of 4 MB hold 122 MB, 3.1 times the body each"; this one
    ok in six. The first 1 or 2: both ok six times, the old test's
    ratio up to 2.73
  LetGo taken out of forwardOnce, -count=10: red 10 of 10, "8 streaming
  requests of 4 MB hold 152 MB, 3.9 times the body each"
  -race -count=20: ok; -cpu 1,2,4 -count=20: ok
  gofmt -l internal/gateway: nothing; GOOS=linux, darwin, windows go
  vet -tags nogui ./internal/gateway: exit 0
  full suite, go test -tags nogui -count=1 -timeout 45m ./... at this
  commit: 63 packages ok; internal/gateway ran 445 s, this test ok in
  it. 7 packages red, each of this machine and named before (#3480's
  d970371e): #3141's lookup tick (TestInstalledVersion,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir,
  TestZedAppPath); Reasonix's two (a /tmp/.git that isn't this user's);
  every connection proxied, even to this machine's own non-loopback
  addresses (TestCallbackGoesPastTheAgentsProxy,
  TestClaudeToolCallbackOnANonLoopbackAddress,
  TestGatewayFixQuitsOnlyAMagpie, TestGatewayHeldByAContainer); umask
  077 (TestWriteAtomicReadOnlyHardLink, testenv's TestProgram); Bun
  1.3.11 (TestBunProxyLoginWithReservedCharacters, #3397)
Not tried: macOS, Windows, CI's runners.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00
yetone 067e4c4846 gateway: Raccoon's token wall (user_model_rate_limited) isn't asked again in place (plugins#512)
SenseTime Raccoon answers an account whose token throughput is used up
with 429 {"error":{"code":"user_model_rate_limited","message":"您的模型请
求频率超限,请稍后重试","type":"rate_limit_error"}} and no Retry-After.
Its words read as a short rate limit, so the lone account was asked again
by the same-one retries (passing: 1, 2, 4s) and then by the plain
provider's patience (busy/replan: 2, 4, 8, 16s): eight asks in ~38s,
each one resending the whole ~88k-token request into the bucket it was
waiting on (cycocyco's numbers in plugins#512).

A 429 whose error.code is in wallCodes (only user_model_rate_limited) is
now neither passing nor busy. It still reads as failRate and rests as one
(a minute, doubled each time it comes back, up to 30 min, rateRest), so a
group's next member or the provider's next account is asked, and a lone
one hands the agent the vendor's error after one ask. The code is matched
at error.code only, not as words anywhere in the body. Other rate limits,
the same Chinese words under another code included, are retried as
before. The plugin passes the vendor's body through unchanged, so this is
the place for it.

Run (mote, at this change on origin/main 244d80e23):
- go test ./internal/gateway -run 'TestTokenWall|TestRateLimitIsWaitedOut|TestShortReset|TestLastOneLeft|TestGroup': ok
- gofmt -l internal cmd: clean; GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok
- go test -timeout 45m -count=1 ./...: every package ok except
  internal/gui, whose ten real-window AppKit tests (dock, panel, tray,
  titlebar, plugin page) were killed at their deadlines, mote's known
  state (#4125, #2645); this change touches no GUI code.
Rebased on origin/main 88e6fb9cf: go test -timeout 45m ./internal/gateway
./internal/usage: ok. Rebased again on 88e6fb9cf (routing.go's credit
rests changed, not the rate path): go test ./internal/gateway -run
'TestTokenWall|TestRateLimitIsWaitedOut|TestShortReset|TestLastOneLeft|
TestGroup|Rest|Credit': ok; the whole package not rerun there.
Broken by hand: with both !walled(body) guards taken out,
TestTokenWallIsNotRetriedInPlace is red (passes, busy) and
TestTokenWallFailsFast is red with "429 after 16 tries".
Not tried: the real Raccoon API (no account here), nor the reporter's
Hermes on Windows.
2026-10-30 15:40:49 +08:00
yetone 88e6fb9cf7 provider: a signed-in subscription's models stay in every agent's list with a group listing alone on
士奇 on Discord (Simplified Chinese GUI, the third report of this): with
routing groups off, Hermes Agent's and WorkBuddy's model lists had the
ChatGPT subscription's GPT models. With routing groups on, they were gone.

Cause: the user's group names those models and lists itself alone
(Group.Unlists, the routing plugin's option for that, #1783). While the
group is on, catalogKeeping drops what it names from Catalog(), and every
agent's list starts from Catalog(). With groups gated off the group's
Unlists goes away, so the models came back. a3ee00c05 kept them for the
Codex agent only; its body said other agents still didn't see them.

Fix, at the one point every agent's list starts from: catalogOf(agent)
keeps a signed-in subscription's own models (SubscriptionKept: no group
entry, Provider.Account set, the provider not kept for routing groups)
for every agent, so a group is added on top of what agents had. A client
that is no agent ("" on /v1/models) still gets the group alone, as #1783
asked. Provider.Unlisted ("Only through routing groups") still hides the
provider's models from agents other than Codex. Unlisted() no longer names
a kept subscription model, so the picker's note doesn't call it kept for
groups.

Siblings: every agent writer reaches catalogOf through CatalogFor and
ListedFor. Two gateway lookups read Catalog() directly and now use the
agent's catalog (CatalogOf): /v1/models/{id} and Claude Desktop/Science's
alias lookup. agent.go and codex.go read Catalog() only for error text or
a fallback and are left alone. The routing plugin's hint for that option
says, in every language, that a signed-in subscription's models stay in
agents' lists.

Test: TestSubscriptionModelsStayInEveryAgentsListWithGroupOn signs in a
ChatGPT account in a sandbox and switches on a group naming its 5 models
that lists itself alone. For every agent that lists the group (68,
including hermes, workbuddy, claude and codex), the agent's list and
CatalogFor have the models, and a picker offering the group offers them.
Catalog() and CatalogFor("") still don't. With the provider set to
Unlisted, Hermes doesn't list them. TestCodexOwnModelsListedOnlyThroughGroups
now expects Claude Code to keep the models under a group alone.

Run (on mote):
- Broken by hand: catalogOf reverted to a3ee00c05's Codex-only version.
  The new test went red with 340 errors across 68 agents, e.g.
  "codex/gpt-5.5 not in hermes's list map[group/mygpt:true]", and the
  same for workbuddy, claude and claude-desktop. Green with the fix back.
- gofmt -l; go vet on darwin, linux (nogui) and windows; builds: clean.
- go test -timeout 45m ./... at 035d87b80 (this change on 4a4a90c23,
  before a test comment was reworded): every package ok except
  - internal/gui TestMainWindowCorners/macOS_26_SDK: #3949, red on
    origin/main accb951ab on mote too (macOS 27);
  - internal/provider TestClaudeAccountServesModelsListedSinceItsFetch:
    #3174 (red in a full run, green alone). 5 of 5 green alone and
    green in a whole internal/provider run at that head.
- At this commit on b26fa0903: gofmt -l on the
  changed Go files, go vet of provider, gateway and gui on darwin, linux
  (nogui) and windows: clean. internal/provider whole: ok.
  internal/gui and internal/gateway with -run
  "Codex|Group|Subscription|Unlist|Catalog|AgentModel": gui ok; gateway
  red on TestAntigravityTurnsCodexsGPT5ThreadAwayOnce and
  TestCodexSpentGrokFailingIsTold, both red the same way on origin/main
  b26fa0903 (3 of 3) and filed as #4362.
- GUI files the change reaches, on b26fa0903: agent-model*, group-unlists and
  i18n-keys: every Chromium case and i18n-keys pass (46); every WebKit
  case timed out launching the browser (180s, #4125: WebKit doesn't start
  on mote right now). The same files at 035d87b80 passed in both engines
  but i18n-keys, whose one red (the new test quoted a routing-plugin
  word) is fixed here.
- Rebased on 101775657 (main had moved models.go and gateway.go): gofmt,
  go build for darwin, linux (nogui) and windows, go vet of provider,
  gateway and gui on all three: clean. go test -run
  "Codex|Group|Subscription|Unlist|Catalog|AgentModel" ./internal/gui
  ./internal/provider and -run "Model|Desktop|Alias|Catalog"
  ./internal/gateway: ok.
- The whole GUI suite (1004 files) at fd50ed116 was still running when
  this was pushed (mote shared with other sessions' suites). Reds it
  shows get their own issue unless already red on main.

Not tried: no live ChatGPT account and no real GUI app run (the test signs
in a sandbox account). No separate gateway test for /v1/models/{id} or the
Desktop alias lookup. Provider.Unlisted stays honoured, on purpose.
2026-10-30 15:38:06 +08:00
yetone 322ec8b7ce gateway: a key out of credit rests longer each time it is refused so again, up to a week
PaulT on Discord #feedback: an OpenAI API-key provider answering 402 out
of credit showed "Resting · 402 out of credit · back at 04:10 PM" and was
asked again every 30 minutes, refused the same each time. 1534474c8 gave
ChatGPT accounts a rest until their credits are back; keys still had the
flat 30-minute creditRest.

An API key (Account == nil) whose vendor says it is out of money now
climbs creditLadder: 30m, 2h, 8h, 24h, 3d, then 7d each time after.
Refused again while it still rests (the lone key, asked all the same)
keeps its rung; a rest that ended and is refused again goes a rung up.
"Try now" (Unrest) and an answer (servedCandidate) start it over at 30m.
It covers what failure() already calls failCredit: a bare 402, OpenAI's
insufficient_quota (its billing errors are 429s with type
insufficient_quota and codes credit_balance_exhausted,
organization_/project_spend_limit_exceeded,
organization_usage_limit_exceeded, per
developers.openai.com/api/docs/guides/error-codes), DeepSeek's
"Insufficient Balance" 402, Anthropic's "credit balance is too low" 400,
Zhipu's 余额不足 and WorkBuddy's exhausted 429.

What stays as before: a refusal that names when it is back (resets_at,
a reset header) rests till then, capped at longestMonthly. A 402 that can
pass soon or for a smaller request rests creditRest flat and never climbs:
one with Retry-After (OpenRouter's openrouter_in_flight_budget, per
openrouter.ai/docs/api-reference/errors), OpenRouter's "can only afford" /
"fewer max_tokens", and "try again in N" / "N 分钟后" (creditSoon).
Subscription accounts other than ChatGPT's keep 30m flat, and another
computer's magpie rests the model only, flat (TestCreditLadderIsKeysOnly).

Run (mote-run; first at this change on origin/main d31710c71):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/gui: internal/gateway red only on TestAntigravityTurnsCodexsGPT5ThreadAwayOnce,
  TestAntigravityTurnedAwayIsForeseen, ...LastIsNoQuota, ...InsideTheReplyLast
  and TestCodexSpentGrokFailingIsTold, each red the same on origin/main
  d31710c71 (#4362), and TestBurstTellsNoSpeed under load (#2719);
  internal/gui red only on the real-window AppKit tests killed at their
  20-40s deadline under mote's load (TestDockJoinLeadsCommandTab,
  TestPanelCloseHidesIt, TestMainWindowCorners, TestCoveredWindowStaysUp,
  TestTrayCellClickReleasedPanel and others: #2645, #4125, #1936, #3178);
  the same five red at origin/main d31710c71 alone; TestBurstTellsNoSpeed
  passed alone on both; TestCoreScriptBudget passed
- earlier, -run 'Credit|Rest|Quota|...' ./internal/gateway: red only on
  TestAntigravityTurnedAwayLastIsNoQuota, red the same on origin/main
  d31710c71, filed as #4362.
- rebased on 764a032f6 (c37b8b659's remote-magpie quota change among
  it; the routing doc line conflicted and was merged by hand): go vet
  ./internal/gateway native, GOOS=linux, GOOS=windows ok; -run
  'Credit|Rest|Quota|Remote|Magpie|Unrest|Codex|Spent|Broke|Balance|Afford'
  ./internal/gateway red only on #4362's tests. Then rebased again on
  the 20 commits after it (46fb0c1b9) with no conflict; there go vet
  ./internal/gateway and the three new tests pass.
- gofmt -l clean; go vet ./internal/gateway native, GOOS=linux and
  GOOS=windows.
- The full go test ./... is still to come: mote was running other
  sessions' full suites. Any red it shows gets an issue.

Broken by hand, each red:
- the credit branch in restAfterMarked off: "refusal 2: rests 30m0s ...
  want 2h0m0s".
- the rung climb after an ended rest (else if had) off: red.
- creditSoon off: OpenRouter's "can only afford" climbs ("failures 1 ...
  want flat").

Not tried: PaulT's own 402 body (not known; the test holds OpenAI's
documented bodies and the vendors' bodies magpie's tests already had).
No real out-of-credit key was asked. A key's balance reading doesn't
lift its rest early; "Try now" does. The ladder is in memory, so a
restart of magpie starts it over at 30 minutes.
2026-10-30 15:30:55 +08:00
yetone 1bbaded622 usage: an agent's call to magpie's own MCP tools is a row of Requests
ferock (Discord) asked to see calls to magpie's MCP tools, such as
magpie-image's generate_image, generate_video and generation_result, in
Routing > Requests.

Each tools/call to magpie's own MCP servers (image, vision, web search,
tools and the Library hub) is now a row of the request log. The row has
Source and Kind "mcp", the tool as its model, the server as its host,
how long the call took, and its error if it failed. The provider and
model it shows are those of the model requests the call made, collected
through the request's context in appendUsage. generation_result names
the model of the job it answers. The stdio Magpie Image server reports
each call it answered to the gateway as "magpie/toolCalled". That report
carries the tool, ms, model and error, never the prompt.

The arguments are never stored at all, so there is nothing to mask. The
rows go down the probe lane: they are listed, but no total, host list,
budget or key limit counts them. The model requests a call made are rows
of their own.

In the GUI the row reuses the Requests list. It gets a muted "MCP" badge
with a tooltip, the server beside the provider, and a Succeeded/Failed
status. The Purpose filter gains "MCP tool" in every language. There is
no new page, no <select> and no left border.

The core scripts went over their budget with the new purpose.
genpurposes now writes purposes.js as compact JSON, which makes the core
448 bytes smaller than main in all, and coreScriptBudget is lowered to
the new total, 1,538,975. No room is added.

Run on mote, at the rebased head:
- gofmt -l: clean. go vet -tags nogui ./... with GOOS darwin, linux
  and windows: ok.
- go test -tags nogui -timeout 45m: ./internal/usage, ./internal/imagemcp,
  ./internal/usageapi and ./internal/gui ok. internal/budget has no test
  files. ./internal/gateway (805s): every test ok except five Antigravity
  and Codex/Grok tests. They fail the same on a clean origin/main
  3bebc3839 and are filed as #4362.
- GUI, the usage-ledger*, routing-request*, purpose*, i18n* and
  gui-zh/ja/de files (25). On mote, Chromium: 32 of 32 ok; WebKit
  could not launch (10 other sessions' suites on mote). On Linux
  (wsl-run), both engines: 335 of 355 ok. The 20 reds are
  routing-request-model, usage-ledger, -ttft, -chart and
  -open-settled, which fail the same at the parent 1534474c8 (#4120).
  usage-ledger-mcp, purpose-filter and i18n-keys are ok in both.
  The whole GUI suite runs after the push, and each red it finds gets
  an issue.
- At the pushed head, rebased on 0804f2d97: ./internal/gui (the
  budget and purpose asset tests among them), ./internal/usage,
  ./internal/imagemcp and ./internal/usageapi ok, and ./internal/gateway
  -run "MCP|Purpose|Probe" ok.
- usage-ledger-mcp.test.cjs covers 5 languages, widths 1180 and 420,
  light and dark, with no sideways scroll.

Broken by hand. Each break went red:
- sawHost's MCP skip removed: TestMCPCallRowsListedNotCounted (the hosts
  list had magpie-image).
- Row/Record.IsProbe's MCP case removed: the same test (3 calls counted),
  and TestMCPCallCountsInNoKeyLimit (Calls: 1).
- The callMCPTool hook removed: TestMCPToolCallIsARequestRow and its
  siblings (no rows).
- The appendUsage hook removed: the row had no provider or model.
- imagemcp's report removed: TestToolCallsAreReported.
- The gateway's magpie/toolCalled case removed:
  TestMCPCalledFromStdioIsARow.
budget's in-memory counts() now skips these rows too. Breaking only that
stays green, because budget.Of reads the file through usage.Visit, which
already skips probes, and limits count tokens and cost.

Not tried:
- no real agent calling a real vendor's drawing;
- no test run on Windows or Linux;
- the page not checked in the real app or in WebKitGTK.
A generate call that answers while its drawing still runs has no model on
its row. The generation_result row that follows names it.
2026-10-30 15:00:16 +08:00
yetone 0804f2d97d search: Tencent Cloud's Yuanbao Search (wsa) is a built-in search API (plugins#509)
chenjiangzi asked for Tencent Cloud's WSA SearchPro (元宝搜索). It is added
as vendor "wsa", following Doubao Search (dca3e2d71), from Tencent's
own docs:
- API-key method (cloud.tencent.com/document/product/1806/130615):
  POST https://api.wsa.cloud.tencent.com/SearchPro with
  Authorization: Bearer <key> and a JSON body {"Query", "Cnt": 10}.
  Keys come from console.cloud.tencent.com/wsapi/index (KeysURL).
- SearchPro (121811): Response.Pages is an array of JSON strings, each
  with title, url, date, passage and content. The text is passage, or
  content when passage is empty or only the title. Tags are stripped.
- Errors (121818/121820, 130615): HTTP 200 with Response.Error{Code,
  Message}. AuthFailure*, UnauthorizedOperation and ResourceNotFound are
  turned away (403); ResourceUnavailable (欠费), LimitExceeded and
  ResourceInsufficient are out of credit (402); RequestLimitExceeded* is
  rate limited (429); others are plain errors, with the key masked.

The fixtures in testdata are the docs' two example replies. 130615's is
shown with its quotes escaped twice, which isn't JSON; they were
unescaped once and nothing else changed. The GUI's picker is built from
SearchVendors, so no GUI file changes. README (en, zh), the CLI help and
gateway-routing.md name it.

Run on mote (mote-run), at the rebased head:
- go test -run 'SearchAPI|WSASearch|Volcengine|Search' ./internal/gateway/
  ./internal/gui/
  ./internal/provider/ ./internal/cli/: ok
- go vet -tags nogui darwin/linux/windows: ok; gofmt -l clean
- GUI (no GUI file changes; the picker reads SearchVendors):
  search-api.test.cjs in Chromium 4/4 ok. Its WebKit cases and
  searcher-pick timed out at browserType.launch (180s) on mote,
  where ~57 WebKit pw_run launches from several sessions hang. Not
  a result about this change; WebKit not run.

Broken by hand, each made TestWSASearchAPI red: the wsaSearchError call
removed, and Cnt dropped from the body.

Not tried: the real API. No WSA key was available, so the request,
reply and error mapping rest on Tencent's docs only. The full go test
./... is to follow.
2026-10-30 14:56:01 +08:00
yetone acbd6b11ab search: a search API's URL given with the path magpie adds is its base, never …/search/search (plugins#509)
chenjiangzi set Tavily's url to https://api.tavily.com/search, and magpie
appended /search again. Each vendor now names the paths magpie puts after
its base (SearchVendor.Paths). A url that already ends in one of them,
with or without a trailing slash and in any case, is cut back to its base.
This happens when it is saved (SetSearchAPI) and again when it is read
(SearchAPI.Base), so an entry saved before this change works too, and so
does Tavily's quota URL built on the same base. Every vendor is covered:
tavily, brave, exa, firecrawl, you (both paths), deepseek, volcengine,
searxng, and wsa in the next commit. A path of the user's own
(/my-search) is left alone. The url= help and gateway-routing.md say so.

Run on mote (mote-run), at the rebased head:
- go test -run 'SearchAPI|WSASearch|Volcengine|Search' ./internal/gateway/
  ./internal/gui/
  ./internal/provider/ ./internal/cli/: ok
- go vet -tags nogui for darwin, GOOS=linux and GOOS=windows on
  provider, gateway, cli (and gui on darwin): ok; gofmt -l clean
- GUI (no GUI file changes; the picker reads SearchVendors):
  search-api.test.cjs in Chromium 4/4 ok. Its WebKit cases and
  searcher-pick timed out at browserType.launch (180s) on mote,
  where ~57 WebKit pw_run launches from several sessions hang. Not
  a result about this change; WebKit not run.

Broken by hand: ownBase returning the URL unchanged made
TestSearchAPIBaseURLWithItsPath red ("asked /relay/tavily/search/search,
want /relay/tavily/search").

Not tried: a real Tavily request; the full go test ./... (to follow).
2026-10-30 14:56:00 +08:00
yetone d80d75f300 gateway: a spent last member already resting, or turned away for a prompt, keeps its old path (3f91b98ea)
3f91b98ea (dbydd) turned five internal/gateway tests red in the full
suite at 1534474c8:

- TestCodexSpentGrokFailingIsTold (every shape): the Codex account was
  already resting out of its quota and asked only as the one back
  soonest. spentAfter had already asked Grok again as the last that may
  answer; lastSpent then replanned Grok another dozen times, and the
  Routing page no longer showed Codex's 429 as the earlier one told.
  lastSpent now holds only for a last member not already resting out of
  its allowance (!spentAfter([]candidate{c})).
- TestAntigravityTurnsCodexsGPT5ThreadAwayOnce, ...TurnedAwayIsForeseen,
  ...TurnedAwayLastIsNoQuota, ...TurnedAwayInsideTheReplyLast:
  Antigravity's 429 to Codex's prompt reads as quota by failure() alone,
  so the widened #1772 block rested that account, which isn't at fault.
  The account case now needs it not turned away and its try not
  failPrompt; a key's stays as it was.

Run (mote): the six families above plus the dbydd and PaulT tests, then
go test -count=1 -timeout 45m ./internal/gateway: ok (686s).
Broken by hand: lastSpent forced false -> TestGroupRelayBlipDoesNotEnd
OnSpentLast red; the #1772 block back to keys only ->
TestGroupSpentLastAccountRests red ("Codex asked 2 times").

The full suite at 1534474c8 had other reds, none in code touched here:
internal/gui's real-window AppKit tests (killed at their deadlines; the
same three chosen ones fail on origin/main f2c6831a3; #2645, #4125,
#1936, #3178), and TempDir-cleanup reds in TestLibraryMCPHub (#4140),
TestRelaunchOpenTriedAgain (#3881) and TestRequestChunksFromDisk
(filed #4390); all three pass alone at both heads.

Not tried: a full ./... again after this change (gateway alone was run).
2026-10-30 14:51:00 +08:00
yetone 8ebf9cbea9 claude: add an account from a setup-token (CLAUDE_CODE_OAUTH_TOKEN)
sfss5362 on X asked "支持 CLAUDE_CODE_OAUTH_TOKEN 吗". It didn't work
before: cleanClaudeEnv strips the variable everywhere, and the import
flow needs a refresh token and an email.

A Claude account can now be added from the token `claude setup-token`
prints. In the window: the sign-in's "Use a setup-token instead…" and
the accounts list's "Add an account by setup-token…", which post to
POST /api/signin/claude-token.

The token is kept in logins.json as {"setupToken":…}. The real Claude
Code gets it in CLAUDE_CODE_OAUTH_TOKEN, and only for runs in that
account's own config directory (inClaudeDir via
provider.ClaudeDirToken). It never goes on the command line or into a
log. magpie never asks Anthropic anything with it. The bridge, the
sdk-cli entrypoint and the weighting are unchanged.

What such a token can't do: it has the inference scope only.
- Claude Code's `auth status` gives no email or plan. The account is
  named "Claude setup-token <6 hex of its hash>".
- Its /usage prints the API cost view. /usage is never run for it, so
  its allowance is unknown (errClaudeSetupToken, which `passing` keeps
  as saying nothing about the account), not zero. Windows heard on
  real replies still fill it in.
- Its config directory holds no .credentials.json, so Claude Code has
  no sign-in to fall back to if the token is refused.
- Claude Code itself is never signed in to it. addLogin, switchLogin,
  putClaudeLogin, SetKeepLoginAs, NextLogin and signInToFirst all pass
  it over. Its row shows Remove and "magpie only", and the switch menu
  leaves it out.
New strings are in zh, zh-TW, ja and de. Docs: providers-accounts.md
and claude-subscription-bridge.md.

Run:
- mote: gofmt -l (clean); go vet ./internal/...; GOOS=linux go vet
  -tags nogui and GOOS=windows go vet of provider, gateway and gui; go
  build ./...
- mote: go test of provider and gateway, -run on SetupToken, Claude
  usage, warm-up, saved, account, logins, switch and keep-login: ok.
- New tests, with a fake claude binary in a sandbox HOME:
  - TestClaudeSetupTokenAccount, TestClaudeSetupTokenSignsClaudeCodeInToNothing,
    TestClaudeSetupTokenAllowanceUnknown and TestCheckClaudeSetupToken
    in provider;
  - TestClaudeSetupTokenReachesItsOwnRunsOnly in gateway: the token
    reaches only its account's run, not "" or another dir, even with
    the shell's CLAUDE_CODE_OAUTH_TOKEN=leaked, and never in args;
  - claude-setup-token.test.cjs: Chromium on mote and WebKit on
    xiaomi-gpu, each in en, zh, zh-TW, ja and de.
- GUI files the change reaches (signin-link, signin-web-blocked,
  signin-closes-sheet, revoked-signin-account, account-eye,
  account-row-line, i18n-keys and the new one): 73/73 on xiaomi-gpu
  Chromium.
- On mote, 33 account, sign-in and i18n files had 96 reds. mote was
  overloaded by another session's full GUI suite. Six of those files
  fail 58 of 64 the same way at origin/main dafe4af82 there, and pass
  on xiaomi-gpu. WebKit on mote timed out on the untouched
  copilot-ghe.test.cjs too.

Size: app.js was 2,885 bytes over its budget after the rebase. The
new comments were cut, and the budgets were raised to the measured sizes
(app.js 1,317,705, core 1,539,423) with no room added, as
core_budget_test.go says. After the rebase onto origin/main 969868ccd,
these were run on mote at this head: TestCoreScriptBudget and the
SetupToken tests ok, and claude-setup-token plus i18n-keys in Chromium
9/9.

Broken by hand (each went red):
- without the token line in inClaudeDir, the gateway test;
- with addLogin allowed to sign Claude Code in, two provider tests;
- with /usage run for a token account, AllowanceUnknown ("told no
  allowance").
- With switchLogin's guard removed, the tests stay green, because
  putClaudeLogin still refuses.

Not tried: a real setup-token against Anthropic. The full Go and GUI
suites will be run after the push.
2026-10-30 14:50:44 +08:00
yetone f2c6831a31 gateway: a read-only gateway key reads quotas and usage and uses nothing (Steven on Discord)
Steven's ESP32 desk display polls magpie (Docker, on his LAN) every 15s
on GET /v1/magpie/quotas and /v1/magpie/usage and never sends a model
request. Only a key held to nothing was told the usage summary, so the
key kept in the device's flash had to be one that could spend every
account.

A gateway key can now be read-only (access.Key.ReadOnly):
- `magpie gateway-key add <name> --read-only`, `magpie gateway-key access
  <id> [read-only|full]` (`gateway-key --help` lists it; `list` has an
  ACCESS column), and "Make read-only" / "Give full access" in the key's
  menu in Gateway -> Gateway keys, with a "Read only" tag on its row.
- readOnlyGuard (internal/gateway/readonly.go), after callerGuard and
  before withCaller/keyLimited, judges the pattern ServeMux.Handler routes
  the request to. A read-only key is answered GET /, /v1, the quotas,
  their history and cards, the usage summary and its requests, its limit
  and the concurrency. Every other route is refused with 403
  gateway_key_read_only: every model route, count_tokens, the Responses
  WebSocket's upgrade, every MCP server, Codex's and Gemini's backends,
  /v1/models and the Ollama routes, the catch-all, the trace and route,
  debug profiles, and every write (usage ingest, quotas refresh). It is
  default deny, so a route added later is refused until it is classified.
- The key is held to nothing else, so heldKey leaves it alone: it reads the
  usage summary and every account's quotas, as a key held to nothing does.
  None of those routes holds a key's secret.
- The sharing key can't be made read-only, since magpie gives it to its own
  agents (LANSecret). Update refuses it, and the GUI item is off with why.

Older versions: a magpie from before this commit doesn't know `readOnly`
and treats such a key as a full one, so downgrading magpie widens the key.

Tests:
- TestReadOnlyKeyEveryRoute (internal/gateway/readonly_test.go) takes the
  patterns from the router itself (routes() records each HandleFunc). It
  fails when a pattern is in neither readOnlyRoutes nor its refused list.
  It sends every refused pattern, by each method it takes, from
  192.168.1.9 and from loopback, plus a WebSocket upgrade and an unclean
  chat path, and expects 403 gateway_key_read_only with the upstream never
  reached. It checks that every allowed route answers, that no body holds
  any key's secret or the upstream key, that the usage summary names the
  other key's use, and that a full key and a key made full again still
  reach the model.
- TestReadOnlyKey (access) covers add-key and access-key on and off,
  Authenticate, List, and the sharing key refused.
- TestGatewayKeyCLIReadOnly covers --read-only before and after the name
  and beside --key, access, the list column, bad values, and --help.
- gateway-key-readonly.test.cjs runs Chromium and WebKit, 1100 and 420px,
  in en/zh/zh-TW/ja/de. It covers the tag, both menu items and what they
  post, the status line, the sharing key's item off with its why, no
  scroll on click, no sideways scroll, no select, and no left stripe.
  gateway-card.test.cjs now expects the menu's 4th item.
- TestClientPathCoversHandler takes the patterns from routes() instead of
  parsing Handler's source, which moved into routes().

Broken by hand:
- readOnlyGuard passing everything: TestReadOnlyKeyEveryRoute red (103
  lines, /v1/models 200 onward).
- A new `POST /v1/new-thing` route in routes(): red, "in neither
  readOnlyRoutes nor readOnlyRefused".
- The GUI item not off for the sharing key: gateway-key-readonly red 10 of
  10 in Chromium.

Run at the pushed head (on origin/main 0911a65e7), on mote: TestReadOnly*,
TestHeldKey*, TestClientPathCoversHandler, TestGatewayKey*, TestCaller*
in access, cli and gateway ok; TestCoreScriptBudget ok; on Linux
(wsl-run, both engines) gateway-key-readonly, gateway-card, i18n-keys,
gateway-caller-keys and gateway-key-quotas 68/68.

Full Go suite on mote (macOS) at the same change on origin/main
dca3e2d71 (94630237d), -timeout 45m: 78 packages ok; internal/gateway
red only on the four TestAntigravityTurned* and
TestCodexSpentGrokFailingIsTold (red the same at origin/main, #4362);
internal/gui red only on ten AppKit window tests that hit their 30s
bar while mote's launchd throttled every app launch (#4125).

Run on mote (macOS) on origin/main dca3e2d71:
- go test ./internal/access ./internal/cli ./internal/gateway: access ok;
  cli red only on TestLibraryMCPHub's TempDir cleanup (#4140); gateway
  red only on the four TestAntigravityTurned* and
  TestCodexSpentGrokFailingIsTold, red the same at origin/main (#4362).
  TestReadOnly*, TestHeldKey*, TestClientPathCoversHandler,
  TestGatewayKeyCLIReadOnly pass.
- TestCoreScriptBudget ok (no budget raised). gofmt clean; go vet
  darwin (access, cli, gateway), GOOS=windows ./... and GOOS=linux
  -tags nogui ./... clean.
- GUI, earlier at 807048470 on mote: gateway-key-readonly,
  gateway-key-quotas, i18n-keys, gateway-card, api-key-theme,
  gateway-connect-keys and gateway-caller-keys 34/34 in both engines.
  At this tree mote's WebKit hung at launch for every test (#4125), so
  the 43 gateway-*/key-*/api-key-*/caller-*/menu-*/i18n-* files ran on
  Linux (wsl-run, both engines): 501 of 514. The reds in api-key-theme,
  gateway-key-limit, gateway-key-models, key-replace and menu-input-scroll
  are red the same at origin/main e8d42c02d (#4120, #3523, #4081, #4126,
  #3402); gateway-keys-empty's WebKit wait was red 1 in ~13 runs here and
  0 in 4 at main, filed as #4383 (this change doesn't touch its path).
- Full Go suite on Linux (wsl-run, at 807048470 with this change): reds
  only where Linux can't build the GUI (no gtk4/webkitgtk) and in
  internal/agent's install tests (#4033) and the gateway reds above,
  each red the same at origin/main dca3e2d71; plus
  TestClientPathCoversHandler, which parsed Handler's source and is now
  read from routes() (fixed here).

Not tried: a real ESP32 or Docker magpie; a remote client against a
running gateway (only httptest through lanGuard/Handler); the Windows
test runs (vet only); the whole GUI suite (mote's WebKit hung, #4125).
2026-10-30 14:33:01 +08:00
yetone 764a032f6f gateway: a thinking block Claude says is another conversation's is left out and asked again (ferock)
ferock (Discord, 10-30): Command Code requests sometimes fail with 400
"messages.3.content.20: Invalid signature in thinking block. The block
is bound to a different conversation ...". The client's history carries
thinking blocks signed for another conversation or account (a switch,
a fork, another provider), and the plugin passes the Messages body
through as written, so this is fixed in magpie, not the plugin.

forward(), which every Anthropic-protocol route goes through (relayed,
translated, plugin fetch, count_tokens), now reads that refusal
(thinking_bound.go). It remembers the block it names and every thinking
block after it, for that provider and account only, then asks again
without them. An assistant message left empty is dropped. The next turn
leaves them out at once. Other 400s, and other providers, keep every
block byte for byte. The drop_block beta isn't sent: Claude Code sends
it only behind a flag, and magpie doesn't mimic Claude Code.

Run (mote, at this head rebased on cae785a37):
- go test -run 'TestBoundRefusalRead|TestBoundThinkingLeftOut|
  TestOtherRefusalKeepsThinking|TestWithoutThinkingBlocks|
  TestPluginBoundThinkingLeftOut|TestPluginThinkingOff|TokenField|Beta'
  ./internal/gateway: ok
- go test -count=1 -timeout 45m ./internal/gateway (before the rebase):
  every test ok except five Antigravity/Grok tests. They are red the
  same way on origin/main e8d42c02d, and #4362 covers them.
- gofmt -l clean; go vet ./internal/gateway for darwin, linux, windows: ok

Broken by hand:
- the retry turned off: TestBoundThinkingLeftOut and
  TestPluginBoundThinkingLeftOut go red with ferock's exact 400
- only the named block dropped, not the ones after it: red, because the
  fake refuses message 5's block next

Not tried: a real Command Code account (the fake replays ferock's
literal error). The full ./... suite hasn't run yet. Claude
subscription accounts go through the bridge and are not covered here.
2026-10-30 14:20:39 +08:00
yetone cae785a37a chat: max_completion_tokens to OpenAI's own API, and the other name once a 400 asks for it
GoxxKintBlade on X (tweet 2116038360645206158, v0.1.2145) and Jothulmo
(tweet 2116045916549652992): an OpenAI API key provider's test was red
for every model, "gpt-6.1-sol: 400 Unsupported parameter: 'max_tokens'
is not supported with this model. Use 'max_completion_tokens' instead."

Cause: the model test's Chat body (provider.tinyBody) sent max_tokens
to every host but Bedrock and Azure. The gateway had the same gap on a
pass-through: a chat client's max_tokens (and magpie's own image
describer and classifier, which ask the gateway in Chat with max_tokens)
went to api.openai.com as sent. Only the Anthropic/Responses-to-Chat
translator (buildChat) already used max_completion_tokens there.

Fix, scoped by vendor:
- provider.OpenAIHost: openai.com and *.openai.com only (not Azure,
  not "notopenai.com", not a relay).
- The test's Chat body asks OpenAI's own API with max_completion_tokens.
- The gateway's forwardOnce, the one place every upstream request
  passes, renames max_tokens to max_completion_tokens for OpenAI's own
  API (chatTokenField). DeepSeek (deepseekTokenField), Zhipu and relays
  get the body as the client sent it.
- A Chat 400 whose words name the other field as the one to use
  (provider.TokenFieldWanted: "use 'max_completion_tokens'" or "use
  max_tokens"; a limit on the value is not one) is asked once more with
  that name, in the model test (probe) and in the gateway (forward,
  retryTokenField), and the gateway remembers it per provider in unfit.
  That covers a relay in front of OpenAI's reasoning models. The key is
  renamed in place (provider.WithTokenField), so the rest of the body
  keeps its bytes.

Tests (new): TestOpenAIProbeAsksMaxCompletionTokens,
TestProbeRetriesTokenFieldNamed, TestTokenFieldWanted, TestWithTokenField
(internal/provider); TestOpenAIChatGetsMaxCompletionTokens,
TestChatTokenFieldRetriedWhenNamed (internal/gateway). The last one also
checks that a vendor reading max_tokens gets the body as sent, in one
request; TestDeepSeekChatGetsMaxTokens still passes unchanged.

Broken by hand: OpenAIHost taken out of tinyBody, probe's retry turned
off, chatTokenField and retryTokenField returning early. All four new
behavior tests went red with real FAILs (the probe test: "Status:400 ...
Use 'max_completion_tokens' instead."; the gateway retry test: HTTP 400
from the relay), and green again with the change put back.

Run on mote (mote-run): gofmt -l internal/ (nothing),
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... (VET-OK),
go test -timeout 45m -count=1 ./internal/provider ./internal/gateway
at base dca3e2d71: internal/provider ok (340s); internal/gateway was
still running at push time. Rebased onto e8d42c02d (6 commits, which
change both packages), then at this head on mote: gofmt -l (nothing),
linux and windows go vet ./internal/... (VET-OK), and go test -count=1
-run "TokenField|OpenAIProbe|OpenAIChat|DeepSeekChatGetsMaxTokens|
Bedrock|Azure|Mantle|TestModels|TestTest" on both packages: ok.

Not tried: a real OpenAI key (no real network in tests; the fixture is
OpenAI's own 400 text from the report). The full ./... suite runs on
mote after the push.
2026-10-30 14:17:26 +08:00
yetone e8d42c02db gateway: a masked request tells the model its placeholders are used as written (treeMan)
treeMan on Discord: with masking on, weaker models refuse to search
with a {{NAME_xxxxxxxx}} placeholder, ask to verify it, or rewrite it as
"an example name", which breaks long tasks. A request in which masking
swapped a value (maskHits.n > 0) now carries one short note, on each try:

  Values written like {{NAME_ab12cd34}} are placeholders for real values.
  Use them exactly as written, in replies and in tool calls alike: they
  are filled in with the real values before anything runs. Don't ask to
  verify them, and don't replace them with examples.

It names neither magpie nor a vendor or client (TestPlaceholderNoteIsNeutral
fails on magpie, Codex, Claude, a vendor's name, "provider", "gateway"...).
Its example uses a '1', outside the placeholder alphabet, so it is never
taken for a real placeholder or restored.

Where: where placeholders first appear, so it is new text the first time
and the same text on every later turn (the cached prefix holds). In the
instructions when they or the tools hold one (Anthropic system's last
block, Chat's first system/developer message, Gemini systemInstruction's
parts); otherwise on the earliest message that holds one, as a block or
part after its content (a string content becomes [text, note] blocks on
Anthropic, a paragraph on Chat), and on Responses as a developer message
after that item and the tool outputs following it. Responses
`instructions` (Codex's base_instructions) is never touched. A note
appended after text starts with a blank line, so a translator that joins
blocks (Anthropic to Chat) keeps it apart from the user's words.

Not added:
- a Claude subscription: the bridge puts the caller's instructions into
  the run's first message, which Anthropic classifies; text added there is
  risk for no gain;
- a ChatGPT/Codex sign-in (Account.Agent codex); Codex's own turns on
  codexUpstreamOn don't pass this loop either;
- a Responses turn with previous_response_id: the note would pile up in
  the stored conversation.
count_tokens counts without it.

A first version put the note in the system prompt. The full suite showed
TestMaskedConversationKeepsItsCachedPrefix red (a secret first found in a
tool output changed the system at turn 1 and rewrote the cache), hence
the first-appearance placement.

Run (mote, through mote-run):
- go test ./internal/gateway ./internal/redact -run
  'TestPlaceholderNote|TestMaskedRequestTold|TestMaskedConversation|
  TestUnredacted|TestRedacted|TestMask|TestMiddlewareThroughGateway': ok.
- Full suite at 46bdbad8f (-timeout 45m, log kept whole): red in
  internal/gateway TestMiddlewareThroughGateway (mine: its fake echoes the
  last message, which now holds the note; the fake strips it now), and
  five tests red alone on origin/main cc81ad4ea too, filed as #4362
  (TestAntigravityTurnsCodexsGPT5ThreadAwayOnce, TestAntigravityTurnedAway*,
  TestCodexSpentGrokFailingIsTold); internal/gui TestMainWindowCorners
  (#3949). Every other package ok.
- At 79c6a487c (this change on cc81ad4ea): go test -timeout 45m
  ./internal/gateway ./internal/redact ./internal/masking/...: redact and
  masking ok; gateway red only in the five #4362 tests.
- go vet ./internal/gateway ./internal/redact on macOS, CGO_ENABLED=0
  GOOS=windows go vet ./... on mote, go vet of both in WSL (Linux): ok.
  (CGO_ENABLED=0 GOOS=linux go vet ./... stops in wails' menu_linux.go on
  main too, so Linux was vetted natively.)

Broken by hand:
- note always in Anthropic's system (`if true ||`):
  TestMaskedConversationKeepsItsCachedPrefix, TestPlaceholderNotePlaces,
  TestMaskedRequestTold and the TestUnredacted* echo tests red.
- wiring off in serve: TestMaskedRequestTold red.
- the claude/previous_response_id skips removed:
  TestPlaceholderNoteNotOnClientPaths red.

Not tried: no real vendor or weak model was run with the note, so whether
it stops the refusals treeMan saw is not measured; no real Claude
subscription or Codex sign-in request (both skipped by design).
2026-10-30 14:08:22 +08:00
yetone dafe4af822 gateway: the ChatGPT backend's "auto"/"default" tier is recorded as unknown (jjt on Discord)
The ChatGPT Codex backend says service_tier "auto" in response.created
and "default" in response.completed whether priority ran or not. jjt's
measurements on gpt-6.1-sol with a Plus account: Fast decodes at about
200 tok/s, without it about 110, and the reply says "default" both times
(real-priority.sse, speed-plus.txt). magpie copied that into tier_served,
so the usage log, its CSV and /v1/magpie/route said served = default for
requests that ran Fast.

servedTierAt (tier_record.go) leaves those two words empty when the
reply came from CodexBase's host. It is applied once per routed try, in
attempt (gateway.go, a defer, so every return path and the route's tries
see it), and on the relay of Codex's own sign-in (codexUpstreamOn).
OpenAI's API, where service_tier means what it says, keeps it as given:
a provider at api.openai.com and Codex with an sk- key relayed to it.
"priority" or "ultrafast" said by the ChatGPT backend is still kept.

Display: tier_served is shown by the CSV (an empty cell), the JSON log
and /v1/magpie/route (omitempty). No GUI page or TUI shows a tier
(grep of internal/gui/assets and internal/tui for tier_served,
tier_asked, tierServed: none), so no strings changed. docs/reference.md
and docs/subsystems/gateway-routing.md say it.

Tests:
- TestChatGPTBackendTierUnknown (new): the backend says auto, then
  default (jjt's events, cut to the fields read); a routed try asked
  priority and one asked nothing, and Codex's own sign-in relayed, all
  record "" in usage and the route.
- TestOpenAIAPITierKept (new): api.openai.com's "priority" and
  "default" kept, routed and through the sk- relay.
- TestTierRecordedPerTry: its "none asked" case on the ChatGPT backend
  now expects "" where it expected "default".

Run on mote (mote-run; the wider run at base cc81ad4ea, the tier run
again after the rebase, at this commit on c37b8b659: ok, 22 pass):
- go test ./internal/gateway -run 'Tier|ChatGPTBackend|OpenAIAPI'
  -count=1 -v: ok, 22 tests pass.
- go test ./internal/usage: ok. go test ./internal/gateway -run
  'Codex|Usage|Route|Tier': two reds, TestAntigravityTurnsCodexs-
  GPT5ThreadAwayOnce and TestCodexSpentGrokFailingIsTold, red the same
  on a fresh origin/main c37b8b659 and filed as #4362; the rest ok.
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: clean.
- gofmt -l internal/gateway: clean.
Broken by hand: servedTierAt returning t unchanged -> TestChatGPT-
BackendTierUnknown and TestTierRecordedPerTry red ("served default");
the host check removed -> TestOpenAIAPITierKept red (served "", want
"default"). Both green again with the fix.

Not tried: a real ChatGPT account through the built gateway; the full
Go suite (the coordinator asked for the targeted run under mote's load
of ~200); Windows and Linux test runs (vet only). No GUI file reads the
tier, so no GUI test was run.
2026-10-30 13:57:36 +08:00