Commit Graph
1402 Commits
Author SHA1 Message Date
yetone 9d4a4bfd3f gateway: a late Claude Code call tells the client after 500ms, not 1s
In Claude Code's interactive mode a call of a client's tool waits callFirst
for its message in the transcript before the call tells the client itself.
Measured on a real account (a probe build logging the time from the MCP call
to the transcript's tool_use), a message written before its call was read
118 to 162ms after the call came in, 8 calls of 8. 500ms leaves it room and
halves what a late message costs.

Run: go test -race -count=3 -run 'TestClaudeTUI|TestSubscription'
./internal/gateway on mote, ok. Real account (claude-haiku-5-5, sandbox
HOME, interactive TUI): 9 runs of the one/two/text scenarios, all ok, every
call told once with its own id; 1 took the late path, none fell back to -p.
Not tried: sonnet/opus, Linux.
2026-10-31 04:35:16 +08:00
yetone e647a1fd54 plugins: an npm registry of the user's own is used for installs and lookups (timwangdev on X)
timwangdev asked on X for plugins to take a custom npm registry. Zero-config
first: Registry() (internal/plugin/registry.go) takes, in order, the one set
in magpie (settings npmRegistry: `magpie plugin registry <url>|default`, or
Plugins › Discover's new npm registry row), BUN_CONFIG_REGISTRY /
NPM_CONFIG_REGISTRY / npm_config_registry in magpie's environment, then the
login shell's (cached probe only, proc.LoginEnvKnown, never waits on a
shell), install.registry in the plugins folder's or the user's .bunfig.toml,
registry= in the plugins folder's or ~/.npmrc, then the 国内镜像 switch's
npmmirror, then npm's own. The switch no longer puts npmmirror over a
registry the user named: before, bun was handed BUN_CONFIG_REGISTRY=npmmirror
whenever it was on, over the user's .npmrc. bun is told the registry only
where it wouldn't find it itself (magpie's setting, the shell's, the
switch's). magpie's own npm questions (latest version for the market,
Update and the hourly check, README, search) go to the same registry, a
package's @scope:registry= to that scope's, with the .npmrc's
//host/path/:_authToken (${VAR} expanded, longest prefix) sent to that host
alone, dropped on a redirect to another host, never logged or shown.
Download counts stay npm's. Only http(s) with a host, no userinfo, query
or fragment is taken; anything else is refused and not saved, and a bad
value hand-written into settings.json is passed over. /api/plugins says
which registry is in use and where it came from.

The GUI row is in registry.js, imported when Discover draws it, so the
core script budget isn't raised (plugins.js is 292 bytes smaller than
before, one long comment there condensed).

Left out: bunfig [install.scopes] for magpie's own lookups (bun reads them
for installs), .npmrc _auth and username/password, NPM_CONFIG_USERCONFIG
and npm's global npmrc, and internal/agent/cliupdate.go's agent CLI update
lookups, which still ask npm's own.

Run (mote and wsl-run). First at this change on 2ac423f4f:
- go test ./internal/plugin/ ./internal/source/ ./internal/gui/
  ./internal/proc/ ./internal/cli/ ./internal/settings/ -timeout 45m:
  plugin, source, cli, settings ok. gui: only the real-window AppKit tests
  killed at their deadline on mote (dock, panel, titlebar, tray; #2645,
  #4125), TestCoreScriptBudget and TestSettingsSaveKeepsWhatItDoesNotSend
  green after the fixes in this commit. proc: TestNoCommandBypassesProc red
  on origin/main itself (internal/claudetui/tui.go:183), filed as #4491.
- gofmt -l internal: clean. GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok.
- GUI (wsl-run, magpie-desktop): plugin-registry.test.cjs in Chromium and
  WebKit, 5 languages each, 980px and 380px; i18n-keys, old-webkit and
  plugin-market (WebKit): 19/19 pass. On mote the browser runs timed out
  launching (#4125).
Again at this tree rebased on fa5e86cf2 (upstream changed app.js and
i18n.js): go build ./...; go test ./internal/gui/ ./internal/cli/
./internal/plugin/ ./internal/settings/: cli, plugin, settings ok, gui only
the same ten AppKit window tests killed on mote (#2645, #4125), the core
budget green; gofmt clean; plugin-registry (Chromium, WebKit), i18n-keys
and old-webkit on WSL: 22/22 pass.
Rebased once more on 45de2ddb9 (app.js and i18n.js again): gofmt clean,
go vet of gui and plugin ok, TestCoreScriptBudget and
TestSettingsSaveKeepsWhatItDoesNotSend ok, i18n-keys 4/4.

Broken by hand, each red, then restored:
- A: old registryEnv (npmmirror whenever the switch is on):
  TestBunTakesTheUsersRegistry red.
- B: lookups always to npm's own: TestLookupsAskTheUsersRegistry red.
- C: no URL check: TestSetRegistryRefusesWhatIsntOne red.
- D: the switch before the user's registry: Precedence, BunTakes and
  Lookups red.
- E: no token sent: Lookups red.
- F: scopes ignored: Lookups red.

Not tried: a real private registry (Verdaccio, GitHub Packages, Nexus) with
a real token; a real bun install through one; Windows (the login shell
probe is a no-op there, so only env, bunfig and .npmrc apply).
2026-10-31 04:24:59 +08:00
yetone 45de2ddb96 provider: a provider the user counts free goes first under Free first (jiabubu on Discord)
jiabubu asked on Discord #help for a way to mark a provider, model or key
as free, so that Free first routing spends it first. Their example is
ModelScope, which has a free daily quota. Until now routes.Seat.Free
came only from the vendor catalog's Free flag, and there was no way for
the user to set it.

Provider.CountFree ("Free for me" in the provider editor's Advanced fold,
`magpie provider set <id> free=yes|no` in the CLI) makes FreeModel true
for every model of that provider. Routing therefore treats it like a
vendor's free model: Free first uses it before paid ones, and Cheapest
first weighs it at nothing, because PriceAt, which only routing reads,
returns 0 for a free model. Prices shown (ListPrice and the model list)
and the costs Usage counts (EffectivePrice) are unchanged. The mark says
what to spend first, not what a call cost, and a quota that runs out
still bills at the listed price. Key and account (subscription)
providers both carry it, through withPicks, the account literal and the
copy merge.

Tests:
- internal/gateway TestFreeFirstSpendsTheProviderTheUserCountsFree:
  - a Free first group [paidv/m, mine/m] sends its first call to mine
    once mine is marked, and the trace row says Free;
  - EffectivePrice is still the listed 3/15;
  - Cheapest picks mine first;
  - unmarked, paidv goes first again.
- internal/gui TestProviderSaveKeepsCountFree: the preset and typed-in
  providers save the mark and clear it, and /api/providers reports it.
- internal/cli TestProviderSetFree: free=yes and free=no work; the value
  shows in `provider <id>`; free=maybe, an empty value and --help are
  refused and change nothing.
- GUI internal/gui/tests/provider-count-free.test.cjs covers the
  ModelScope preset, a custom provider saved with the mark, and a Codex
  account. It runs chromium and webkit, in en, zh, zh-TW, ja and de, at
  widths 900 and 440. It checks the Advanced fold, the check and save
  POST bodies, that the row fits with no sideways scroll, and that each
  string has a translation in I18N.

Core script budget: rebased on fa5e86cf2, the core's scripts came to
1,538,236 bytes, 880 over coreScriptBudget, which TestCoreScriptBudget
caught. The budget is not raised. countFreeField's comment and five
long comments on the editor's helpers (proxyPicker, concurrencyField,
priceRateField, pluginOptionsField) are cut down, so app.js ends 212
bytes smaller than before this change.

Run (mote via mote-run, at this change's tree on base 8ee75adbf):
- go test of internal/gateway (-run FreeFirst|InOrder), internal/gui,
  internal/cli and internal/provider: ok.
- GUI test: chromium 30/30 on mote. WebKit could not launch on mote at
  all at the time (a bare webkit.launch probe timed out at 60s, and
  other sessions' WebKit launches were stuck there too). WebKit was run
  on Linux instead (wsl-run, magpie-desktop): 30/30.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./... ok; go build for darwin, linux (nogui) and
  windows ok.
- At the pushed head (rebased on fa5e86cf2, comments cut): go test of
  internal/gui, internal/cli, internal/provider and internal/gateway
  -run FreeFirst|CountFree ok (internal/gui was red only on
  TestCoreScriptBudget before the cut); node --check app.js ok; the GUI
  test in chromium 30/30.
- The full Go suite (go test -tags nogui -timeout 45m ./...) is still
  running on mote at ship time, per the owner's ship-at-once rule. Any
  red it finds gets a follow-up commit. The whole GUI suite was not run:
  mote's WebKit cannot launch and the Linux box was running other
  sessions' GUI suites.

Broken by hand:
- With the CountFree line taken out of FreeModel, all three Go tests
  went red, e.g. 'Free first went to "paidv" (free false) first'.
- With `pr.CountFree = in.CountFree` taken out of the preset save
  branch, TestProviderSaveKeepsCountFree went red ("the preset's mark
  wasn't kept").

Not tried:
- A real ModelScope account; the tests use fake upstreams.
- A per-model mark (optional in the request); the mark is
  provider-wide.
- The TUI editor (the CLI setter covers the terminal).
2026-10-31 04:21:21 +08:00
yetone c799934e1b claude: the gateway logs why a run is -p
Finding why the real-account runs went -p (the previous two commits'
end-to-end) took reading a run's stderr by hand: the bridge keeps Claude
Code's stderr for an error only, and claudeTUI said nothing of why it
chose -p.

claudeTUI's conditions move into claudePrintWhy, which names the one
that held ("Claude Code in WSL", "a JSON schema", "the interactive mode
is turned off", ...), and claudeTUI logs "claude: this run is -p: <why>"
(not in the tests' binary, claudeTUIRuns off). lockedWriter logs the
helper's "claude-tui: ...; this run is -p" line (a failed start, an
untrusted folder, the 30-minute mark) as "claude: ...". The rest of
Claude Code's stderr is kept as before and not logged.

Run:
- mote: go test -count=1 -run TestClaudeTUI ./internal/gateway ok:
  TestClaudeTUIChosen now checks each case's reason,
  TestClaudeTUIFallbackLogged the helper's line logged and nothing else.
  go vet ./internal/gateway on darwin, linux, windows; gofmt -l clean.
- Real account, sandbox HOME, a gateway on this build: before the trust
  fix, the helper's line is what named the cause ("Claude Code ended
  before it showed its prompt (exit status 1): B").

Broken by hand: the log in lockedWriter taken out:
TestClaudeTUIFallbackLogged red (logged "").

Not tried: the log on Linux.
2026-10-31 04:20:10 +08:00
yetone 123d72be68 claude: a call Claude Code makes before writing its message is the reply
In the interactive mode the bridge learns of a call from the session's
transcript. Claude Code sometimes writes the message holding a client's
tool_use only after that MCP call returns (4 of 8 real runs before this).
The call waits on the client, and the client waits for the call it was
never told of: a deadlock until the run's timeout.

mcpCall now hands each call to run.onCall, which readOutput sets for a
TUI run. If callFirst (1s) after the call it isn't in the transcript yet
and still waits, the call itself becomes the reply: a message with one
tool_use and stop tool_use, with the MCP helper's id, name and arguments
(the id is the transcript's, from _meta "claudecode/toolUseId"). The
message written after such calls is the late one: its rows aren't told
again (lateID), a call in it not yet told is told by its own turn
(written), and its usage is counted in the next reply. Such a reply has
no words or thinking; the model's text before its call is lost to the
client. -p runs don't set onCall and are unchanged.

docs/subsystems/claude-subscription-bridge.md has the paragraph.

Run:
- mote: go test -count=1 -race -run TestClaudeTUI ./internal/gateway ok
  at this tree; earlier, -race -count=5 of the new tests ok.
- TestClaudeTUICallBeforeItsMessage (output 47 = late 40 + answer 7),
  TestClaudeTUICallAfterItsMessage (told once, output 7),
  TestClaudeTUIParallelCallsBeforeTheirMessage (written after both, and
  between).
- mote: go vet ./internal/gateway on darwin, linux, windows; gofmt -l
  clean. go test -timeout 45m ./internal/gateway ./internal/claudetui
  ./internal/claudebridge ok before the previous commit's rebase
  (gateway 522s); a run with all three commits is going.
- Real account, sandbox HOME, a gateway running this build, haiku: "two
  calls in one message" logged "Claude Code called get_secret before
  writing its message; the call is the reply" for both calls, and the
  client got red then blue as two replies and the answer naming both
  secrets. One call, and words then a call: answered from the
  transcript. Every row "entrypoint":"cli".

Broken by hand: onCall never called: the three tests red ("deadlock").
lateID never set: the late message told again, red.

Not tried: sonnet or opus in the real run (haiku only); a call whose
client takes longer than the run's timeout.
2026-10-31 04:20:10 +08:00
yetone faaba45236 claudetui: the folder-trust question is answered Yes only once Yes is drawn
The real-account end-to-end through a running gateway found every
interactive run going to -p. The gateway's working folder
(magpie-claude-work-<uid>) wasn't yet trusted under the account's config
dir, so Claude Code 2.1.314 asked whether to trust it, with "No, exit"
chosen. The helper pressed down and then, 300ms later, Enter without
looking. Its down was lost when sent as the question was first drawn
(the question is drawn again on No), Enter chose "No, exit", and Claude
Code ended with status 1 (screen: "B"). The start failure marked the
interactive mode broken for 30 minutes and every run went to -p, so
v0.1.2266's default did nothing on a fresh account.

ready() now reads the choice as the last of "❯ No, exit" / "❯ Yes, I
trust" drawn, presses down (at most once a second) while No is chosen,
and Enter only on a Yes that stayed drawn for 300ms (trustSettle). The
test's fake asks as the real one does: words placed by cursor moves, No
chosen first, keys in its first 150ms lost, and drawn again on No; Enter
on No exits 1.

Run:
- By hand: real Claude Code 2.1.314 in a PTY in the gateway's folder,
  sandbox HOME with a real account's config dir: the question opens on
  No; a down sent at once is undone by the redraw, one sent 0.3s or 1.5s
  in moves to Yes.
- mote: go test -count=3 -run TestShim ./internal/claudetui ok; go test
  ./internal/claudetui ok; go vet ./internal/claudetui on darwin, linux,
  windows; gofmt -l clean.
- Real account, sandbox HOME, a gateway running this build (and the next
  commit's), haiku: a tool call, two calls in one message, words then a
  call: all answered, every transcript row "entrypoint":"cli", no broken
  mark.

Broken by hand: the old ready() with the new fake:
TestShimTrustsWhenTold red, "Claude Code ended before it showed its
prompt (exit status 1)", the real failure.

Not tried: Linux with a real Claude Code; a Claude Code version whose
question words differ (it then waits out 45s and goes -p, marked).
2026-10-31 04:20:10 +08:00
yetone 2ac423f4f2 kimi: a Kimi Code plan model is told always_thinking, dynamically_loaded_tools and its default effort, as Kimi's list says (jiabubu)
jiabubu on Discord (Kimi Code 2.2.0, Windows): Kimi Code's own provider
gives K2.8 Preview and K3.1 Pro the capabilities thinking,
always_thinking, image_in, video_in, tool_use and
dynamically_loaded_tools; through magpie they had thinking, image_in and
tool_use, so Kimi Code offered a thinking switch the models refuse to
turn off, and started K2.8 on high where Kimi's own starts it on max.

Kimi Code 2.4.1's managed provider (packages/oauth managed-kimi-code.ts,
capabilitiesForModel) derives them from /coding/v1/models:
supports_thinking_type "only" -> thinking + always_thinking,
supports_dynamic_tools -> dynamically_loaded_tools, supports_video_in ->
video_in, think_efforts.default_effort -> the default. magpie now reads
the same fields (flat, or nested reasoning.type, tools.dynamic_load,
reasoning.effort.default) into catalog.Model (AlwaysThinks,
DynamicTools, DefaultEffort; kimiFacts), carries them through
provider.Entry and the agent's model list, and the new Kimi Code's table
gets always_thinking, dynamically_loaded_tools and default_effort at the
vendor's default (else high, as before). Only Kimi's list sends these
fields, so another vendor's model is written as before; kimi-cli, which
refuses unknown words, gets none. A routing group has none of them.

default_effort is now recorded in the stash as magpie's (kimiOwn), so a
level the user picked stays while the model has it. A table with high
and no record is read as the high magpie wrote before it kept one, and
becomes the vendor's default (max on K2.8, high on K3/K3.1).

Left out:
- video_in: with type="kimi" Kimi Code uploads a video to
  {base_url}/files (purpose=video) and sends the ms:// id. The gateway
  has no /files route, and the id belongs to the account that stored it.
  Filed as #4485.
- dynamically_loaded_tools works (Kimi Code's tool select is behind
  KIMI_CODE_EXPERIMENTAL_TOOL_SELECT): the loaded tools' system message
  is lifted into the request's tools (liftMessageTools, #2322), so they
  stay callable (TestKimiCodeLoadedToolsReachKimi), but each load
  restarts Kimi's prompt cache. Filed as #4486.
- max_output_size: Kimi's own provider writes none; magpie keeps writing
  the model's known reply cap (32768 on K2.8 per models.dev), unchanged.

This also covers #3399 (K3.1 offered thinking off): Kimi's list says
"only" for both K3.1 models.

Real list: tests read Kimi's /coding/v1/models reply of 2026-10-31
(internal/catalog/testdata/kimi-code-cn-models-2026-10-31.json, read
with the owner's kimi-code-cn key, no key in the file).

Run (mote, at this commit on origin/main b62fa332f; the agent-wiring.md
line was added after the run, docs only):
- go test -tags nogui -count=1 -timeout 45m ./... : 79 packages ok;
  internal/proc (TestNoCommandBypassesProc) and internal/sqlitedb
  (TestOnlyThisPackageReachesSQLite) red on a Go module cache my e2e
  sandbox had left inside the run folder (vendor files under
  e2e-kimi/sb/home/go/pkg/mod); with it removed both ok.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./... ok; gofmt -l clean.
- Real Kimi Code 2.4.1 (npm) in a sandbox HOME/KIMI_CODE_HOME on mote,
  with a sandbox magpie serve (MAGPIE_ADDR 127.0.0.1:34652), the
  kimi-code-cn preset pointed at a fake upstream that serves the real
  list: magpie wrote the six tables (K2.8: thinking, always_thinking,
  image_in, tool_use, dynamically_loaded_tools, support_efforts low/high/
  max, default_effort max; K2.7 Highspeed without
  dynamically_loaded_tools), Kimi Code took the config, and `kimi -p`
  reached the upstream with thinking enabled and reasoning_effort max
  (K2.8) and high (K3.1 Pro).
- Rebased onto 43966a53f..f2eb56c6b (claude, GUI budget, usage; none of
  them touch these files) as f5a82f215, then again at this head:
  internal/agent, internal/catalog, internal/provider ok, internal/gateway
  -run 'Kimi|MessageTools|Lift' ok. The full suite was not rerun there.

Broken by hand, each red then green:
- kimiFacts not called: TestFetchKimiCodeFacts and
  TestKimiCodePlanCapabilities red.
- fields not carried in route.go / entryFor: TestKimiCodePlanCapabilities
  red.
- the unrecorded-high rule off: TestKimiCodeOldHighBecomesTheVendorsDefault
  red.
- always_thinking without the !legacy guard: the kimi-cli case red.

Not tried: the TUI picker by eye (that the thinking switch is gone);
tool select with a real MCP server and the experimental flag; Windows
(the reporter's system; nothing here is OS-specific); a real Kimi
upstream through magpie (the list was real, the chat was a fake).
2026-10-31 03:27:34 +08:00
yetone 43966a53fb claude: a subscription's run is Claude Code's interactive mode, -p only as the fallback
The owner (10-31): a Claude subscription ran `claude -p`, whose
requests Anthropic labels sdk-cli and counts at about twice the
interactive mode's cli (anthropics/claude-code#97074). Running the real
interactive Claude Code is what its terms describe and uses the plan as
a person does. Wanted inside magpie, on by default, with a way off.

`magpie claude-tui-helper <claude> <-p args>` (internal/claudetui)
stands where `claude -p` stood and speaks the same stream-json. It
turns the -p arguments into the interactive mode's (no -p, no
--dangerously-skip-permissions: --permission-mode default with only
mcp__magpie, and the WebSearch -p was given, allowed; --no-chrome;
--session-id or the --resume given), starts Claude Code in a
pseudo-terminal of its own (no tmux), pastes each message into its
prompt and presses Enter, and tells the session's transcript back as
-p's lines: whole assistant messages, an API error as the turn's error
result with its rate_limit_info, turn_duration as the result. Nothing
sets CLAUDE_CODE_ENTRYPOINT, and the user's ~/.claude and
~/.claude.json are never written. The folder-trust question is
answered only for magpie's own folder or a saved account's config
directory (MAGPIE_CLAUDE_TUI_TRUST).

A Claude Code that doesn't start or show its prompt in 45s becomes
`claude -p` on the same pid, its input still unread, so the turn is
answered all the same; that is remembered for 30 minutes
(<cache>/magpie/claude-tui-broken). An untrusted folder goes to -p
without the mark.

claudeTUI keeps -p for Windows and WSL, Settings › Models › Replies ›
Claude Code's interactive mode Off (claudePrintMode), safeguards,
client cache marks, a JSON schema, images and a first message over
400KB. A TUI run ends instead of taking an image turn, a rewind or an
effort change, and letGo doesn't take one back. The gateway's tests
run with claudeTUIRuns off: their binary has no claude-tui-helper.
docs/subsystems/claude-subscription-bridge.md has the section.

The core's scripts grow 725 bytes with the setting's row;
coreScriptBudget is raised to the exact size, 1,537,356, with no room
added.

Run (rebased on f2eb56c6b and its budget fix):
- mote: go vet of claudetui, gateway, cli, settings on darwin;
  GOOS=windows of claudetui, gateway, cli; GOOS=linux of claudetui,
  gateway; gofmt -l clean.
- mote: go test ./internal/claudetui: TestShimTurnsInteractive (a fake
  interactive Claude Code in the PTY: two turns, a /help pasted as
  words, the arguments it was given), TestShimFallsBackToPrint (failed
  start marks broken; untrusted folder doesn't), TestShimTrustsWhenTold,
  TestPasteable, TestTranslatorAPIError.
- mote: go test ./internal/gateway -run TestClaudeTUIChosen (plain,
  off, WSL, safeguards, cache marks, schema, image, long prompt),
  TestClaudeLean*, TestCleanClaudeEnv.
- mote: go test -timeout 45m ./internal/claudetui ./internal/cli
  ./internal/settings ./internal/gateway: all ok (gateway 524s).
  go test -run Budget ./internal/gui: ok after the raise below.
- Linux (magpie-desktop): go test ./internal/claudetui ok natively,
  the PTY's Linux ioctls among it. GOOS=linux go vet -tags nogui of
  cli, gateway, claudetui, settings ok.
- Linux box, Playwright 1.62, chromium and webkit: claude-tui-setting
  16/16, claude-lean-prompt-setting 16/16, i18n-keys 4/4, mobile-web
  30/30 against 74f1df869's tree. mote's WebKit didn't launch (other
  sessions' GUI suites, running 11-16h, held ~108 WebKit processes),
  so the GUI ran there instead.
- Real Claude Code 2.1.314 on a real Claude account's magpie config dir,
  haiku, through the built helper with the bridge's exact -p arguments
  (an MCP server named magpie with one tool, --tools "",
  --system-prompt-file, --thinking disabled, --effort low,
  --thinking-display): the tool was called without a permission prompt
  and its answer used; the system prompt's end token in every reply;
  a second turn on the same run; a later run with --resume remembered
  the first. All 18 transcript rows say "entrypoint":"cli". Startup to
  init 0.7–1.5s, a haiku turn 1.4–4s. Two messages sent at once are
  one turn, as Claude Code queues them.

Broken by hand:
- each claudeTUI condition taken out in turn (WSL, safeguards, cache
  marks, schema, images, the setting, the 400KB bound): its case red.
  The WSL case first passed with the check gone (its claudeCLI had no
  path); given one, it is red without it.
- the trust check taken out of ready(): TestShimTrustsWhenTold red
  (the run went to -p).

Not tried: a turn through a running gateway into the helper on a real
account (a sandbox HOME would copy the sign-in into a new keychain item
and refresh it apart from the live one); a ~400KB paste; Linux with a
real Claude Code; an API error from the real service (the translator
is tested on its rows). The full go test ./... did not run (mote was held by those suites);
the four packages this touches ran whole.
2026-10-31 03:20:45 +08:00
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 7bc602236b library: the MCP hub is called the MCP router
The owner asked why it was a "hub". Composio calls the same thing a Tool
Router; "router" says what it does (one server that routes each call to
the right one), and "gateway" is taken by magpie's LLM gateway. Only
the words change: MCP router / MCP 路由 / MCP 路由 / MCP ルーター /
MCP-Router, "Router address", and the CLI's `magpie library mcp router
on|off`, where `hub` still works. The URL /mcp/magpie/hub, the mcpHub
setting, the servers/hub API and the Go names stay, so nothing a user
or an agent config holds changes. docs/subsystems/mcp-hub.md moves to
mcp-router.md and the pages that link it follow.

#4382's new words follow too: "Through the MCP router", "Not through
the router" and their hints in every language, and the CLI's
`magpie library mcp router <name> shared|direct` (`hub` works there
too; library_hub_test.go says router for direct, hub for shared).

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.
The CLI's TestProviderAddressMovesALocalServer red at -count=3 was
the same on origin/main 380032cda and is fixed in 65c792410.
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.
2026-10-31 02:49:08 +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
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 a5ccf3f23f plugins: an update of an unfixed git source re-resolves the branch, not the lock's old commit (#2954)
What changed
- Before Bun resolves a git plugin's spec, the branches and tags of its
  repository are fetched into the bare clone Bun keeps in its install
  cache (refreshGitCache in gitrev.go): best-effort before install's
  bun add (a remote that can't be reached leaves the install to what the
  cache has), an error before reinstall's bun update (an update that
  didn't happen is not reported as done).
- When bun update exits 0 but the plugin is still behind the commit the
  update checks saw the repository at, reinstall says so instead of
  claiming the update.
- A spec that names a commit (#<sha>) is left alone: nothing is resolved
  for one, and its pin stands.
- docs/subsystems/provider-plugins.md: this git update path.

Why
A plugin added from an unfixed git+https://... URL could not be updated
(#2954): plugins/package.json named no commit, but Bun resolves a git
spec through its own bare clone of the repository in the install cache,
whose refs stay at the first install - a fetch there moves FETCH_HEAD,
not the clone's refs/heads. Every resolve after the first, bun update as
much as a bun add after a remove, therefore named the old commit again,
bun.lock re-recorded it (name@git+...#bb961b2...), and the update said it
had installed while node_modules kept 0.1.3. The lock is the record of
that resolution, not its cause. Verified with Bun 1.4.2 (the version
magpie runs) against a local git+file:// repository: after the branch
moved, bun update my-plugin answered "no changes" and exited 0, and so
did bun install with the lock entry dropped, bun update --force and bun
install --force; with the clone's refs fetched, the same bun update
installed the branch's commit now.

Run
go test ./internal/plugin/ -count=1 (ok; new: TestGitUpdateInstallsTheBran
chsCommitNow and TestGitUpdateKeepsACommitPin on the bun on PATH against
a local git+file:// repository, TestGitUpdateSaysWhenItDidnt with the
fake bun keeping the lock's commit, TestRefFixed,
TestSameRepoAndCloneOrigin)
go test ./internal/cli/ ./internal/provider/ -count=1 (ok)
gofmt -l (clean); go vet ./internal/plugin/ on darwin, linux and windows
(ok); builds of darwin and of windows (CGO_ENABLED=0 -tags production,
as the Makefile cross-compiles it) and of the 79 Linux packages that
don't need Linux GTK cgo (the GUI and cli are built natively per machine,
as the Makefile says).

Review (magpie): patch sha256 checked against the issue; read whole.
Run at the batch head on the Mac mini: go test ./internal/plugin
-count=1 ok, the real-Bun git e2e among them (not skipped); on the
Windows box TestGitUpdate* pass. Broken by hand: store.go at the base -
TestGitUpdateInstallsTheBranchsCommitNow ("still at 1.0.0, want
2.0.0") and TestGitUpdateSaysWhenItDidnt red; only install()'s refresh
removed - "installed again: 2.0.0, want 3.0.0". Not tried: a real
plugin from a real GitHub branch.

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-31 02:00:10 +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 2604d68db0 routing: the live card stays on the request it tells of while others come at once
qiang2040 on Discord ("狂闪", a screen recording): with Codex
conversations sending at once on group/glm-5.3-flash-free and
group/deepseek-v4.1-flash, the Routing page's top card (head, story,
context window) jumped to the newest request on every trace update,
and to "magpie hasn't routed this request yet" for each new one.

told() picks the request the card tells of: it stays on the one it
shows until that one is done, then goes to the newest, and a newer
request routing hasn't picked for yet doesn't take it from one that
was routed. play(), resume(), the live poll and rebuild() use it;
requests that come meanwhile still fly on the stage, without a caption
of their own. Pinned, replay and day views are unchanged.

Run:
- routing-concurrent-hold.test.cjs (new; two conversations interleaved,
  every frame's head watched; en, zh, zh-TW, ja, de): red on the old
  code in Chromium (mote); green on this code in Chromium (mote and
  WSL) and WebKit (WSL).
- Broken by hand: told() returning newest() -> 6 of 6 red in Chromium
  and WebKit (WSL), "the card stays on 101 while it is under way".
- routing-* and panel-routing* in both engines on WSL, against a base
  worktree at origin/main: the reds are the same on base. row-swap is
  red 3/3 on base too (#3799); live-patch's folded sample caught a
  count-up mid-way once (129K vs 130K, the right request; #2174); the
  rest are WSL WebKit reds under #4121.
- go test ./... -timeout 45m on mote: 80 packages ok; internal/gui's
  10 real-window AppKit tests were killed at their deadlines (mote's
  pboard/launchd state, #4125; also #2645, #1936). This change is
  JavaScript only.
- The whole GUI suite (node --test, both engines) is still running on
  WSL at push time; reds it shows that aren't on file get issues.

- At the pushed head (rebased on 59bdd4dbc): the new test 12/12 green in
  both engines on WSL.

Not tried: the real app with several real Codex conversations sending
at once (the test drives a mocked trace). WebKit on the old code
(WebKit can't launch on mote now).
2026-10-31 01:04:08 +08:00
yetone 59bdd4dbc3 routing: a group's pattern members can be put in order by hand (usrname1833)
In a routing group, members a pattern added followed the catalog's
order. The editor gave them no grip or Up/Down, and the gateway tried
them in that order. Now every row gets the same grip, Alt+arrow and
Up/Down that named members have. Matched rows still have no Remove,
since the pattern decides those.

The order is stored as Group.Placed, keyed by provider/model as Members
spells them. It is nil while the order equals the default (named, then
matched in catalog order), so existing groups.json files don't change.
Read (withMatches -> placedIn): members follow Placed. A model matched
since goes after them, and one no longer matched drops out. The gateway
tries members in the order the group is read, so it follows the editor.
Saved (SaveGroup -> placedOver): Members orders the named members, and
Placed (sent, or the stored one when a save doesn't send it) places the
matched ones. A save that doesn't know Placed (card routing, the CLI's
models+=, TUI, import) keeps the matched where they were, and a model it
names newly goes after the last named one. A provider rename, fold,
group rename and RenameMember carry Placed along.

Run:
- go test -timeout 45m -count=1 ./... on mote: 80 packages ok.
  internal/gui fails 10 AppKit window tests at 30s (TestDockJoinLeadsCommandTab,
  TestPanelCloseHidesIt, TestMainWindowCorners, ...). On a fresh origin/main
  cf9ea977c the five I reran fail the same way. That is mote's #4125 (open).
- TestGroupPatternMembersKeepTheirPlace is red on the old code
  (read [zen/y or/a:free or/c:free]).
- Broken by hand, each red at its own step: no stored-Placed fallback
  ("after a named-only save"), a newly named model put last instead of
  after the last named one ("after an add"). On the earlier draft, no
  rename mapping ("after a rename").
- GUI: group-member-drag and group-patterns in chromium and webkit on
  Linux (wsl-run), 8/8 at this head. group-member-drag was red on the old
  client.js. The whole GUI suite ran at the draft before the save
  payload's `placed` field. It was still running when this was pushed,
  and its reds will be filed once it ends.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of provider and
  gateway on mote.

Not tried: a real account or the real app's window; WebKit on macOS
(mote's browser launches hang, #4125), so WebKit only on Linux. The TUI
has no way to reorder matched members; it keeps the stored order.
2026-10-31 01:02:35 +08:00
yetone a45a0f1c5d signin: Settings can keep sign-in pages out of the default browser (max2020)
max2020 on Discord signs in from a separate, fingerprint browser so the
vendor never sees their default one. Every waiting sign-in already shows
its link with Copy link (since 52c8e838d), but magpie still opened the
page in the default browser first.

Settings › Privacy › Sign-in pages › "Open sign-in pages in the browser",
On by default, so nothing changes unless it is turned off. Off
(settings.SignInLinkOnly) opens nothing: /api/signin and
/api/plugin-signin go through openSignIn, which skips the open and
answers linkOnly; a web tab skips window.open on linkOnly, after an
install step too; the box says the page wasn't opened and its button
reads Open, not Open again. `magpie accounts add` and a plugin's
command-line login print the link without opening it. A plugin whose own
CLI opens the page (Grok Build on macOS and Windows, opened) still does.

Callbacks, by flow: Claude Code's login, Codex (localhost:1455), ChatGPT
API, Gemini/Antigravity and localhost plugins come back to this machine,
so another browser on it finishes them, and the pasted final address
covers one whose proxy keeps it off loopback. Copilot, Grok and other
device-code flows work from any browser.

Run:
- TestSignInLinkOnlyOpensNothing (new; built-in and plugin sign-in, the
  setting on and off) with TestPluginSignIn*, TestSettingsSave*,
  TestCoreScriptBudget and TestI18n* on mote: ok. Budget holds with no
  raise (app.js 1,313,244 of 1,315,316).
- signin-link-only.test.cjs (new; every language, Chromium and WebKit,
  900 and 360px), signin-link and account-discovery on WSL: 42/42 and
  the neighbours green.
- Full Go suite on WSL (go test -timeout 45m ./...): every package ok
  except internal/agent's TestInstalledVersion, TestGrokInstalled,
  TestOmpDetectedWithPiDir and TestZedAppPath, red the same on
  origin/main 387e8572a there (#4033, #3548); root, internal/cli and
  internal/gui need gtk4 there and were run with -tags nogui: ok.
- gofmt; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
- The whole GUI suite (both engines) is still running on mote at push
  time; reds it shows that aren't on file get issues.

Broken by hand: openSignIn ignoring the setting made the Go test red
("built-in: kept to its link, its page was opened 1 times"); dropping
startSignIn's linkOnly check made the GUI test red ("no page opened",
12 of 42).

Not tried: a real vendor sign-in from a fingerprint browser; Grok on
macOS/Windows still opens its own page; MCP server sign-ins unchanged.
2026-10-31 01:02:24 +08:00
yetone 3b5dccd527 accounts: a plugin account goes by its usage's name, not its id (#4416)
A Huawei Cloud CodeArts account is kept by its accountId, an IAM id
(iam::<domain>:user:<name>), and every list showed that id while its
quota card showed the masked phone the plugin's usage() names it by.
Display only: an account now reads as the name the user gave it, else
the `user` its plugin's last usage read gave (PluginUserOf: the
in-memory read, else quotas.json), else its id. The id stays the key
everything is kept by; nothing stored changes or migrates. A read that
fails keeps the last good name; nothing read yet is the id, never blank.

One rule in provider (AccountShown, AccountShownOf, AccountLabelOf),
used by every list: cards' Alias (Usage page, tray panel,
/v1/magpie/quotas, magpie quota), magpie accounts, magpie providers,
the TUI's Providers rows and quota titles, usageapi's Account filter,
the quota alert. The GUI gets it as /api/providers' accountUsers
(accountShownOf in app.js): the editor's account rows (the id in the
tooltip), the per-account proxy lines, Routing's userShown, the
Providers search, Hide accounts. app.js's account lookups share one
helper, so the core stays in its budget (1,536,561 of 1,536,586), with
no room added.

Run:
- go test ./... -timeout 45m on mote at 2f5a3f1c0 + this change: all ok
  but internal/agent TestPiModelsAskedOnTheirNativeAPI (fixed on main
  by 7474a86f1, green there; this is rebased onto it),
  internal/update TestRelaunchOpenTriedAgain (#3881, green alone x3),
  and internal/gui's real-window AppKit tests (TestPanelCloseHidesIt,
  TestMainWindowCorners, TestTrayCellClickReleasedPanel red the same
  on origin/main 99ad38b7c; #2645, #4125, #1936).
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of the
  touched packages; gofmt -l clean.
- TestPluginAccountShownByItsUsageUser (new, real plugin host and fake
  plugin): id before a read, phone after, phone after a restart from
  quotas.json, phone kept over a failed read, own name wins, id when
  nothing is known. Red on the old code.
- GUI on the Linux box (mote's Chromium segfaults on these pages on
  origin/main too, #4125): account-plugin-user (new),
  routing-account-name (extended) and account-alias, Chromium and
  WebKit, every language, 34/34; the new checks red on the old code;
  the whole suite (make test-ui on the Linux box) was still running at
  push: 417 files in, 5 reds, none on a page this changes
  (account-models' row-moved check in WebKit, 81 vs 79px, and
  agent-models-all-hidden), not yet compared with origin/main; any
  that are new get an issue once it ends.
- At the rebased head (3bce283df): go test of provider, cli, tui,
  usageapi, plugin, agent -run TestPi, gui -run
  Budget|Provider|Quota|Account: all ok. Core scripts 1,535,513 of
  1,536,586.

Broken by hand: dropping the quotas.json fallback turns the test red
at "after a restart".

Not tried: a real Huawei CodeArts account (none here). A plugin whose
windows are all model pools isn't kept in quotas.json, so after a
restart it shows its id until its first read.
2026-10-31 01:01:49 +08:00
yetone 0621e70fb9 routing: leave a provider out of the groups magpie finds
chenxiang0010 on Discord asked to keep a provider or a model out of the
auto-created routing groups. A model could already be kept out (remove
its found group; magpie keeps it removed), but a provider could only be
turned off per group or everywhere. Now Routing -> Groups, under "Find
groups on their own", has "Leave out a provider..." (app menu, saved
when it closes) and `magpie group auto skip <provider>...|none`. The
providers chosen (providers.json autoGroupSkip) join no found group; a
group the user made or changed keeps them, a found group left with one
provider goes away, and a request for it is served by AutoStandIn from
a provider still in, and agents on it are reseated (agent.Reseat). A
rename carries the id along. en, zh, zh-TW, ja, de.

Run at 383947fce (this change on origin/main 2ff75161d):
- go test -timeout 45m ./... on mote: 80 packages ok; internal/gui red
  only in its real-window AppKit tests (TestDockJoinLeadsCommandTab,
  TestPanelCloseHidesIt, TestMainWindowCorners, ...), which fail the same
  on fresh origin/main 2f65a33aa on mote (#4125, #2645).
- gofmt -l clean; go vet ./... on Windows (win-run) clean; on Linux
  (wsl-run) clean with -tags nogui (the WSL distro has no gtk4).
- GUI: group-found-skip (new) and group-found-off, all five languages,
  1100px and 390px, Chromium and WebKit on Linux (wsl-run): 24/24. On
  mote every WebKit launch times out (#4125), Chromium 12/12 there.
- The routing files the full run flagged (concurrency 6) rerun alone on
  wsl-run, here and at fresh origin/main 380032cda: click-scroll's
  WebKit case and group-morph's WebKit 420px cases fail the same on
  origin/main. group-duplicate's de case was mine: the found groups'
  new "Anbieter ausnehmen..." line made German taller than the test's
  420x1200 window, which it assumes needs no scroll; it now uses 1400
  and passes 10/10 in both engines.
- Whole GUI suite on wsl-run, concurrency 6: still running at push time
  (5092 ok, 170 not ok so far, mostly in files this change doesn't load:
  account-*, agent-*, connect-*, gui-de/gui-ja's "{agent}" placeholder
  string). They are compared against origin/main after the push.

Broken by hand: foundGroups without unskipped -> TestAutoGroupSkip and
TestGroupsSkip red. Test calls before the fix to groupCmd's args ->
TestGroupAutoSkip red.

Not tried: the real app with real providers; a model-level skip (a
model is kept out by removing its found group, as before).
2026-10-31 00:57:21 +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 b889ffe813 library: a server can stay each agent's own entry with the MCP hub on (#4382)
cuipengcx90's #4382, Option A's first step (nifengfanpan asked on
Discord): with the MCP hub on, every Library server went behind magpie's
one entry, so a server that reads its project from the folder it starts
in, or keeps a session's state, resolved the wrong repository or shared
state across agents. A server now has a hub policy, Server.Hub ("hub" in
library.json): "" (shared, the default, so nothing changes for existing
users; "shared" is saved as "") or "direct". A direct server is left out
of the hub through inHub, the test that already keeps magpie's own image
server out, so each agent given it keeps its own entry written as with
the hub off, beside the hub's entry for the rest. An agent whose every
server is direct gets no hub entry. The hub neither lists nor runs a
direct server, at /mcp/magpie/hub either, and hubPrune ends one it held.
Switching goes through change(), so the agents are written again at once
and the entry from the other policy is removed. An unknown policy is an
error.

- GUI: with the hub on, the server editor has a "Through the MCP hub"
  switch (role=switch, not a <select>; not shown with the hub off or for
  the image server), a direct server's row has a "Not through the hub"
  tag, and the hub's line and the Connect sheet name the direct servers
  with the image server as given directly. Strings are in zh, zh-TW, ja
  and de ("MCP 聚合" as the core uses it).
- CLI: magpie library mcp hub <name> shared|direct (ServerHub), and
  magpie library marks a direct server.
- TUI: an edit keeps the policy.
- Not done: Option B (per-roots/project backends behind the hub, keying
  hubPool by roots). It is left for later; #4382 stays open for it.

Run:
- TestHubDirectServer (internal/library) and the extended
  TestLibraryMCPHub (internal/cli) on mote. Broken by hand: inHub back to
  !isSelf(s) makes TestHubDirectServer red ("codex with the hub on:
  [magpie], want [index magpie]").
- Real configs in a sandbox HOME on mote (fake claude on PATH, the real
  binary built from this tree): mcp add index + web for claude and codex,
  hub on, hub index direct, shared, then both direct. The direct index
  entry was in .claude.json and .codex/config.toml beside magpie's; with
  every server direct both files were byte-for-byte as with the hub off
  (json.tool diff and diff); shared again removed the index entry.
- Full Go suite (-tags nogui -timeout 45m ./...) on mote at this tree
  rebased on origin/main 72ed121fd: 81 packages ok. Before the rebase
  the only red was TestQuotaSpanCarriesEveryWindowField (#4457, fixed by
  ccbefe2a2). GOOS=linux and GOOS=windows go vet clean, gofmt clean.
- GUI on WSL (magpie-desktop; mote's GUI is broken, #4125), both engines,
  every language: the new mcp-hub-direct.test.cjs (1100 and 390 wide,
  hub on and off), library-mcp-hub, mcp-local-server, i18n-keys: 88 pass.
  Broken by hand: not sending hub in the save makes mcp-hub-direct red
  (11 of 11 in chromium).
- The 54 library/mcp/i18n GUI files at --test-concurrency=4 on WSL at load
  ~160: 978 of 988 pass. Red: library-chip-fan (webkit, fan positions),
  library-mcp-tools (chromium ja 420, "the click scrolled the page") and
  mcp-oauth-app (chromium de 390). None of them touch the hub switch or
  the editor's new field. They are being rerun alone, here and on
  origin/main, after this push; a red that only this change has is fixed
  next, and a red on main too is filed.

Not tried: the whole GUI suite (1028 files); a real cwd-sensitive
server in a real agent session; the live app window.
2026-10-31 00:34:45 +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 d6beb9975a agent: T3 Code gets magpie on Codex too, picked in T3's model picker
karissasel_ on X: T3 Code through magpie could only run Claude Code; the
harness couldn't be chosen. T3 runs a thread on the driver of the provider
instance its model is picked under, and magpie wrote only a claudeAgent
instance. It now also writes `magpie-codex` ("magpie · Codex", driver
codex) in ~/.t3/userdata/settings.json. Its config.launchArgs (T3's
CodexSettings key, passed to `codex app-server`, and its -c pairs to
`codex exec`) are Codex's own -c overrides: model_provider=magpie, the
same model_providers.magpie table codex.go writes, and model_catalog_json
pointing at magpie-codex-models.json beside settings.json. Values are
quoted for T3's tokenizeCliArgs. ~/.codex/config.toml is not written. A
binaryPath/homePath the user gave T3's own codex instance is carried over.

The user's name, on/off and unknown keys are kept; launch args and catalog
are magpie's, and Check says when they no longer reach the gateway
(the base_url read back through T3's tokenizer; a reverse proxy to magpie
the user put there counts, reachesMagpie, as for every agent). An
older Claude-only wiring gets the instance once on Sync; one the user
removed stays removed (stash t3code.codex) until magpie is turned on for
T3 again. Turning magpie off removes both instances and the catalog. The
option's note says where to pick (4 languages); reference.md and
agent-wiring.md describe it.

Run (on mote, the tree as committed):
- real end to end, sandbox HOME (~/t3e2e/home): settings written by this
  code, magpie serve on 127.0.0.1:47811 with a fake Responses upstream,
  T3 Code server 0.1.5 (npm t3) and @openai/codex 0.165.0.
  `t3 thread start . "Reply with the word pong." --provider magpie-codex
  --model fake/fake-model --wait` answered PONG-T3-CODEX; the upstream saw
  POST /v1/responses, model fake-model, stream true, with the provider's
  own key (sent by magpie's gateway).
- go test -tags nogui ./internal/agent -count=1 -timeout 45m: ok
- gofmt -l; go vet (darwin, GOOS=linux, GOOS=windows) ./internal/agent
- node --test internal/gui/tests/i18n-keys.test.cjs: ok

Broken by hand, each red then restored: no escaping in t3Arg
(TestT3CodeCodexInstance red); Sync without t3CodexSync (both new tests
red); no stash check (TestT3CodeCodexInstanceAddedOnce red); t3CodexOff
never reporting (TestT3CodeCodexInstance red). The first full run
was red in TestReverseProxyIsStillMagpie, Check comparing the launch
args by string; that red is the break for the proxy rule.

Not tried: T3's desktop app window (the server CLI is what it runs); the
Windows quoting on a Windows box; a real vendor upstream (fake one only);
T3's other drivers (cursor, opencode, pi, grok, ...), which are off by
default in T3 and not wired.
2026-10-31 00:11:10 +08:00
yetone b5aa56e42d providers: a model test fails fast on an unreachable host and can be stopped (RIck)
RIck (Discord #feedback): after pressing 测试模型, the error took too long
to show, and the test couldn't be cancelled.

Fail fast. Each probe now has 10s (connectWait) to get a connection,
traced through httptrace's GotConn. If it doesn't get one, the error says
"couldn't connect to <host> in 10s". In the past a refused, unresolved or
silent host waited out the whole 20s probe, or TLS's own timeout, once for
every model. TestModels keeps the hosts it couldn't reach for the run
(withUnreached). Once one model on a host fails to connect, the rest of
that host's models fail at once with the same error, so they don't each
wait 10s in turn, four at a time. The 20s per-probe bound and the GUI's
3m/25s bounds are unchanged. A stream that breaks off before the model
answers is now a failure ("the stream broke off before the model
answered"), not a long wait. Plugin and account transports don't get the
connect bound, since they dial for themselves.

Stop. While a provider has a test running, its Test models button (the
model editor), its endpoints' Test, and a chip's own right-click test all
read Stop (停止 / 停止 / 停止 / Stoppen). Pressing Stop aborts the fetch
and posts provider/teststop with the run's token. The handler keeps each
run's cancel in testRuns, so the vendor's request ends on the server too.
This matters on WebView2, where a fetch abort never reaches the request's
context. The status line then reads "Test stopped". Every entry point goes
through one helper (provTest, testButton), so they behave the same.

app.js fits its budget with no raise. The helpers are compact, and three
comments in the editor's Fetch models were cut down.

Tests:
- TestTestModelsUnreachedHostFailsOnce: a listener that accepts and never
  speaks TLS, connectWait set to 200ms and 8 models. Every model's error
  must be "couldn't connect", and the listener may get at most 4
  connections.
- TestStreamAnswerBrokenOff.
- TestProviderTestStops (models and endpoints): a fake vendor holds the
  request until its context ends. The test waits for the request to
  arrive, posts teststop, and waits for the reply to say canceled and for
  the vendor's request to end. It waits on that state, not on a duration.
- model-test-stop.test.cjs: all three buttons read Stop, teststop is
  posted with the run, the labels come back, the status reads Test
  stopped, there is no left-border accent, and nothing overflows at
  560px. It runs in Chromium and WebKit, in en, zh, zh-TW, ja and de.

Broken by hand (each one went red, then the fix was restored):
- the GUI test against origin/main's app.js;
- teststop's post removed ("Stop posted no teststop");
- teststop not cancelling ("the test went on after Stop");
- dead.Store removed (8 connections);
- the connecting wrap removed (TLS handshake timeout after 10s).

Run:
- At the pushed head:
  - mote: TestCoreScriptBudget, TestProviderTestStops, the i18n Go tests,
    TestTestModelsUnreachedHostFailsOnce and TestStreamAnswerBrokenOff:
    ok.
  - wsl-run (load 179): model-test-stop 10/10 and i18n-keys 4/4.
  - model-test-one: webkit zh was red, "model-c moved on its right-click",
    445.37 vs 444.89. origin/main's app.js was red the same way 3 of 6
    times, in en and zh. That file is on #4218.
  - provider-typed: 4 red (locator.fill 5s); see #4461.
- On the change before its last rebase:
  - gofmt clean. GOOS=windows go vet and GOOS=linux -tags nogui go vet:
    ok.
  - Full Go suite on mote (-timeout 45m, tee'd): 79 packages ok.
    internal/gui failed only on the ten AppKit window tests #4125 names.
  - Whole GUI suite on Linux WSL (both engines, every language): 15,767
    tests, 502 red across about 125 files, at load 160 to 175. The 8
    provider-editor files gave the same pass and fail set at fresh
    origin/main ccbefe2a2. The reds are on the WSL issues; the 12 files
    no issue named are filed as #4461.

Not tried:
- Stop in the real Windows app (WebView2).
- A real vendor, or a real unreachable host outside the tests.
- Plugin and account transports (no connect bound for them).
- The Fetch models step inside the endpoints' test.
- The CLI's test path and Detect, which get the connect bound through
  probeOnce but weren't exercised.
- The macOS GUI suite, since mote's WebKit is broken (#4125).
2026-10-31 00:08:29 +08:00
yetone 72ed121fd2 agent: the Codex row asks for a reopen only when Codex's models change
Qyburn3 on X ("为什么我每天好多次要重启"): the Agents row of a Codex
app already connected said 已接入 · 退出并重开 Codex 应用后生效 several
times a day.

Cause: StaleCopies counts a running copy as behind when a digest of
what magpie writes for Codex changed after it started. That digest took
magpie-desktop-models.json byte for byte. Beside the ChatGPT sign-in
(since add927e60) that file holds the ChatGPT backend's entries as
sent (base_instructions, comp_hash, available_in_plans...), asked for
again each hour, and each entry's details follow magpie's version and
models.dev, so a rewrite with the same models moved the digest and the
row asked for a reopen. The same digest drives KeepCodexDaemonCurrent,
so the CLI's app-server daemon was restarted for it too.

Fix: of Codex's two lists (magpie-models.json, magpie-desktop-models.json)
the digest takes which models they hold, slug and visibility in no
order (listedModels), beside the wiring keys and magpie's table as
before. A list that doesn't parse is still taken whole. A digest an older
magpie stashed is kept at its time when it matches the files as they are
(readsBefore), so the update itself doesn't ask every user to reopen
once more. Claude Desktop's reads already hash model ids only. The file
is still written only when its bytes differ (deskList); a running Codex
keeps working on its startup copy, and new details reach it on its next
start.

Run at this head (ccbefe2a2 + this), through mote-run:
- go vet ./internal/agent, GOOS=linux and GOOS=windows: ok
- go test ./internal/agent -count=1 -timeout 45m: ok (147.6s)
- wsl-run go test ./internal/agent -run 'TestCodexStale|TestChangedAt': ok
- the real ~/.codex/magpie-desktop-models.json (35 models) through
  listedModels in a throwaway test, with every base_instructions,
  priority and comp_hash changed and two entries swapped: same part.

Broken by hand: with the old byte-for-byte reads,
TestCodexStaleNotForAListsDetails is red at "the same models, other
details: 1 stale, want 0"; with the readsBefore carry-over off, red at
"an older magpie's stash, nothing changed since: 1 stale, want 0".

Not tried: a real Codex app beside a real ChatGPT sign-in watched over a
day; whether a list that flips between two model sets (a plugin's
listing failing and coming back) still asks for a reopen each flip (it
does: only the last digest is kept). No GUI change, so no GUI run.
2026-10-31 00:00:11 +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 7d4a631480 tray: pick which of a subscription's windows the menu bar shows (StrikingRaw on X)
Claude Pro's menu bar card drew its 5-hour and 7-day windows as two
small stacked numbers, and the user wanted one of them alone. Settings ›
Usage › Menu bar windows (under Allowances in the menu bar) lists a pill
per ticked subscription with two or more windows ("Claude Code · All
windows"), opening the app's menu: All windows, then each window. The
choice is settings.TrayWindows, by provider id (every account of it, the
in-use "|*" card too) and by window kind from the span ("5h", "1d", "7d",
"month", "15m", "name:<name>" when the span is unknown), so a vendor
reordering windows changes nothing. Unset shows every window as before;
a pick whose windows are all gone shows every window again, never an
empty card. Only the bar's rows and the Linux label are filtered; the
tooltip still says every window. One row draws at mpRowFont's 11pt
single-row size. Hidden on Windows (its tray shows no text). Per
computer through KeepOwn. The GUI learns kinds from trayKind on
/api/usage/quotas (withTrayKinds; model and aside windows get none). The
row's code is a lazily imported traywindows.js, so the core script
budget is not raised (app.js +4 lines for the call and the prefs keep).

Run:
- mote (macOS): go test -run 'TrayWindow|TrayUsage|WithTrayKinds|
  CoreScriptBudget|AppScript|TrayImage' ./internal/gui/ ok;
  ./internal/settings/ ok; davsync TestSync ok. TestTrayImageOneWindow
  draws through AppKit: Claude's card one line ("42%"), both windows two;
  the PNGs were looked at.
- mote: gofmt -l empty; go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./... ok; go build, GOOS=linux go build
  -tags nogui, GOOS=windows go build ok.
- magpie-desktop (Linux VM), --test-concurrency=1, BROWSER=chromium and
  webkit: tray-windows (en, zh, zh-TW, ja, de; picking All; hidden on
  Windows / single-window / no cards; 360px narrow), i18n-keys,
  old-webkit, tray-usages, tray-logos, tray-cost, quota-pace: 43/43 each.
After rebasing on ec5571d6f: the focused Go run above, davsync and vet of
the touched packages ok on mote; tray-windows, i18n-keys, old-webkit,
tray-usages 27/27 in chromium and webkit on the Linux VM.
Broken by hand: the row filter in trayCardText off -> TestTrayWindowsPicked
and TestTrayImageOneWindow red; trayWindows out of prefsKeep ->
tray-windows.test.cjs red in every language. Restored, green.
Not run: the full Go suite (owner: ship each verified fix at once; mote
was at load 20-27 under another session's full GUI suite) and the whole
GUI suite. The GUI ran on the Linux VM because mote's browsers crash or
hang under that load (#4125; TestTrayCellClickReleasedPanel is red the
same way on origin/main c84c3e1c0 there).
Not tried: the live app's real menu bar with a signed-in Claude account
(the AppKit drawer was exercised in-process instead); Linux tray label
on a real desktop.
2026-10-30 23:14:08 +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 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 2ff75161dc switch: Claude Code near out or refused for its limit is moved on within a minute (#4443)
In switch-only mode, Claude Code asks Anthropic directly, so magpie learns
the active account is out only from a `claude -p /usage` read. That read was
due 5 to 15 minutes (claudeUsageWait) after the last one, and
KeepOnAnAccountWithRoom looked at Claude's sign-in only every 5 minutes.
Codex already had a 1-minute near-out cadence; Claude had none. mydosu's
account read 4% left at 12:16:15, which is under Smart's 98% threshold, so
it was rightly not moved then. It burnt through within the 5-minute gap,
and Claude Code refused for about 1.5 minutes until a hand switch, while
the other account had 100% left.

Changed:
- While Claude has an account to move to, the loop looks at its sign-in
  every claudeLookEvery (1 min) between the full looks (claudeLookDue).
- Near out (an all-model window at 90% or more, codexNearShare), the
  active account's /usage is due a minute after the last read instead of
  at its 5-15 minute wait (claudeWaitOf).
- When Claude Code writes its own rate_limit refusal ("You've hit your …
  limit": error "rate_limit", isApiErrorMessage) into a session in
  ~/.claude/projects/*/*.jsonl, the next look reads /usage at once and
  marks the reading stale (StaleAllowance). Only the bytes appended since
  the last scan are read (at most 1MB per session per scan). The first
  scan only marks where the sessions end. The refusal is a cue for the
  read, not a switch by itself: the transcript doesn't say which account
  was refused.
- Cost per minute: Logins("claude") plus leftAlone. With a spare, also a
  stat of each session file and a read of the appended bytes. /usage runs
  every minute only while the account is near out and in use, or after a
  refusal (30s floor still applies).

Run:
- New tests: TestClaudeNearOutIsReadEveryMinute,
  TestClaudeRefusalInSessionReadsAtOnce, TestScanClaudeLimits,
  TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut. Pass under -race
  -count=3 on mote, with TestClaudeSwitchOnly* and TestClaudeUsage*.
- Broken by hand, each red: no near-out wait ->
  TestClaudeNearOutIsReadEveryMinute ("switched to \"\""); no refusal due
  -> TestClaudeRefusalInSessionReadsAtOnce; no in-between look in the loop
  -> TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut (still on pro@x.com
  at its 1-minute deadline).
- Windows (xiaomi-gpu, win-run): the new and Claude tests pass. The whole
  internal/provider package has 13 reds there, and all 13 fail the same way
  run alone at origin/main d99e213f5: #2808 (keychain, SavedButSignedOut),
  #4115 (CodexDaemonEnv, CodexListTag), and #4446, filed now
  (TestCodexSignInKnown, TestGitOnDisk*).
- mote at eaa2eeb29 (this commit on fa427216a): gofmt -l clean; go vet
  (nogui, GOOS=linux nogui, GOOS=windows); go build for darwin, linux and
  windows; go test -tags nogui -count=1 -timeout 45m ./... exit 0, every
  package ok (gateway 672s, agent 268s, provider 173s).
- Rebased on 4 commits (gateway, plugin, provider/codex_models; none
  touch these files), at the pushed tree on mote: go vet (nogui, linux,
  windows), darwin and windows builds, internal/provider ok (213s) and
  internal/gateway ok (716s).

Not tried: a real Claude account running out, and a real Claude Code
session on Windows writing its refusal. The refusal line's format was
checked read-only against real local transcripts. No UI added.
2026-10-30 22:05:12 +08:00
yetone 2ec3453647 gui: the main window opens where it was left (jorbenzhu)
jorbenzhu on Discord: after every update and restart the panel is back in
the middle of the screen. It is the main window: after an update magpie
starts again with `magpie gui <tab>`, and Wails opens a window centred
unless told otherwise. Its size and maximised state were kept; its place
never was (gui-shell.md said "The window's position is not kept"), so
nothing was lost on upgrade, there was nothing to restore. The tray's
panel opens under the tray icon on the Mac and Windows, and where the
click was on Linux, so it is not what moved.

Now settings.WindowAt keeps the window's top left corner (system
coordinates across every screen), per machine like Window (KeepOwn, and
the Settings page's save carries it over). keepAt saves it once a move or
resize has rested 500ms, unless the window is maximised, full screen,
minimised or hidden; settings.Save writes through temp and rename, and an
unreadable settings file is left alone. On the first show placeMain puts
it back (putBack): openAt picks the screen holding most of the window and
moves it fully onto that screen's work area; when no screen holds any of
it (a monitor gone) or the screens or the file can't be read, it stays
centred. Under Wayland a window can't place itself, so nothing is kept or
restored there unless GDK_BACKEND is x11 (keepsPlace).

Run:
- mote, at 3f8f1d88b (on d99e213f5): go test -timeout 45m -count=1 ./...
  80 packages ok; internal/gui red only in its 10 real-window AppKit
  tests (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
  TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
  TestDockReopenKeepsTheWindowsSpace, TestMainWindowCorners,
  TestMainWindowRightToLeft, TestHandoverLeavesTheMenuBarIconForTheNextMagpie,
  TestTrayCellClickReleasedPanel, TestCoveredWindowStaysUp), each killed
  at its deadline. The same 10 fail the same way on origin/main
  fa427216a: mote has no console session (#4125).
- mote, after rebasing onto 024393fbb (two gateway commits, none of
  these files): internal/gui (less the 10 above), internal/settings and
  internal/gateway: ok.
- mote: gofmt -l; go vet ./internal/gui ./internal/settings; GOOS=linux
  go vet -tags nogui ./...; GOOS=windows go vet ./...; go build, and
  GOOS=windows / GOOS=linux -tags nogui builds: clean.
- Windows (win-run) and Linux (wsl-run, -tags gtk3): TestOpenAt,
  TestSettleAt, TestKeepsPlace, TestOpenSize, TestSettle*,
  TestSettingsSaveKeeps*, TestWindowMaximisedKeptAndOwn: ok.

Broken by hand (each red, then restored):
- api.go not carrying WindowAt over a Settings save:
  TestSettingsSaveKeepsWhatItDoesNotSend red ("WindowAt: [] after a save
  of the Settings page, was [-1440 120]").
- KeepOwn not keeping WindowAt: TestWindowMaximisedKeptAndOwn red.
- openAt without the clamp and the gone-screen check: TestOpenAt red in
  7 of 12 cases.

Real app, Linux X11 (magpie-desktop, Xvfb 1920x1080 + xfwm4, sandbox
HOME/XDG dirs, MAGPIE_ADDR 127.0.0.1:3447, gtk3 build of this tree):
first start centred (630,240 in X terms); xdotool moved it to 200,150 and
settings.json got windowAt; restarted, it opened at 200,150; windowAt
[5000,4000] (a gone monitor) opened centred; [1700,900] opened at
[1260,480], flush with the bottom right (660x600 + GTK's 26px shadow).

Not tried: the real app on macOS (mote has no console session, #4125)
and on Windows (a sandbox magpie.exe rewrites HKCU\Software\Classes\magpie,
which points at another session's build there). Wayland is not restored
by design. Multi-monitor setups with mixed scaling were not tried on real
hardware; openAt's cases cover a second screen left of and right of the
main one.
2026-10-30 21:56:29 +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
yetone d99e213f5b codex: an account switch restarts nothing while Codex's provider takes no ChatGPT account
danzi002 on Discord: with requires_openai_auth = false on Codex's provider,
switching the Codex account in magpie still restarted the Codex app's
app-server and said the app and daemon were left on the old account.

Codex's provider with no requires_openai_auth = true goes by no ChatGPT
account: codex-rs ModelProviderInfo::account_state answers no account, and
resolve_provider_auth sends the table's key, never auth.json. So which
account auth.json holds is nothing a running Codex uses.

- provider.CodexNoAccount (set to agent.codexNoAccount): the config's top
  model_provider is not openai, has a [model_providers] table, and the table
  doesn't say requires_openai_auth = true. A profile, the built-in provider,
  no table or an unreadable config count as false (may use the account).
- codexAppStep forgets a switch (and a spent switch) while it holds, so the
  app-server is left running; a route change still restarts it.
- CodexAppStale / CodexDaemonStale say nothing, and `magpie accounts`'
  switch line says nothing needs restarting.
- Kept: route-change restarts (model_provider, openai_base_url,
  model_catalog_json, base_url, catalog hash: read only as the app-server
  starts) and the daemon's model-list restarts; and switch restarts when
  magpie writes requires_openai_auth = true (ChatGPT sign-in with room).

Run (mote-run; full suite at this change on e0ad48641):
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./..., go build for darwin/linux(nogui)/windows: ok.
- go test -tags nogui -timeout 45m ./...: 81 packages ok, no FAIL.
- New tests: TestCodexNoAccountSwitchRestartsNothing (provider),
  TestCodexNoAccountFollowsRequiresOpenAIAuth and
  TestCodexNoAccountOfEachConfig (agent).
- Broken by hand: codexNoAccount returning false in provider made
  TestCodexNoAccountSwitchRestartsNothing red (ended the app-servers);
  agent's codexNoAccount returning false made both agent tests red.
- Real codex-cli 0.165.0 in a sandbox CODEX_HOME with a provider table at
  requires_openai_auth = false: app-server account/read and getAuthStatus
  answered no account before and after auth.json was switched from a@x to
  b@x, and `codex exec` against a loopback capture server sent
  `Authorization: Bearer <the table's key>` with no chatgpt-account-id for
  both accounts.

After rebasing onto origin/main (2 commits: gateway desktop probe,
usage purposes): go vet ./... and go test of internal/agent, provider,
cli, usage and gateway at the pushed head: ok.

Not tried: the real Codex desktop app (macOS or the Windows MSIX) through
a switch; a daemon with live sessions through a switch; the GUI suite
(no GUI asset changed; the switch notice reads CodexAppStale).
2026-10-30 21:01:09 +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 48edbcb674 library: RTK covers Droid, and lists Qoder, Cline and Kimi Code with why
lml0664 on Discord: Library > RTK offered a fixed few agents, even on the
latest magpie. RTK 1.1.0 (rtk-ai/rtk, Latest, 2026-10-25) has `rtk init`
agents claude, cursor, trae, windsurf, cline, kilocode, antigravity, kimi,
pi, hermes, droid, vibe, omp, plus --codex/--gemini/--opencode/--copilot.
Every one with a global hook that magpie has an agent for was already on
the page except Factory's Droid, which is added now:

- droid: rtk's own `rtk init -g --agent droid`, given Droid's folder as
  FACTORY_HOME_OVERRIDE (magpie's droid agent honours it). rtk writes its
  Execute group (`rtk hook droid`) into the root hooks.json, or into
  settings.json's hooks.PreToolUse when Droid's hooks already live there
  (src/hooks/init/droid.rs), so ReadRTK and switching off look at all
  three files rtk may use (hooks.json, hooks/hooks.json, settings.json)
  and leave the user's own hooks and settings. rtk before 0.44 has no
  Droid agent, so it is blocked with "needs RTK 0.44 or newer".
- dropHook no longer slices key[:-1] for a top-level key (hooks.json's
  "PreToolUse"); before, it would have panicked.

Listed with the switch off and their own reason (rtkNoHook and the page's
rtkNoHookWhy, in zh, zh-TW, ja and de too):
- Qoder, Qoder CN: rtk 1.1.0 has no Qoder agent (`--agent qoder` is an
  invalid value), rtk-ai/rtk#1327 (PR #1721 open).
- Cline: `rtk init --agent cline` only writes a .clinerules in the
  current project asking the model to type rtk, no hook (#3841).
- Kimi Code: Kimi's hooks can't rewrite a command; rtk writes only one
  project's AGENTS.md and refuses -g ("Kimi AI is project-scoped").
RTK's Trae, Windsurf, Kilo Code and Mistral Vibe have no magpie agent.

Run:
- go test -tags nogui ./internal/library -run TestRTK on mote: ok
  (TestRTKDroid home/override, TestRTKDroidSettingsHooks,
  TestRTKNoHookQoderClineKimi new, sandbox HOME, fake rtk).
- Red on old code: rtk.go at HEAD^ -> TestRTKDroid, ...SettingsHooks and
  ...NoHookQoderClineKimi red. Broken by hand: version gate at 0.43, the
  settings.json entry dropped -> red; FACTORY_HOME_OVERRIDE not passed ->
  TestRTKDroid/home red. client.js at HEAD^ -> library-rtk-nohook red
  (Qoder's reason was the generic one).
- Real rtk 1.1.0 (release tarball, sha256 checked against checksums.txt)
  on mote in a sandbox HOME through SetRTK/ReadRTK: plain ~/.factory,
  settings.json with the user's own Execute hook (kept, rtk's taken out)
  and FACTORY_HOME_OVERRIDE: on, seen on, off, seen off. Real rtk also
  refuses --agent qoder and -g --agent kimi, and cline writes .clinerules.
- Full suite on mote, go test -count=1 -timeout 45m ./...: 80 packages
  ok; internal/gui red only in its 10 real-window AppKit tests (#4125).
- GOOS=linux and GOOS=windows go vet ./internal/library: ok. gofmt clean.
- GUI on the WSL box (mote's browsers crash at launch, #4125):
  library-rtk-nohook (chromium+webkit, en+zh) and i18n-keys 10/10; all 45
  library-*.test.cjs files 810/824, the 14 reds (library-chip-fan webkit,
  library-items webkit, library-mcp-tools chromium ja 420) are the same
  at origin/main cf9ea977c and are #4120.

Not tried: a real Droid session running the hook; the whole GUI suite
(only the Library files); Windows (Droid's folder there is the same code
path; no run).
2026-10-30 20:03:32 +08:00
yetone f63ea1d5b2 agent: omp asks a Gemini model on Gemini's own API at /v1beta (#4277)
omp gave a model served on Gemini's API the provider's openai-completions,
so the gateway translated Chat for it. ompProviderAt now writes such a
model as OmO does: api google-generative-ai, baseUrl <gateway>/v1beta.

Checked in omp's source (pi-ai providers/google.ts, 16.0.0, 16.3.5,
18.9.1, 18.14.0): it posts to baseUrl/models/<id>:streamGenerateContent
?alt=sse with x-goog-api-key, and throws only when the key is empty. The
issue's claim that auth: none breaks it is wrong: under auth: none omp's
model registry hands the client its no-auth key "N/A" (kNoAuth), which
loopback takes, so the provider stays keyless; a WSL omp under NAT sends
its apiKey there as before. Unlike pi-ai, omp's Google client takes a
custom fetch, so the Raft reason Pi stays on Chat doesn't apply.

Thinking: a Gemini 3+ model gets mode google-level (thinkingLevel; xhigh
and max go as HIGH, pi-catalog model-thinking.ts), a Gemini 1.x/2.x one
mode budget, since 2.5 refuses a level; omp sends that as
thinkingBudget -1 (custom models.yml has no effortBudgets).

Run:
- TestOmpGeminiModelsAskedOnGeminisAPI, TestOmpGeminiMode (new), and
  TestOmp*/TestPi* on mote: ok.
- Broken by hand (Gemini case taken out): the new test is red on api,
  baseUrl and thinking mode for gem/gemini-3-flash, gem/gemini-2.5-pro and
  hybrid/gemini-3-flash; TestOmpGeminiMode doesn't build on the old code.
- go vet ./internal/agent for darwin, linux, windows: ok; gofmt clean.
- Real omp 18.14.0 (Bun 1.4.4) in a sandbox HOME on mote: magpie built
  from this tree, `magpie provider add gem gemini=<fake>/v1beta`, `magpie
  serve`, `magpie omp gem/gemini-3-flash`, then `omp -p`. omp answered
  with the fake upstream's text through the gateway's /v1beta. Pointed
  straight at a fake server, omp sent POST
  /v1beta/models/gem/gemini-3-flash:streamGenerateContent?alt=sse with
  x-goog-api-key: N/A and User-Agent: omp, and thinkingConfig.thinkingLevel
  HIGH for --thinking high (MINIMAL for off).
- Full suite (go test -timeout 45m -count=1 ./...) on mote at c9b5fbb04
  (origin/main cf9ea977c): every package ok except internal/gui, whose ten
  real-window AppKit tests (panel, dock, tray, titlebar, plugin page) were
  killed at their 20-80s deadlines, #2645 and #4125 (mote's AppKit/launchd
  hang). This change touches no GUI code.

Not tried: a real Gemini account (the upstream was a fake); a Gemini 2.5
model through omp; a WSL omp.
2026-10-30 20:01:38 +08:00
yetone 57e58595b9 agents: Claude Desktop says its signed-in chats and projects stay, before it is turned on
xgddm88 on X: after turning Claude Desktop on in magpie (to use DeepSeek
V4.1 Flash), Desktop started with none of the earlier projects or chats.

Cause, from Desktop 2.7032's app.asar (index.pre.js, read only): in
third-party mode Desktop calls app.setPath("userData", …"Claude-3p")
("[custom-3p] userData mkdir"), so it runs in a profile of its own. The
signed-in (1P) chats, projects and Code sessions stay in
~/Library/Application Support/Claude. They are not deleted, only not
shown, and come back when Desktop is off magpie. magpie writes nothing
in Claude/ but deploymentMode, and only reads its config.json for the
language. There is no supported way to show 1P history in 3P mode.

So magpie says it before the switch is touched, and after:
- the Agents row, not connected: "Not connected · on magpie, Claude
  Desktop opens a separate profile: chats and projects from your
  Anthropic sign-in stay, and are back when you turn it off"
  (CONNECT_BEFORE);
- the opened row, once connected (CONNECT_COST);
- the notice after On and after Off (noticeClaudedesktop3/4).
In en, zh, zh-TW, ja and de. agent-wiring.md says where Desktop's
history is and that Opus beside DeepSeek comes from a Claude
subscription added in magpie.

Run (worktree at cf9ea977c):
- gofmt -l internal/: nothing.
- mote: go vet ./..., GOOS=windows go vet ./..., GOOS=linux go vet
  -tags nogui ./..., go build ./..., go test -timeout 45m
  ./internal/agent ./internal/gui: vets and build ok, internal/agent
  ok; internal/gui red in 10 real-window AppKit tests (dock, panel,
  tray, main window), each at its 20-40s deadline. Four of them, run
  at origin/main cf9ea977c on mote, fail the same way; that is mote's
  window server (#4125, #2645), not this change, which touches no Go
  in internal/gui.
- GUI, Chromium on mote and WebKit on Linux (wsl-run; mote's WebKit
  launches hang behind ~48 stuck pw_run.sh from other runs):
  desktop-history (10+10 pass), and i18n-keys, agent-connect,
  agent-failover, desktop-longest, desktop-tiers, desktop-model-menu,
  desktop-subagent-model (36 pass in each engine).

Broken by hand:
- Notice without the new sentences: TestClaudeDesktopKeepsTheSignedInHistory
  fails on the On and the Off notice.
- desktopOn writing Claude/config.json: the test fails, "on changed
  …/Claude/config.json".
- connectLine without the CONNECT_BEFORE line: desktop-history fails
  10 of 10 ("Not connected · Claude Desktop uses its own settings").

Not tried: a real Claude Desktop launched on magpie (sandbox and live
were both left alone); leaving disableDeploymentModeChooser unset so
Desktop's login screen offers Claude.ai sign-in beside magpie (unverified,
unchanged); Windows' Claude-3p path in a real app; WebKit on macOS.
2026-10-30 19:59:07 +08:00
yetone cf9ea977ca agent: Droid gets a GPT on openai and a Claude on anthropic, as droid asks, and keeps an entry edited by hand
ji233 on Discord: droid warned at session start that "ultrafast/gpt-6.1-sol
appears to be an OpenAI model, but is configured with provider
generic-chat-completion-api". magpie wrote every model on a Chat provider
as generic-chat-completion-api, whatever its name.

droid's own rule, read from its bundle (droid 0.231.0, xs and g2): a
custom model's "model" matching /\bgpt[-_.]?\d/i, /codex/i or
/\bo[1-9](?:[-_.]|$)/i on any provider but openai is warned about as
OpenAI's; then one matching /claude|haiku|sonnet|opus/i on neither
anthropic nor bedrock-converse as Claude's. droid first looks the name up
among its own models; every OpenAI one there matches the patterns except
gpt-image/gpt-transcribe, so the patterns alone are used (droidWants).
Such a model now goes on the provider droid asks for (openai on the
gateway's /v1, anthropic on its root), and the gateway translates
(Responses->Chat: TestResponsesClientChatUpstream; groups on Responses
as for Codex). Other models keep their native API as before.

A provider, displayName, maxContextLimit, maxOutputTokens or
noImageSupport the user changed in one of magpie's entries stays through
a sync and a new pick: what magpie last wrote is stashed
(droid:<path>:wrote), a value other than it is the user's. Keys magpie
doesn't write stay too (droid's index aside). baseUrl follows the
entry's provider; apiKey is wiring, put back at every sync. With no
record (entries an older magpie wrote, which each sync wrote over
anyway), magpie's values are taken, so ji233's entries move to openai on
the next sync. Disconnect forgets the record. Doc: agent-wiring.md.

Run (mote):
- go test ./internal/agent -run TestDroid: ok. Red on the old droid.go
  (TestDroidWantsItsOwnRule, TestDroidProviderByName,
  TestDroidKeepsAnEntryEditedByHand all FAIL); with droidMerge forced
  to magpie's values, TestDroidKeepsAnEntryEditedByHand FAILs.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/agent ok.
- go test -count=1 -timeout 45m ./... at 5be7d8ab7 (on 133493488): 79
  packages ok; internal/gui's real-window AppKit tests killed at their
  deadline (TestPanelCloseHidesIt and TestTrayCellClickReleasedPanel
  fail the same on origin/main b4cb946f9 on mote: #4125, #2645), and
  internal/update TestRelaunchOpenTriedAgain's TempDir cleanup (#3881;
  passes -count=3 alone at this head, and alone on b4cb946f9).
  After rebasing on b4cb946f9: go test ./internal/agent ok.
- Real droid 0.231.0 in a sandbox HOME on mote, no sign-in, against a
  sandbox `magpie serve` built from this tree with a Chat-only provider
  "ultrafast" (gpt-6.1-sol, claude-opus-4-7, kimi-k2.5) on a fake
  upstream: `magpie droid magpie/ultrafast/gpt-6.1-sol` wrote openai /
  anthropic / generic-chat-completion-api; `droid exec -m
  custom:magpie/ultrafast/<m> "say pong"` answered PONG for all three
  through /v1/responses, /v1/messages and /v1/chat/completions, the
  upstream got Chat each time, and no "appears to be" warning was in
  droid's sessions. The same droid on generic-chat-completion-api for
  gpt-6.1-sol stored the warning in its session; on openai it didn't.

Not tried: droid's interactive TUI (exec only); a real vendor upstream
(fake Chat upstream only); Windows/WSL droid; droid's built-in-name
lookup cases the patterns miss (gpt-image-*, gpt-transcribe).
2026-10-30 19:34:45 +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
yetoneandYangHonghang 9e73f69af4 providers: rate windows bill a provider's hours at its own rate (#2463)
A provider can have up to 8 rate windows: days, a span that may cross
midnight (on this computer's clock), and a rate. Inside a window a call
costs the base price times the rate. The base is the user's model price
as set, or the list price times PriceRate with the vendor's own peak
(DeepSeek, Command Code, OpenCode Go) already in it. The author gave
this order as the spec: a 0.8 window on a shared DeepSeek key takes 0.8
off the peak price at peak. The editor's hint says not to set the
official peak hours again as a window, in every language.

Each call is priced at its own time on the Usage page and its CSV, in
the Requests tab's rows, and against a gateway key's cost limit. The
Sessions page, group templates and the model list written into an
agent's own config use the base price. /v1/models prices at now.

Ported from YangHonghang's 2c9d459ff (rate-windows-2463-v2). The Go
pricing, its tests and the translations are theirs. Changed here:
- No budget raised. Their commit raised appScriptBudget and
  coreScriptBudget; core_budget_test.go is main's again. The editor's
  window rows, time menus, validation and hint moved to ratewindows.js,
  which app.js imports when the field is drawn (as signsheets.js is).
  The sliding-thumb and modalDepth comments were cut down to make room.
  The core is 1,535,528 of 1,536,586 and app.js 1,312,242 of 1,315,316.
  Until the script has loaded, a save leaves rateWindows out, and the
  server keeps the saved ones.
- Their unrelated TestAssetsHaveNoConflictMarkers is dropped (one
  commit, one goal).
- The row badge shows only for a provider with windows. Before, every
  provider with a price rate alone got a new ×badge. Its title is
  shorter, and so are its translations.
- AgentPricer (agent model files: Pi, omp, OpenCode cost) uses the base
  price. Nothing rewrites those files when a window opens or closes, so
  a price taken at Sync stayed on outside the window.
- internal/budget gets a TestMain through testenv, so the new test
  runs in a home of its own.
- old-webkit's list of lazily loaded scripts names ratewindows.js.
- The draft keeps each window as a shallow copy, and a day chip
  replaces its days array, so the saved provider is never changed.
- The GUI test waits for the lazy script's hint, not a fixed 300ms.
  It also checks the peak note in each language.

Run first on 2f5a3f1c0, then again after rebasing on 70d9996c5,
8acb0d3a7 and d609729cf. The rebase onto 70d9996c5 met main's ruleedit.js in
old-webkit's list, and both are listed.
- gofmt -l internal: clean at 8acb0d3a7 (129578c3d gofmt'd main's
  pi_api_test.go).
- mote, on 8acb0d3a7: go vet on usage, provider and gui
  ok; GOOS=linux and GOOS=windows go vet -tags nogui ./... ok.
  go test -tags nogui for internal/usage, provider, gui, budget and
  sessions: ok. The five internal/agent tests that are red on WSL
  (below) pass on mote there. On d609729cf (a one-line mover min in
  internal/provider), internal/provider again: ok.
- On 2f5a3f1c0: internal/provider, usage, budget and sessions, and the
  gui RateNow|PriceRate|CoreScript|Budget tests, each under TZ=UTC,
  Asia/Shanghai and America/Los_Angeles: all ok.
- wsl-run (magpie-desktop, Playwright chromium and webkit) on
  70d9996c5: provider-rate-windows, old-webkit, i18n-keys,
  provider-price-rate, provider-advanced-fold, agent-hides-editor,
  key-box-once, provider-many-keys, nokey-editor and
  editor-short-window: 200/200. On 2f5a3f1c0 the first five and
  model-price-edit: 132/132. On mote the same files hit WebKit launch
  timeouts (180s) under another session's full GUI suite (load 30), and
  that run was stopped.
- Full suite, wsl-run (mote was running another session's full suite),
  go test -tags nogui -count=1 -timeout 45m ./... at 6e534f546 (this
  change on 70d9996c5): every package ok except internal/agent.
  internal/agent fails TestInstalledVersion, TestGrokInstalled,
  TestCursorFolderFromTheEditorIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath. This change doesn't touch internal/agent. At
  origin/main 8acb0d3a7 on the same box, TestInstalledVersion,
  TestGrokInstalled and TestOmpDetectedWithPiDir fail too: a fake CLI
  in /tmp exec'd with "Invalid argument". That is #4033 and #3548
  (WSL2 binfmt interop).
- Broken by hand, red each time:
  - Pricer without the window: TestPricerRateWindows,
    TestBlockRowsTakeTheirRateWindow, TestCostLimitCountsTheRateWindow.
  - Block rows without atWindow: TestBlockRowsTakeTheirRateWindow.
  - AgentPricer at now: TestAgentPricerLeavesTheRateWindowOut.
  - Badge for a price rate alone: TestRateNowOf.
  - Peak note removed: provider-rate-windows, 10 of 10 chromium
    layouts.
  - ratewindows.js not in old-webkit's list: old-webkit.

Not tried:
- A real relay billed by the hour.
- The real desktop app (WebKitGTK, WKWebView).
- The full GUI suite (mote was running another session's).
Known limits:
- No rate is stored per record, so changing the windows reprices
  history, as a changed PriceRate does.
- Windows follow this computer's zone, with no zone of their own.
- The Sessions page uses the base price.

Co-authored-by: YangHonghang <honghang.yang@qq.com>
2026-10-30 18:55:51 +08:00
yetone 8acb0d3a7d codexcat: a DeepSeek model's Codex entry says what DeepSeek's own Codex setup says
Rollkey8 on X found DeepSeek in Codex through magpie duller than
DeepSeek's DSH. A real Codex 0.165.0 -> magpie -> api.deepseek.com
recording lost nothing in translation; what differed was the catalog
entry magpie writes for the model. DeepSeek's own Codex setup
(cdn.deepseek.com/api-docs/codex-deepseek-setup-en.sh) writes a
models.json for deepseek-flash and deepseek-v4-pro, and a DeepSeek
model's entry now takes its non-prompt fields from it:

- shell_type "shell_command" (Codex 0.165 reads it as unified_exec, its
  only shell tool, per openai_models.rs's serde alias; a Codex before
  that had a one-shot shell_command tool, which is what DeepSeek picks)
- support_verbosity true, default_verbosity "low" (text.verbosity low
  is sent)
- default_reasoning_summary "none": reasoning.summary "auto" is no
  longer sent; DeepSeek streams its reasoning as text
- multi_agent_version "v2" where magpie had none
- supports_image_detail_original on a model whose entry takes images

A DeepSeek model is deepseek-v4*/-flash/-pro/-chat/-reasoner after any
provider or relay prefix (codexcat.deepSeek); a routing group or an
R1-distill isn't one. Every other vendor's entry is unchanged.
default_reasoning_summary is tagged keep:"unset", so a value the user
put by hand in another model's entry stays through Keep, as it did
before magpie wrote the key anywhere.

Not taken, and why:
- base_instructions / model_messages: magpie never rewrites a model's
  Codex prompt (owner's rule).
- auto_compact_token_limit null: magpie's 272K Long conversations
  default came from a DeepSeek-flash latency report (e950eb080, ~550K
  turns waited 70-90s for a first token); Full window, or the model's
  Compact at, gives the whole 1M, and a model_auto_compact_token_limit
  the user set still comes first.
- supports_search_tool false on v4-pro: kept true for #258.
- reasoning levels: the provider's, as for every model.
- comp_hash, max_context_window (same as the window), web_search
  (config.toml, not the catalog).
- v4-pro's images: DeepSeek's pricing page, its live /models and
  models.dev all say text only, and magpie's own entry (/v1/models)
  says text. Codex's catalog lists it with image only when Settings ›
  Vision describes images for text-only models (codexListed's
  described()), by design.

Also adds the agent-wiring.md row "Codex: DeepSeek models".

What was run, at this tree (as daf576653, the same tree before the
gofmt commit was split out under it):
- TestCodexCatalogDeepSeekAsDeepSeekSays and
  TestCodexCatalogKeepsUsersSummary: red on the old codexcat.go (both
  FAIL with it stashed), green on the new.
- go test ./internal/codexcat ./internal/provider -run 'Codex|DeepSeek'
  on mote: ok.
- gofmt -l: clean. On mote: go vet ./..., GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go
  build -tags nogui, GOOS=windows go build: all ok.
- Full suite on mote, go test -count=1 -timeout 45m ./..., alone on
  the box: 79 packages ok; internal/gui red only in its 10 real-window
  AppKit tests, each killed at its deadline, which is #4125 (mote's
  AppKit hang; recorded there).
- Real use: Codex 0.165.0 in a sandbox HOME against a magpie built
  from this tree with the owner's DeepSeek provider copied in (deleted
  after). The written catalog has shell_command for both models. A
  multi-step task on deepseek-v4-pro (write a module and unittest file,
  run the tests, fix, report) ran to the end, tests pass. Through a
  recording proxy the requests carry text.verbosity "low", reasoning
  {effort: high} with no summary, and the same tools as before
  (exec_command, write_stdin, apply_patch, ...).

Not tried: a Codex older than 0.165, where shell_command is a tool of
its own; deepseek-flash in a real run (only v4-pro); a blind side by
side against DSH on answer quality.
2026-10-30 18:44:23 +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