Commit Graph
2297 Commits
Author SHA1 Message Date
yetone f5e1b10913 settings: longest context can hold a model's own window too (WJaunita45604 on X)
v0.1.3681's Longest context left a window the user set for a model, or "*"
on its provider, alone even when longer. Settings > Models > Routing now has
a menu beside the field: "Models without their own" (the default, as before)
or "Every model". In both modes the shorter of the cap and the user's own
window is told; they differ only when the user's own is longer (own keeps it,
every model brings it down). Settings.ContextCapAll, Settings.CappedOwn,
POST /api/settings/context-cap-mode {all}, magpie model context-cap all|own.
Applied in provider.windowIn (so /v1/models, catalogs, compaction), Codex's
CodexNativeWindow/CodexWindow (the list's ETag tag carries the mode) and the
gateway fallback window. i18n in zh, zh-TW, ja, de.

Run (wsl-run, mote's disk was full): provider (full), settings, settingsapi,
codexcat packages; cli -run ContextCap; gateway -run ContextCap|ModelsList;
GUI context-cap, i18n-keys, model-load, settings-places, settings-general in
chromium and webkit; TestCoreScriptBudget; gofmt; go vet nogui and
GOOS=windows vet. Broken by hand: windowIn's CappedOwn removed turns
TestContextCapAllHoldsTheUsersOwnWindowsToo red.
Not tried: the whole Go and GUI suites, a real Codex reading the list, macOS
or Windows runs, GUI in zh-TW/ja/de beyond the i18n-keys check.
2026-11-11 14:28:17 +08:00
yetone 032340056e gateway: a context kept after its handler returns no longer reaches the request's body (#5250)
TestSocketTurnBodiesFreed went red on ubuntu CI at a3d2a85dd ("turn
bodies [8] of 12 still kept"), after a268aadc4 had let the unrouted
watch's own timers go. Two more paths kept a turn's request, and with
it the whole conversation it was sent with:

- A context timer. Any WithTimeout under the request's context, stopped
  as its call ended, is kept with its context in the timer heap of the
  P that set it until that P tidies its heap, and an idle P never does.
  Through the context's values it reached the watch twice: the
  unroutedKey value held the watch itself, and inflightOf's value held
  the inflight, whose f.unrouted is the watch. The watch holds the
  request (u.r), and the request's Body and GetBody the bytes.
  The unroutedKey value is now the watch's held pointer, as its timers
  already were (unroutedOf), let go as the handler returns; done clears
  f.unrouted too. Its readers (noteRoute, showRedacting, notDescribed)
  run inside the handler, before done.
- An asynchronous release. holdBody and the body room let go of a body
  in a context.AfterFunc, which runs in a goroutine of its own once the
  turn's context ends, so under load the test's one collection could
  come first. The test now collects until every body is gone, within
  10s: far under unroutedShow (15s) and unroutedMost (2m), the times a
  real holder kept one for.

Run (the Linux box, wsl-run, since mote is out of disk):
- origin/main 4ddc150c6, TestSocketTurnBodiesFreed -race -cpu 1,2:
  1 red in 80. With a probe, the red was a body still held after 10s,
  and in 9 of 300 runs bodies were freed only 30-120ms after the first
  collection (the async release).
- With the context-value half only: 3 red in 200, each held over 10s.
  With holdBody's sharing turned off: still 1 red in 200, so it isn't
  a decoded string sharing the body. A goroutine dump at the red had 7
  goroutines, none of the gateway's: a heap reference, not a runner.
- With both halves and the new test: 300 of 300 green (-race,
  -count=150, -cpu 1,2).
- TestUnroutedContextLetsGoOfRequest, new, holds the request's context
  past its handler: red 5 of 5 on the old code, red 5 of 5 with only
  the context-value half, red 3 of 3 with only the f.unrouted half,
  green with both. TestUnroutedTimersLetGoOfRequest still passes.
- go vet ./internal/gateway on Linux: ok. gofmt -l: clean.
- The whole internal/gateway package runs next on the Linux box; its
  result goes on #5250.

Not tried: macOS and Windows runs (mote is out of disk and refuses
ssh); other context values that might hold a request are not audited.
2026-11-11 14:24:25 +08:00
yetone 4a7d222dc8 providers: an OpenCode Go key takes the usage cap an account does (@wanggenjidev on X)
Backend only; GUI follows. Tests: provider TestKeyTakesUsageCap, gateway TestKeyUsageCapPassesTheKeyOver (red with the hold removed by hand).
2026-11-11 14:18:10 +08:00
yetone d936be7639 usage: Claude's card shows the extra-usage cap and its spend (Shinji_Zl on X)
Claude Code's `claude -p /usage` text omits extra usage, but with
`--output-format json --verbose` a message carries
usage_report.rate_limits.extra_usage (cap and spend in cents). The gateway
adds it as a line; parseClaudeUsage reads it as an Aside "Usage credits"
window (n / cap USD), so a spent cap never marks the account used up.
magpie asks Anthropic nothing itself, and cannot make a request spend
credits: Anthropic decides. The prepaid balance is a separate endpoint and
is not shown.

Run (wsl-run, linux): TestClaudeUsage*/TestClaudeOverage in provider and
gateway, go vet linux/windows/darwin, i18n-keys, i18n-en-no-cjk and
claude-overages GUI files (chromium + webkit).
Broken by hand: Aside false -> TestClaudeUsageCredits red.
Not tried: a real account with extra usage on (the owner's is off); full
suite after the tag; Windows run.
2026-11-11 14:08:18 +08:00
yetone 1315ac7d99 update: the first update finds a magpie without gateway.json, and a restart waits a bounded time (ljlwlcz on X)
Two edges of v0.1.3687's gateway.json:

1. The first update from a magpie older than the record found no gateway.json,
   asked 3425, said "isn't running" and left a service on MAGPIE_ADDR=0.0.0.0:10100
   on the old version. With no record, no MAGPIE_ADDR and no answer at the usual
   address, `magpie update` now tries the installed service's MAGPIE_ADDR (read
   from its unit or launch agent, daemon.Addr), the port in Settings and 3425,
   and takes the first that answers as magpie. --addr and MAGPIE_ADDR stay the
   user's word.
2. A restart asked by `magpie update` waited on "N requests" with no end (Windows
   hands nothing over, long streams never finish). The app and magpie serve now
   wait at most 10 minutes for that ask, then restart; the output says so
   ("or in 10 min at the latest, which cuts what is still running"). `magpie
   update --force` restarts at once (gateway.SetForceRestarter), and says if the
   running magpie is too old to know --force. The app's own look at the disk
   (followReplaced) and autonomous serve follow still never cut a request.

Run (mote refused SSH; win-run on xiaomi-gpu): go vet cli/gui/gateway/daemon
(windows), linux nogui vet; go test -run TestUpdate|TestServeFollow|
TestTerminalUpdate|TestRestart over cli, gui, gateway, daemon: ok except
TestUpdateThatWontStart, red on origin/main on the same box too (#6059).
Broken by hand: drain bound off, record fallback off, serve bound off: the new
tests TestTerminalUpdateWaitIsBoundedAndCanBeForced, TestUpdateFindsAMagpieThatWroteNoRecord,
TestServeFollowDrainIsBounded go red.
Not tried: a real systemd service upgrade; darwin cross vet (cgo) and the full
suite (started after the tag if mote is back).
2026-11-11 13:01:11 +08:00
yetone 5399c33728 healthcheck, update and status find the running gateway by its own record (ljlwlcz on X)
The gateway now writes gateway.json (addr, pid, role, version) in magpie's
config folder while it serves; healthcheck, update, status and the other
CLI clients read it when MAGPIE_ADDR is unset, trusting it only if the pid
on GET / matches. --addr overrides. New: magpie status [--json] for
watchdogs (role, pid, listen address).

Run: new gateway and cli tests on Windows via win-run (pass); broken by
hand (record disabled): they go red; gofmt; vet windows and linux nogui.
Not run: mote/Linux (SSH down, WSL broken), darwin vet, a real systemd
service. TestEveryRouteHasACommandOrIsNamed is red on the base for two
GUI routes, unrelated to this change.
2026-11-11 12:00:19 +08:00
yetone a982f34130 plugins: async gateway hooks get the request's kind, subagent or not (ahwulv on X, #4655)
GatewayContext had no subagent marker, so OpenViking could not skip memory
recall for Claude Code's subagents. It now carries kind: "subagent" when the
client says so on that request, "" otherwise (main conversation, or a client
that doesn't say). hookKind (internal/gateway/middleware.go) reuses the
gateway's own readings: Claude Code's x-claude-code-agent-id (subOf), and
Codex's x-openai-subagent collab_spawn (callKind + usage.PurposeOf, so a
Codex review or compaction is not a subagent). Headers from #4655's real
Claude Code 2.1.312 capture. It is read per request, so onRequest and that
request's onResponse see the same value and the main turn after a subagent
in the same session is "". Never guessed from the prompt or Agent tool
history. Documented in docs/subsystems/gateway-request-hooks.md.

Before/after: a hook's ctx had no kind; ctx.kind is now "subagent" for such
requests (the OV plugin already reads ctx.kind === "subagent").

Run: TestHookKindFromClientHeaders (claude subagent, claude main in the same
session, codex collab_spawn, codex review, none) and
TestAsyncGatewayHookKindReachesPlugin (real gateway + Bun: main, subagent,
main again; onRequest and onResponse) on mote at the commit before the final
rebase and on a WSL box; with Kind dropped from the context the e2e test
goes red (saw "" want "subagent"). go vet darwin green. Not tried: the real
OpenViking plugin; Claude Code itself against this build; linux/windows vet
was still queued on mote when this was pushed.
2026-11-11 11:50:13 +08:00
yetone 8aae124b02 gateway: Claude Code's tool-list notices after a result are not the user's message, so a steer sent with them reaches the model (magicalaciw18 on X)
Claude Code's deferred-tools and MCP-server notices ("The following deferred
tools are now available via ToolSearch…", "…are no longer available…",
"# MCP Server Instructions", "The following MCP servers have disconnected /
failed to connect / are still connecting…", literal strings from its own
transcripts) were not in `injected`, so agentNotice passed them to the run as
the user's words. The model read a new "user message" that was only the notice
(and a steer sent beside it arrived with the notice glued on its front).

Run on the Windows box (xiaomi-gpu, win-run; mote and WSL refused every
connection), at the pushed head (rebased on 914fcf59b):
- Old prompt.go: TestClaudeToolListNoticesAreNotTheUsersMessage (7 subtests)
  and TestClaudeSteerBesideToolListNoticeGoesOnAlone red; the lone-steer
  tests pass on old and new code (they guard that a steer alone still goes
  through, as a text after the result and as 2.1.296's system message).
- Fix: the new tests, TestClaudeHook*, TestAgentNotice*, TestUserWords green.
- go vet ./internal/gateway on Windows: clean. gofmt clean.
- -run 'Prompt|Classify|Turn|UserWords|Reminder|Notice|Claude' on the package:
  only TestClaudeAsRootEnv red, a known Windows red (#2425), untouched here.
Not run: mote (down), darwin/linux vet, the full suite, a real Claude Code.
The first quote of the report (a steer read as command output) is #1878,
fixed in v0.1.1220; not reproduced here.
2026-11-11 11:41:40 +08:00
yetone 7476328901 settings: one longest context for every model (WJaunita45604 on X)
Settings > Models > Routing has a Longest context field (magpie model
context-cap [<size>|off], POST /api/settings/context-cap). It lowers every
model's window to it, so a user need not set each model. A window the user
set on a model, or on its provider with "*", wins and is not capped; a model
whose window is unknown stays unknown.

It is applied where the window is derived, provider.windowIn, so /v1/models,
every agent's catalog, group windows and the compaction thresholds that
follow the window all agree. Codex's own models take it through
CodexNativeWindow, CodexWindow and codexcat.Cap on the list the gateway
serves; the list's ETag carries the cap so Codex asks again. The provider
editor's Listed value stays the vendor's.

Run (mote): provider, codexcat, cli, settings, settingsapi, gateway tests;
GUI context-cap, model-load, settings-places, i18n-keys, settings-general in
chromium and webkit (en, zh); TestCoreScriptBudget; gofmt; vet on darwin,
linux nogui and windows. Broken by hand: windowIn without the cap turns
TestContextCapHoldsEveryModelButTheOnesTheUserSet and TestModelsListContextCap
red.
Not tried: the whole GUI suite (one row added to an existing list, no new API
read on page load), a real Codex reading the capped list, Windows run.
Not covered: Claude Code's own [1m] choice (claudeRunName) and agent/claude.go's
fallback when a ref has no window.
2026-11-11 11:07:57 +08:00
yetone 1f99f6f0b5 provider, gateway: a backend that only streams is tested and served (Cyrus_4433 on X: claude-relay-service "400 · Stream must be set to true")
A CRS Responses endpoint, like Codex's own backend, turns away a request that
doesn't ask for stream:true. The editor's Test models and protocol detection
send one small body, so every model of such a relay was red; an agent that sent
stream:false got the same 400 through the gateway.

Probe: probeAt asks once more with stream:true when a 400/422 says the stream
must be set (provider.StreamRequired, WithStream). Chosen over streaming every
probe so a vendor that takes one body keeps being asked for one; every probe
(model test, per-model check, detect, key check) goes through probeAt.
Gateway: passthrough marks the model stream-only on that 400 for a request
asking one body and returns done=false; attempt then translates on the same
API (always streamed upstream, whole reply to the client), and asks so at once
from then on, as a refused custom tool is.

Run (mote): new tests built from the reporter's literal error, red on the old
code (TestProbeStreamsWhereTheBackendOnlyStreams, TestDetectFindsAStreamOnlyBackend,
TestWholeReplyFromAStreamOnlyBackend), green on the new; go vet darwin, windows,
linux nogui; go test ./internal/provider ./internal/gateway ok. Each fix broken
by hand (probe retry stashed, gateway hook stashed): red. Not tried: a real CRS
relay; the rest of ./... (started after the tag).
2026-11-11 10:37:13 +08:00
yetone 9cdeb485bb gateway: a limit that names one model rests that model, not the whole key (WJaunita45604 on X)
A 429 or quota refusal whose body names the model asked (Groq's per-model
TPD, OpenAI's per-model TPM, Gemini's QuotaFailure, any vendor's "limit for
model X") used to rest the account's key, so every other model of the
provider waited. modelNamed (routing.go) now sends such a refusal down the
same path as modelCooledDown: it rests restID (key/model). Readers of rest
state (restingOf, sink, GUI badges via Rest.Model) already understood those.
Account-wide refusals (no model named, another model named, credit, auth)
still rest the key. The id match is on whole ids (gpt-4o is not gpt-4o-mini).

Cline's and ZCode's guard tests expected another vendor's words to rest the
key even when they named the very model; they now expect the model alone.
The "not a trial" ZCode row moved to the new test.

Run (mote): the new TestModelNamedLimitRestsTheModelNotTheKey,
TestLimitNamingNoModelRestsTheKey and TestModelNamedReads, red on the old
code (mr-red.log); gateway tests matching Rest|Rate|Quota|Fallback|Limit|
Cooled|Pool|Overload|Sink|Credit|ZCode|Cline; gofmt; darwin, linux and
windows go vet of internal/gateway.
Broken by hand: modelLimited back to modelCooledDown only, the new tests go red.
Not tried: a real vendor account; the full suite (started after the tag).
2026-11-11 10:31:29 +08:00
yetoneandRainier 5c05ac41b9 web: a LazyCat sign-in takes no peer on a public address; the manifest lists /magpie-ca.crt (forgetable024 on X, #5987)
Follows Rainier's two commits (cherry-picked with authorship, #5987).

What LazyCat's own docs say (developer.lazycat.cloud/en/http-request-headers.html,
read today): lzc-ingress authenticates a request, and after a success sets
X-HC-User-ID, -User-Role (NORMAL or ADMIN), -Device-*, -Login-Time; "if
authentication fails, it will clear the above X-HC-XX headers", and "lzcapp
developers ... can directly trust X-HC-User-ID". X-HC-User-Groups is said to
have the caller's own removed. X-HC-Source is in no page of the docs; the
sign-in's use of it only narrows who gets in. The docs name no address for
the ingress, so the peer can't be named; a TCP ingress or port forward passes
headers as sent (the docs for it say no authentication), which the manifest
section already says to keep off the page's port.

This commit: lazyCatSignIn turns away a peer that isn't on a private,
loopback or link-local address (or isn't an address), whatever headers it
sends. The client-routes list gains /magpie-ca.crt, which main added after
the branch's base (TestLazyCatManifestListsTheClientRoutes was red on it).
TestTranslatedRoutesDropProxyIdentity adds the chat and messages routes to
the vendor-leak tests (native, Codex relay and MCP were covered).

Run (mote, go1.26.8): gofmt clean; go vet on gui, gateway and cli for darwin,
linux nogui and windows; LazyCat, ProxyIdentity, OnePort and Web tests in
internal/gui and internal/gateway ok.
Broken by hand: with the peer check off, TestLazyCatSignInIgnoresAPublicPeer
is red; with X-Hc- out of proxyIdentity, TestNativeAnyDropsProxyIdentity and
TestPassthroughDropsProxyIdentity are red.
Not tried: a real LazyCat box (none here); the plugin fetch route builds its
headers from the request magpie made, read, not run. Full suite and GUI
tests follow the tag.

Co-Authored-By: Rainier <74943233+Rmosser@users.noreply.github.com>
2026-11-11 10:15:40 +08:00
RainierandClaude Opus 5.5 4d9b798d50 web: a LazyCat box's administrators open the page with the box's sign-in (MAGPIE_WEB_SIGN_IN=lazycat) (#5987)
magpie in a LazyCat app (懒猫微服) is opened from the box's app list by
someone signed in to the box already, and asks for a key they never
saw: it is in the container's log. A package can only hand the key to
every browser that reaches the app, or put a proxy in front that adds
the key's cookie to what the box signed in.

The box's ingress, lzc-ingress, sends a browser that isn't signed in to
the box's login page, and puts on every request it passes the app the
box account (X-HC-User-ID), its role (X-HC-User-Role, ADMIN or NORMAL)
and what sent it (X-HC-Source, client for a browser), in place of what
the caller sent. With MAGPIE_WEB_SIGN_IN=lazycat webGuard takes that
sign-in besides the key: lazyCatSignIn lets in an ADMIN account sent by
a browser, each of the three named once, and tells anyone else the box's
reason.

The box's sign-in is a cookie of the box's, and the box's apps are one
site, so a browser sends it with another app's page's requests too: an
earlier build of this change let another app's page on the box include
/boot.js and read window.bootPrefs. So it is taken only for what the
page itself or the user asked for (boxFetched, the Fetch Metadata:
Sec-Fetch-Site same-origin or none, or a GET or HEAD navigation to a
document from another page), never for another page's script, frame,
fetch or form POST, nor from a browser that sends no Fetch Metadata.

It sets no cookie of the page's own, so signing out of the box signs out
of the page. The key's link and cookie work as before, /api still
answers the page alone (webOwnPage), and the gateway's client routes on
the page's port go to the gateway first (onePort), which asks for a
gateway key. StartWeb refuses another value, and lazycat where
LAZYCAT_APP_DOMAIN, which LazyCat sets in an app's containers, isn't
set: all magpie can check, so the setting is the package's word that the
box's ingress is the only way to the page's port. magpie web prints the
box's address beside the link.

Docs: reference.md's new LazyCat section, with a manifest and what must
never reach the page's port, and gui-shell.md's Browser mode row.

On a box (lzcos 1.6.2+fix.4), a probe app that echoes its request
headers: a signed-in browser's request carries X-HC-User-ID,
X-HC-User-Role ADMIN and X-HC-Source client, forged ones replaced; not
signed in, / goes to the login page and a public path gets none of the
three (forged ones taken off, repeated or in lower case too), while
X-HC-User-Groups passes on as the caller wrote it, so it is never read;
a TCP ingress passes every header as sent. Another app's container
reaches the app through the ingress alone (straight to the app's
container it times out); the box itself, and a container in its network
(network_mode: host, which a manifest may set), reach the port.

A test app made from the docs' manifest, running a build of this change
on 68cb92e8e in the image's place as its user (uid 65532): the box's
administrator opens the console with no key, and no cookie is set;
/v1/models still asks for a gateway key; from another app's page a
navigation opens the console, while a script include of /boot.js and a
frame are turned away; in the container, past the ingress, a request
with no Fetch Metadata, no X-HC-Source, NORMAL or a header twice gets a
401. Bound to /lzcapp/var/config, which the box makes as root's, magpie
couldn't write /config; bound to /lzcapp/var it can, and a gateway key
outlived the container.

Tests, through webServed with the headers the probe saw:
TestLazyCatSignInOpensThePage, TurnsAway, AsksWhereFrom, IsAskedEachTime
and IsNoGatewayKey (the client routes, with each sign-in that opens the
page), and TestWebBoxSignInChecksItsValue.
TestRemoteOpensTheOtherMagpie, new on main, gives webHandler no box
sign-in.

Run, at this tree, on 6c3f113ce: Docker golang:1.26.8 (linux/arm64):
gofmt clean; go vet -tags gtk3 ./... (with the GTK and WebKitGTK
headers, as CI), -tags nogui and GOOS=windows clean; both builds ok.
macOS 27.2 (go1.26.8, not root, a temporary HOME): go vet ./... and the
two cross vets clean, the three builds ok; go test -tags nogui ./...,
TestScriptFindsClaudeMoved skipped (it runs the real
/Applications/Claude.app, #5989): 92 packages ok; red outside
this change, each red the same at 6c3f113ce:
TestBunProxyLoginWithReservedCharacters (#3397),
TestGitUpdateInstallsTheBranchsCommitNow and
TestGitUpdateKeepsACommitPin (#5988), on this Mac's bun 1.3.11,
older than MinBun; TestEveryRouteHasACommandOrIsNamed: POST
/api/settings/join, new with e053c337a, has no command. /join, new
with it too, is a client route, so the docs' manifest lists it.

Broken by hand, each red, all green again put back; a break that lets in
what must be turned away was seen to reach the page: TurnsAway with the
once-each check out, no sender taken, the role in any case, the role or
the sender check out (IsAskedEachTime too), app:… and system alone
turned away, or the key's "open the link" kept in the box's 401;
AsksWhereFrom with boxFetched out, no Fetch Metadata taken, another
page's navigation taken of any method or into a frame, an object or an
embed (or anything but an iframe), its request for a document that isn't
a navigation, or another app's page's script (same-site, no-cors);
OpensThePage with another page's navigation taken by GET alone, or none
taken (IsNoGatewayKey too), a cookie set, or webOwnPage out;
IsAskedEachTime with the first sign-in kept; ChecksItsValue with lazycat
taken outside LazyCat or StartWeb not asking webBoxSignIn's error;
IsNoGatewayKey with the client routes behind the box's sign-in, or one
the box signs in on, or a HEAD to one, given to the page;
TestLazyCatManifestListsTheClientRoutes with /me out of the docs.

Not tried: a NORMAL account in a real browser (the box has one
account); signing out of the box in a browser; the box's own client
apps opening the page; a browser without Fetch Metadata; a header named
twice on a signed-in request through the ingress (a browser can't send
one); a multi-instance app; another lzcos version; a community plugin's
page on the box; a real vendor call through the box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:15:40 +08:00
RainierandClaude Opus 5.5 db4da33bc6 gateway: a LazyCat box's X-HC-* headers go on only to a provider whose PassHeaders names them (#5987)
On a LazyCat box (懒猫微服) every app sits behind the box's ingress,
lzc-ingress, which puts on each request it passes the app who sent it:
the box account (X-HC-User-ID), its role (X-HC-User-Role), what sent it
(X-HC-Source), the device (X-HC-Device-ID, -PeerID and -Version) and
when it signed in (X-HC-Login-Time); the box's docs name
X-HC-User-Groups and X-HC-User-Ticket too. A request signed in to the
box gets them on the app's public paths as well, where a package serves
the gateway's client routes. The native route, the Codex passthrough and
relay to the ChatGPT backend (copyHeaders) and /mcp/<server> passed them
all on, so a vendor, the ChatGPT backend or a remote MCP server was told
the box account's name and role and the device's ids.

proxyIdentity takes any X-Hc-* as what a proxy says of the caller, as
it takes Tailscale-*, so nativeHeaderDropped, copyHeaders and the MCP
proxy's header loop skip them. lzc-ingress's X-Forwarded-By was dropped
already (X-Forwarded-*). What 7d196b679 checked and left stays as it
is: a provider's PassHeaders passes on the names it lists, these too, as
the user chose them (gateway-routing.md now says so); Codex's
allow-listed codexHeader, the Codex websocket's headers (taken from a
request magpie built) and passOnCaller are as they were.

What the ingress puts there was read off a probe app on a box (lzcos
1.6.2+fix.4) that echoes its request headers: a browser signed in to
the box got X-HC-User-ID, X-HC-User-Role ADMIN, X-HC-Source client,
X-HC-Device-ID, -PeerID, -Version and X-HC-Login-Time, on a public path
the same as on /.

Tests: TestNativeAnyDropsProxyIdentity and
TestPassthroughDropsProxyIdentity send ten X-HC-* headers and
X-Forwarded-By beside the twelve they sent, and check that none arrive
and X-Custom still does.

Run (macOS 27.2, go1.26.8 darwin/arm64), at this tree, on 6c3f113ce:
gofmt clean; go vet, GOOS=linux -tags nogui go vet and GOOS=windows go
vet of internal/gateway clean; go build -tags nogui ok; both tests ok.
The next commit adds a test to internal/gateway and changes nothing else
of it; the whole package ran there: ok.

Broken by hand: with the X-Hc- prefix out of proxyIdentity, both are
red: the native vendor, the ChatGPT backend and the MCP server were each
told all ten X-HC-* headers.

Not tried: a real vendor call through a box; a provider whose
PassHeaders names an X-HC-* header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:15:40 +08:00
yetone bd60473c52 gateway: the MCP relay gives up a request body that stops moving over HTTP/2
The relay to a remote MCP server (mcpClient) is a Go http.Transport with
HTTP/2 on and carried request bodies, so a server that answers pings but
never opens its flow-control window held the call as long as the caller
waited (the same hang as f6c24c680's, @imty42 on X). It goes through
stallGuard now.

Audit of every Go sender a plugin-served request can pass: the gateway's
call to a plugin is pluginFetch -> plugin.Fetch, a JSON line on the host's
stdin to Bun's fetch, no Go HTTP client. The netproxy bridge relays a
CONNECT as a raw tunnel (Bun does the TLS and h2) and a plain-http request
over an HTTP/1.1 Transport with no TLS. internal/plugin's own Go clients
fetch the plugin market with GETs. None sends an h2 body. image_fetch_guard
and wbConfigClient only GET; codexrelay is HTTP/1.1 with keep-alives off.

Run (mote-run): TestMCPRelayBodyStalledIsGivenUp red 60s on the old code
(guard taken off by hand), green 2.9s with it; TestBodyStalled*, TestMCP*
ok; go vet linux, windows, darwin clean; gofmt clean.
Not tried: a real remote MCP server; the full suite after this commit.
2026-11-11 10:10:12 +08:00
yetone f6c24c6809 gateway: a request body that stops moving is given up on, and its connection dropped (@imty42 on X)
Over HTTP/2 a vendor can answer the health ping and never send WINDOW_UPDATE: the sender sits in awaitFlowControl for good, the connection counts as healthy, and the header wait never starts (net.send 535971ms, 499 after 8m56s). The ping watch and WriteByteTimeout can't see it: nothing is written, and the ping is answered.

stallGuard wraps each of upstreamTransport's three transports: a request body whose transport holds a chunk for bodyStall (90s) without asking for the next is cancelled, its connection closed, and the request sent once more on a new connection (GetBody; a body Go's own retry takes from GetBody is watched too). Still stalled, the error says so (errUploadStalled, read by failure as failProxy: nothing reached the vendor whole, nobody rests, the next member is asked). The clock runs only while the transport holds a chunk, never while the body makes one, and stops at the body's end, so a slow upload that moves or a long streamed reply is never cut.

Tests: TestBodyStalledByFlowControlIsGivenUp (h2 vendor, 128KB windows, never reads: red on old code, 60s ctx deadline; green after, 2 tries on 2 connections), TestBodySlowButMovingIsNotCut, TestStallBodyClock. Broken by hand: stallGuard taken off the transport. -race not run; 960 stressed runs (24 parallel x 10 x 4) of the three green. Not tried: the real commandcode account, WSL/Windows runs.
2026-11-11 09:53:25 +08:00
yetone 76d6296edf gateway: the key-slot keepalive test skips SSE comments before the first chunk
TestKeyConcurrencyKeepsStreamAlive went red on macOS CI (Race run
42920368236 at 8fa91a852) with `first = ": keepalive\n"`. The test sets
keepHeldAfter to 10ms, so a first chunk slower than that under -race
comes after a keepalive comment, and the test read that comment as the
vendor's reply. The first read now skips comment and blank lines and
checks the first data line.

Broken by hand: a 60ms sleep before slowVendor's first chunk for
"first" turned the old test red 3 of 3 with CI's exact message; the
new test passed under it. The sleep is reverted.

Run on mote: gofmt -l (clean), go vet ./internal/gateway, and
go test -race ./internal/gateway -run "TestKeyConcurrency|TestKeySlot"
-count=10: ok.
Not run: the full suite (test-only change in one test).
2026-11-11 08:58:10 +08:00
yetone bf4d8f3e5d gateway keys: a model may be a re: pattern, and a key may rename a model (tsingchao on X)
Access layer, CLI and gateway; GUI and docs follow. Tests: access pattern and alias tests; gateway TestGatewayKeyModelPatternHoldsEveryRoute and TestGatewayKeyAliasRenamesAModel, each red with the pattern match or aliasRequest switched off by hand.
2026-11-11 06:24:47 +08:00
yetone 5068e46fb6 provider: raise ZCode's plugin min to 0.1.58; a coding plan's 1310 leaves the trials (plugins#438)
takomitkm (plugins#438) hit two problems. The busy hold armed with one
account and one agent. A GLM Coding Plan model's weekly or monthly limit
(1310) also rested the whole account, so its -Trial models got the
cached 1310 without being asked. zcode 0.1.58 (ea3573bf in the plugins
repo, on npm) fixes the first in the plugin and lists the -Trial entries
free. magpie's PaidBesideFree then rests only the refused coding-plan
model. Raising the min brings every moved user up to 0.1.58.

TestZCodeCodingPlanLimitLeavesTrials holds both sides. With the trials
free, the 1310 rests GLM-5.3 alone and GLM-5.3-Trial is still sent. With
no free entries, or with another vendor, the same refusal still rests
the account. The fake plugin's $FAKE_ZCODE_FREE marks the trials free,
as 0.1.58 does.

Run (mote): go test ./internal/gateway -run 'TestZCode' -count=1, ok;
go test ./internal/provider ./internal/plugin -count=1, ok; go vet of
the three packages on mote, in WSL (magpie-desktop) and on Windows
(xiaomi-gpu), ok; gofmt -l is clean. All of this at this head, rebased
on origin/main. A whole-tree Linux vet in WSL stops at Wails' cgo
(webkitgtk-6.0 and gtk4 aren't installed there), so it doesn't cover
the GUI.

Broken by hand: with the fake's free mark dropped, the zcode 0.1.58
subtest fails, because the 1310 rests the account key.

Not tried: a real dual ZCode account that has reached its weekly limit.

Reported-by: takomitkm
2026-11-11 04:42:15 +08:00
yetone 6fa02550af gateway: TestServingGatesTools waits for the gate, not the listener (#6016)
ListenAndServe sets s.ln, then loads rests, acks, observers and groups,
and only then takes gwtool.Gate(), before the HTTP server starts. The
test waited for s.ln and checked Served at once, so on a loaded machine
it checked in that gap and read web search as still served. That was
the one red in a full -race run of internal/gateway on mote (2272s).

No user sees the gap: nothing is served before the gate is taken. So
the test now waits, up to its own 10s, for the gate to close, and still
fails if it never does.

Run on mote:
- with time.Sleep(300ms) injected after `s.ln = ln`: the old test red
  (search_plugin_test.go:151), this one green, -count=3 each;
- go vet -tags nogui ./internal/gateway; gofmt -l clean;
- go test -tags nogui -race -count=5 -run 'TestServingGatesTools$|Gate'
  ./internal/gateway: ok (150s).
Not run: the full suite again; the full -race gateway run before this
had this test as its only red.
2026-11-11 04:25:27 +08:00
yetone d77eb6d236 memory: search by meaning, on a small model on this computer
A memory search now finds what means the same in other words or another
language ("什么时候上线" finds "Releases go out on Tuesdays"), for the
MCP server's memory_search and the Library's Memory tab alike. It is off
until switched on under Memory → Search by meaning, since it downloads
paraphrase-multilingual-MiniLM-L12-v2 (Xenova's int8 ONNX, ~135 MB,
pinned revision, size and sha256 checked); switched off, the model is
deleted.

- internal/pii/guard: the BERT code runs the embedder too (LoadEmbedder,
  mean pooling; the tokenizer reads 250,002 pieces and WhitespaceSplit).
  Its vectors match ONNX Runtime's int8 to cosine >= 0.995 and are no
  further from fp32 than ORT's own; testdata carries both.
- internal/memembed: the switch, the download, vectors.bin keyed by each
  memory's sha256 (read once, again when the text changes, a cut-short
  file read as none), Keep reading in the backend, the model let go after
  10 minutes unused.
- internal/memory: memory.Semantic fuses the meaning ranking with the word
  ranking by reciprocal rank; a tie goes to the nearer in meaning, since
  a first word hit may hold one common word ("when do we release" had
  "Never delete images when..." first). Near 0.30 / Within 0.15 come from
  97 real memories and 16 queries, half Chinese for English memories:
  12 of 16 sought found with ~4 others each. Rank searches without noting
  memories used.
- GUI: the Search by meaning row (download %, memories read, failures),
  and the tab's search lists what the backend ranked first
  (POST /api/memory/rank), then word matches. zh, zh-TW, ja, de.
- docs/subsystems/memory.md: the section, out of "Not built yet".

Why not multilingual-e5-small, which this was built on first: run for
real, its cosines sat at 0.78-0.89 for everything, and a Chinese search
ranked Chinese memories over the English one it meant. e5-small, e5-base
and MiniLM were compared in ONNX Runtime on the same 97 memories; MiniLM
put the sought one first 9 of 16 and in the top 3 12 of 16, with the
rest at a median cosine of 0.16.

Run before the rebases (mote, on origin/main as of the work):
- gofmt -l internal/ clean; go vet of memembed, memory, pii/..., gui,
  library; GOOS=linux and GOOS=windows vet of memembed and pii/guard.
- MAGPIE_EMBED_DIR=~/models/pml go test -run Embedder ./internal/pii/guard:
  7 texts (CJK, full width, emoji, digits before runs of spaces) at
  0.9962-1.0000 with ORT int8.
- go test memembed, memory, memdistill, pii/..., library, browsermcp.
- Linux (magpie-desktop, -tags nogui, mote's disk was full): go test
  memembed, memory, pii/guard, gui (461s), cli (1228s, past the default
  10m timeout, so -timeout 30m); gateway -run 'MemoryMCP|OwnMCP'.
- Rebased on origin/main 3ebb1ba2c, on mote at this tree: gofmt -l
  internal/ clean; go vet of memembed, memory, pii/..., library, gui,
  gateway, and GOOS=linux and GOOS=windows vet of the first four; go
  test memembed, memory, pii/..., library, browsermcp (Embedder test on
  ~/models/pml); gateway -run 'MemoryMCP|OwnMCP'; cli -run
  'Settings|Parity|Budget'.
- Rebased again on origin/main 5d6935b11 (title bar, cli parity,
  account export, provider catalog): go vet of gui and cli; go test -run
  'Settings|Parity|Budget' of cli and gui, ok with the Bark test fix two
  commits up (TestSettingsSaveKeepsWhatItDoesNotSend, red on main).
- GUI on mote, this commit plus the next (90f4a377b, which fixes
  library-bar-more for #5982): every library-*.test.cjs, i18n-keys and
  i18n-en-no-cjk, BROWSER=chromium and webkit, 701/702 each. The red is
  library-loading's tab list, which has no "Claude plugins" (6af54dc9a)
  and is red alone at origin/main faffb1e95 (#5997). library-bili's
  webkit saved count times out about 1 run in 3, on main too (#6015).
- A real switch-on: the pinned files downloaded from Hugging Face and
  checked in 11s, 5 memories read; 什么时候上线, 端口被占用怎么办, 清理磁盘,
  回复用什么语言 and "when do we release" each find their memory first.
  缩进用什么 finds nothing (0.23 to the tabs memory, under Near).
- Broken by hand: without the tie rule, TestSearchFindsByMeaning's new
  case is red (images first).

Not run: the whole Go suite and the whole GUI suite; go test of
internal/gui and the whole of internal/cli after the rebases (WSL kept
restarting, and they passed on Linux before).
2026-11-11 04:14:58 +08:00
yetone 3ebb1ba2cb gateway: Antigravity's refused lines get two zero-width spaces a word, not one after the first letter (shzutbi1 on X)
Claude Code's chats on Antigravity answered 429 "Resource has been
exhausted" again. Reproduced on the owner's real Antigravity account with
Claude Code 2.1.316's own system blocks (claude -p captured through a
local server): both x-anthropic-billing-header and "built on Anthropic's
Claude Agent SDK" are still turned away, and the first-letter break the
cloak made ("x", U+200B, "-anthropic...", "b", U+200B, "uilt on ...") is
turned away too, so the cloak did nothing. Bisected on the account:
a break after the second character, two breaks, or a break in each word
of the line go through (3 of 3 each); a break after the third character
of "x-a" does not. Codex's and Hermes' lines now go through as written.

antigravityCloak now puts a zero-width space after the first and the
second character of every run of three or more letters or digits in each
matched line. The full captured Claude Code prompt with that transform
was answered 3 of 3 on the real account. The refusal is still told
against the prompt as written (hint, 400, no rest), unchanged.

Run: go test -run Antigravity ./internal/gateway on mote (ok), gofmt,
go vet darwin, linux nogui, windows. New TestAntigravityCloakClaudeCode2316
pins the real prompt's output. antigravity_codex_test.go and the Codex
check in antigravity_cloak_test.go read the sent prompt past the breaks.
The old test expectation (first letter only) was changed, not broken by
hand: the old code can't compile against the new helper.

Not run: the full suite (started after the tag), a sandbox magpie binary
(the transform was sent through the live gateway's real account), Hermes
and Codex lines against the real account beyond "as written goes through".
The community plugins carry the same cloak and are fixed in
magpie-community/plugins (antigravity 0.1.1, antigravity-cloak 0.1.3).
2026-11-11 03:54:37 +08:00
yetone 696556e26c provider: Google Vertex AI takes an API key (express mode) and a base URL (Langanpaibian on X)
Vertex AI could only be signed with gcloud credentials and a project id.
A provider now takes one API key instead: a Key with no project is Vertex
express mode, asked at https://aiplatform.googleapis.com/v1/publishers/
google/models/<model>:streamGenerateContent with the key in x-goog-api-key
(Google's docs), no project, no token minted. Express serves Gemini
models only, so Base(Chat)/Base(Anthropic) are empty and the models list
drops partner and Claude models. A key with a project is asked at the
project's address, signed by the key. Vertex.BaseURL (optional, /v1
stripped) replaces Google's host for a keyed provider, such as a proxy.

Security: a Google token or gcloud credentials go only to Google's own
address. A BaseURL is honoured only with a key, and the key is the only
credential sent there; without a key Save refuses it and a providers.json
holding one has it dropped on load.

Wired through: provider.Save/normalize/Sign/Base/planModels, `magpie
provider add google-vertex <key>`, `provider key`, `provider set ... url=`,
`provider <id>` and the list, the editor's API key and Base URL fields
(app.js, 4 translations each), the Providers row pill, and the
providers-accounts subsystem page.

Run (mote-run): gofmt -l clean; go vet for darwin, linux -tags nogui and
windows over ./...; go test -run Vertex for provider, cli, gui, gateway
and tui, all green, with new tests TestVertexExpressKey,
TestVertexExpressBaseURL, TestVertexExpressEditor (fake server) and the
gateway's TestVertexExpressStreams (chat, streamed and whole, asks
/v1/publishers/google/models/... with the key header, no token minted);
vertex-editor, i18n-keys and ledger-protocol GUI files in chromium and
webkit (en and zh editor flows; the i18n check covers zh, zh-TW, ja, de).
Broken by hand: Sign without x-goog-api-key turns the provider, gui and
gateway express tests red. The existing tests that pinned "a key is
refused" now pin the new rules.

Not tried: a real Vertex AI key (no account on hand; the endpoint and
header are from Google's express-mode docs, the tests use fakes), the
full GUI suite in webkit, Windows and Linux runs of the tests.
2026-11-11 03:54:21 +08:00
yetone 0a4c2b29a5 gateway: a translated reply's reader takes its keepalive interval from the request (#5973)
askTranslated's event goroutine can outlive the request that started it:
probeTranslated (a model test) returns at the first word and leaves the
reader to see the cancel. The reader, and the keepThroughSilence ticker
it starts, read the globals keepaliveEvery and keepaliveGap themselves,
so a later test's keepFast wrote them with no order between the two, and
-race failed TestQueuedStreamKeptAliveForTheMinute/chat on ubuntu CI
(run 42866003708, at 90f9f01a2). keepThroughSilence now takes the
interval as an argument; askTranslated reads both values on the
request's goroutine before starting the reader, and continuation.go
(whose reader runs on its handler) passes keepaliveEvery.

TestTranslatedReaderReadsNoKeepaliveLater asks a translated round, reads
the first word, then writes the intervals while the reader still runs,
as a model test leaves it.

Run on mote (macOS), -tags nogui:
- go vet ./internal/gateway: ok.
- go test -race -count=3 -run 'TestTranslatedReaderReadsNoKeepaliveLater|
  TestQueuedStreamKeptAlive|TestTranslatedStreamKeepsClientAlive|
  TestAntigravityModelTest' ./internal/gateway: ok (67.7s).
- Broken by hand: the new test on the old search.go, gateway.go and
  continuation.go goes red under -race (DATA RACE, FAIL in 0.01s).
- go test -race -timeout 45m ./internal/gateway: every test ok except
  TestServingGatesTools (0.04s), which passes alone -race -count=5 on
  this tree and does not touch the changed code. It is filed on its own
  issue; its full output was lost when the log was rewritten.
Not tried: Linux and Windows (wsl-run failed with E_UNEXPECTED).
2026-11-11 03:45:29 +08:00
yetone 6d78627693 gateway: an empty reply on two accounts of a model ends the request there (vhjjkkhg on X)
Alma on Responses to Antigravity's Gemini 3.8 Flash got "an empty reply"
now and then in multi-turn tool turns, and each account's in-place
re-asks plus the next account took 8 to 9 tries over 10+ minutes. A reply
that said nothing on a second account of the same provider's model is
about the request, not the account: the model's remaining accounts are
not asked (emptyAccounts = 2, `emptied` in the candidate loop). Other
providers and a group's other members still are, and nobody rests (the
#1221 branch is unchanged).

Cause of the empty reply itself: NOT found. Chat and Responses build
byte-identical Code Assist contents for a tool conversation (compared),
and about 50 real-account runs in a sandbox HOME (Antigravity login only)
across efforts none to xhigh, multi-user-turn tool loops over both
protocols, gave no empty reply. It looks like upstream's occasional
behaviour (#667 / #1221), so this commit bounds the cost and does not
claim a translation fix.

Run (mote-run): TestEmptyReplyOnTwoAccountsEndsTheRequest (Responses and
Chat; 5 accounts), TestGeminiEmpty*, TestLateRests*, full
./internal/gateway, gofmt, go vet darwin/linux/windows (nogui).
Broken by hand: with gateway.go's change reverted the new test is red
(12 asks, 5 accounts tried; 8 asks and 2 accounts with it).
Not tried: a real Alma turn on an account that returns the empty reply.
2026-11-11 03:32:27 +08:00
yetone 418bb6c9e1 codex: Show Codex's own models off leaves them out of Codex's own picker (iiiiiimone on X)
The switch (#1642) only narrowed the Agents page's pickers. Codex's own list,
which the gateway hands it beside its sign-in and as the Codex app's list
file, kept every model of the ChatGPT account, also with the Codex provider
switched off. codexMerged now leaves the sign-in's visible models out when the
switch is off (provider.CodexOwnLeftOut); the model Codex is set to, models
magpie serves on a ChatGPT account and hidden jobs stay, and the list's ETag
carries the switch so Codex asks again. Codex has one openai_base_url for every
model, so one it is still set to goes through the gateway to OpenAI on its own
sign-in; a model of it can't be sent direct beside magpie's models.

Run: TestCodexListWithOwnModelsOff, red with the filter turned off (own models
all listed, ETag unchanged); gateway, provider tests at this tree.
Not tried: a real Codex app against the list.
2026-11-11 01:54:05 +08:00
yetone 6b11914dfb gateway: name magpie's CA route for the one-port page and read-only keys
4623f5419 registered GET /magpie-ca.crt without classifying it, so
TestClientPathCoversHandler and TestReadOnlyKeyEveryRoute have been red
on ubuntu and macOS CI since (runs 42842906906, 42857020211).

The CA is answered without a key (caFileOpen), so a read-only key may
read it too, as it may the key and join pages; and `magpie web`'s port
hands it to the gateway like those pages, so the other computer fetches
it from the address it gives its agents.

Run (wsl-run, magpie-desktop, -tags nogui, at this tree):
go test -count=1 -run 'TestClientPath|TestReadOnlyKey|TestBrowserKey|
TestHTTPS|TestKeyPage|TestJoin|TestOnePort' ./internal/gateway: ok.
Red before: the two guards on CI at db0f2f20d and 5b28e8599.
Not run: the whole gateway package (running after the push).
2026-11-11 01:31:26 +08:00
yetone 4623f54190 gateway: HTTPS for other computers, from magpie's CA or an imported certificate (zhangly1 on X)
zhangly1 on X: Claude on another computer on the LAN needed magpie at
https://. Settings → Network and sharing → HTTPS (magpie https on)
serves other computers TLS on the gateway's own port, with a
certificate magpie's CA (the mTLS one, in ~/.config/magpie/mtls) signs
for this computer's names and addresses; this computer keeps plain
http://. The switch is read per connection, so no restart.

- Certificate row: Import… takes the user's own PEM certificate (with
  chain) and unencrypted key, in any files and order; a pair that can't
  be served (no key, no cert, a stranger key, a passphrase, run out,
  nothing PEM) is refused with the reason in the page's language and
  leaves nothing behind. Remove goes back to magpie's CA. --tls-cert
  still comes first.
- magpie's CA row: SHA-256 shown, Save puts magpie-ca.crt in Downloads;
  the gateway serves it without a key at /magpie-ca.crt to any address
  the share lets in. Rows under it give curl -kO, macOS, Windows, Linux
  and NODE_EXTRA_CA_CERTS steps with Copy.
- A page open from another computer can't turn HTTPS on or off under
  itself (it would lose its own address).
- magpie https status|on|off|import|remove|ca --out; the serve banner
  names magpie's CA or the imported file instead of "(mTLS)".
- docs/reference.md and gateway-routing.md say all of it, and that
  Windows' curl.exe needs --ssl-no-revoke for any private CA.

Run:
- gofmt -l clean; go vet linux -tags nogui ./internal/..., GOOS=windows
  and GOOS=darwin -tags nogui vet of the touched packages (WSL, mote
  refused ssh all evening).
- WSL: go test -tags nogui gateway -run HTTPS|MTLS|ClientCert|CAFile|TLS|LAN
  ok; gui -run HTTPS|MTLS|Keep ok; settings, settingsapi, mtls ok;
  cli -run Help|HTTPS|TLS|Serve|Banner|Flag|Unknown ok. The whole cli
  package hit its 40m timeout in TestEveryAgentFieldNameWritesNothing
  (#5234, #4247, not this change).
- GUI (WSL Playwright, chromium + webkit): https-settings (en, zh, 390px,
  strings in all four languages) ok, plus mtls-settings, allow-ips,
  browser-access, cors-origins, gui-de/ja/zh-tw, i18n-keys,
  i18n-en-no-cjk, lan-*, public-url*, api-key-theme,
  connect-address-kept, gateway-connect-keys, gateway-caller-keys,
  side-gateway-lan, menu-scroll. Reds at load ~130: api-key-theme
  (#5044), connect-address-kept (#5972), gateway-caller-keys (#2572),
  gui-ja (#5943), lan-docker (#4692), all red the same at base
  10bef5fe0 run beside it; allow-ips and gateway-connect-keys went red
  once under that load and pass 18/18 at concurrency 1, base and this
  change side by side.
- Real: a sandbox HOME gateway built from this tree on WSL
  (MAGPIE_ADDR=0.0.0.0:3593, a gateway key, magpie https on, magpie
  serve). From the Windows host: curl -k /magpie-ca.crt 200 without a
  key; Node fetch with NODE_EXTRA_CA_CERTS=magpie-ca.crt 200 on
  /v1/models, 401 without the key, SELF_SIGNED_CERT_IN_CHAIN without
  the CA; plain http:// 400; curl.exe --cacert needs --ssl-no-revoke
  (schannel), then 200. Cert SANs: localhost, the hostname, .local,
  127.0.0.1, ::1 and every address. magpie https import of an openssl
  CA's leaf on the running gateway: Node trusting that CA 200, magpie's
  CA alone refused. remove + off on the running gateway: plain http://
  from Windows 200. This computer's plain http:// 200 throughout.
- At the pushed tree (on origin/main ee818e8bc), WSL:
  gofmt -l clean; go vet -tags nogui linux, GOOS=windows, GOOS=darwin
  nogui of gateway, gui, cli ok; go test -run 'HTTPS|CAFile|MTLS|LAN'
  gateway, gui ok. GUI https-settings, mtls-settings, i18n-keys,
  gui-de/ja/zh-tw, allow-ips, lan-* (both engines): 147/155; reds are
  gui-ja (#5943), lan-docker (#4692), allow-ips webkit under load, and
  gui-zh-tw chromium under load (2 of 3 green alone, filed #5983).

Broken by hand:
- TLSOn without HTTPSOn: TestHTTPSOtherComputer red.
- lanGuard without the caFileOpen exemption: TestHTTPSCAFile red.
- mtls config without GetCertificate = settingsCert: all three
  serving tests red.
- app.js without renderHTTPS(s): https-settings red in both engines.

Not tried: the macOS, Windows and Linux system trust commands on a real
store (they change the box's trust); Claude Desktop itself; a darwin
GUI run (mote unreachable); the full suite before the tag (started
after it).
2026-11-10 23:05:47 +08:00
yetone 6c3f113cee routing: a rule's hours over give the conversation back; looser times (MinglunZhu on X)
MinglunZhu asked twice for a provider by time of day and said the time
setting in Routing rules is awkward. Three causes:

- A conversation a night rule sent to its member stayed there after the
  hours: no rule matched the new turn, so Auto affinity kept it on the
  night's member by its cache (Smart and every routing but In order).
  ruleFor now sets RuleHit.Ended when the last turn's rule had hours
  that are over, and affine lets the conversation go (Affinity.Why
  "hours"); the trace says so in en, zh, zh-TW, ja, de. Tool rounds of
  a turn begun inside the hours stay put; Session, Strict and In turn
  keep their own way.
- The time boxes took only ASCII "HH:MM", while their numeric keypad
  on a phone has no colon and a Chinese IME types ":". clockOf (GUI)
  and clockMinutes (CLI, saved files) now read "22", "2200", "930",
  "22:00", "22.00", "22点30" and full-width digits; "9:5" is still
  no time. time=22~08 takes ~ and ~ for the dash.
- A new rule starts with an intent box; hours took an × and a +. Adding
  another condition now drops the intent box while it is empty.

A time rule in a nested group doesn't give its conversation back yet:
#5977.

Run (mote): go test ./internal/provider (ok); go test -run
'TestRuleHoursOver|TestRuleTime|TestRule|Affinity|StandIn|Session|TestParse|Clock'
./internal/gateway (ok); go vet darwin, GOOS=linux -tags nogui,
GOOS=windows for gateway and provider; gofmt. GUI, chromium and webkit:
routing-time (8/8 after the new trace test's fix), and 28 rule/affinity/
i18n files (routing-rule-*, routing-time*, routing-intent-entry,
routing-folder, routing-pause*, routing-smart-intent, routing-save*,
routing-rules-line, routing-affinity-*, routing-behind-why,
routing-kept-again, routing-session-folder, i18n-keys, i18n-en-no-cjk):
477/481, the 4 reds the new trace test's first wording, fixed and rerun.

Broken by hand: affine's "hours" case off -> TestRuleHoursOverGiveThe
ConversationBack red (Smart stays on kb by cache); origin's
grouprule.go/ruleparse.go -> TestRuleTimeTypedLoosely red; client.js's
"hours" case and the intent give-way off -> routing-time 0/4 in
chromium; the old clockOf -> routing-time red on "9:00".

Not tried: the real app with a real night/day pair of providers; the
full gateway package and full GUI suite (the full Go suite runs after
the tag); Windows run of the touched packages (vet only).
2026-11-10 22:57:20 +08:00
yetone 72e804d2b5 gateway: a provider set Never a fallback takes no other model's request (sonnnnnnnnnnnna on X)
sonnnnnnnnnnnna asked that a request a local uncensored model was given
never falls back to an online provider (Anthropic, OpenAI) when the local
model is full (kv slots) or down, where it could get the account banned.

A provider now has Never a fallback (NoStandIn), off by default: the
Providers page's right-click, under Use first, ticks it; the CLI's
`magpie provider set <id> fallback-for-others=no` sets it. Its keys and
accounts are dropped from a request's plan once a candidate of an
unmarked provider was planned before them (standInsOut, run in planPaused
and in planGroup before restLast and sinkPlanned, so a local model that
failed and is resting still counts as first; a primary with nothing
planned counts too). A request that goes to a marked provider first still
moves on as before, and a weighed group (Smart, Cheapest) that picks a
marked member first sends it there. The dropped rows go to the trace's
left-out list as StandIn; the Routing page says why ("it is set never to
be a fallback for another model"), and the cap, held and barred refusal
checks ignore them so a refusal keeps its old status.

No classifier was built: the model that would judge the request is the
local one that is down, and any other would send the text somewhere the
user didn't choose.

Run on mote (macOS 27) at this tree on 065ca02c2: gofmt -l clean; go
vet darwin, GOOS=linux -tags nogui, GOOS=windows over gateway, provider,
gui, cli; go test ./internal/cli ./internal/gui ./internal/provider ok
(TestCoreScriptBudget after four comments cut in app.js, core 1,533,187
of 1,533,802, no raise), ./internal/gateway -run
'StandIn|UseFirst|Fallback|Barred|Capped|Group' ok (the whole package
ok at e6f151507); GUI in chromium and webkit, 126 of 126: stand-in (new,
5 languages, 1100 and 420 wide), provider-find (with the next commit),
use-first, menu-first-second, routing-held-member, unlisted-models,
i18n-keys, i18n-en-no-cjk; plugin-actions, routing-wb-refused and
group-found-skip ok at ca7a39291. provider-models-rest is red the same
at ca7a39291 (10 !== 83), #4396.

Broken by hand: standInsOut's drop turned off (`other && false`), and
TestNoStandInTakesNoOtherModelsRequest went red ("local down: 200 ...
from cloud2, want the spare").

Not tried: a real local model (llama.cpp/Ollama) going full or down, the
Windows box, a click in the real app.
2026-11-10 22:53:58 +08:00
yetone ee818e8bce gateway: a Claude run reads its flags, so Message Threads stop re-sending every image (nylesssssssss on X, #5963)
Every bridge run started Claude Code with
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 (there since the bridge's
first commit, 702477525, not added for #5582). With it, or
DISABLE_TELEMETRY or DO_NOT_TRACK, Claude Code 2.1.316 reads none of its
GrowthBook flags (its privacy level must be "default"), and Message
Threads are on by one of them, tengu_curious_tower. So every turn sent
the whole history again, every image in it (#4496's slow turns).

A turn's run (claudeRunEnv) now leaves the quiet variables out, so Claude
Code reads the account's own flags as a plain claude does. Updates and
error reports stay off (DISABLE_AUTOUPDATER, DISABLE_ERROR_REPORTING,
which the flags don't need). A quiet variable the user set, in magpie's
environment or in their Claude Code's settings.json env, is passed as
they set it (their telemetry choice; the run reads no settings of its
own). WSL runs get DO_NOT_TRACK too. The one-off runs (model test,
warm-up, /usage) keep the switch: no history, and an interactive one
would send probeQuotaStatus's request as it starts (#5582).

The issue's patch set CLAUDE_CODE_TETHER_LIVE=1 instead. Not taken: in
2.1.316 that variable wins over the account's flag (ryr(): the env value
is returned before tengu_curious_tower is read), so it would turn threads
on for accounts Anthropic hasn't given them, or has turned them off for.
Here nothing is forced; an account without the flag goes whole, as its
own claude does. Nothing of magpie's sends a request; CLAUDE_CODE_ENTRYPOINT
is untouched.

Run:
- Real Team account (sandbox CLAUDE_CONFIG_DIR + HOME, the keychain item
  copied to the sandbox's name and deleted after, token not rotated),
  claude 2.1.316 -p stream-json, haiku, one process, a 3 MB noise PNG then
  three text turns, bytes to api.anthropic.com per turn through a
  counting CONNECT proxy:
    magpie's old env (NONESSENTIAL=1): 672, 667, 667, 668 KB
    this env (no quiet vars, updater + errors off): 737, 6.3, 2.6, 2.6 KB
  Turn 4 answered the codeword from turn 1 both times. The fresh config
  had no cached flags; after the run it had 1223, tengu_curious_tower true.
  Other traffic with this env: one connection to Datadog's log intake
  (1.5 KB), Claude Code's own.
- go test -count=1 -run 'Claude|WSL|Warm|Usage' ./internal/gateway on mote:
  ok (139s). The full package queued behind ten suites on mote's lock
  and was not run before the tag; the full suite runs after it.
- TestClaudeRunReadsItsFlags: red with the run back on cleanClaudeEnvTTL
  (3 of its 4 cases; the one where magpie's env sets them passes on both), green with it.
- gofmt; go vet darwin, linux (nogui), windows of internal/gateway.

Not tried: a run through a sandbox magpie end to end, the interactive
(TUI) mode with a real account (an image turn runs as -p anyway), WSL, an
account whose flag is off.
2026-11-10 22:44:04 +08:00
yetone e053c337aa gateway: join a shared magpie with a password (EV_John_Liu on X)
EV_John_Liu asked for quick setup on a LAN: the central magpie serves a
page behind a password where other PCs and Macs get their config and a
new key of their own.

Settings -> Network and sharing -> Join with a password sets the
password (at least 8 characters; only a salted PBKDF2-SHA256 hash is
kept, in join.json, 0600, written through temp-and-rename; a file that
can't be read or parsed means joining is closed). The row then shows the
address to give out, <shared address>/join, and Turn off joining.

/join is the key page (/me) opened to join: the visitor types a name for
the computer and the password. POST /v1/magpie/join makes a gateway key
named after that computer (or "Joined from <ip>"). The key is listed in
Gateway keys like any other, where it can be limited or removed. The
page shows the key once and then the setup for that key: Claude Code,
Codex, a new magpie tab (`magpie provider add remote-magpie '<key>'
url='<address>'`), OpenAI-compatible and curl.

Every route judged:
- lanGuard lets another machine reach GET /join and the join route
  without a key, only while magpie is shared. The route checks the
  password itself.
- A browser's POST must come from the page itself. Host must be one of
  this computer's own names (IP, localhost, MAGPIE_PUBLIC_URL's, its
  hostname), so a DNS-rebound name is refused. Origin must equal Host.
  Missing Origin and Origin "null" are refused, and so is any
  Sec-Fetch-Site but same-origin. corsGuard still refuses null, foreign
  and *.localhost Origins before this. curl and scripts, which send no
  browser marks, are judged on the password alone.
- Throttle: each try from another machine costs a token, a right
  password too. The bucket holds 10 and refills one every 10s, so a
  guesser gets about 360 tries an hour, and a flood of tries makes no
  flood of keys. Over the limit the route answers 429 with Retry-After.
- The password and key never go in a URL or a log line. The key comes
  back only in a no-store 201 body. Logs name the key's id and the
  caller's address.
- The routes are classed in the key-slot and read-only route lists.
  They carry no key.

Run on mote at this head (rebased on 065ca02c2):
- gofmt clean
- go vet: darwin, linux -tags nogui and windows, for access, gateway
  and gui
- go test: access, gui, and gateway's join, route-list, key page and
  LAN tests
- The whole gateway package ran before the rebase, and its only reds
  were the two route-list guards fixed here.
- GUI (node --test), chromium and webkit: lan-join (new), key-page,
  mtls-settings, allow-ips, i18n-keys, lan-docker, lan-lazycat,
  lan-address-height, side-gateway-lan: all ok before the rebase, and
  lan-join, key-page and i18n-keys ok again at this head.
- That GUI run caught a TDZ error: JOINING was read before its const,
  which broke /me too. It is fixed in this commit, and key-page went
  from red to green.

Broken by hand (each red, then put back):
- no throttle: TestJoinHoldsAGuesser red
- no lanGuard bypass: TestJoinMakesARevocableKey, TestJoinHoldsAGuesser
  and TestJoinClosed red
- no ownHost check: TestJoinRefusesOtherPages red
- joinRefusal returning "": rebound remote, cross-site and no-Origin
  browser POSTs each got a 201, red
- Dropping only the Origin comparison stayed green, because corsGuard
  refuses the same Origins first.

Not tried:
- a real two-machine LAN join with the built app
- a Windows or Linux run of the tests (vet only)
- the full suite, which starts after the tag
2026-11-10 22:42:11 +08:00
yetone 87b3af7653 library: a project turns a global MCP server or skill off, out of git, and its worktrees follow (WhyULose0 on X)
WhyULose0 asked for MCP servers and skills per project: a global set every
project inherits, each project that set ± items (a global one turned off
for one project too), one place to tick for every agent, nothing written
into the project's git, the router running a shared server once, and a
new git worktree following its main project.

What was there: projects could add skills and servers (Library → a
project's card), the MCP router ran each server once, but a project could
not turn a global item off, magpie wrote its entries into the project's
.gitignore (a tracked file), and a worktree got nothing.

What changed:
- Turning a global item off in one project (ProjectServerOff,
  ProjectSkillsOff; POST /api/library/projects/server-off, skill-off),
  done the way each agent reads a folder: Claude Code's record of the
  project in ~/.claude.json (disabledMcpServers; magpie takes out only
  names it put there), Codex's project .codex/config.toml
  ([mcp_servers.X] enabled = false, only for a server in Codex's own
  config), Claude Code's skillOverrides "off" in the project's
  .claude/settings.local.json.
- With the router on, a project that adds or turns off a routed server
  gives Claude Code (local scope in its project record) and Codex (project
  config) the hub at /mcp/magpie/hub/<agent>~<projectKey>; hubServers
  serves that address the project's set, each server still started once.
  gateway.HubAgentOf cuts the key off for the log, errors and on-demand.
- Out of git: entries go to the repository's info/exclude (one block per
  project, shared by every worktree); the .gitignore is left as the user
  wrote it, and a block an older magpie wrote there is taken out. A folder
  git-inited later gets its block on the next KeepLinked.
- Worktrees: the project's folder in each worktree of its repository gets
  the same skills, servers and offs, found on KeepLinked, let go when
  removed.
- GUI: a project's card lights each agent that has an item from the
  Library; a click turns it off (or back on) in that project. An agent that
  can't take an off (Gemini CLI etc., or a skill that goes through the
  skill router) stays lit and says why. The Skills menu ticks inherited
  skills; unticking turns one off. zh, zh-TW, ja, de.

Limits, per agent:
- Offs only for Claude Code (servers and skills) and Codex (servers).
  Codex reads the project config only in a trusted project.
- A skill reached through the skill router can't be turned off in one
  project.
- Claude Code keys its record by the repository's main top folder, so a
  project in a subfolder turns its server offs on repo-wide.

Run (mote's SSH refused every try today, kex reset; every run went to
the WSL box through wsl-run, linux, at load 60 to 80 from other runs):
- go test -tags nogui ./internal/library: ok at this head. At the base
  before (4a9142ccd) TestEveryAgentInLibrary was red on main's own
  avibe/obsidian, fixed upstream since.
- go test -tags nogui ./internal/gateway ./internal/gui, one rebase back:
  gateway ok; gui ok but for TestSetAnswersWhileDevinAndProvidersHang
  (a set waited 37s; #1375, numbers added there). An earlier run had one
  TestMiddlewareThroughGateway red (the reply's first delta skipped a
  middleware's onEvent; nothing here touches middleware), 5 of 5 alone,
  filed as #5955.
- go vet: linux (-tags nogui) and windows clean; darwin (-tags nogui,
  cross from linux, no cgo) clean but for internal/gui's
  traywindows_darwin_test.go, which needs trayImagePNG from a
  darwin && cgo file, untouched here.
- gofmt -l: clean
- GUI, chromium + webkit: project-*, i18n-* and library-* 4 wide, then
  each red file alone at this head. Alone, all pass, project-scope
  included, but for library-mcp-copy-config ja chromium (#5941) and
  library-browser-setup (#5974); both are red the same way at origin/main
  without this change (40ca0c88d and 6bac8f8a5). library-all webkit
  (#4967) was red alone before the rebase, also at 40ca0c88d.

At 82a8acb09 (this change on 065ca02c2): go vet -tags nogui ./...
clean, ./internal/library ok, project-* and i18n-* GUI 32 of 32. Then rebased over b2b83d4f9's four commits (lessons,
gateway plugin models through a remote, a plugin hook test, agent auto
mode), none of them in a file this change touches.

Broken by hand, each red:
- Claude offs not written: TestProjectServerOff (no record)
- Codex offs not written: TestProjectServerOff (codex project config)
- hubServers ignoring a project's offs: TestProjectSetThroughRouter
- skill offs not written: TestProjectSkillOff
- worktrees not listed: TestProjectWorktreeFollows
- writeExclude a no-op: TestProjectServerOff, TestProjectKeptOutOfGitByExclude,
  TestProjectOutsideGit
- every chip click sent to the add path: project-scope.test.cjs

Not tried: a real Claude Code or Codex run in a project with an off (the
record and table shapes are read from Claude Code 2.1.316's and Codex's
config code, not watched working); darwin (mote down), Windows runs;
a real `git worktree add` (the test writes git's worktree files by hand).
2026-11-10 22:39:29 +08:00
yetone 53db4fda65 gateway: test a plugin's models through a Remote magpie (eachg0 on X)
eachg0 on X said Tabbit's plugin doesn't work when its magpie is
another magpie's Remote magpie. No magpie or plugin fault was found
on that path, so this adds only a guard: a plugin serving Chat alone
(the fake plugin, as Tabbit) is listed by the other magpie and
answers Chat, Responses and Messages, streamed and not, with tools,
each request passed to the remote once.

Run:
- TestRemoteMagpieServesPluginModels on mote at 065ca02c2: pass.
  Broken by hand (plugin rows left out of the list given to another
  magpie): red, "no models listed".
- go test -run 'Remote|Plugin' ./internal/gateway on mote: ok;
  go vet darwin, linux -tags nogui, windows: ok; gofmt clean.
- Two magpie processes in sandbox HOMEs on mote, the real Tabbit
  plugin (0.1.3) against a fake Tabbit site, A sharing with a gateway
  key, B's Remote magpie at A, over loopback and over the LAN IP:
  B lists office/tabbit/Default and GLM-5.3-Flash; Chat, Chat stream,
  Messages stream with tools and Responses stream all answer; a
  second turn in one session continues Tabbit's room (only the new
  message sent); three parallel requests queue behind maxConcurrency 1
  and all answer (3s, 6s, 9s).

Not tried: a real Tabbit account (none here), web.tabbit.ai (its 492
gate is plugins #833), the GUI on either side, Windows.
2026-11-10 22:37:48 +08:00
yetone c6bdce26fe agent: auto mode works on every model; its check is turned off unless each model gets Anthropic's results back (JoyYoung2Lucky on X)
Claude Code 2.1.322 in auto mode, routed through magpie, denied every
action it would check with "Auto mode can't check actions in this
session. Its safety check runs on the server, and your requests go
through 127.0.0.1:3425, which doesn't pass it through"
(auto_mode_no_check_in_session), on DeepSeek and on a Claude model
alike. 2.1.316 fell back to its own classifier there; 2.1.322 doesn't
when telemetry or feature flags are off (DISABLE_TELEMETRY,
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, ...), unless
CLAUDE_CODE_AUTO_MODE_SERVER is "0".

magpie wrote that "0" only when no model Claude Code could reach was
reviewed. Any reviewed one, a relay's Claude on its Anthropic endpoint
included, left it unset, and /model (or a route that drops
safeguard_results) then left the session with no check. That is why a
Claude model failed too.

Now claudeReviewed asks every reachable model (shown entries, group
members, fallbacks, the models it is set to) for
gateway.AutoModeAnswered: a reviewable model on the Claude subscription
or on api.anthropic.com. Any other writes "0", and Claude Code runs its
own classifier through the gateway, fitted to any model
(classifierStandIn); its model is the Claude Code card's auto mode
square (CLAUDE_CODE_AUTO_MODE_MODEL). An empty slot Sync passes (no
small model, say) is skipped, not judged as a model. The gateway still
passes safeguards to relays as before. Nothing mimics Claude Code and
CLAUDE_CODE_ENTRYPOINT is not set.

Real runs, Claude Code 2.1.322 in a sandbox HOME against the live
gateway as a client, auto mode, `ls /`, DISABLE_TELEMETRY=1:
- deepseek/deepseek-flash: the user's exact denial (before).
- deepseek/deepseek-flash with CLAUDE_CODE_AUTO_MODE_SERVER=0 (what
  the fix writes), with and without a classifier model set: the local
  classifier ran (permission_check_status checking -> done), Bash ran.
- openrouter/anthropic/claude-opus-5.5: ran (OpenRouter returned the
  results; the fix still writes "0" for it, which also works).
- claude/claude-sonnet-5 (subscription bridge): ran.
Fake upstreams with and without safeguard_results (in a stream's
message_delta delta) showed the same split.

Tests: TestClaudeAutoModeReview (DeepSeek beside a Claude model writes
0, the user's case), TestClaudeReviewedOnlyWhereResultsComeBack,
TestClaudeReviewedJudgesTheSetModelWhereItGoes (empty slot),
TestT3CodeAutoModeReview, TestAutoModeAnsweredOnlyWhereResultsComeBack.
Broken by hand on WSL, each went red: AutoModeAnswered true for any
reviewable model (relay cases red in agent and gateway); the old
"any shown entry reviewed" rule (the user's case and T3 Code red); an
empty slot judged as a model (three Claude-alone cases red).

Runs, each at the tree named (the diff is the same in all three):
- On 7e1858515 (this commit is on 065ca02c2 after it, a provider
  preset only), WSL magpie-desktop:
  go test -tags nogui -run 'AutoMode|ClaudeReviewed|ClaudeFirstWrite|
  T3Code|ProxyKept|Claude' ./internal/agent ./internal/gateway: ok.
- On a1ba92ad8: WSL full ./internal/agent and ./internal/gateway:
  gateway ok; agent ok but TestGrokInstalled, red on WSL at main
  already (#3548, binfmt interop). mote (darwin) ./internal/agent ok
  (267s); its gateway run lost SSH midway, so darwin gateway is not on
  record. Windows (xiaomi-gpu): the auto mode, T3 Code and proxy tests
  ok; TestT3CodeCodexInstance red as at main (#5130).
- On c2c2c82ca, mote: the targeted tests ok, go vet darwin, linux
  nogui and windows ok for internal/agent and internal/gateway.
- gofmt clean. The full suite starts after the tag.

Not tried: Claude Code versions other than 2.1.322; Bedrock, Vertex
and Copilot routes with real accounts (judged by AutoModeAnswered's
tests only); T3 Code's instance live.
2026-11-10 22:35:57 +08:00
yetone 7e1858515b remote magpie: name its models by the provider serving them there (lcc580 on X)
lcc580 asked for a pass-through on the Remote magpie provider: show the
upstream magpie's own provider beside each model, so an agent can tell the
same model from two of its providers apart. Before, the names followed
both magpies' Provider in model names: with either one Off, both relays'
DeepSeek Chat reached the agents as "DeepSeek Chat · Office" (or plain
"DeepSeek Chat").

- The list a magpie gives another magpie (X-Magpie-Drawers) now names,
  as magpie_by, the provider serving each model there (Entry.ServedBy):
  "routing group" for a group, and for a model of its own Remote magpie
  the provider at the start of that chain. The fetch keeps it as the
  model's By (catalog/live.go).
- A Remote magpie provider gets upstreamProviders: the editor's "Model
  names" tick ("With the provider serving it there"), or
  `magpie provider set <id> upstream-providers=on`. With it on, each of
  its models is labelled "DeepSeek Chat · Office › Relay A" in every
  agent's list, whatever either magpie's Provider in model names says,
  unless the user named the model themselves under Own
  (Entry.Label/upstream, LabelsFor). Model settings' "Agents' lists show"
  line follows the tick at once.
- Ids are unchanged, so a request still goes by office/relay-b/model.
  Off (the default) names everything as before. A remote older than
  magpie_by has nothing to add, so its names stay as before.
- The core's scripts stay in budget: four long comments in app.js were
  cut to pay for it, no raise.

Run:
- Tests that fail on the old code: TestRemoteMagpieUpstreamNames
  (gateway: an httptest remote with two relays' DeepSeek Chat and a
  group, every Provider in model names mode, on and off, the third
  magpie's magpie_by, ids kept), TestServedByAndUpstreamLabel (provider),
  and name-suffix-remote.test.cjs's new case (tick, hint, save body).
- Broken by hand: upstream() returning "" and the magpie_by line removed;
  both Go tests went red with the plain labels, then restored.
- Two real gateways, built -tags nogui on the Linux box (WSL) under
  sandbox HOMEs: B with Relay A and Relay B both serving deepseek-chat,
  A with B as Remote magpie "Office". A's /v1/models before:
  "DeepSeek Chat · Relay A · Office"; after
  `provider set office upstream-providers=on`:
  "DeepSeek Chat · Office › Relay A" / "› Relay B" / "› routing group".
  A request for office/relay-b/deepseek-chat reached relay-b on B.
- gofmt -l clean; go vet darwin, linux (nogui), windows on the touched
  packages; go test catalog, provider, gateway, cli, gui on mote
  (macOS) at the rebased head: ok (catalog 2.6s, provider 165s, gateway 948s, cli 56s, gui 149s).
- GUI on mote, chromium and webkit: name-suffix-remote, remote-magpie,
  remote-self, i18n-keys, i18n-en-no-cjk, gui-ja, gui-de, gui-zh-tw,
  provider-detect-draft, provider-unmasked, routing-remote-windows,
  usage-remote-cards: all green except reds that fail the same on origin/main 388ca9ad4 (run there on the Linux box): gui-ja "ja has every zh string" (#5943) and remote-magpie "asks for the other magpie's address" in both engines (#4398); name-suffix-remote's old "named alone under Off" once in chromium de (#5147, scrollends.js import under load). The new case first failed in webkit (route lost after the save, the page's host went to DNS); it now uses one route whose server is swapped, 20 of 20 on the Linux box (WSL), both engines.

Not tried: the full suite (starts after the tag); the real desktop app's
editor by hand; a chain of three real magpies (the third magpie's
magpie_by is covered by the gateway test only).
2026-11-10 22:20:17 +08:00
yetone b9a1b4aa1d copilot: each account's own models, listed together and routed only to the accounts that have them (applemacssma on X)
"支持多个ghcp账号轮换和平均负载均衡吗,每个ghcp账号有的模型不一样。"
Several Copilot accounts and the Routing strategies (In turn, by usage)
worked already. What didn't: the copilot provider's list was the first
account's /models alone, so a model only another account's plan has was
nowhere to pick, and the gateway took every account to have every model.

Now each Copilot account's /models is kept as its own (accountModels,
read by Account.Lists), and the provider's list is their union
(copilotPoolModels over poolModels, the body codexPoolModels had). A
fetch of the first account's list also asks the other accounts on: one
with no list at once, of the rest the stalest once its list is a day
old, one per fetch. Only a failed ask is remembered (retried after an
hour). A model Copilot refused one account (model_not_supported) stays
in the list while another account on lists it (copilotOthersList).

Run (WSL magpie-desktop at 425195bf3; mote refused SSH all session):
- go test ./internal/provider/ ./internal/gateway/ -timeout 45m: ok
- go vet linux, GOOS=windows, GOOS=darwin CGO_ENABLED=0 for both: ok
- gofmt -l: clean
- TestCopilotAccountsWithOtherModels: octocat lists gpt-4.1 and
  claude-opus-9, hubot gpt-4.1 and gemini-9-pro; the list is the union,
  each model goes only to its account under In turn, gpt-4.1 to both.
- TestCopilotRefusedModelGoesToTheAccountServedIt: octocat's list has
  gemini-9-pro but Copilot refuses it; it then goes to hubot alone and
  stays listed.

Broken by hand:
- copilotPoolModels call removed: the first test red ("lists [gpt-4.1
  claude-opus-9 auto], without gemini-9-pro").
- models.go's union check dropped: the second test red (gemini-9-pro
  left the list).
- A refusal check in Account.Lists made no difference (the gateway
  already keeps a refused account off that model), so it isn't in.

Not tried: real Copilot accounts on two different plans; the full
suite (runs after the tag).
2026-11-10 22:19:31 +08:00
yetone ca7a392919 gateway: MiniMax's image-01 draws on its own image_generation API (rocbomb123 on X)
minimax-cn/image-01 went to chat completions (catalog.ImagesAPI doesn't
know image-01), and MiniMax answered "invalid params, unknown model
'image-01' (2013)". MiniMax draws only on POST <host>/v1/image_generation
(platform.minimax.io and platform.minimax.cn API reference, t2i and i2i,
checked against the docs, not the report).

- draw_minimax.go: a MiniMax API key (filmsMiniMax: the minimax and
  minimax-cn presets, or any provider at api.minimax.io, api.minimaxi.com
  or api.minimax.cn) lists image-01 and image-01-live as drawers and
  draws them at its own host: size -> aspect_ratio (a listed ratio or its
  size; else image-01's width/height in 512..2048 by 8; else the nearest
  ratio; 21:9 image-01 only), n, response_format base64, edit images as
  subject_reference type character, the caller's seed, prompt_optimizer,
  aigc_watermark and style passed on; mask and markup refused before
  asking. data.image_base64 / image_urls are read; base_resp failures in
  a 200 are told by code (1004/2049 key 401, 1008 balance 402, 1026
  content 400, 1002 rate 429, 2013 400), and all images held back
  (metadata.failed_count) says so.
- draw.go: viaFor sends them to the images path, drawImages to
  drawMiniMax, DrawersOf adds them for a MiniMax key.
- A relay serving MiniMax models under another host is unchanged. The
  minimax-code plugin sign-ins are not API keys and are untouched.

Run (mote, at e6f151507 + this change; after the rebase onto
origin/main, which touched no gateway file, -run 'MiniMax|Draw'
./internal/gateway again at the pushed tree: ok):
- go test -count=1 -timeout 45m ./internal/gateway: ok (947s)
- go vet ./internal/gateway on darwin, GOOS=linux -tags nogui, and
  GOOS=windows: ok; gofmt -l clean.
Broken by hand: with the viaFor case and the drawImages hook removed,
TestMiniMaxDrawsOnImageGeneration fails for minimax and minimax-cn with
the reporter's exact "unknown model 'image-01' (2013)".
Not tried: a real MiniMax key (no account here); the fake answers with
the documented bytes. GUI suite not run (no GUI file changed; the
Providers page reads Drawers from the API). Full ./... suite runs after
the tag.
2026-11-10 21:47:45 +08:00
yetone e6f151507f sessions: each session's output speed, a curve of its last two minutes
The owner liked a tweet's token-speed curve and approved a mockup
(claude.ai/artifact/7mrkMKdVi6jA3HA1Z6pRr5). Each Sessions row now
shows its output speed with a small curve; clicking it opens a popover
with the current tok/s, two minutes of seconds, tool gaps, and the
round's average, fastest second and output so far. A row not live
shows "Avg {n} tok/s".

Gateway: a curveMeter (session_speed.go) on the Server counts every
reply's content bytes per agent and session, from liveRow.observe, the
same count the Live view uses, and turns them into tokens with the
learned per-model rate (tokenRates.rate). A model with no rate yet
shows the curve's shape and no number: a guess would be a wrong
number. counted() opens a session's in-flight span, so a second with
nothing in flight is a gap (a tool ran), not a zero. A pause past 2m
starts a new round; 10m of quiet forgets the session; at most 256
sessions. Codex's own sign-in (codex_backend.go) went past serve and
liveRow before; it now has a liveRow too, so its sessions are counted.

GUI: GET /api/speeds, kept out of /api/sessions* so a once-a-second
poll doesn't set off session reading. The page polls only while
Sessions is shown and visible. managedJSON gains keys, so a row
matches a session the gateway saw under another of its keys. The
curve hides below 620px.

Run (mote's sshd resets every connection today, so Linux and Windows):
- Linux (magpie-desktop, wsl-run): gofmt clean; go test -timeout 45m
  ./internal/gateway ./internal/sessions ok except
  TestGroupFailoverTimesEachTry, red once under load, 5/5 green alone
  here and on main (#5948); node --test over every sessions-*.test.cjs
  and i18n-*.test.cjs: 546/549, the reds sessions-export en in both
  engines, the same on origin/main d657e182a alone (#5947), and
  sessions-folder-paging webkit zh, green alone. sessions-speed in
  Chromium and WebKit x en, zh, zh-TW, ja, de (row, popover, live
  update, narrow width, no poll off the page).
- Windows (xiaomi-gpu, win-run), at this head: go vet ./... clean; the
  curve/live/rates/codex tests of ./internal/gateway ok; go test
  ./internal/gui ./internal/sessions ok but 12 tests, every one red the
  same on origin/main 4d95d81ea and filed (#4115, #5928, #4043, #4925,
  #5324; TestAntigravityAppFolder new as #5957). (internal/gui needs gtk4 for cgo, which
  the WSL distro lacks.)
- At the pushed head (on 6886da1ca, which changed core i18n.js and
  gateway.go), Linux: sessions-speed, i18n-keys, i18n-en-no-cjk,
  sessions-row-narrow 22/22; the gateway curve/live/rates/codex/CORS
  tests ok. The Windows run above was at 4d95d81ea.
Broken by hand: with live.go's curves.add skipped, both
TestSessionCurveFromARealStream and TestSessionCurveFromCodexOwnSignIn
went red; green once restored.

Not tried: a real agent session in the built app; macOS (mote down);
darwin vet; the full go and GUI suites (run after the push, reds
filed).
2026-11-10 20:22:17 +08:00
yetone f92c0a2bdd plugins: a plugin is told the effort asked, and its usage windows keep their pool and family
What a ported Antigravity needs from the host, kept generic:

- The gateway puts the request's reasoning effort on a plugin's fetch as
  X-Magpie-Effort (provider.EffortHeader), so a plugin that serves one
  model at several levels can pick the level. host.js strips it with the
  other magpie-only headers, so the vendor never sees it.
- A plugin's usage window may name a Pool and a Family; quotaOfPlugin
  passes them through, so PooledWindows names a shared pool
  ("Gemini · 7 days") as it does for the built-in.

Run (WSL magpie-desktop; mote unreachable, kex reset):
- TestPluginToldTheEffort: xhigh, low and none reach the plugin; the
  vendor gets no X-Magpie-Effort. Red with the MAGPIE_ONLY entry removed
  by hand (the vendor saw the header).
- TestPluginWindowsKeepPoolAndFamily, TestPluginToldTheSession: pass.
- Full suite: in the next commit's body (run at the head of both).
2026-11-10 20:16:44 +08:00
yetone 4a9142ccd4 agent: Obsidian, magpie's models in Copilot for Obsidian (shirotokiren on X)
shirotokiren asked for magpie to set up Obsidian's AI plugins, naming
Copilot and Smart Connections.

The new agent "obsidian" finds the vaults in Obsidian's obsidian.json:
~/Library/Application Support/obsidian on a Mac, %APPDATA%\obsidian on
Windows, and on Linux $XDG_CONFIG_HOME/obsidian or the Flatpak or Snap
folder. In each vault that has Copilot for Obsidian 4+
(.obsidian/plugins/copilot), magpie edits data.json in the shape
Copilot 4.0.19 reads:
- it adds providers.magpie, openai-compatible at /agent/obsidian/v1,
  with requiresApiKey false and no keychain id;
- it adds one configuredModels entry per magpie model, with a
  deterministic uuid v5 id, plus limits, image input and reasoning
  efforts;
- new models go into backends.chat.enabledModels;
- on the first wire it sets defaultModelKey, and stashes the old value.

A sync keeps the models the user turned off, their default, and the
name they gave the provider. It writes only the keys that change
(edit.PatchJSON, then temp and rename), and nothing when nothing
changed. A provider named magpie counts as magpie's only when its
baseUrl is magpie's Obsidian route. One the user added by hand under
that name is theirs: it doesn't read as connected, Disconnect leaves
it, and Connect says so and writes nothing. Disconnect takes magpie's entries out and puts the old default
back. Copilot 3, a data.json it can't parse, and no vault with Copilot
are each an error, and nothing is written. A notice asks the user to
reload Copilot, since Obsidian holds the settings in memory.

The gateway now answers CORS for app://obsidian.md keylessly
(appOrigin). Copilot streams through the window's fetch, and without
CORS headers it can read no reply. Only Obsidian's own window sends
that origin, so it gets no more than its calls without an Origin get.
From the network it still needs a key.

Smart Connections is not wired. Its free plugin embeds with a local
model only, and its API providers are in the closed Pro plugin, with
keys in the keychain.

Run (mote, at 401187300 + this commit, then again after rebasing on
9c39edb92):
- gofmt
- go vet for darwin, linux nogui and windows
- go test -run 'Obsidian|Notice|CORS|Craft' ./internal/agent ./internal/gateway
- GUI, chromium and webkit: i18n-keys, i18n-en-no-cjk, icon-one-tone
  (56 of 56)
At 9c39edb92 + this commit: the whole internal/agent package ok
(211s), vet for darwin, linux nogui and windows, CORS tests ok.
At 4d95d81ea + this commit: Obsidian, HandWired and Spelled tests,
vet for darwin and windows, and the three GUI files again (56 of 56).
win-run: TestObsidian* ok on Windows 11.

Broken by hand (each went red, then was restored):
- corsGuard without the appOrigin branch: TestCORSObsidian, preflight
  404.
- re-enabling every magpie model on sync: TestObsidianCopilot, "a
  model the user turned off came back on".
- dropping the user's configuredModels: TestObsidianCopilot.
- counting any provider named magpie as magpie's:
  TestObsidianCopilotHandWiredMagpieIsTheirs.

Not tried: a real Obsidian with Copilot loading the written data.json.
The fixtures follow Copilot 4.0.19's types and migrations. Not tried
over LAN either. The full suite runs after the tag.
2026-11-10 20:06:21 +08:00
yetone 18c932385e claude: a Claude model Claude Code doesn't know is run to 1M, so Codex compacts on Fable 5.2 (magicalaciw18 on X)
Codex on claude/claude-fable-5-2 (the Claude subscription bridge) never
auto-compacted. magpie tells Codex the model's 1M window and Codex
compacts at 272K, but Claude Code 2.1.316 doesn't know claude-fable-5-2,
so it assumes a 200K window. It turned every conversation past 200K away
before Anthropic was asked ("Prompt is too long", blocking_limit, 0
tokens). Codex got that refusal as a failed turn, not a compaction.

claudeRunName now asks Claude Code for such a model by its "[1m]" name.
That applies to a Claude model of generation 5 or later that Claude Code
doesn't know (claudeKnownLong) and whose window magpie doesn't know to be
under 1M. Models it knows keep their names, since a new name misses the
prompt cache once. Every generation 4 model keeps its name too:
claude-sonnet-4-6[1m] is refused even a short turn on an account without
usage credits. Only Claude Code's --model changes. The reply, the saved
session and the logs keep the model as asked.

Real runs (sandbox CLAUDE_CONFIG_DIR, real accounts, claude -p 2.1.316,
~275K-token prompt):
- claude-fable-5-2: Prompt is too long / blocking_limit.
- claude-fable-5-2 with CLAUDE_CODE_MAX_CONTEXT_TOKENS=1000000, or with
  CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT=1: still blocked.
- claude-fable-5-2[1m]: OK.
- fable-5-1, sonnet-5-5, opus-5-5, haiku-5-5 plain, and fable-5-1[1m],
  sonnet-5-5[1m]: all OK.
- Short turn: sonnet-4-6[1m] got 429 "Usage credits required for 1M
  context" on one account; opus-4-6[1m], opus-4-8[1m] and fable-5-2[1m]
  were OK.
- The live gateway gave the same refusal: 230K to claude/claude-fable-5-2
  was refused, while claude/claude-fable-5-1 took 269K.

Siblings: Copilot lists max_prompt_tokens 200000 for claude-sonnet-5.5,
while magpie says 1M. A real 265K turn on copilot/claude-sonnet-5.5 (and
on copilot/claude-fable-5.2) was served, so that limit isn't enforced and
was left alone.

Tests: TestClaudeRunName, and TestClaudeRunAsksUnknownModelLong, which
uses a fake claude that records its args.
Run on mote:
- the new tests with TestClaudeCLI* and TestClaudeRunKept*: ok;
- go test -count=1 -timeout 45m ./internal/gateway/: ok (900s);
- go vet for darwin, linux -tags nogui and windows on ./internal/gateway/;
- gofmt -l: clean.

Broken by hand:
- passing the bare model to claudeCLIArgs made
  TestClaudeRunAsksUnknownModelLong red (asked for "claude-fable-5-2");
- dropping the generation 4 floor made both tests red (sonnet-4-6[1m],
  haiku-4-5[1m], opus-4-8[1m]).

Not tried:
- a real Codex session compacting through a sandbox build end to end;
- Claude Code versions other than 2.1.316, where the list of models it
  knows differs;
- Windows (the fake claude is a shell script, so the test skips there).
The full suite runs after the tag.

Rebased on 9c39edb92 (32 commits on, incl. 401187300 catalog fallback and 543eb39b9 interactive runs): the Claude run tests in internal/gateway, go vet darwin/linux nogui/windows ok again at this head on mote. The interactive mode takes the run's args (interactiveArgs), so it asks the [1m] name too.
2026-11-10 19:55:26 +08:00
yetoneandRex Zhou 5673eab0ba redact: mask crypto wallet keys, seed phrases and exchange passphrases (#4025, rexzh0u on X)
Rex Zhou's #4025 proposed default rules for crypto secrets. This ports
them with every shape that can also be ordinary text checked first:

- WALLET_KEY: 64 hex digits (0x or bare) only after a key's name on the
  same line (private key, secret, signer, deployer, wallet, pk, 私钥 …),
  and not when a hash, sha, digest, sum, pub, addr, tx or an id name sits
  between: tx hashes, block hashes, storage slots and sha256 sums go as
  written. noIDs keeps it, since the name already says it is a key.
- WIF and BIP32 xprv/tprv: base58check (double sha256) and payload length,
  so a random base58 run, an xpub or an address is not one.
- Solana: a base58 secret or a 64-number keyfile counts only when its
  second half is the ed25519 public key of its first; a tx signature,
  same length, goes as written. Each number in a keyfile is <= 255.
- Stellar S... seeds: StrKey version byte and CRC16-XModem.
- Prefixed kinds: NEAR ed25519:, Sui suiprivkey1, Aptos AIP-80
  ed25519-priv-0x, Nostr nsec1, age, Zcash secret-extended-key.
- SEED_PHRASE: after seed/mnemonic/phrase/recovery (and zh, ja, ko), the
  longest run of words from the BIP39 English list, cut to 12/15/18/21/
  24/25 words. The list is embedded, its sha256 checked by a test against
  the published one. A sentence after "recovery" has words off the list.
- Exchange keys: secretNames gains passphrase/pass (OKX, Coinbase, KuCoin)
  and priv_key; API key and secret fields were already masked by name.

What the patch had that does not ship: every 0x+64 hex masked (tx and
block hashes), unchecked base58 lengths for WIF and Solana (any long
base58 run), and a phrase pattern that took prose after "recovery".

The three rules with no marker (WIF, Solana, Stellar) run their pattern
only after a byte scan finds a long enough run (rule.may). Without it the
prose benchmark went from 2.9ms to 15.8ms per MB; with it 3.0ms, the
same as without the rules (profile: sha256 of the memo and memmove).

Run (wsl-run magpie-desktop, mote refused SSH all session):
- go test -count=1 ./internal/redact: ok
- go test -run TestCountTokensRedacted ./internal/gateway: ok (crypto on
  with Redact, off with RedactPersonal only)
- gofmt -l; go vet linux, -tags nogui, GOOS=darwin, GOOS=windows for
  internal/redact and internal/gateway: clean
- node --test site/worker.test.mjs (llms-full, docs): 7 of 7
- false positives: 1000 npm sha512 integrity lines, go.sum h1 lines,
  git shas, uuids, sha256 sums, std and URL-safe base64 blobs, xpub,
  addresses, IPFS CIDs, bech32, npub, public keys: none masked.
- 1MB inputs of each shape stay linear (RE2, no backtracking).

Broken by hand, each red: Solana unchecked (Lookalikes, Lengths), WIF
unchecked (Lookalikes), WALLET_KEY without its name check
(WalletKeyNeedsItsName, LockfilesAndBlobs), phrase without the wordlist
(SeedPhrase), Stellar unchecked and keyfile unchecked (Lookalikes), rules
unwired (7 tests).

Not tried: real wallets (test vectors are the BIPs', NIP-19's and
derived keys); Monero's own word list; other BIP39 languages; a Windows
or macOS run of the tests; the full suite (after the tag).

Co-authored-by: Rex Zhou <zhouzhuojie@gmail.com>
2026-11-10 19:00:46 +08:00
yetone a16da55d39 gateway: only an image message beside tool results carries the turn; the user's words still begin one (#5767, nylesssssssss on X)
ggbdpq's turnIn change (the commit before) carried every message after a
tool result within the turn. match and findRun read only a message with
images there as the result's caption; the user's text-only message beside
results is saidWithResults, a new user turn. turnIn now carries a message
on only when it has images, so a text "stop, read the other one" after a
result still starts a turn and router affinity moves with it.

Ported for nylesssssssss on X: #5584 (Suge8's interactive effort patch,
ae3ba37a9) and #5767 (ggbdpq's image-beside-result patch, de4ac2fb0),
both kept as their authors' commits after the look-for-harm check.

Run (wsl-run, linux; mote refused SSH):
- internal/claudetui -run TestTap (bun and node): ok
- internal/gateway -run "TestClaudeTUI|TestTurnIn|TestToolResultsName|
  TestSubscriptionToolResultImages|TestClaudeToolResultsKeepTheSelectedAccount|Affinity": ok
- internal/claudetui and internal/gateway whole (wsl-run, -count=1): ok
  (claudetui 123s, gateway 1545s), at the base before the rebase
- rebased on origin/main again (its claudetui pty_darwin/tui and gateway
  ir/rules changes): go vet linux/darwin/windows, internal/claudetui
  whole (122s) and the gateway -run set above: ok; gofmt -l clean
Broken by hand:
- resume back to abortFor: all three TestClaudeTUIEffort* red
  ("started 2 runs, want one at medium")
- the image case taken out: TestTurnInCarriesAnImageBesideItsToolResult red
- `said && results` back: the new user's-words case red
  ("turn 1 within true, want 2 false")
Not tried: a real interactive Claude Code run with an effort change
against a real subscription; #5853 (no patch, still open).
2026-11-10 18:57:44 +08:00
ggbdpq 800c7c1884 gateway: an image beside its tool result carries the turn (#5767)
pi sends a tool's picture in a user message after its text-only tool
message ("Attached image(s) from tool result:"). turnIn read that
message as the user's next ask — an image of theirs begins a turn —
and ended the turn there. The bridge reads it as the result's, and
hands the picture to the waiting run (match); the router, told the
turn was over, stopped keeping the conversation to the account that
answered it, and re-decided it per request. When the pick landed on
another account, the bridge let the run go — another account's Claude
Code must not spend its quota — and a new one was told the whole
conversation: "tool results account changed", the fixed prefix read
from the cache, everything after it written again, at each of the
session's image reads. The same results as text carry no picture
message, the turn held, and nothing restarted.

An image beside the turn's results now carries the turn on, as the
bridge tells it; the user's own image with no result of the turn's
waiting still begins one. And when a changed owner still lets a run
go, the log names both sides — "account changed: the run was on
claude (a@example.com), this request goes to claude (b@example.com)",
own sign-ins and plan-named accounts marked — instead of a bare
"account changed" that left the reporter guessing at image hashes.

Ablation: with the carries-the-turn case out,
TestTurnInCarriesAnImageBesideItsToolResult fails at "turn 2 within
false, want 1 true" — the reporter's shape. Whole, it passes, and
the user's own image still counts a turn.

Run at upstream/main e3ab7f3bf + this commit, macOS 15 (darwin/arm64):
TestTurnIn*, TestToolResultsNameTheChangedOwner, the turn/affinity/
bridge family, and internal/gateway whole (-tags nogui, 826s) ok.
2026-11-10 18:57:44 +08:00
Suge8 543eb39b94 gateway, claudetui: an interactive run asked another effort goes on in its run, the conversation read from the cache
#5584 (Suge8, magpie 0.1.3216, Claude Code 2.1.318, Pi on Opus 5.5,
interactive mode): a turn asking another effort than the one before let
the run go ("its effort is set at its start, and the next turn asks
another"), and a new Claude Code was told the conversation from a
transcript: 72,416 tokens written to the cache on a 108-message
conversation, 178,309 on a 148-message one (first token after 94.4s).

-p runs take a new level by apply_flag_settings (#502). The interactive
mode can't, as measured on the real 2.1.318 (Haiku 5.5, tmux, magpie's
own arguments):
- typing `/effort high` keeps the cache (55,310 read before, 55,400
  after), but saves the level as the default for new sessions:
  modelSettings.<model>.effortLevel in the settings.json of the
  account's folder, the user's own ~/.claude for Claude Code's own
  sign-in, even with --setting-sources ''. Only `max` is session-only.
- a --settings file rewritten (effortLevel, or modelSettings.<model>)
  changes nothing: the request stays at medium, with or without
  --effort. Claude Code pins the file's content as it starts.
- after `/effort max`, the one field of its requests that changes is
  output_config.effort.

Fix:
- Every interactive run has the guard file (guard.json, {} with no
  safeguards); guardBody writes its safeguards and, once the run was
  told another level than its --effort (ownEffort), "effort" beside
  them. setSafeguards and the new setTUIEffort both write it from the
  run's state (tellGuard, under settingsMu).
- tap.js asks each main request (x-claude-code-request-class: main) at
  the file's effort in output_config.effort, and leaves Claude Code's
  other requests as they were; CLAUDE_CODE_EXTRA_BODY gets the file
  without "effort". It writes guard.json.live at the first main request
  as well as the first one carrying safeguards.
- resume: an interactive run asked another effort calls setTUIEffort.
  A run with no .live (no tap), or a turn asking Claude Code's own
  level ("") of a run started at another, is let go as before, the log
  saying which.
- A level the model refuses (real 2.1.318 on claude-haiku-4-5 through
  such a rewrite: "API Error: 400 This model does not support the
  effort parameter.") fails the turn as a run started at it would; the
  existing path (ended, !ok) lets the run go, and the turn asked again
  starts a Claude Code at that --effort.
- docs/subsystems/claude-subscription-bridge.md says so.

Run at this tree (base 9e6687e3):
- New: TestTapAsksTheGuardFilesEffort (bun and node),
  TestClaudeTUIEffortChangeGoesOnInItsRun,
  TestClaudeTUIEffortChangeWithoutTapStartsAnew,
  TestClaudeTUIEffortRefusedStartsAnew: ok; with the guard tests,
  -race -count=3: ok.
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...; go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok.
- go test -tags nogui ./... (Go 1.26.8, go.mod's; sandbox HOME):
  everything ok but TestPluginSOCKSProxy (#2207, Bun 1.4.4 here) and
  TestLaneLimitRoutes (#5150, reads the running gateway; ok alone).
- The built binary, `magpie serve` on 127.0.0.1:34251 in a sandbox HOME,
  XDG dirs and TMPDIR, Claude Code 2.1.318 signed in from a copy of the
  access token (no refresh token), three turns of one conversation on
  claude-haiku-5-5 at medium, high, medium (~20K tokens of history):
  one Claude Code pid for all three, no "its effort is set at its
  start"; the requests as sent (a read-only preload under the tap) asked
  medium, high, medium; usage read/written 795/19,413, 19,869/384,
  20,228/71. ~/.claude/settings.json byte for byte unchanged.

Broken by hand:
- resume's old abortFor back: the three gateway tests red ("started 2
  runs, want one at medium"; the log's reason; the refused turn
  answered 200).
- tap.js not asking the effort: TestTapAsksTheGuardFilesEffort red
  ("request 1 was sent … medium").

Not tried: Opus and Sonnet through the interactive mode (Haiku 5.5
only); whether Anthropic thinks harder at the rewritten level (the
request asks it, the reply doesn't tell); a Claude Code in WSL.
2026-11-10 18:57:44 +08:00
yetone 99b080e2ee agents: an agent can have its own Provider in model names (KillTry27355 on X)
"希望 可以在不同的 agent中选择是否显示供应商名字,现在只能统一开关":
Provider in model names was one switch for every agent. An agent's
Details on the Agents page now has a Provider in model names row: As in
Settings · <mode> (the default, kept for everyone), On, Not on names I
set, or Off, for that agent alone. The CLI has the same thing:
`magpie model suffix <agent> [on|own|off|every]`.

- settings.AgentSuffix keeps the agent's own mode by the id its lists are
  kept by (Agent.ListsFor, lower-cased, without @wsl: or #profile). An
  agent with none follows PlainNames/PlainOwnNames as before, so nothing
  a user already set changes.
- provider.LabelsFor(agent, es) reads that agent's mode. Every place
  that named models with Labels for an agent now passes the agent: Codex's
  catalog, the agents' written lists (route.go, Pi's extension), the
  gateway's /v1/models (by agentOf(r)), Muse, Antigravity, Ollama, Claude
  Desktop's catalog and descriptions, Claude Science. Labels is
  LabelsFor("").
- POST /api/settings/agent-suffix sets it and rewrites the agents'
  configs (catalog.Touched), as Settings' switch does.
- docs/subsystems/agent-wiring.md says where the mode is kept and read.
- The picker is in agentsuffix.js, imported when an agent's Details open,
  so the core grows by the one line that loads it (1,529,335 of its
  1,533,802 budget, after the previous commit's move). An agent whose
  list takes no names of magpie's (noNames) has no row.

Tests, each red on the old code: TestAgentSuffix (provider: modes, keys
with @wsl and #profile, reset, bad input), TestAgentSuffixReachesItsFileAlone
(agent: Pi's file follows its own mode while Codex's follows Settings'),
TestModelsListFollowsAgentSuffix (gateway /v1/models per agent),
TestModelSuffixAgentCmd (cli), settings_keep (AgentSuffix survives a
Settings save), agent-suffix.test.cjs (5 languages x 1180/390 x chromium
and webkit, and a noNames agent has no row).

Broken by hand (a copy with LabelsFor ignoring the agent and the picker
reading no own mode): TestAgentSuffix, TestAgentSuffixReachesItsFileAlone,
TestModelsListFollowsAgentSuffix and every agent-suffix GUI case went red.
TestModelSuffixAgentCmd stayed green; it checks what is saved, not the
names.

Run on mote at this change on top of 720200092: gofmt -l clean; go vet darwin, GOOS=linux
-tags nogui and GOOS=windows clean; go test -count=1 of internal/provider,
cli, gui, settings, settingsapi and agent: ok; internal/gateway in an earlier
run of this change at 3b261932e: ok (1044s), and at this head -run
'Desktop|Models|Suffix|Science|Muse|Ollama|Antigravity|Codex.*Catalog': ok.
node --test of every agent-*, i18n-* and gui-* file plus old-webkit, both
engines: 1026 of 1049. The reds are all on main or under load:
agent-switch-accounts' 20 not-connected cases (red at origin/main 7c41060c2
too, filed as #5925), old-webkit's Safari 15 styles (#5919), and one case
each of agent-compact (#5607) and agent-stale-copies (#1949), which pass
44/44 when run alone. panel-fold's 'keeps what was clicked' is red on main
too (#5796).

Rebased on 0f94acc99 and run again at this change (9d82986ea): gofmt
clean, go vet clean for darwin, linux (nogui) and windows; provider,
gui, settings, settingsapi and agent ok, the gateway's suffix and
agentOf tests ok; GUI agent-suffix, old-webkit, agent-bulk-visibility,
visibility-saving, i18n-keys and i18n-en-no-cjk in chromium and webkit,
57 of 58, the one red Safari 15's styles (#5919). internal/cli was red
only on /api/model-price having no command, from main's 40ca0c88d;
the next commit names it. Rebased again on ccc96b4a7 before the push
(proc, codex, claudetui, a remote window, routing rules, redact;
no conflict), core budget test ok there.

Not tried: a real agent with a real account picking its own mode; WSL and
Windows agents (the @wsl: key is covered by a unit test only).
2026-11-10 18:57:16 +08:00
yetone 82962db79a routing: a rule can match the system prompt or the last user message, by words or a regex, with no model asked (SucroseMoE on X)
SucroseMoE asked for routing on plain string and regex matches instead
of an intent model: `system[0] matches /^你是对话标题命名/` → model A,
`user[-1] matches /^正在上下文压缩/` → model B, so any harness's title
and compaction calls can be routed without a classifier.

Two new rule condition fields, beside message/effort/subagent/agent:

- system: any block of the system prompt as the agent sent it (Anthropic
  system blocks, Chat system/developer messages, Responses instructions
  and system/developer items, Gemini systemInstruction). Any block, not
  only the first, because Claude Code's first block is its billing
  header.
- last: any text of the request's last user message as sent, reminders
  the agent adds included, so an anchored ^ still meets a compaction ask.

Ops for both: contains, doesn't contain, starts with, matches (regex,
case-insensitive; a value written /…/ has its slashes dropped). The
gateway reads system and last only when a rule asks (RulesRead), and
decodes raw system JSON lazily then. Like every rule, the decision is
made as a turn starts and its tool rounds keep it.

GUI: Routing → group → Rules, "+" on a rule row offers "System prompt text"
and "Last user message" pills (no modal), with tooltips, placeholders
and the bad-regex mark; zh, zh-TW, ja, de. CLI: `--when "system matches
^You are"`, with aliases system[0], user[-1], last-user. TUI hint, docs
(gateway-routing.md, site start pages) say the same.

Ran, on mote (macOS) until its sshd began refusing connections: gofmt
-l internal/ clean, go vet of provider/gateway/cli/tui, the rule tests;
the routing GUI files (routing-rule*, routing-rules-line,
routing-pause*, group-*, i18n-*, routing-compact, routing-intent-*,
routing-smart-intent) in chromium and webkit: 751 of 781, the 30 reds
being "System prompt" taken by a core word (now "System prompt text"),
routing-rules-line's + menu count (now with system and last), and
routing-intent-entry, red on main since 01a260af4 (#5392, next commit).
Then on the Linux box (wsl-run, magpie-desktop): go vet -tags nogui and
GOOS=windows go vet of the same packages; go test -tags nogui of
internal/provider, gateway, cli, tui, gui; node --check of the routing
plugin; routing-rule-ops, routing-rules-line, routing-intent-entry,
i18n-keys, i18n-en-no-cjk, routing-rule-example in chromium and webkit,
the new test 16 of 16 over four repeats.

Broken by hand: holdsIn's system/last cases returning false turns
TestCondHolds and 8 of TestRuleSystemAndLastText's cases red; dropping
the Anthropic system wiring turns its two Anthropic cases (one the real
Claude Code system fixture) red.

Not tried: a real harness's title or compaction request end to end
through a live gateway; the fixtures are Claude Code's, Codex's and pi's
recorded system prompts.
2026-11-10 18:48:13 +08:00
yetone f1996e7e5d gateway: a provider named past its usage cap is not sent on to a group (Anotiaww on X)
Anotiaww on X: magpie on server B asked magpie on server A for
claude/claude-opus-5-5. A's Claude account was past its usage cap (the
trace: "a usage window at 98%, over the account's 98% cap"), and the
Claude provider had no fallback set. The request was answered by a
WorkBuddy member of the user's routing group claude-opus-5.5 (the trace
row marked Fallback), with nothing said. They expect the cap's refusal.

Cause: 44d6dd75d (adorable_piglet, v0.1.3354) made serve plan a capped
provider again with every user-built routing group that has the model
in it (provider.GroupsAfter, groupsAfter) whenever no candidate was
left, so the Codex app, which asks its own model bare and never the
group, reaches the group's APIs. That rule did not look at what the
client asked for: a request naming the provider itself got the same
implicit fallback. Not the cause: the remote/shared path, auto groups
(GroupsAfter leaves them out), or a peer magpie's model mapping; the
peer sent claude/claude-opus-5-5 as written.

Fix: namedProvider(r, call.Model) in serve's groupsAfter arm. A model
asked with its provider in it (call.Model after unprefixed, so a flat
or aliased spelling of one too) is that provider's alone: past the cap
it goes to the provider's own Fallback list (planned before, untouched)
and else gets cappedError's 429 "usage cap reached". A bare model, and
Codex's own model that codexAccounts rewrote to codex/<model> on the
backend path (marked with providerPicked), still go on to the groups as
adorable_piglet asked; so does a turn codexFallBack hands on. CapStop is
unchanged. GroupsAfter's only other caller, codexFallsBack, is the
backend path, where Codex asks bare. Images and embeddings never read
GroupsAfter.

Tests:
- TestNamedProviderCappedRefuses: codex/gpt-5.5 past its 98% cap, a
  group [codex/gpt-5.5, a/m], on /v1/chat/completions, /v1/responses
  and /v1/messages, stream and not: 429 "usage cap reached" and the
  group's API not asked; with a fallback f/m set on the provider, the
  fallback answers (the user's fallback still holds).
- TestPluginCarefulPool: the plugin's model asked bare ("fake-1") still
  goes to the group; named "factory/fake-1" it is the 429.
- TestCappedCodexOwnModelGoesToItsGroup keeps the backend path's bare
  gpt-5.5; its /v1/responses "codex/gpt-5.5" subtest is now the named
  case above, the reverse answer.

Broken by hand (mote-run): the namedProvider guard out of serve:
TestNamedProviderCappedRefuses 6 subtests red (200 "from the group")
and TestPluginCarefulPool red ("named, group, stop off: 200 ... from
kf"). Restored: green.

Run (mote-run, mote at load ~130-165):
- gofmt -l internal empty.
- At the pushed tree, rebased on origin/main 208b89422: go test -count=1 ./internal/gateway -run 'TestNamedProviderCappedRefuses|
  TestCappedCodexOwnModelGoesToItsGroup|TestCappedSubscriptionGivesWayInGroup|
  TestSubscriptionCappedMidConversationGivesWay|TestCodexOneAccount|
  TestPluginCarefulPool|Fallback|Cap|Group': ok (144.6s; 138.9s before the rebase).
- go vet ./internal/gateway ./internal/provider: darwin, GOOS=linux -tags nogui, GOOS=windows: ok.

Rebased again onto 6b92824ff before the push (26 files of usage,
sessions and provider window-hold changes, none of the files here); the
runs above were at 208b89422, the tests run again at the pushed head
after the tag.

Not tried: a real Claude account past a real cap, and a real second
magpie (fakes only). The full suite runs after the tag. No GUI change.
2026-11-10 18:04:25 +08:00
yetone 44732325e7 gateway: test that OpenCode Go's keys take over at its usage limit (MelWoutersgghi on X)
MelWoutersgghi asked for an OpenCode Go provider that holds several
keys and switches between them. That already works: OpenCode Go is a
built-in key provider (presets.go), and every key provider keeps
several keys (Provider.Keys, keys.go). The provider's editor lists
them under Accounts with "Add another key" (renderKeyAccounts), a key
is turned on or off by its dot, and with more than one on, Routing
says how requests spread. Each key's 5-hour, weekly and monthly Go
windows are read on its own (planquota.go, key_allowance.go).

Nothing guarded it with OpenCode Go's own refusal, so this adds
TestOpenCodeGoKeysTakeOverAtUsageLimit: the first key answers the 429
GoUsageLimitError body OpenCode's client records (its composer.spec.ts
fixture), the second key serves the request, a key that is off is
never tried, and the next request goes straight to the second key
while the first rests.

Run: go test -run 'TestOpenCodeGoKeysTakeOverAtUsageLimit|
TestSeveralKeysOnTakeOverFromEachOther' ./internal/gateway, PASS, and
go vet ./internal/gateway, clean, both on Linux (wsl-run; mote refused
SSH six times in a row). gofmt -l clean.
Broken by hand: KeysOn returning only the first key for opencode-go
makes the test red (429, tried k-spent only); restored.
Not tried: a real account with two OpenCode Go keys; the full suite
(test-only change).
2026-11-10 18:00:14 +08:00