Commit Graph
677 Commits
Author SHA1 Message Date
yetone e740ee7cc0 agent: a Claude Code tier set to a model keeps it when the main model moves onto that model, not "Same as main model" (#2257, luokinging)
A Fable tier set to GPT-6.1 Sol read "Same as main model" once the main
model was switched to Sol, and the next main-model move took it with it.
On a move of the main model, a tier equal to the new main model was kept
as its own only when it equalled what it would follow there. Fable follows
nothing on a model that is no Fable, and haiku follows a Claude model on
its Haiku, so neither was marked: Get then hid the tier as following, and
the next move rewrote it. The new main model itself now counts as the
tier's own model too, for every tier and both routes (magpie and Claude
Code's /model). GUI, TUI and CLI all read the same Field.

A user already caught by it sees "Same as main model" and sets the tier
again once; that state can't be told from a tier that follows.

TestClaudeFableTierOnClaude modelled 0.1.1229's wiring with fable=Sol
written before the main model moved onto Sol, which is this issue's own
case; its fixture now writes it after, as 0.1.1229 did.

Run:
- TestClaudeOwnTierOnTheNewMainModelStays (every tier, two own models,
  magpie and /model): on the old code fable fails for both models and
  routes, and haiku given Opus fails ("haiku reads \"\""); passes now.
- CLI in a sandbox HOME/CLAUDE_CONFIG_DIR, old and new binary: main ->
  k2.8, fable -> Sol, main -> Sol, main -> GLM. Old: fable gone after the
  move onto Sol, no ANTHROPIC_DEFAULT_FABLE_MODEL after GLM. New: fable
  Sol after both, env ANTHROPIC_DEFAULT_FABLE_MODEL=oa/gpt-6.1-sol.
- go test -tags nogui ./internal/agent/ ./internal/tui/ ./internal/cli/:
  ok. gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
Not tried: the GUI by hand (no asset changed; it reads the same Field).
2026-10-15 06:07:43 +08:00
yetone 9916a94608 gateway, usage, plugins: OTel export is the first plugin on the gateway's observer point (P3)
P3 of docs/subsystems/plugin-runtime.md opens the gateway to plugins. The
observer point is first: it only reads, so it carries the least risk.
With plugins/otel off, the gateway exports nothing and does no observing
work. It keeps no reply whole and adds no request context.

- usage.Observer:
  - Methods: Serve, Bodies, Begin(Request) Watch and Ledger(Record). Watch
    has Attempt and End.
  - Observe(o) registers an observer until its remove is called.
  - ServeObservers is counted, and only Server.ListenAndServe calls it.
  - ObservedBodies takes the most any observer wants.
  - Record.SkipOTel becomes Watched, set by appendUsage for a request an
    observer watched.
- The gateway's otel.go becomes observe.go:
  - observeRequest asks each observer through Begin.
  - attempt and end call each Watch. Bodies are added only when an
    observer asks for them, and the whole reply only for WholeBodies.
- internal/otlp: the exporter (otel*.go) moves out of internal/usage, and
  the gateway's per-request span state moves into request.go. otlp.New()
  is an Exporter, a usage.Observer. What it sends is unchanged.
- plugins/otel:
  - Apply registers otlp.New() and disposes of it when turned off.
  - InUse is 1 while settings.OTelExport says to send. A user who exports
    only through MAGPIE_OTEL_* keeps the plugin on under Essentials.
- pluginrt.KeepFresh: the process serving the gateway refreshes every 2s
  when plugins.yml or settings.json changes. A switch made in the window or
  the CLI reaches a running gateway, or a headless serve, without a restart.
- docs: plugin-runtime.md gets a P3 section, a gateway runtime path and an
  updated failure section; reference.md says the export is the otel plugin.

Run at this tree on origin/main 82f48f093 (rebased onto 52ee84761 after,
which touches only the Linux tray icon):
- gofmt -l is clean. go vet passes on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -count=1 -timeout 25m ./...: ok, 55 packages, none failed.
- New tests:
  - usage: TestObserverServesWithTheGateway and TestObserverLedgerAndBodies.
  - gateway: TestObserverPoint, covering unwatched, no bodies, captured,
    whole and whole streamed.
  - plugins/otel: TestOnExportsOffSendsNothing (on, off, on, with a real
    collector) and TestInUseByEnvironment.
  - pluginrt: TestKeepFreshFollowsPluginsYml.
  - The OTel tests moved with their code to internal/otlp.

Broken by hand, each red, then restored:
- Apply without Observe, and without its dispose.
- KeepFresh refreshing only once.
- InUse reading settings.json only.
- Ledger keeping Watched rows: 3 gateway OTel tests red.
- ObservedBodies taking the last observer's answer.
- Observe not serving a late registration.
- appendUsage not setting Watched.
- Whole bodies never kept.
- Bodies always on with no observer asking.
2026-10-15 05:39:01 +08:00
yetone 52ee847612 gui: a Linux bar's tray icon is the bird's silhouette, not the app's tile, and the tooltip says today's total (ylorn on Discord)
ylorn (Hyprland, 0.1.1241): the StatusNotifierItem's IconPixmap was the
coloured app icon on an opaque white tile, which clashed with a bar's
monochrome icons and became a solid block on bars that tint icons by
alpha; the tooltip said only "magpie".

- Linux now gets the macOS menu bar's template bird (tray.png) in one
  colour on transparency (trayIconFor / linuxTrayIcon, trayglyph.go):
  light, or dark when xdg-desktop-portal's org.freedesktop.appearance
  color-scheme is 2 (prefer light); it is set again on the portal's
  SettingChanged (watchTrayScheme, own D-Bus connection). An unreadable
  portal counts as no preference (light). No IconName is set: a host
  that resolves a -symbolic name but draws it untinted would show a
  black bird on a dark bar with no pixmap fallback. macOS keeps its
  template icon, Windows the coloured app icon.
- With no cards in the menu bar the tooltip is "magpie" over one line of
  today's total, as the panel's Usage tab sums it (trayIdleTip: all
  tokens, cost in Settings' currency, requests), refreshed with the
  cards' loop. Cards picked: unchanged.
- The menu is unchanged (Open / version / Quit): no info lines. The
  panel one click away has the models and usage, and the menu is shared
  with Windows and macOS.

Run (sandbox HOME, pinned GOMODCACHE, shared GOCACHE), on origin/main
21aa40285:
- TestTrayIconPerOS fails with Linux given appIcon back ("linux:
  (0,0)-(64,64), want the menu bar bird's (0,0)-(44,44)"); TestTrayIdleTip
  fails with the tooltip back to plain "magpie". Both pass restored, with
  TestPortalLight, TestTrayTotals, TestTrayIconSize, TestSNITipIsSafeMarkup.
- gofmt -l clean; go vet ./... (darwin), GOOS=windows go vet ./...,
  GOOS=linux go vet -tags nogui ./... clean; GOOS=windows go build and
  GOOS=linux go build -tags nogui OK.
- traytip_linux.go (linux && !nogui, cgo) can't be vetted from macOS: the
  two new functions were copied into a darwin build and vetted there.
- go test -p 4 -timeout 40m ./...: exit 0, 53 ok, no FAIL.
- GUI: tray-*.test.cjs (Playwright 1.62.0): 112/112 pass.

Not tried on a real Linux bar (the Windows box with its WSL2/Omarchy VM
was unreachable over ssh): the pixmap, its colour on a light/dark scheme
and the tooltip on waybar/Quickshell/KDE are unverified on hardware.
2026-10-15 05:30:58 +08:00
yetone 82f48f0935 gateway, provider, gui: a provider set to compact natively is asked Codex's compaction_trigger as sent and its sealed compaction goes back unchanged; a checkpoint stays with its writer (#1099)
A new per-provider option, off by default. With it on, Codex's
compaction_trigger reaches the provider as Codex sent it, and the
provider's encrypted compaction item goes back to Codex unchanged instead
of magpie's magpie1: summary. Off, nothing changes.

Where it can be on (provider.CarriesCompaction): a provider with a
Responses API (Sub2API and other OpenAI relays, a remote magpie), a
ChatGPT (codex) account, and the built-in GitHub Copilot on its GPT
Responses path. Copilot's Claude models are asked on chat completions, so
they still get magpie's summary (CompactsOn). A group compacts natively
only when every member does.

No silent downgrade:
- A turn carrying a sealed compaction goes only to the key or account that
  wrote it (compactions.json beside affinity.json, 0600, 1024 entries /
  30 days). With none left, Codex gets a 400 saying the conversation was
  compacted natively on <who>, not a summarised or dropped context.
- A provider whose request would have to be translated (not relayed) is
  refused with a 400 instead of losing the item.
- The upstream's own refusal goes back to Codex as it came, one call.
- base_instructions and Codex's identity are untouched.

Turning it on:
- GUI: the provider editor's Compaction row, "Codex compacts on this
  provider" (shown only where the wire can carry it; zh, zh-TW, ja, de).
- CLI: magpie provider set <id> compaction=native|magpie. A provider that
  can't carry it is refused.

Run on origin/main 00501401a, then rebased onto 84f14e555 (no file in
common) and reran gofmt, vet and go test for gateway, gui, provider,
cli, usage and sessions: all ok. Rebased again onto 8d2a4a7da (gateway.go
and codex_backend.go changed on both sides, merged clean) and reran
gofmt, vet (darwin, linux nogui, windows) and go test for gateway, cli,
provider and gui: all ok. Last rebased onto 7a3fed6bb (only
gateway-routing.md shared, merged clean): gofmt, vet on all three OSes,
and go test -run for the native compaction, sink, CORS, rebind and origin
tests in gateway plus the provider tests: ok.
- gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows:
  clean.
- set -o pipefail; go test -timeout 40m ./...: every package ok but
  internal/provider's TestCopilotSecretToolUsername (copilot_cli_test.go:93
  token "", 10.05s), the open load flake #1627; it passes alone -count=5
  and this change doesn't touch it.
- GUI (node --test, chromium + webkit): the provider-editor files, 946
  pass, 0 fail; the new provider-native-compaction.test.cjs runs 5
  languages at 1100 and 420 (60 cases).
- New Go tests: TestNativeCompactionPassesTheTrigger, ...RefusalGoesBack,
  ...StaysWithItsWriter, ...Copilot (gateway), TestCarriesCompaction,
  TestSetNativeCompaction (provider), TestProviderSaveNativeCompaction
  (gui), TestProviderCompactionPair (cli).

Broken by hand, each red, then restored:
1. codexInputAs dropping the trigger even when native: all 4 gateway
   tests fail.
2. checkpoint filter off: StaysWithItsWriter fails.
3. forced relay off: all 4 gateway tests fail (the web_search tool sends
   the turn to translation).
4. GUI save sending nativeCompaction false: the GUI test's first case
   fails.

Not tried: any real upstream (Sub2API, ChatGPT, Copilot). Copilot may
refuse a compacted history holding web_search items; that refusal would
go back to Codex as-is.
2026-10-15 05:20:17 +08:00
yetone 118f4f28bf plugin: a community plugin npm doesn't have installs from the plugins repo's dist branch, so a reviewed plugin no longer waits unmerged for an owner's npm 2FA (magpie-community/plugins#84)
npm's Trusted Publishing can't create a package, so a new plugin's first
version needs an owner's 2FA, and reviewed PRs sat unmerged for it. A
trust made after 2026-09-03 also allows stage publish only, which is why
npm refused zed 0.1.7 and zen-free 0.1.7.

The plugins repo now packs every merged version onto its `dist` branch
(scripts/dist.mjs, magpie-community/plugins f5308cd): tgz/<file> and an
index.json with each version's sha512, manifest and README, with no
credentials. magpie still asks npm first. Only when `bun add` fails for a
@magpie-community package at latest or an exact version, and not because
of the user's minimumReleaseAge (that hold is kept), does installDist
fetch the tarball. It refuses the tarball unless its sha512 is the index's,
keeps it in plugins/dist and runs `bun add ./dist/<file>`. A later npm
install replaces it, and pruneDist removes tarballs package.json no longer
names. npmAsk (market version, Update, the hourly check) takes dist's
latest when npm errors or is behind, and Readme falls back to dist's. The
branch is read through jsDelivr when the China mirror switch is on, else
raw.githubusercontent.com. installMu is now held for the whole install,
fallback included.

Run at this head (on origin/main 8d2a4a7da):
- go test ./... -count=1: all ok but internal/gateway, which hit the
  600s default timeout inside a file rename. The disk was at 5.3 GB free
  and the load around 22. Rerun alone with -timeout 30m: ok in 559.7s.
- gofmt -l clean. GOOS=windows go vet ./... ok. GOOS=linux go vet ok on
  every magpie package that doesn't import Wails (its Linux files need
  cgo, which can't be cross-compiled from macOS).
- New tests, with real Bun 1.4.2 against a fake npm and a fake dist:
  TestDistInstallsAPackageNPMDoesntHave, TestDistServesAVersionNPMRefused,
  TestDistRefusesATarballNotItsIndexs and TestDistWanted.
  TestUpdateBunHoldsBackSaysWhy now has dist holding the held version too.
- Broken by hand, each went red: no fallback, no sha512 check, no prune,
  no dist version in npmAsk, a loose file regexp, and no minAge guard.
- The real dist branch serves index.json and zed's 0.1.7 tarball from
  raw (200). jsDelivr's @dist answered 200, cold in ~20s.

- Real use, sandbox HOME, live npm and live dist: Info said zed 0.1.7
  (npm has 0.1.6), and Add@0.1.7 installed it from dist, package.json
  naming ./dist/magpie-community-opencode-zed-auth-0.1.7.tgz.

Not tried: the GUI's Add on the live branch, or the China mirror path.
2026-10-15 05:18:56 +08:00
yetoneandggbdpq 7a3fed6bb5 gateway: a group in the group sinks its own rate-limited keys by its own Sink, not only the group the agent named (#2255, ggbdpq)
What changed
- planLevel applies a nested group's own Sink (sinkOwn) to its own
  candidates and their trace rows at both places it plans one: the
  weighed units (Smart, usage, pace, weight) and the ordered walk. A
  key or account of that group rate limited with quota left goes behind
  its group's others, within that group's place, as it plans by its own
  routing (#576) and rules. The group the agent asked for still sinks
  the whole after, as before. sinks() still leaves out rotate, weight
  and manual.
- Why: only planGroup read Sink, for the group asked for; an inner
  group's switch did nothing, and its rate-limited account went back
  to the front as soon as its rest ended.
- provider/group.go's comment and gateway-routing.md's Sink row say so.

Ran
- TestNestedGroupSinksItsOwnOrder (outer ordered, smart and by weight;
  three levels deep with the middle group's Sink and with the
  innermost's; inner Sink off; the outer's Sink alone): fails on
  origin/main 00501401a ("order [a b x], want b then a"; "mid's Sink:
  order [a b c y], want [b c a y]"), passes with the change.
- Broken by hand, each red: sinkOwn never sinking (all subtests); only
  the ordered path left unsunk (outer ordered and deeper).
- TestGroupRateLimitedSinks, TestRateLimitedSinksToTheBack (-count=3),
  and -run 'Sink|Nested|OwnRouting|Weighted|Group': ok.
- gofmt -l clean; go vet ./..., GOOS=windows go vet ./...,
  GOOS=linux go vet -tags nogui ./... clean.
- go test -p 4 ./... (macOS): ok in every package but internal/agent and internal/gateway, which hit the 10m package timeout under load ~30 with no test hung (the running test 1-2s old); rerun with -timeout 40m: gateway ok 551s, agent ok 426s.

Not tried: a real nested pool with live accounts. The report's sibling,
a nested group's Affinity read only from the outer group, is left for
its own issue.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 05:17:38 +08:00
yetoneandggbdpq d182294be7 gateway: a page at a localhost subdomain spends a subscription only with a gateway key, as Origin null does (#2256, ggbdpq)
What changed
- corsGuard refuses (403) an http(s) Origin at a subdomain of localhost
  unless the call carries an enabled gateway key (localhostSubdomain),
  the rule Origin "null" got in #2242. foreignPage still passes it, so a
  page there that holds a key keeps working; neither gets CORS headers.
- Why: Chrome and Firefox resolve *.localhost to loopback themselves,
  but Safari and other WebKit views hand the name to the system
  resolver, which before macOS 26 asks the network's DNS (WebKit bug
  160504, closed MOVED: "implemented in OS frameworks below WebKit",
  2025-09-19; fails on macOS 15.7). A captive portal's or hostile
  network's resolver serves such a page from anywhere, and its "simple"
  text/plain POST spent subscriptions with no key.
- tauri.localhost and wails.localhost stay keyless on Windows only,
  where Tauri's and Wails' webviews serve themselves at those names. On
  macOS and Linux those apps use tauri:// and wails://, so the two names
  are any page's there, and a hostile resolver answers them as readily
  as any other (the residual the report left open). webviewOS
  (runtime.GOOS) lets the test be each system.
- The same page also reached the gateway rebound: at evil.localhost:3425
  once the name turns to 127.0.0.1, its GET carries no Origin, and
  lanGuard's ownHost counted every *.localhost Host as this computer, so
  GET /v1/models and /v1/magpie/quotas answered 200. ownHost no longer
  counts a subdomain of localhost (localhost itself and
  docker.for.mac.localhost still count); a browser at one needs a key.
- TestForeignPagesRefused's tauri.localhost row now sends a key, and
  TestReboundPageRefused expects wails.localhost refused.
- docs/subsystems/gateway-routing.md says both.

Ran
- TestLocalhostSubdomainNeedsAKey (darwin, linux and windows as
  webviewOS; six routes; cross-origin and rebound; the fake vendor never
  reached): fails on origin/main 00501401a (76 errors, e.g. "POST
  /v1/chat/completions from http://evil.localhost with no key: 200"),
  passes with the change.
- Broken by hand, each red: ownHost counting *.localhost again (the
  rebound GETs 200); localhostSubdomain always false; the Windows-only
  exception dropped (tauri.localhost answered keyless on darwin).
- The cors, rebind, LAN, usage-ingest and allow-list tests: ok.
- gofmt -l clean; go vet ./..., GOOS=windows go vet ./...,
  GOOS=linux go vet -tags nogui ./... clean.
- go test -p 4 ./... (macOS): ok in every package but internal/agent and internal/gateway, which hit the 10m package timeout under load ~30 with no test hung (the running test 1-2s old); rerun with -timeout 40m: gateway ok 551s, agent ok 426s.

Not tried: a real Safari on macOS 15 against a resolver that answers
*.localhost; Tauri or Wails apps on Windows.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 05:17:37 +08:00
yetone 84f14e555c usage: a Codex call with no response_id leaves compaction out of Usage requests instead of saying false (#1591)
Codex added token_usage_record and compaction_response_id together, in
openai/codex#41912 (2026-08-31). A call that magpie reads from a
token_count event alone, as in older rollouts, has no response_id. It
can't carry the compaction marker either way. The previous commit
reported such calls as `compaction: false`, which claims they were not
compactions. codexCompactionOf now returns no state for them, so the
ledger and the requests page leave the field out, as they do for any call
with no native evidence.

What was run:
- New test TestCodexCallWithoutResponseIDHasNoCompactionState. On the
  previous commit it fails with `ledger: a call with no response_id claimed
  a compaction state: {..."compaction":false...}`, and with the same message
  for the requests page. It passes now.
- go test -tags nogui ./internal/sessions ./internal/usage: ok.

For all three commits on origin/main 1ad60446f:
- gofmt -l on the changed files: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: ok.
- go build for darwin, linux (nogui) and windows: ok.
- Full suite: go test -tags nogui -timeout 40m ./... (pipefail, sandbox
  HOME): 53 packages ok, exit 0.
- No GUI asset changed, so no Playwright run.
- Not tried: a real Codex subagent rollout (legacy or paginated). The
  formats are from Codex's source, and Hogeexxl checked two real paginated
  subagents.
- Rebased onto origin/main f255a3e3b (12 commits newer, including #2233 and
  #2234 in internal/sessions; no cache-version clash). Rerun there: go
  test -tags nogui -count=1 ./internal/sessions ./internal/usage
  ./internal/gui, gofmt and vet on both packages: ok.
2026-10-15 04:21:31 +08:00
yetone a78ac27532 sessions: a Codex subagent in a legacy-history rollout gets its spawn task_name too, and a forked child's copy of its parent's spawns no longer erases its siblings' titles (#1591)
Two gaps in the previous commit's title link:

- Legacy rollouts. Codex's ThreadHistoryMode is Legacy by default. The local
  thread store has only defaulted to Paginated since openai/codex#47900
  (2026-09-24). A legacy rollout doesn't persist item_completed for a started
  SubAgentActivity. It persists an event_msg instead:
  {"type":"sub_agent_activity", "event_id": <call id>, "agent_thread_id",
  "kind":"started", ...}. Its children got no title. That event now links
  the same way, through one helper (codexAgentStarted) shared with the
  item_completed path.
- Forked children. A forked child's rollout repeats its parent's history,
  including the spawns of its siblings. The same call id then linked from
  two files, which counted as a conflict and erased the sibling's title.
  Titles are now keyed by {child, parent}, and only the file of the child's
  own parent_session names it or takes a name away from it.

What was run:
- New tests. On the previous commit each fails with:
  - TestCodexSubagentTaskTitleFromLegacyActivity: `legacy activity title
    for child-started = "", want "Legacy started task"`.
  - TestCodexSubagentTaskTitleComesFromItsOwnParent: `a fork's copy of the
    parent's spawn erased the child's title: ""`.
- Broken by hand: with the parent dropped from the key, the second test
  fails with `a spawn its parent never made named the child: "Only in the
  fork's copy"`.
- go test -tags nogui ./internal/sessions ./internal/usage: ok.
- The event's field names come from Codex's source (protocol
  SubAgentActivityEvent and the rollout persistence policy, openai/codex
  669449b). Not tried: a real legacy-history Codex subagent rollout.
2026-10-15 04:21:31 +08:00
Hogee 3c4b4dc973 sessions, usage: a Codex subagent with no title takes its parent's spawn_agent task_name, its nickname shows apart, and Usage requests say which calls were compactions (#1591, Hogeexxl)
Hogeexxl's change (his fork branch codex/codex-session-details, f7c176c9),
cherry-picked with his authorship:

- A Codex child thread whose title is still empty after the existing
  precedence takes the task_name of the parent's spawn_agent call, linked by
  the call id and the SubAgentActivity "started" item that names the child's
  agent_thread_id. Conflicting links leave the title empty.
- session_meta.agent_nickname is exposed as `nickname` on the list, one,
  manage and overview responses, beside the title, not in place of it.
- GET /api/usage/requests and /v1/magpie/usage/requests carry `compaction`
  (true/false) for Codex calls with native evidence, and leave it out
  otherwise. A gateway row matched by a unique response_id takes the marker
  and keeps its own model, usage, cost and kind.
- Flags bits 1024 (rowCompactionKnown) and 2048 (rowCompaction) are new.
  TestRowFlagsApart covers them, and they don't overlap 1..512. The sessions
  cache goes to version 21 and the calls cache to calls-v15.

Review:
- Rollout format checked against Codex's source (openai/codex 669449b):
  - v2 spawn_agent args carry task_name.
  - A paginated rollout persists item_completed with a SubAgentActivity
    item: kind "started", id = the call id, agent_thread_id.
  - SessionMeta has a top-level agent_nickname, which Codex's own list.rs
    and metadata.rs read too.
  - compaction_response_id lives in token_usage_record.
  Gaps in legacy rollouts and in calls without a response_id are fixed in
  the next two commits.
- Privacy: only a title string the user's own Codex wrote and a boolean
  are added to local API responses. Nothing new goes to a vendor or to
  telemetry. The ingest POST parses fields one by one, so it is unchanged.
- No .github, dependency or network changes.

What was run:
- His tests pass: go test -tags nogui ./internal/sessions ./internal/usage,
  and the two new internal/gui API tests.
- Broken by hand, each caught by his tests:
  - the nickname read removed;
  - the conflict checks removed;
  - mergeCodexCompactions broken;
  - the gateway pair's setCodexCompaction removed;
  - the flag read forced to true.
- Not caught:
  - the parent check on the title link (covered by a test in the next
    commit);
  - `copy.codexCompactions = nil` in cloneCodexChunks removed. That line is
    defensive only: the shared chunks never hold the map.
- The gofmt, vet and full-suite record for the three commits is in the
  last one.
2026-10-15 04:21:31 +08:00
Haogao Gu d966e19154 gateway, gui: the Routing page tags a Claude Code subagent's turn as it does Codex's
Codex names a subagent's request (x-openai-subagent: collab_spawn), and
the Routing page tags its row Subagent, with why it went where it did.
Claude Code names no kind, so Claude Desktop's subagent turns, which
magpie now moves to their own model and effort, read as the lead's: a
Desktop session's rows on one routing group could not be told apart.

Claude Code 2.1.295 sends x-claude-code-agent-id from every agent context
but the main one. Its x-claude-code-request-class and
x-claude-code-agent-type hints go only to a first-party base URL or with
CLAUDE_CODE_GATEWAY_HINT_HEADERS, so magpie doesn't get them.

- subagentTurnOf keeps the id in Route.SubagentID for a request that
  offers tools and names no kind: the turn desktopSubagentPick and
  desktopSubagentEffort take. Desktop's and terminal Claude Code's turns
  are kept, moved or not. The lead's turns, a subagent's tool-less helper
  calls (#2081: Claude Code's housekeeping) and a blank id are not. A
  kind wins over the id.
- A Desktop pick or effort that found the turn is trusted, so the body
  isn't decoded again; a request without the id isn't decoded at all.
  Only a subagent's turn with neither setting reads its tools once.
- Kind stays empty (#2081), so the ledger, the Usage page and the
  Purpose filter keep the turn unmarked. The ledger's Subagent already
  keeps the same id, on the helper calls too.
- routing.js tags it through tagKind in the request list (by request and
  by session), the story, the replay and the tray panel, with Codex's
  words and reasons (kindWhy's collab_spawn: moved or kept, within a
  routing group, on the model asked for). No new strings.
- The day's history keeps the id. A route kept before it has no tag, and
  its moved/kept story reads as before.

Verified at this head, on b9c589eb, under a temporary HOME with Go's
caches pinned:
- Each new test fails with its guarantee broken by hand (a real FAIL, not
  a build error), then passes restored. Go, 10: the id never set; tools,
  kind or the trusted pick ignored; tools decoded before the header (the
  lead's request then allocates 10 times, 1 for its headers); the route
  not given the id; Desktop only (terminal fails); every request trusted
  (the helpers fail); the JSON key renamed; the field left out of the
  history. GUI, 8, each 0 pass / 4 fail (Chromium and WebKit, 1100 and
  420, zh) at its own assertion: tagKind ignoring the id; the list, the
  story, the replay or the panel testing Kind alone; kindWhy's
  collab_spawn reasons on Kind alone; the id over a kind; the Purpose
  filter following the tag.
- go test -tags nogui ./...: 53 packages ok.
- go test -race -count=20 -run
  '^(TestSubagentTurn|TestHistoryKeepsSubagentID|TestDesktopSubagent)'
  ./internal/gateway: ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: exit 0.
- claude-subagent-tag.test.cjs: 20/20 (Chromium and WebKit; en, zh,
  zh-TW, ja, de; 1100 and 420), three runs in a row.
- Desktop-bundled Claude Code 2.1.295 through the built gateway, a
  temporary HOME, a loopback-only sandbox and local fixture replies, its
  Agent tool spawning a real subagent: with nothing set, with a subagent
  model, and as terminal Claude Code, each run kept 4 routes; the
  subagent's one turn has the id the client sent upstream, the lead's 3
  requests none, Kind empty; the model pick moved it to m2. No tool-less
  helper call came in these runs; the Go tests cover them.
- The Routing GUI tests around it, 91 files (every routing-*, the tray
  panel's two, purpose-filter, click-scroll, the Codex and Desktop
  subagent files, subagent-effort, search-instead, search-mcp, vision-mcp,
  remote-group-served, reasoning-speed, usage-ledger, sessions-overview
  and the new one), six files at a time: Chromium 602/617, WebKit
  572/617. Each failure fails without this commit too. On b9c589eb
  untouched (checked for the effort commit): routing-days-fit,
  routing-failed-open and routing-side-calls in both engines (their
  position checks against #2134's at-top rule), routing-wb-restricted
  (#2115's wheel), and at 420 in WebKit routing-agent-gone,
  routing-agent-hue-not-red, routing-rest-off and routing-held-member.
  On 6926b7ce: search-instead in WebKit, 5 of 5 alone, and
  routing-context-fold's picked request in WebKit, a row out of view, 2
  of 5 runs alone there and 3 of 5 here.

Not run: the whole GUI suite, a real Claude Desktop window or Cowork,
Linux and Windows machines (GOOS vet and build only), WebKitGTK.
2026-10-15 03:34:59 +08:00
Haogao Gu b476dc5a93 agent, gateway, gui: Claude Desktop's subagents can have a reasoning effort of their own
After #2081 gave Desktop a subagent model, its effort still came from the
request. Add subagent_effort beside that model, using the existing effort
slider. The live setting DesktopSubagentEffort belongs to magpie; no
Claude client file or binary is changed.

Empty preserves the request's effort, including disabled thinking. A pick
applies only to Desktop requests with an agent id and tools, independently
of model replacement: unset, equal and unavailable model picks all work.
Reuse the attempt-level fitting; fixed group-member efforts and reasonless
models keep their existing precedence. count_tokens applies the pick after
unmasked-body restoration. A Codex SubagentPick is not evidence of a
Desktop tool turn.

Route.Effort keeps the incoming level, SubagentEffort records the configured
pick, and tries/usage keep the actual level. Routing explains the pick
even without a model replacement. Options follow the target model; a
saved level survives a model change. POST /api/settings preserves it.
Disconnected preferences, Disconnect/reconnect and restored settings work;
a Live pick gives restart advice only when it actually connects the agent.
Codex's own settings and default-effort explanation are unchanged.

Verification on b9c589eb plus this change, with temp HOME and pinned Go
caches:
- go test -tags nogui ./...: 53 packages pass.
- Gateway effort tests under -race -count=20: pass.
- gofmt -l: empty; darwin, linux nogui and windows vet/build: exit 0.
- 23 intentional Go behavior breaks produce real FAILs, then pass
  restored: application, scope, model independence, Default/none,
  disabled thinking, fitting/member priority, counts, next request,
  trace, saving/validation, Live notices and model-dependent options.
- Three UI breaks fail in both engines at 1100/420: default explanation,
  missing effort story and missing translation. Restored: Desktop's new
  controls/story matrix passes 20/20 across five languages. Desktop,
  Codex, tier/effort and translation regressions pass 97/97.
- Desktop-bundled Claude Code 2.1.295 runs real Agent calls through the
  built gateway, temporary HOME and loopback-only sandbox, all replies
  local fixtures. Low/high/Default sends its child low/high/xhigh on m2;
  its lead remains xhigh on m1. All three runs exit 0.

The expanded Routing run is not green: Chromium 510/525, WebKit 485/525.
These failures reproduce on untouched b9c589eb, including targeted reruns.
The day/row anchor assertions conflict with #2134's at-top rule: undoing
that one guard makes all 12 tests pass. A narrow request lies below the
viewport; user wheel input makes the failed click pass. WorkBuddy's wheel
pointer/hidden-button failures overlap #2115; moving the wheel to the
view gutter fixes 3/4 selected cases, one WebKit 420 case remains.
The held-member clipping assertion also reproduces on base; its timing
cause is not established. This baseline evidence is reported separately
in the follow-up feature issue, not counted as passed or fixed here.

Not run: the complete GUI suite, the Electron window/Cowork, native
Linux/Windows or WebKitGTK. Cross-builds are not runtime checks.

Reported-by: Koohoko
2026-10-15 03:34:59 +08:00
JasonBuildAI 7c5bfd7a1d gateway: auto affinity keeps a conversation where a vendor's cache is kept without saying so (#2230, JasonBuildAI)
A vendor that keeps the prompt cached by itself and reports nothing of it —
OpenAI's automatic prefix cache, Gemini — says neither a read nor a write of
the turn that built the cache. affine judged that turn's stick by what the
reply read and wrote (0 + 0), found it under cacheWorth and moved the
conversation's second turn as "no-cache": the whole prompt went afresh to
another key or account and was paid for in full, on every turn after the
first, for anyone with more than one key or account and Affinity auto (the
default).

7f968b95b named this as not covered: "a vendor that caches without reporting
a write (OpenAI's automatic prefix cache, Gemini) still reports CacheWrite 0
on a first turn, so its second turn may still move".

What such a vendor holds of the conversation after a turn is the prompt that
turn was sent, which is what its cache now has. answered takes the reply's
usage rather than its two cache counts, and where the reply reports neither
a read nor a write, the prompt it was sent (Input) stands for the write: the
second turn stays to read it, as it does for a turn that wrote its cache. A
reply that reports no usage at all (Input 0) counts as no cache, as before,
and a prompt under cacheWorth (1024) still moves. A read or a write the
vendor does report is used as it was, and resting, spent, cold, strict, turn
and rotate are judged before this, so nothing else changes.

The observable change: with Affinity auto, a conversation whose last reply
reported neither a cache read nor a cache write, and was sent at least 1024
tokens, is kept where it was (Why "cache", Kept true) rather than moved
(Why "no-cache"). Its stick, affinity.json and the trace's
Affinity.CacheWrite carry the prompt sent, and Affinity.CacheRead stays 0,
which is what the Routing page shows as read and written; the page itself is
unchanged.

Tests:
- affinity_silent_cache_test.go (new): TestAffinityKeepsACacheTheVendorKept
  Silently. Two keys, least-used routing, and a Chat vendor reporting
  prompt_tokens 3000 with cached_tokens 0 — what OpenAI and Gemini send of a
  first turn — keeps the second turn on k1 as "cache", with the trace
  telling CacheRead 0 and CacheWrite 3000; a vendor reporting no usage at
  all still moves to k2 as "no-cache".
- TestAffinityKeepsACacheJustWritten, its "too little either way" (300/300,
  no-cache) case included, passes as it did.

Run:
- go test -tags nogui -count=1 -run TestAffinity ./internal/gateway: ok,
  80.982s (TestAffinity 39.36s, TestAffinityKeepsACacheJustWritten 26.54s,
  TestAffinityKeepsACacheTheVendorKeptSilently 9.68s).
- go test -tags nogui -count=1 -timeout 45m ./...: every package passes
  except 21 tests red on this Windows machine — agent 4
  (TestInstallWithoutNodeParses, TestWSLClaudeFollowerOnTheMainModelIsNoDrift,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI), gui 4
  (TestGatewayHeldByAContainer, TestGatewayFixQuitsOnlyAMagpie,
  TestFXStateDoesNotWait, TestUpdateThatWontStart), library 3
  (TestAgentsSkillsFolders, TestRemoveFoundSkill,
  TestHooksCodexTrustMovesWithTheGroups), gateway 2 (TestClaudeAsRootEnv,
  TestSweepBridgeProjectsTakesOnlyTheBridgesFolders) and one each in backup,
  davsync, pluginrt, provider, sessions, update and usage. A fresh worktree
  at the base e98440ae, without this change, fails the same 20 of them. The
  21st, gui's TestPurposeAssetMatchesUsage, fails only in this checkout,
  whose internal/gui/assets/purposes.js is CRLF (git says i/lf w/crlf) and so
  keeps the "\r" its TrimSuffix(";\n") doesn't cut; the file is not in this
  diff and the test passes in the base worktree.
- gofmt -l on the changed files: nothing. go vet ./..., GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./...: nothing. go build,
  GOOS=linux go build -tags nogui, GOOS=windows go build: ok.
- Broken by hand: with the substitution removed the new test fails —
  "silent cache: affinity &{... CacheRead:0 CacheWrite:0 ... Why:no-cache},
  want cache". At the base commit the case fails the same way, the second
  turn going to k2.

Not tried: the Playwright suite (no GUI asset changed; the Routing page
reads the same JSON) and a live OpenAI or Gemini key.
2026-10-15 03:34:58 +08:00
yetone 1ad60446ff gateway: a model failing between its siblings' answers climbs its own rest ladder, not a minute forever (#2241, weizsw)
The backoff count was kept per account (restKey), and any model's answer
cleared it. On an account serving several models, a model that kept
failing while its siblings answered was counted 1 every time and rested
one minute, forever. weizsw's Antigravity seat: 41 of 43 rests at
failures: 1.

restAfterMarked now also counts each model's own failures (restID), and
only that model's answer clears that count (servedCandidate). When a
model's own count is past the account's, a sibling answered since the
model last did, so the failure belongs to the model. It climbs its own
ladder (1, 2, 4, 8, 10 minutes) and rests alone, keyed by restID, while
its siblings stay served. If every model fails with no answer between
them, the account still climbs and rests whole, as before. A window
rest wins as before. A candidate naming no model keeps the account's
count alone.

What was run:
- TestModelLadderClimbsPastSiblingAnswers (new, model_ladder_test.go).
  Old code: FAIL ("failure #2 after a sibling's answer: 1 failures,
  rests 59.99s; want 2m0s"). With the restID choice taken out by hand:
  FAIL ("rests antigravity@seat@example.com, want the model alone").
  With the fix: pass.
- The first full run caught TestSmartRouting. Its modelless candidate
  ("t#fail") was given a "t#fail/" count that its served() call never
  cleared. Fixed by counting per model only when the candidate names
  one. TestSmartRouting and the rest/ladder tests pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui and GOOS=windows
  clean.
- HOME=<scratch> go test -tags nogui -timeout 40m ./...: every package ok
  except gateway's TestSmartRouting (above). After the fix, gateway was
  rerun whole: ok (468s).
2026-10-15 03:25:41 +08:00
yetoneandJasonBuildAI c20bb76c4c gateway: a sandboxed frame's Origin: null spends a subscription only with a gateway key (#2242, JasonBuildAI)
A sandboxed iframe, or a page opened from file://, sends `Origin: null`.
foreignPage judges only http and https origins, so corsGuard let "null"
through without a key. A simple text/plain POST from such a page (no
preflight) reached /v1/chat/completions and spent the user's
subscription. corsGuard is where every route's same-origin is decided,
so the fix goes there: a request with Origin: null is answered only
when it carries a working gateway key (keyedCaller, which the listed-
origin 401 path now uses too). It gets 403 and a message that says how
to send a key. App schemes (app://…) and requests with no Origin are
unchanged.

The patch is JasonBuildAI's fe11a8abd (fork branch
fix/null-origin-keyless-spend-a13b21). docs/subsystems/gateway-sessions.md
also says that a null Origin needs a key.

What was run, at this commit's parent 8e8316ed2 vs. this tree:
- Repro with a sandbox HOME, a fake upstream on 127.0.0.1:3672 that logs
  each hit, and `magpie serve` on 127.0.0.1:3671. On main, curl POST
  with Origin: null got 200 and reached the vendor. A sandboxed srcdoc
  iframe in a file:// page, in Playwright WebKit and Chromium, reached
  it too (2 hits). Fixed: null POST and GET /v1/models got 403,
  app://cherry and no-Origin got 200, and both browsers were refused
  with 0 upstream hits.
- With main's cors.go and the new tests, TestForeignPagesRefused and
  TestOpaqueOriginNeedsAKey FAIL ("a sandboxed frame with no key reached
  the vendor 5 times"). With the fix both pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui and GOOS=windows
  clean.
- HOME=<scratch> go test -tags nogui ./...: every package ok except
  internal/gateway and internal/agent. Those hit the 10m timeout at load
  average 76-91: the running tests were 14s and 23s old, not hung. Rerun
  with -timeout 40m: gateway ok (724s), agent ok (620s).

Co-authored-by: JasonBuildAI <jasonbuildai@gmail.com>
2026-10-15 02:58:41 +08:00
yetone d5847f1985 provider: a Codex token refresh replaces ~/.codex/auth.json through a flushed temp file, so a crash or a file held on Windows leaves Codex signed in, not an empty auth.json or a spent refresh token (#2239, JasonBuildAI)
codexToken wrote the rotated tokens back into the user's own Codex
sign-in (~/.codex/auth.json, $CODEX_HOME when set) with a bare
os.WriteFile: O_TRUNC, then write, error dropped. A machine going down
between the two leaves the file empty or zeroed (#1505's shape, on the
vendor's sign-in), and on Windows a file another program holds for a
moment refuses the open, so the rotation never reached the disk while
the refresh token on it was spent (refresh_token_reused on the next
refresh, magpie's or Codex CLI's). It now goes through writePrivate
(edit.Target + steady.WriteFile: temp file beside it, fsync, rename,
held target waited out by steady.Rename for up to 0.5s, mode 0600); a
write that still fails is logged rather than dropped silently, and the
fresh access token still serves the request. codexToken is the one
path for the default home's account, its usage, resets, keep-alive and
the Usage page.

Siblings: grepped every os.WriteFile / O_TRUNC / os.Create outside
tests. The only other write of an agent's live sign-in that truncated
was writeClaudeCredential's file branch (Claude Code's
.credentials.json, written when magpie switches Claude Code's
sign-in off the Keychain); it now goes through writePrivate too and returns a failed
flush as an error instead of "saved". Saved accounts' refreshes
(logins_on.go) already go through writeLogins; Kiro's IDE file through
writeFileAtomic; Codex/Claude switches through writePrivate; mcpauth
and plugin-auth through steady. Gemini's oauth_creds.json, Cursor's,
Grok's, Command Code's, ZCode's credential files are only read. The
remaining os.WriteFile calls write magpie's own caches, marks, ids,
temp files, or create a file only when it is empty (dsh, zcode).
docs/subsystems/providers-accounts.md's #1505 entry says so.

Tests (internal/provider/credentials_write_test.go, _windows_test.go):
- TestCodexRefreshFlushesAuthJSONBeforeReplacingIt: steady.Sync made to
  fail leaves auth.json byte-identical and no temp file; with a working
  flush, auth.json still holds the old sign-in at flush time, the temp
  is beside it, the result keeps every other field and mode 0600.
- TestClaudeCredentialFlushesBeforeReplacing: same for
  .credentials.json, and a failed flush is an error.
- TestCodexRefreshOutlastsAHeldAuthJSON (Windows): auth.json held with
  CreateFile(GENERIC_READ, FILE_SHARE_READ) for 100ms during the
  refresh; the rotated r-work-2 must be on the disk afterwards.

Broken by hand: with both writes put back to os.WriteFile, on macOS the
first two FAIL ("a flush that failed left auth.json ...r-work-2...,
want the sign-in as it was"; "a write whose flush failed reported as
saved"), and on the Windows box (Windows 11 x64, amd64 test binary,
sandbox USERPROFILE/APPDATA/LOCALAPPDATA/TEMP) all three FAIL, -count=3,
the third with "the rotated tokens are not on the disk, only the spent
one's: ...r-work...". With the fix all three PASS 3/3 on Windows and
the two PASS on macOS.

Run on origin/main 7be68467f: gofmt -l (empty),
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build,
and go test -tags nogui ./... under a sandbox HOME with pinned caches
(every package ok but internal/agent and
internal/gateway, which hit go test's default 10m timeout with no hang
in their stacks, the machine at load average 50-90 from other
sessions; rerun with -timeout 40m both ok, 800s and 874s). On the Windows box: the full internal/provider
test binary run from the package folder:
all pass but TestPluginsCarried (open #2229, the same on the old
binary), TestBorrowedOffLevelIsNotAdvertised and
TestAsksOwnBackendAgreesWithTheGatewayDispatch, which read ../catalog
and ../gateway that weren't copied there.

Rebased onto origin/main 3d3a834d6 (30 files, none of them these):
go vet ./internal/provider for darwin, linux (nogui) and windows, and
go test ./internal/provider in the sandbox HOME, ok.

Not tried: a real Codex refresh against OpenAI (the change is only the
write; the refresh request is unchanged), and a real power cut.
2026-10-15 02:47:23 +08:00
EdwinDigital 595b9a25bc gateway: WorkBuddy's own X-Conversation-ID names its session, so Routing groups its requests by conversation, not under No session ID (#2236, EdwinDigital)
WorkBuddy and CodeBuddy name their conversation in X-Conversation-ID,
which sessionHeaders didn't list, so every WorkBuddy request had no
session: Routing put them all under "No session ID", and affinity, usage,
transcripts, OTel and a remote magpie lost the conversation too. The header
is appended last, so the aliases already read keep precedence, and the
vendor is never sent it.

Moved users are covered by the same line: the gateway gives a plugin the
session as ConversationHeader from conversationID(), plugins.go passes it
as FetchRequest.Session, and the WorkBuddy plugin derives its own
X-Conversation-ID from that. No plugin change is needed.

EdwinDigital's record (Windows ARM64, Go 1.26.8, temporary HOME):
- Removing only the alias makes TestWorkBuddySessionHeader,
  TestWorkBuddySessionThroughGateway and TestRemoteMagpieKeepsTheSession
  fail. They pass with -count=20.
- gofmt and git diff --check are clean. Windows go vet ./... and Linux
  ARM64 go vet -tags nogui ./... pass.
- Installed WorkBuddy 5.8.2 (engine 2.161.0) ran against the patched
  gateway and a loopback streaming mock. Two native sessions grouped 2+1,
  with both titles resolved.

Review and run at this head (macOS, Go private cache, sandbox HOME):
- I read the patch line by line.
- The three tests pass. Commenting out the alias by hand makes all three
  fail.
- gofmt -l is clean. go vet passes on darwin, linux -tags nogui and
  windows.
- go test -tags nogui -count=1 -timeout 40m ./internal/gateway/: ok (811s).

Not tried by me: a real WorkBuddy or CodeBuddy client, and real vendor
calls. EdwinDigital ran WorkBuddy against a mock.
2026-10-15 02:36:26 +08:00
yetone 3d3a834d62 gateway: a held key its owner lets see quotas is told those of the providers and accounts it may use, not none (#2216, Kenoia)
#1981 refused every quota route to a gateway key held to a budget, models
or accounts, so a Remote magpie set up with such a key showed none of the
providers it may use. A key's owner can now let it be told them:
access.Key.Quotas, set from the key's new "Quotas" badge on the Gateway
page or `magpie gateway-key quotas <id> on|off`. Off stays the default,
so #1981's answer is unchanged for every key until its owner says so.

With it on, /v1/magpie/quotas (and ?kept=1), /quotas/history,
/quotas/cards and POST /quotas/refresh go through scopeQuotas
(internal/gateway/quotas_scope.go):
- a provider is told only when the key may use every model the catalog
  lists of it: a key with some of a provider's models is told nothing of
  it, since the models it may not use spend the same quota;
- of those, only cards of accounts and keys AllowsAccount lets it use,
  matched by the card's User against AccountIDs (a name two accounts
  share needs both; a card no account is known by only where the key's
  list names none of that provider's); a provider's only key's card,
  named by no one, is that key's;
- cards read from another magpie (From) are never told;
- a refresh of a card outside the scope is 403 gateway_key_held, one
  naming no card reads again only the scope's cards, not ReadAllCards;
- a scope with no card answers the cards routes 403 gateway_key_held, so
  the remote shows the key's own card rather than "nothing read".
/v1/magpie/concurrency and /v1/magpie/usage still refuse a held key.

Run at the reviewed head:
- gofmt -l: clean; go vet ./... (darwin), GOOS=linux -tags nogui,
  GOOS=windows: clean.
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, after the
  rebase onto 7be68467f (#2227's several limits; conflicts in access,
  the CLI usage and test, keys.js and providers-accounts.md resolved by
  keeping both): every package ok but internal/gateway, whose
  TestTranslatedSilenceStillTimesOut went red once at load ~95 (its
  400ms deadline also covers the response headers; filed #2248) and
  passed 5 of 5 alone. Before the rebase the whole suite was ok, with
  agent and gateway rerun at -timeout 40m after the 10m timeout under
  load.
- TestHeldKeyToldItsOwnQuotas (new): a provider-wide key sees A only,
  a key with A/m1 sees nothing of A, an account-held key sees only its
  key's card, a provider's only key, a key told nothing gets 403 from
  the cards route, Quotas-off still 403 everywhere, refreshes outside
  the scope 403. Broken by hand, each red: scope returned nil (every
  card told), every[id] forced true (partial models), the account check
  skipped, the refresh check removed, the only-key rule removed, and the
  told-none 403 removed. TestHeldKeyToldNoAccounts (#1981) still green.
- TestRemoteMagpieShowsHeldKeyItsQuotas (new): a magpie with this one as
  its Remote magpie provider, through a key held to alpha's Two, shows
  office/alpha's Two card beside the key's own; a key told none shows its
  own card alone. Red with the told-none 403 removed ("nothing read on
  that magpie yet").
- TestGatewayKeyQuotasCLI (new): show, on, off, bad values refused.
- GUI: gateway-key-quotas.test.cjs (new) in chromium and webkit, at 1100
  and 420, in en, zh, zh-TW, ja, de: 20/20; red when the badge sends the
  value it already has.
- The badge is a gateway key row's: off, it folds to no width until the
  row is hovered (the row had no room left at 390px: gateway-connect-keys
  went red in en until it did), and on a phone it is shown like the
  row's other controls (phone-rows went red until its rule won).
- GUI, 119 files matching gateway|key|usage|quota|remote|i18n|caller|
  web-|phone|narrow, both engines, concurrency 2: 1349/1385. The reds
  besides phone-rows (since fixed, above): quota-count-wrap and
  quota-name-translated webkit (#2228), usage-agents-hide (#2211) and
  usage-fold chromium en/zh (#2163), each red alike on a fresh
  origin/main. gateway-key-quotas, gateway-connect-keys, phone-rows and
  gateway-key-groups rerun: 38/38; after the rebase every gateway-*,
  phone-rows and key-limit file, both engines: 210/210.

Not tried: a real Remote magpie against a second machine with a held key;
the GUI badge in the Linux and Windows apps.
2026-10-15 02:29:11 +08:00
yetone 8e8316ed2f provider, gui: a routing group's pickers offer OpenRouter's decision models only as the provider's picks say (coeo91 on Discord)
coeo91 picked two free OpenRouter models, and a new routing group's member
picker showed those two and then a run of others. Those were OpenRouter's
decision models (liquid/d1, pplx-decider, jev-latest and the rest of its
output_modalities=decisions list): Deciders() took decideModels() for a
provider that lists its decisions (OpenRouter, oMLX, MLX-Serve), Bailian,
a remote magpie or a plugin, whatever its picks, while the provider editor
draws the same models as unpicked chips.

OfferedDeciders is what a group's pickers offer: with picks saved, only
the picked decision models plus any a group already names as a member or
classifier (so a group made before reads the same); with no picks, every
one, as before. /api/groups' deciders (member and classifier pickers),
the templates and the TUI's member picker use it. Deciders() is
unchanged, so the gateway still lists every decision model to a remote
magpie (X-Magpie-Deciders) and RouteDecider still answers an unpicked one.
docs/subsystems/providers-accounts.md says which is which.

Run in a private GOCACHE and sandbox HOME:
- the new TestOpenRouterDecidersOfferedAsPicked passes; with the pick
  filter turned off by hand it fails ("chat models picked, offered:
  [pplx-decider-v1-27b liquid/d1 jev-latest]").
- go test ./internal/provider -run 'Decide|Decider|OpenRouter|Template|
  RemoteMagpie|Bailian|OMLX|Omlx|MLX': ok.
- go test -tags nogui ./...: every package ok except internal/library,
  which hit the 10m timeout with the machine at load ~150 (stacks in
  mcpauth flow.end sleeps; nothing here touches library). Rerun alone
  at the same load with -timeout 25m: ok in 252s, 285 tests passed, the
  slowest TestAgentMCPFiles at 33s, so the 10m was the whole suite's
  load on this box, not a hang.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows;
  GOOS=linux -tags nogui and GOOS=windows builds.

After rebasing on origin/main 924f62e90: provider, gui, tui ok; gateway
ok alone with -timeout 28m in 1129s at load ~100 (it hit the 10m default
beside the other three packages; it passed in the full run before).

Not run: the Playwright GUI suite. internal/gui/assets is unchanged and
those tests mock /api/groups, so they can't see this server-side list.
Not tried against the real OpenRouter API or in a running GUI; the fake
OpenRouter serves its real decision-list shape.
2026-10-15 02:00:44 +08:00
yetone f299faef48 gateway keys: a key holds several limits at once, every one must pass, and the 429 names the one that resets last (#2227, oxsean)
A key may now hold up to five limits, each in its own window (5 hours
and a week, say). A request needs every one: budget.Reserve checks
each, holds one reservation per window and settles each, and when some
are spent refuses with the spent limit that resets last, so
X-Magpie-Limit-Reset and Retry-After say when the key is really back.
Two limits in one window are refused (change that one instead).

Saved format: the first limit stays in "limit", which older magpie
reads, the rest go in "moreLimits". A file without moreLimits reads as
before.

- access: Change.Index adds (index = len), replaces (keeps its Since)
  or removes (nil) one limit; reset-limit-key with an index resets one,
  without resets all; the plain limit-key replaces all, as before.
- /v1/magpie/limit: "limit" is the binding one (what older clients
  read), "limits" is each. A remote key card shows a window per cap of
  each limit and falls back to "limit" from an older remote.
- CLI: magpie gateway-key limit <id> list | add <period> ... |
  remove <n> | reset [<n>]; the single-limit form still replaces all.
- GUI: the key's badge names the limit holding it most and "+N limit(s)",
  a line per limit under the row, and the editor has a tab per limit
  with Add a limit / Remove this limit. Strings in en, zh, zh-TW, ja, de.
- docs/reference.md and docs/subsystems/gateway-routing.md say so.

Run (worktree on e98440ae6, sandbox HOME):
- go test ./internal/access/ ./internal/budget/ ./internal/gateway/
  ./internal/cli/ ./internal/provider/ ./internal/gui/: all ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags=nogui, GOOS=windows
  on those packages: clean.
- GUI (Playwright 1.62.0) chromium and webkit: the new
  gateway-key-limits test (5 languages x 1100/420), gateway-key*,
  gateway-caller-keys, gateway-keys-off, gateway-own-key,
  gateway-connect-keys: 94/94; i18n-keys ok. quota-name-translated
  webkit en is red with HEAD's assets too, filed as #2228.
- Broken by hand, each went red: Reserve checking the first limit only;
  the refusal naming the first spent limit, not the latest reset; the
  endpoint without "limits"; every limit saved in moreLimits; duplicate
  windows allowed; the remote card ignoring "limits"; the CLI plain form
  adding instead of replacing; the GUI save without its index; the GUI
  badge taking the first limit.

Not tried: against a real remote magpie or real accounts. Known gaps:
two N-day cycle limits are both named "this cycle" on a remote card;
an older magpie that rewrites the keys file keeps only the first limit.
2026-10-15 01:54:28 +08:00
yetone 3c7ec4ba24 gui: Usage is a plugin's page, its code, markup and words in plugins/usage (P2)
P2 of docs/subsystems/plugin-runtime.md, the fourth page after Sessions,
Library and Routing, and the largest part of app.js.

- The Usage page's code (~3000 lines: the Overview's cards, the
  Requests ledger and heatmap, the Sessions tab, the Agents list) moves
  from app.js to assets/plugins/usage/page.js; its markup, index.html's
  <main id="view-usage">, is client.js's part html. app.js 25756 →
  22675 lines (1,355,376 → 1,198,239 bytes).
- page.js builds on app.js at the top level (its timers, ?view=usage's
  tab and filters), so it is the one plugin script that loads after
  app.js. index.html: kernel.js, the plugins' other scripts, app.js and
  the scripts beside it, each page.js, then start.js, which is app.js's
  old tail (magpie.start(), navHides, OPEN_VIEWS, the first page shown,
  load()), so the first page has its code. TestBuiltinClientsLoaded
  holds that order.
- Hooks: open loads it, refresh(again) is load()'s read of it, reload is
  Refresh now, costs redraws costs on a currency change, tab says the
  tab for focusQuotaCard. app.js calls those through magpie.call. The
  allowance cards, quotasOpened, panelQuotaFocus and panelUseFocus stay
  in app.js: the tray panel draws them too.
- plugins/usage: Essential, Requires window, no InUse. Off, its nav tab
  goes and so do the ways to it (data-feature="usage": the panel's Open
  Usage, Routing's View usage); show("usage") gives way to Agents; the
  panel's Allowances tab stays. builtins.test.cjs switches it off and
  checks each.
- The 173 strings only Usage says move to plugins/usage/i18n.js;
  i18n.js 15032 → 14344 lines. "{n}s" and
  "All sessions" stay: context.js says them too since #1591.
- context.js: with context.js now in before the first page is shown,
  the page's open and load()'s first refresh both reached loadContext,
  and the second drew "Reading…" again over the advice the first had
  just drawn, so its curves never played their entrance (context-tune,
  3 of 3 red). loadContext draws the waiting pane once for the same
  days. Its dead last line, which loaded the tab once context.js came
  in late, goes.
- context-window.test.cjs's "arrives after the state" becomes "loads at
  once though context.js is slow": start.js now waits for it.
  usage-stale-answer reads page.js beside app.js. quota-refresh-order
  (#1630) cut app.js at the period picker's comment, now in page.js; it
  ends at the next comment that stays (5 of 5; without keepRefreshedQuotas'
  call, 2 of 5 red).
- docs: plugin-runtime.md, gui-shell.md.

Run, at this tree on origin/main af27b70b4 (main's keepRefreshedQuotas
and quotaRefresh changes, #1630, stay in app.js beside loadQuotas: the
tray panel draws those cards too):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/gui ./internal/pluginrt ./plugins/...: ok
  (-skip TestMainWindowCorners, #1936); gateway and usage as above.
- usage-card-refresh, quota-refresh-order, builtins, editor-picker-clicks,
  context-window, usage-stale-answer: Chromium and WebKit green.
- The full GUI set: see the Routing commit; every Usage red there is the
  same on main or red only under load.
2026-10-15 01:32:13 +08:00
yetone eb7199e120 gui: Routing is a plugin's page, its script, style and words in plugins/routing (P2)
P2 of docs/subsystems/plugin-runtime.md, the third page after Sessions
and Library.

- routing.js and routing.css move to assets/plugins/routing/ (client.js,
  routing.css). Its part's html is the page's head and boxes that were
  index.html's <main id="view-routing">; the rest is drawn by
  routingPage, run at mount since it builds on app.js. It keeps itself
  after that as it did (its own hidden, the language, focus), so its
  hooks are dirty and discard, a routing group being edited, which
  show() and the window's close ask through magpie.call:
  window.routingDirty and discardRouting are gone.
- plugins/routing: Essential, Requires window and gateway, in use while
  the user has a routing group (not Auto, not Hidden), since the page is
  where it is edited. The gateway routes the same with it off.
- With it off, what leads to the page goes too: the nav and panel tabs
  and the panel's section (data-feature="routing"), the guide's Open
  Routing, Providers' "Make a routing group of …", the Usage list's
  View routing and its time as a link, the context card's Latest
  request. A panel left on its Routing tab shows Agents.
- What other pages use of it stays on window: openRoute (context.js),
  kindName, swapWhy, routedWhy (Usage's Requests), newGroupWith
  (Providers), panelRoutingShown (the panel).
- The 505 strings only Routing says move from i18n.js to
  plugins/routing/i18n.js (4 languages); i18n.js 17048 → 15032 lines.
  The plugin's own name and line stay in i18n.js: the Plugins page
  says them with the plugin off (TestBuiltinsTranslated).
- Tests and comments that named routing.js name the new path (gateway's
  antigravity_rest and loop_guard, codeassist.go, usage.go,
  web_compress, group_member_info, assets_revalidate, font-cascade,
  win-fonts, three routing-*.test.cjs). builtins.test.cjs and
  builtins_test.go count seven built-ins and switch Routing off: its
  tabs go, the page shown stays.
- docs: plugin-runtime.md, gui-shell.md, gateway-routing.md.

Run, first on origin/main 3ec45e715, then after rebasing onto af27b70b4
(main's routing.js, css, app.js and i18n.js changes since were carried
into the moved files; its new Routing words, as the rules' conditions,
are in the plugin's i18n.js):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/gui ./internal/gateway ./internal/usage
  ./internal/pluginrt ./plugins/...: ok (gateway 1800s under load,
  -timeout 45m; gui with -skip TestMainWindowCorners, #1936).
- All 193 GUI test files, 3 at a time at load ~250, Chromium and WebKit,
  at the Usage commit on 743fcc035: 185 and 186 green. Every red run
  alone here and on a just-fetched origin/main c524bc018:
  - the same on main: routing-model-rest (#2115), routing-wb-restricted
    (#1905), usage-agents-hide (11 of 16 in both, #2211), usage-fold
    (#2163: 12 of 14 here, 9 of 14 on main over 7 runs, the same 4px),
    quota-count-wrap and quota-name-translated in WebKit (#2228);
  - red only under load, green alone on both: routing-flood (#2215),
    routing-log-icons, usage-ledger (#2211), and three plugin-* files
    whose tree was rebased under them mid-run.
- days-fit, failed-open, side-calls and burst-speed, red on main after
  cf455ebd5, are fixed before this commit (#2134, d692b2548).
2026-10-15 01:32:12 +08:00
yetoneandXIQIXIQIXIQI b789bcc45d gateway, proc: magpie ends a Claude Code run with SIGTERM and a 5s grace before the kill, so its OAuth refresh lock is let go (#2195, XIQIXIQIXIQI)
subscriptionRun.abort killed Claude Code's process group with SIGKILL at
once. A Claude Code holding ~/.claude/.oauth_refresh.lock at that moment
can't run its exit cleanup, and the lock was left for the next requests to
fail on ("another Claude Code process is refreshing it or exited
mid-refresh").

proc.Tree.Stop(grace) sends SIGTERM to the leader alone, then ends the
tree once it has exited (Wait sweeps the group) or grace has passed
(Kill). A second Stop shares the first's grace. Windows has no such
signal and kills the job at once. abort uses it with stopGrace (5s); the
run still counts as ended at once, and abortAll, as the gateway stops,
waits for every tree. Other agents' trees keep Kill.

Run (macOS, sandbox HOME, pinned caches):
- the real Claude Code 2.1.299 (-p, stream-json in/out, as the bridge
  starts it) under a sandbox HOME/CLAUDE_CONFIG_DIR, no credentials:
  SIGTERM after 4s, it exited in 0.497s with 143.
- go test -race -count=20 -run TestTree ./internal/proc: ok
- go test -race -count=5 -run TestClaudeAbortAllowsLockCleanup
  ./internal/gateway (the reporter's test, trap set before the lock is
  made): ok
- broken by hand: abort back to t.Kill() -> TestClaudeAbortAllowsLockCleanup
  FAIL "Claude abort left refresh lock: <nil>"; Stop killing at once ->
  TestTreeStopLetsItCleanUp FAIL "the command's lock is left after Stop".
- on b9c589ebb plus these commits: gofmt -l (nothing), go vet ./... on
  darwin, GOOS=linux -tags nogui and GOOS=windows, go test -tags nogui ./...:
  every package ok but two filed load flakes, TestMaxRPMWaitsForRoomInTheMinute
  (#1791) and TestCopilotSecretToolUsername (#1627), on a machine at load
  ~200; each passed -count=3 alone.
- rebased onto e98440ae6 (27 more commits on main) and
  run again there: gofmt -l, go vet ./... (darwin, linux nogui, windows),
  go test -tags nogui ./internal/gateway ./internal/proc ./internal/agent.
- then onto af27b70b4 (9 commits; gateway routing.go/gateway.go and agent
  codex.go touched, not these lines): gofmt -l, go vet on the three OSes,
  and the tests named above plus the new remote-magpie and Codex ones.
Not tried: a real OAuth refresh interrupted mid-way (no Claude request was
made); Linux and Windows at runtime.

Co-authored-by: XIQIXIQIXIQI <75725040+XIQIXIQIXIQI@users.noreply.github.com>
2026-10-15 01:22:13 +08:00
yetoneandlidi1011 244a21d471 gateway: a structured-output answer a model wrapped in a code fence reaches the client as the JSON inside it (#2196, lidi1011)
Codex's background memory extraction asks for text.format json_schema and
parses the reply text as JSON. A translated model that answered
```json\n{...}\n``` failed it with "expected value at line 1 column 1".

A client that asked for structured output (a format field, or one told in
the system prompt: Request.FormatTold, set by inSystem) now gets the JSON
inside a single unlabelled or json-labelled fence when that is a complete
valid JSON value: streamed (fenceEncoder, which holds text only while it
could still be a fence and passes other text on at once) and whole
(unfencedResult in render). Invalid or truncated JSON, other languages,
text outside the fence and plain-text clients are left as they came.
Relayed (passthrough) replies stay byte for byte. Rebased onto #2126's
asObject/told format: inSystem keeps its told check and sets FormatTold.

lidi1011's patch from lidi1011/magpie fix/structured-output-code-fence
(e67b4ba7b, 8bc440bbb), taken as is apart from the format.go conflict.

Run (macOS, sandbox HOME, pinned caches):
- go test -tags nogui -run 'Fence|Format|Structured|JSON' ./internal/gateway: ok
- with the encoder and render hooks removed by hand,
  TestStructuredOutputFencedAnswerUnfenced (json_schema/json_object, whole
  and streamed) and TestStructuredOutputFenceAfterSystemFallback FAIL with
  text = "```json\n{...}\n```"; restored, they pass.
- on b9c589ebb plus these commits: gofmt -l (nothing), go vet ./... on
  darwin, GOOS=linux -tags nogui and GOOS=windows, go test -tags nogui ./...:
  every package ok but two filed load flakes, TestMaxRPMWaitsForRoomInTheMinute
  (#1791) and TestCopilotSecretToolUsername (#1627), on a machine at load
  ~200; each passed -count=3 alone.
- rebased onto e98440ae6 (27 more commits on main) and
  run again there: gofmt -l, go vet ./... (darwin, linux nogui, windows),
  go test -tags nogui ./internal/gateway ./internal/proc ./internal/agent.
- then onto af27b70b4 (9 commits; gateway routing.go/gateway.go and agent
  codex.go touched, not these lines): gofmt -l, go vet on the three OSes,
  and the tests named above plus the new remote-magpie and Codex ones.
Not tried: a real Codex memory run against a live model that fences its
JSON; a Gemini stream whose thoughtSignature lands mid-text flushes the
held text and is left fenced (falls back to today's behaviour).

Co-authored-by: lidi1011 <283302260+lidi1011@users.noreply.github.com>
2026-10-15 01:22:13 +08:00
yetone 27a0458de1 gateway: /v1/magpie/concurrency lists each request in flight, its agent, model, start and phase, for a status bar's hover (#2132, bigbitbox)
The concurrency read now carries `active` beside requests/waiting/tools:
one entry per agent request counted for Busy, oldest first, [] when idle:
id, agent, model and provider (once routed, from the routing trace),
session when the agent sends one, started and ms, route (the trace id),
and phase only where the gateway knows it: "slot" waiting in a key's or
account's queue, "rpm" waiting for room in the minute, "upstream" while a
try is out at the vendor. No prompt, reply or key. The entry lives on the
request's context from `counted` (so a GET, this poll included, is never
listed), routing ties it to its first route in trace.beginFor, and
lanes.take / rpms.wait / the try loop note the phase, putting the one
before back when they return. Access is the endpoint's: this machine,
another with a gateway key, never a held key (TestHeldKeyToldNoAccounts).
Nothing in routing or limits reads it.

Run (worktree on e98440ae6, sandbox HOME, GOCACHE pinned):
- TestConcurrencyListsEachRequest (new): one request out and one of the
  same agent waiting for a one-slot provider; checks agent, model,
  provider, session, phase upstream/slot, no prompt or key, [] idle and
  after. Broken by hand, each goes red: active left out ("active left
  out or null"), the slot phase removed ("never one out and one
  waiting"), noteRoute removed (model/provider empty), the upstream
  phase removed (phase "").
- go test -race -count=5 -run 'TestConcurrency|TestBusy|TestMaxConcurrency|TestMaxRPM|TestHeldKey' ./internal/gateway: ok
- go test -tags nogui ./internal/gateway (-timeout 28m; 1394s on a loaded
  machine, the default 10m timeout cut the first run short), ./internal/proc,
  ./internal/usageapi: ok
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  on ./internal/gateway: clean
Not run: the full `go test ./...` (disk tight), a real SketchyBar hover;
no GUI change.
2026-10-15 01:13:18 +08:00
yetone d2d94917a6 provider: a Claude allowance heard as Claude Code answered is on the cards a Remote magpie is told, not "nothing read" (#2206, SuInk)
NoteClaudeLimits keeps the windows a Claude answer tells in claudeUsage
and drops the account's LoginUsage reading (StaleAllowance), while the
cards another magpie is told (CachedCards → withAccountReadings) were
built from loginUsageCache and quotas.json only. On a `magpie serve`
that only requests reach, the latest (often the only) Claude reading
was a header, so the remote's Claude card went missing or stale until
its refresh ran LoginUsage.

- claudeUsageEntry gets heardSeq, taken from quotaReadSequence when a
  header is noted: in the same order readings are (readSeq, which is
  taken when a read starts).
- withHeardClaude lays the kept windows on the Claude account's card
  when they were heard after the card's reading started; a reading
  started after the header stands. An account with no card and no
  reading gets one from the header (Plan from its login).
- A /usage run writes a fresh entry (heardSeq 0), so its own reading,
  carried by the card read that ran it, stands.
- docs/subsystems/providers-accounts.md: the allowance row says so.

Run (sandbox HOME, private GOCACHE):
- TestCachedCardsTellHeardClaudeLimits (new, from SuInk's repro): a
  header with no reading gives a card at 42%; a reading started before
  the header (10%) doesn't replace it; one started after (55%) does; a
  later header (60%) wins again. Red without the cards_kept.go change
  ("no Claude card"); with the seq comparison removed it fails "a
  reading started after the header: used 42, want 55".
- go test -tags nogui ./internal/provider -run
  'TestCachedCardsTellHeardClaudeLimits|TestCachedCards|Claude': ok.

Run on the stack of #2204, #2208, #2206 and #2201 on 743fcc035 (the
same trees as pushed), sandbox HOME, private GOCACHE, go1.26.8:
- gofmt -l on the changed Go files: clean. go vet ./... on darwin,
  GOOS=linux -tags nogui and GOOS=windows: clean. go build . on all
  three: ok.
- go test -tags nogui ./...: 51 packages ok; internal/agent and
  internal/gateway hit the 10m default timeout at load ~200 (#2191).
  Rerun with -timeout 60m: agent ok (1205s); gateway ok but
  TestOTelFastRequestTranscriptDiscovery/true (#1811, the 50ms session
  window under load), which passes alone -count=3.
- go test -race -tags nogui ./internal/gateway -run
  'TestRemoteMagpie|TestVerify' and ./internal/provider -run
  'TestCachedCards': ok.

Not tried: a real Remote magpie pair with a real Claude account (no
Claude API calls are made with a user's token here).
2026-10-15 00:54:00 +08:00
ggbdpqandfactory-droid[bot] ca5dc773c1 gateway: a remote magpie's restricted or verify refusal rests only that model, not the whole remote (#2208, ggbdpq)
remoteModelRest scoped a remote magpie's quota, credit and rate refusals
to the model (caa536733) but left its restricted and verify refusals on
the whole remote: a group whose member was one of the remote's other
models went to the member on this computer for the two hours
restrictedRest names (half an hour for a verify), though the remote
rests its own account itself and its other models keep answering there.
Both are that computer's account, on the model it serves: restricted is
said in magpie's own words, which no vendor uses (restrictedSaid reads
them whoever answered), and verify is the vendor's VALIDATION_REQUIRED
for its account. The key's own limit there, a refused key and an
unreachable computer still rest the whole remote, as before.

Run:
- TestRemoteMagpieRestrictedRestsTheModel (new): a fake remote whose
  workbuddy model answers 403 with magpie's restricted hint, kimi OK; a
  group with this computer's member behind it, then one with the
  remote's kimi first. Red on upstream/main 2c18c697 ("the whole remote
  magpie rests...", the group answered "from ko"), green with the fix.
  TestRemoteMagpieVerifyAndKeyLimitScoping (new): the predicate for
  restricted and verify, the key-limit header still whole-remote, and a
  provider that isn't a remote magpie unaffected. Red on the predicate
  before the change.
- gofmt -l clean; go vet -tags nogui for darwin, GOOS=linux and
  GOOS=windows; three-platform build.
- TestRemoteMagpie*, TestRestCap*, sink and rest tests in
  internal/gateway pass.

Review (yetone): with the verify refusal now resting the remote's model,
the held verify was still looked up by the remote's key alone
(restKey), so a request to that model asked the remote again each time
instead of saying the held reason. verifyHeld (routing.go) now also
looks under the model's rest (restID), and gateway.go's caller uses it.
TestRemoteMagpieVerifyHeldOnTheModel (new): a remote answers
VALIDATION_REQUIRED for antigravity/gemini-3-pro; three requests reach
it once and kimi/kimi-k3 is still served. Red with the old verifyHeld
(the remote was asked 3 times); with the predicate reverted all three
remote tests are red.

Run on the stack of #2204, #2208, #2206 and #2201 on 743fcc035 (the
same trees as pushed), sandbox HOME, private GOCACHE, go1.26.8:
- gofmt -l on the changed Go files: clean. go vet ./... on darwin,
  GOOS=linux -tags nogui and GOOS=windows: clean. go build . on all
  three: ok.
- go test -tags nogui ./...: 51 packages ok; internal/agent and
  internal/gateway hit the 10m default timeout at load ~200 (#2191).
  Rerun with -timeout 60m: agent ok (1205s); gateway ok but
  TestOTelFastRequestTranscriptDiscovery/true (#1811, the 50ms session
  window under load), which passes alone -count=3.
- go test -race -tags nogui ./internal/gateway -run
  'TestRemoteMagpie|TestVerify' and ./internal/provider -run
  'TestCachedCards': ok.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Generated-by: GLM-5.3-Flash (ZCode)
2026-10-15 00:53:59 +08:00
ggbdpq f348ff2c7c agent: a Codex beyond loopback is never pointed at the Codex path for account failover, either (#2204, ggbdpq)
What changed:
- failover() no longer writes the base URL (or a CC Switch mirror's) for a
  Codex that reaches the gateway from another machine: #2145 took the
  joined case out (chatGPT() is false there), but Sync's failover write for
  a Codex signed in to ChatGPT and not connected kept pointing its
  failed-over turns at /backend-api/codex, where the gateway takes a named
  key alone, so every one came back a 401. One written before is taken off
  again by the same Sync (the !on branch drops failover's own base URL).
- docs/subsystems/agent-wiring.md: the failover paragraph says so.
- TestCodexFailoverBeyondLoopbackNotWritten: Sync under MAGPIE_ADDR beyond
  loopback with a second ChatGPT account on writes no openai_base_url and
  marks no codex.failover.

Run:
- red on upstream/main 2c18c697: FAIL "failover written beyond loopback:
  openai_base_url = \"http://172.23.80.1:3425/backend-api/codex\"";
  green with the change.
- go test -tags nogui -count=1 ./internal/agent (152s, sandbox HOME): ok,
  the failover, beyond-loopback and switch-only tests among them.
- gofmt -l internal/agent: clean. go vet ./internal/agent on darwin,
  GOOS=linux -tags nogui, GOOS=windows: clean.
- go build -o /dev/null . on darwin, GOOS=linux -tags nogui,
  GOOS=windows: ok (darwin's known trayimage cgo and ld warnings only).

Not tried: a real WSL distro under NAT with a ChatGPT-signed-in,
not-connected Codex while a second ChatGPT account is on in magpie (the
proxy and reach probes are stubbed in tests); the Windows box.

Review (yetone): the test gains a second half, a config.toml already
holding the failover's openai_base_url
("http://172.23.80.1:3425/backend-api/codex") with codex.failover
stashed: the same Sync takes it off. Red with codex.go reverted, green
with the fix, so the patch's "one written before is taken off" is
covered.

Run on the stack of #2204, #2208, #2206 and #2201 on 743fcc035 (the
same trees as pushed), sandbox HOME, private GOCACHE, go1.26.8:
- gofmt -l on the changed Go files: clean. go vet ./... on darwin,
  GOOS=linux -tags nogui and GOOS=windows: clean. go build . on all
  three: ok.
- go test -tags nogui ./...: 51 packages ok; internal/agent and
  internal/gateway hit the 10m default timeout at load ~200 (#2191).
  Rerun with -timeout 60m: agent ok (1205s); gateway ok but
  TestOTelFastRequestTranscriptDiscovery/true (#1811, the 50ms session
  window under load), which passes alone -count=3.
- go test -race -tags nogui ./internal/gateway -run
  'TestRemoteMagpie|TestVerify' and ./internal/provider -run
  'TestCachedCards': ok.
2026-10-15 00:53:58 +08:00
hhh2210 2a99e7a429 gui: keep refreshed cards when their account identity changes (#1630)
The ce5d9f9d4 review correctly restored replies whose account was first
named by a refresh. Its full-list fallback bypassed the ordering guard:
an older GET could restore the unnamed card, or the fallback could undo
another card's completed refresh.

Apply the fallback to its provider's cards (a remote summary's namespaced
children included), keep other providers, and preserve card refreshes that
completed since the request began. Mark the replaced keys as well as the
new cards, so an old response cannot resurrect the unnamed summary. Only
a serialized whole-page read retires the markers it no longer needs.
No changes to account reading, authentication, throttling or auto-refresh.

Verification on macOS arm64, Go 1.27.2, Bun 1.4.3, isolated homes/APIs:
- On ce5d9f9d4, four new ordering cases fail: renamed account vs old GET,
  crossed card replies, a pending GET after another provider's completed
  refresh, and a remote summary becoming child cards. All nine now pass.
- The real browser page on ce5d9f9d4 reverts 61% to 28% after the late
  response. Named and unnamed cards now pass in both engines/all five
  languages. 21 related frontend files pass 184/184; the whole GUI suite
  was not run. The remote-card suite caught a missing namespace case in
  the first draft; corrected and the 21-file run repeated successfully.
- Three-platform vet and darwin/linux-nogui/windows builds pass. Final
  internal/gui Go tests pass after the namespace correction. Diff clean.
- Full go test -tags nogui ./... completed. The first isolation wrapper
  made TMPDIR too long for the omarchy Unix sockets; shortening TMPDIR
  makes that package pass. The unresolved failure is the already recorded
  TestPluginSOCKSProxy HTTPS/dead-SOCKS response-vs-error mismatch. No Go
  source or proxy paths changed; no full-suite-green claim.

Not tried: the native app or real account identity changes. These are
controlled response-order regressions, not the cause of the user's clicks
on the noninteractive reset-date glyph.

Review record (magpie maintainer session, on origin/main 429698f96, then
rebased onto fad96ea0f; sandbox HOME, private GOCACHE):
- gofmt -l clean; go vet darwin/linux/windows and the three builds pass.
- go test -tags nogui ./...: 52 packages ok at once. agent and gateway hit
  the 10m default under load ~190, middleware's TestFailOpen was slow and
  omarchy's sockets hit a long TMPDIR; rerun with a short TMPDIR and
  -timeout 40m all four are ok. internal/gui ok again after the rebase.
- quota-refresh-order: on main's app.js cases 6-9 fail; patched 9/9.
  Broken by hand, each red: no marker on replaced keys (6,8,9); an older
  reply may restore a removed key (6,8,9); fallback skipping
  keepRefreshedQuotas (7); remote children not matched (9); markers
  retired inside keepRefreshedQuotas (8); belongs() always true (8).
- Full GUI suite in chromium and webkit, 5 languages, 1100/420. Reds also
  red on main alone: usage-agents-hide and usage-fold (#2211, #2163),
  usage-sum-whole ja/de 780px (#1864: main 1/3, patched 2/3; that test
  serves no quotas). quota-name-translated and quota-pace goto timeouts
  under load passed rerun. After the rebase quota-refresh-order and
  usage-card-refresh pass 21/21 in both engines.
- Not tried: the native app or a real account whose identity changes.
2026-10-15 00:44:51 +08:00
yetone 62fc1b4b57 provider: a Codex switched off or removed from magpie has no reset about to run out read or spent (#2226, JasonBuildAI)
SpendExpiringCodexResets, run every five minutes by the gateway, walked
the accounts with auto-use on and read their allowance from ChatGPT, then
spent a reset about to run out, without asking whether Codex was switched
off or its account removed from magpie. Every other background loop asks
leftAlone (75cbc7e1); this one now returns at once when it says so. A
spent reset can't be given back. providers-accounts.md lists the site.

The week-used-up spend (AutoUseCodexReset) is left as it is: it runs only
on a request that reached Codex, not in the background.

Run (sandbox HOME, pinned caches):
- TestExpiringResetLeftAlone without the fix: FAIL "switched off: read
  its allowance 2 times, spent 1 of its resets" and the same for
  removed; with it, ok, and the same account switched on still spends.
- go test -count=1 ./internal/provider/: ok (220s).
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.
Not run: the full go test ./... (disk kept low for other sessions); not
tried against a real ChatGPT account.
2026-10-15 00:36:30 +08:00
yetone e98440ae6b gui, gateway: auto mode's classifier and other side calls in a Claude Code session are no compaction on the Context tab (Player on Discord)
Player (magpie 0.1.1234 in docker, Claude Code in auto mode on glm-5.3)
saw "137 requests · 45 compactions" on Usage → Context for a session
that never compacted (peak ~116K of 1M). Claude Code's auto mode
classifier ("You are a security monitor…", a transcript, no tools,
34–48K) goes under the conversation's own session id, so every one
after a 60–115K turn passed compacted()'s 60% drop. Title, quota
check and a subagent's turns share the id too, and the latest one of
any of them became the session's "latest request".

contextOf now keeps a session's line to its own turns:
- in a session whose turns carry tool definitions, a request without
  any is a side call (classifier, title, quota check) and is left out
  of the session and the agent's stats, as a Kind'd call already was
  (toolSessions, read from the routes on disk, so existing history
  reads right too);
- a Claude Code subagent's request is left out of the session's line
  (still in the agent's stats). The route now records it: Route.Sub,
  from x-claude-code-agent-id (subagentOf), set in serve's beginFor.
An agent that sends no tools at all keeps every request.

Tests:
- TestContextSideCallsAreNoCompaction: an interleaved session like the
  reporter's (title, quota check, 7 turns 60K→120K each followed by two
  classifier calls 34–48K, two subagent turns, then a real compaction
  120K→33K). On origin/main's context.go it fails "compactions: session
  10 agent 10, want the one real one"; with only the subagent check
  removed it fails with 2. Passes now: 1 compaction, 10 points, latest
  is the last turn, peak 120K, baseline 24K.
- TestContextToollessAgentKeepsItsTurns: a no-tools chat app's 70K→20K
  still counts.
- TestRouteSaysItsSubagent (gateway, through Handler with a fake
  upstream): fails "map[:2]" without the gateway line, passes with it.

Run at this head (go1.26.8, darwin): 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; go test -tags
nogui -count=1 ./... under a scratchpad HOME with caches pinned. With the
machine at load ~180-260 the first full run timed out (10m default) in
agent, gateway, library, plugin and provider with no test FAIL; those
five were rerun with -p 2 -timeout 45m and all passed. Everything else
passed in the full run. No GUI asset changed (context.js reads the same
JSON), so the Playwright suite wasn't run. Not tried against the
reporter's own usage.jsonl or a live Claude Code auto-mode session.
2026-10-15 00:17:23 +08:00
yetone 0c0231b80f library: the RTK page lists Antigravity CLI and gives it rtk 0.51's plugin, not leaving agy out (#2202, Chichengmo)
rtk 0.51.0 installs a global hook for Antigravity CLI: `rtk init -g --agent
antigravity` writes ~/.gemini/config/plugins/rtk/{plugin.json, hooks.json,
rules/AGENTS.md}, a PreToolUse hook on run_command that runs `rtk hook
antigravity` (src/hooks/init/antigravity.rs at v0.51.0). The RTK page had
no agy row, so magpie never offered it.

- rtkSpecs gets "agy": installs through rtk's own -g --agent antigravity
  (no --auto-patch; that branch ignores it), reads it as on when its
  hooks.json holds `rtk hook antigravity`, and switching off removes
  plugins/rtk only, never a user's other plugins next to it.
- agyBlocked: rtk 0.50 knows Antigravity only per project and exits 1 on
  -g ("Antigravity is project-scoped"), so an older rtk isn't run for it.
  The row says "Update RTK" with its own reason (installs it only per
  project), not Codex's @RTK.md one; en, zh, zh-TW, ja, de.
- docs/subsystems/library.md says so.

Run (worktree off origin/main 429698f96):
- TestRTKAntigravity (fake rtk with rtk's real hooks.json): red with the
  spec removed, with the gate removed, and with removal widened to the
  plugins folder (it took the user's own plugin out).
- library-rtk-agy.test.cjs: Chromium + WebKit, 5 languages, 1100 and 420
  wide, nothing sideways; red (agy got Codex's copy) without the client.js
  branch. All library-rtk-*, library-loading and i18n-keys GUI tests pass.
- Real rtk 0.50.0 and 0.51.0 with the built magpie CLI in a sandbox HOME:
  0.50 lists agy and refuses `library rtk on agy` with the 0.51 message;
  0.51 writes the three files, off removes plugins/rtk. agy 1.3.5 in that
  HOME: `agy plugin list` shows "rtk (enabled, 1.0.0) 1 rule, 1 hook",
  `agy plugin validate` ok.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows; the three
  builds; go test -tags nogui ./... in a sandbox HOME: all ok but internal/provider,
  stopped at the 10m default at load ~190; alone with -timeout 45m it
  passes (718s). Noted on #2191.

Not tried: an agy turn actually having a command rewritten by the hook;
real runs on Linux or Windows.
2026-10-15 00:02:24 +08:00
yetone 743fcc0351 gui: a click at the view's top keeps the clicked control under the pointer, not the view at its top (#2134)
cf455ebd5 (#2134) kept a view that was at its top when clicked at its
top, whatever came in above what was clicked. That fixed the 2px slide
of Settings' Version row, but on Routing a day picked with the view at
its top brings that day's stage in above the bar (~138px), and the bar
was pushed down out from under the pointer. routing-days-fit ("picking
a day moved the bar") and routing-failed-open ("picking the request
moved the page") went red on main from then, 4 of 4 each in Chromium;
routing-side-calls 2 of 2.

The rule, decided: a view at its top stays at its top only while what
was clicked moves less than half its own height, so it is still under
the pointer. Anything larger above it is scrolled past, and the control
is held where it was clicked as before cf455ebd5. hold()'s comment, the
click guard's header and gui-shell.md say so.

Run on origin/main 7f968b95d, at load ~220-300, and again after moving
onto origin/main a36319d60 (no change to the click guard between):
- routing-days-fit 12/12, routing-failed-open 8/8, routing-side-calls
  4/4, update-auto 10/10, update-restart 22/22, in Chromium and WebKit.
- Broken by hand: with the old `h.top && want > 0` line, days-fit and
  failed-open go red (as on main); with the at-top rule removed,
  update-auto goes red (#2134's 2px).
- The click guard's GUI set (211 files that click and scroll), 4 at a
  time in Chromium and 3 in WebKit, at load ~300: Chromium 208 green,
  WebKit 207. The rest, run alone on this tree and on origin/main:
  routing-keys-fold (#1612), routing-model-rest (#2115) and
  routing-wb-restricted (#1905) fail the same on main;
  routing-flood (#2215) and sessions-folder-delete (#2218) failed once
  under the load and pass alone, 2 of 2 here and on main a36319d60.
- On a36319d60: routing-days-fit, routing-failed-open, update-auto and
  routing-side-calls green in Chromium and WebKit.
2026-10-14 23:27:46 +08:00
yetone d0fcb8bcdf agent: an agent uninstalled with its folder left behind shows "CLI not found" with no live settings, Hermes and the shared-folder agents too (#2177, mengyianx; #2173, SkyTodInfi)
Detection goes by an agent's folder, and an uninstall leaves the folder
behind. Before this commit, Hermes with only its 37-byte
~/.hermes/config.yaml (custom_providers: [], mcp_servers: {}) was listed as
installed in `magpie ls`, the GUI and the TUI, with model and effort pickers
that no program reads. CLIMissing (#843) covered only agents that have an
install command and their own folder. Hermes and the agents whose folder
something else keeps too (claude, codex, cline, opencode, goose) were never
gone.

What changes:
- internal/agent/gone.go adds cliHeld, which asks whether anything here still
  reads the folder:
  - the CLI on PATH or in proc.FindTool's folders (for goose, a binary that
    isn't pressly's Go goose);
  - its desktop app (HasApp) or sign;
  - the vendor installer's own place: ~/.claude/local, ~/.opencode/bin,
    ~/.codex/packages/standalone, Hermes' <home>/hermes-agent checkout;
  - for the shared folders, an editor extension under
    ~/.<editor>/extensions (anthropic.claude-code, openai.chatgpt,
    saoudrizwan.claude-dev), Claude.app or Claude Desktop, OpenCode.app or
    Goose.app on a Mac, a JetBrains IDE's settings (its agents bring their
    own program) or Zed's external_agents.
  When magpie can't tell, the agent is never gone. That covers OpenCode and
  Goose off a Mac, Gemini (its folder is Antigravity's and Code Assist's
  too), agents with their own detect, and WSL and plugin agents. It also
  covers Bin agents with no install command, except Hermes (cliOnly), since
  their installers' paths aren't verified.
- GUI: a gone row shows "CLI not found" and none of its settings, and the
  tag's tip says why. It offers no Apply again. While it is still wired it
  keeps its switch and Disconnect. Once it isn't wired it folds under Not
  set up, and Get started doesn't offer it (connectKind is "no"; the sandbox
  run showed Hermes offered there before). The panel shows the words only.
  The new tip is translated into zh, zh-TW, ja and de.
- The TUI leaves the agent out. `magpie ls` says "CLI not found" beside its
  path.
- docs/subsystems/agent-wiring.md describes all of the above.
- aside-native.test.cjs drops cliMissing from an Aside fixture. That state
  can't happen (Aside has no install command and isn't in cliOnly), and
  that test is about runtime_unavailable.

What was run:
- Sandbox HOME holding only the reporter's ~/.hermes/config.yaml (37 bytes)
  and a bare ~/.codex, with env -i and PATH=/usr/bin:/bin:
  - `magpie ls` at base 331c27703 lists "Hermes Agent — · effort —".
  - The fix lists "Hermes Agent  CLI not found  ~/.hermes/config.yaml".
  - Codex stays listed, because this Mac has ChatGPT.app's Codex (HasApp),
    so a really installed agent is kept.
- `magpie web` from the same sandbox, screenshot in Chromium: the Hermes row
  shows "CLI not found" and no pickers. That run found Get started still
  offering Hermes, which this commit fixes.
- go test ./internal/agent (2255s under load ~250 on 14 cores) and
  ./internal/cli and ./internal/tui pass. ./internal/gui fails only
  TestMainWindowCorners/macOS_26_SDK, killed at its 40s deadline under the
  same load. That is #1936; it has nothing from this change in its path, and
  it passed on base once and failed on it twice.
- GUI in Chromium and WebKit:
  - agent-cli-missing.test.cjs covers 5 languages, widths 1100 and 420, and
    the panel.
  - getting-started.test.cjs adds a gone Hermes to the fixture; the chips
    stay codex, claude and opencode.
  - Also run: i18n-keys, aside-native, agent-*, panel-* and click-scroll.
- gofmt -l is clean. go vet passes on darwin, linux (-tags nogui) and
  windows for the touched packages.

Broken by hand, and the tests went red each time:
- Dropping the openai.chatgpt check made TestCLIMissingSharedFolders' codex
  case red.
- Dropping the hermes-agent case made TestCLIMissingHermes red.
- Dropping the GUI gone branch, or the agentUsed change ("the one not
  connected stayed up"), made agent-cli-missing red.
- Dropping connectKind's cliMissing line made getting-started red
  (30 of 60 failed: chips gained hermes).

Not covered:
- library.Targets (Skills/MCP) still lists a gone agent as a place to give
  skills to.
2026-10-14 22:50:46 +08:00
Hogee 644f4316f9 sessions, usage, gui: separate Codex thread relationships and consumption (#1591)
Preserve native Codex thread IDs and explicit parent chains. Associate gateway
calls with their actual thread by unique response ID before legacy matching;
fold identical native history copies and keep ambiguous actors unknown.

Existing Sessions APIs expose optional Codex roles, parent/root relationships
and per-thread model/effort consumption. The overview uses its existing calendar
range. Usage request APIs expose query-time actor classification and reuse
session/subagent/parent_agent for Codex. Other agents, pricing, gateway routing,
UI assets, raw Usage logs and model-only aggregation retain their semantics.

Verified after rebasing onto main 331c27703a,
at commit 50baace0a52953263dddc49f4dc55f97a8457dd1, code tree
78743e334f8c841e2a188aafe26996c016a8fa4b. Only this message is amended afterward.
Go 1.26.8 darwin/arm64; tests used temporary HOME and pinned Go caches.

Passed (each exit 0):
- git diff --name-only origin/main...HEAD -- '*.go' | xargs gofmt -l (no output)
- go vet ./...
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go vet -tags nogui ./...
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go vet ./...
- go build -o /tmp/magpie-codex-session-identity-p4-darwin
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -tags nogui -o /tmp/magpie-codex-session-identity-p4-linux
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -o /tmp/magpie-codex-session-identity-p4-windows.exe
- go test -tags nogui ./...
- go test -race -tags nogui ./internal/sessions ./internal/usage ./internal/gui -run '^(TestCodexIdentityParentChainsAndSummaryCache|TestCodexIdentityParentMergeAcrossRolloutFiles|TestCodexCallThreadIDPriorityAndCache|TestCodexCompactionPromotesThreadID|TestCodexSourceNativeVariants|TestCodexIdentityFieldsOmitOtherAgents|TestCodexIdentityInvalidatesOldSummaryCache|TestCodexLedgerResponseIdentityAndOwnConsumption|TestCodexRequestPageFoldsCopiesBeforeResponseMatching|TestCodexExactResponsePairPreemptsLegacyMatchInLedgerAndDirect|TestCodexQueryPageExactResponsePairPreemptsLegacyMatch|TestCodexRejectedGatewayDoesNotPairWithNativeCall|TestCodexKnownSubagentWithUnknownRootKeepsOwnConsumption|TestCodexQueryPageRefreshesIdentityAndSharesJSONFields|TestCodexActorSurvivesPackedRequestChunk|TestPackedRequestPageCallerAndRouteIdentity|TestPackedGatewayRetainsOversizedSnapshot|TestCodexSessionAPIAddsOwnModelEffort)$' -count=1
- git diff --check

Behavior-break proof: removing identity/thread-ID promotion fails native identity,
upgrade/conflict and compaction assertions. Disabling exact-pair preemption loses
a neighboring main call. Removing API enrichment yields missing consumption;
using All for a 7-day overview yields 740/74 instead of 40/4. Restored code passed
its targeted tests and the final checks above.

Native checks had Clang enum/linker deployment-target warnings.
Linux/Windows runtime, real accounts/vendors and manual UI were not exercised.
No frontend suite was run because the change does not touch GUI assets.

Refs #1591 (Codex portion only).

Reviewed and applied by yetone (cherry-picked from Hogeexxl's fork, bf8c8c9e).
The one conflict was call_cache.go's version: main had taken calls-v13 for
compaction times (e1dcd1e1d), so this is calls-v14. Run with the follow-up
commit on top, at tree 122b933ba4c474e443f2b29c6d0a4163ae364f78 on origin/main e5cd125f0 (Go 1.26.8
darwin/arm64, sandbox HOME, private GOCACHE):
- gofmt -l on the changed files: none
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- the darwin, linux (nogui) and windows builds
- go test -tags nogui -timeout 40m ./...: all ok
- go test -race -tags nogui -run 'Codex|Packed|QueryPage|RequestPage'
  ./internal/sessions ./internal/usage ./internal/gui: ok
Broken by hand, each red: codexIdentityRow not setting Subagent (8 usage
tests), setting it for a main thread too (2), Session kept raw instead of
the root (7), thread_spawn's parent_thread_id not read (3 sessions tests),
response pairs not reserved before the old matching (6).
Not tried: a real Codex subagent rollout (none on this machine; every
recent rollout is a vscode main thread whose session_id equals its id),
and the GUI by hand. Claude Code's fields are unchanged.
2026-10-14 22:45:40 +08:00
yetone 0c1e9b79d3 agent: Claude Science runs on magpie's gateway, its daemon restarted with ANTHROPIC_BASE_URL (leesunrise2364)
Claude Science (Anthropic's research app, 0.1.62, "operon") has no
third-party inference setting, but its daemon reads ANTHROPIC_BASE_URL
(http allowed on loopback). It still requires its own Claude sign-in
(no API keys); magpie never bypasses, forges or forwards it.

- agent/claudescience.go: a claude-science agent, found in the Mac
  bundle, %LOCALAPPDATA%\Programs\ClaudeScience or ~/.local/bin.
  Connecting runs `claude-science stop` then
  `serve --detached --no-browser --port <its port>` with
  ANTHROPIC_BASE_URL set to the gateway, in that process only (no
  user-wide env); disconnecting restarts it without the variable. A
  mark in magpie's config notes the pid/port/URL; a daemon started
  elsewhere shows as drift, never stopped behind the user's back.
  KeepClaudeScience (WhileServing) starts it again on the gateway when
  none runs (after a reboot). Setting the same value again is a no-op,
  so Connect's connect+Apply restarts once.
- gateway/science.go: a request with X-Anthropic-Surface: operon is
  Claude Science's. /v1/models lists every model by a
  claude-magpie-<n> alias with a non-slug name (its picker drops other
  ids); a Claude id magpie doesn't serve (its default, its haiku) goes
  to the model last picked, else the first listed. Its sk-ant-oat
  bearer is dropped like any Claude sign-in.
- Notice in 5 languages; agent-wiring and gateway-routing docs; README.

Run:
- go test -tags nogui ./internal/agent -run ClaudeScience and
  ./internal/gateway -run TestClaudeScience: pass; each broken by hand
  (no variable in env, keeper touching a running daemon, no
  scienceTurn, isClaudeScience off) went red.
- Real 0.1.62 binary in a sandbox HOME on macOS (from the dmg, port
  8481): connect restarted it once with ANTHROPIC_BASE_URL (ps -E),
  connect again was a no-op, disconnect restarted it without, the
  keeper in `magpie serve` restarted a stopped daemon with it.
- Sandbox gateway with a mock provider, sent the app's post-sign-in
  headers (a made-up sk-ant-oat bearer, X-Anthropic-Surface: operon,
  oauth beta): /v1/models gave the aliases, model retrieve worked, a
  streamed turn and a haiku request went to the mock's model, the
  upstream saw only the provider key, sk-ant 0 times in its log.
- Windows 11: the real daemon runs in a sandbox profile against a
  sandbox gateway; before sign-in it asks nothing.
- gofmt -l clean; go vet darwin, linux (nogui), windows clean; full
  go test -tags nogui ./... green except six packages that hit the
  10m timeout at load average 250-460 (other sessions); agent,
  gateway, cli, gui, library, provider rerun with -timeout 50m: all
  ok; GUI agent-notice-lang + i18n-keys in
  chromium and webkit at 1100/420, 5 languages: 25/25.
- Rebased onto origin/main 6 commits back (874e4e8ad; 29 upstream
  commits incl. gateway.go, i18n.js): vet darwin/linux(nogui)/windows
  clean; go test -tags nogui agent, gateway, cli, gui: ok; GUI
  notice/i18n 25/25. The Windows sandbox gateway was swapped to that
  build and the app's headers replayed through it: the alias list, a
  tools turn and a haiku request reached mock-sci-1, sk-ant 0 times in
  the upstream log.
- Rebased again onto ce5d9f9d4 (6 commits: affinity, max output,
  OpenCode Gemini, i18n.js): vet on 3 OSes clean; gateway
  -run 'TestClaudeScience|Affinity|UserOutput|MaxOutput|OpenCodeGemini|
  TestClaudeDesktop|Alias', agent -run 'ClaudeScience|TestEveryNotice|
  TestAgentConnect|TestRewire', gui notice/i18n Go tests: ok; GUI
  notice/i18n 25/25.

Not tried: a real Claude sign-in (left to the owner) and so any turn
the app itself sends; whether the Mac/Windows window attaches to the
daemon magpie started rather than starting its own (drift is shown
and fixed by picking magpie again); Linux.
2026-10-14 22:24:11 +08:00
hhh2210 86cc7ac56d usage, gui: keep refreshed cards and distinguish deferred readings (#1630)
A card refresh and a whole-page quota read could replace each other's
entire snapshots. An older GET arriving after a successful refresh put
the old number back on screen; two card refreshes could undo each other.
Apply each POST's requested card alone and retain completed card readings
against whole-page requests that began before them. Later reads can still
update or remove cards. Failed refreshes do not block background results.

A saved Claude account not asked for, or allowances held by When I ask,
could also show "couldn't be read just now" without making a request.
Carry readDeferred through the cached card and CLI/gateway report, and
give that state a separate translated notice. Keep original read times,
network-failure notices and authentication errors. Automatic saved-account
reads and the existing 30-second floor are unchanged.

Verification (macOS arm64, Go 1.27.2, Bun 1.4.3; isolated homes/API fixtures):
- On base 2c5db1c6, quota-refresh-order.test.cjs fails three cases:
  old whole-page replies restore 0 over 32; crossed card replies restore
  0 over the other card's 61. With the fix, 4/4 pass.
- TestQuotaDeferredReadIsNotFailure fails the three deliberate-skip cases
  on the base, passes here; checks real read failures and auth refusals too.
- Original assets fail the new browser case with "a request not made was
  described as failed". Related frontend checks pass 71/71, including the
  real card button in Chromium and WebKit across en/zh/zh-TW/ja/de. The
  extra locale/i18n checks pass 12/12. The full GUI suite was not run.
- Provider tests for deferred/kept/saved readings pass -race -count=20.
- gofmt and git diff --check clean. Full vet on darwin, linux nogui and
  windows; darwin build, linux nogui build and windows build pass.
- go test -tags nogui ./... completed: every tested package passed except
  internal/plugin's TestPluginSOCKSProxy. HTTPS through a dead SOCKS proxy
  produces "proxyconnect tcp: 502 Bad Gateway: socks connect ... refused",
  while the test expects an HTTP 502 response. Reproduced unchanged on
  freshly fetched upstream 68552188 in an independent worktree; already
  reported in #1630. The full suite is not green; no proxy change here.

Not tried: the patched native app with a real Claude account. The response
ordering is injected in tests, not captured from the reported incident;
this does not establish that every intermittent refresh failure is fixed.
2026-10-14 21:54:12 +08:00
yetone b9c589ebb1 gateway: the user's own Max output lowers a plain provider's max_tokens, not only a group's (YaCo on Discord)
Claude Code asks claude-opus-5-5 for max_tokens 128000. A relay that
holds back max_tokens x price from a key's quota answered 403 "token
quota is not enough ... need $2.59" for every turn (128000 x $20/M plus
~8K input x $4/M). Setting the provider's Max output didn't help: the
gateway lowered max_tokens with withMaxOutput only inside a group
(outputLimit), so a request routed straight to a provider went out as
the agent asked.

userOutput finds the Max output the user set for the provider's model
(provider > model or the provider's "*", Entry.OutputSet) and lowers a
larger request to it on any route. Only the user's own value does this
outside a group: a vendor's catalog figure may be stale. Group routing
is unchanged.

Run:
- TestUserMaxOutputLowersAPlainProvidersRequest (new): 128000 -> 32000
  with Max output 32k on the model, 8000 kept, a sibling model with no
  Max output kept at 128000. Red without the gateway.go change ("went
  as 128000").
- go test ./internal/gateway -count=1 (whole package, -timeout 45m):
  ok, 1200s, before rebasing onto 4e9335c96; after the rebase the
  Output/MaxTokens tests again: ok.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
- A real Claude Code 2.1.29x against a fake server with the reporter's
  env: it sends max_tokens 128000 for claude-opus-5-5 with or without
  magpie. Not tried against the reporter's relay.
2026-10-14 21:11:42 +08:00
yetone 7f968b95dd gateway: auto affinity keeps a conversation on the cache its last reply wrote, not only one it read (vilicvane on Discord)
Affinity's auto mode kept a conversation on its last answerer across turns
only while that reply had read at least cacheWorth (1024) tokens from the
vendor's cache. A first turn reads nothing and writes the whole prompt
(Anthropic's cache_creation_input_tokens), so the second turn was moved as
"no-cache" and the cache just built was thrown away (vilicvane on Discord,
「会话保持 → 自动」: 「新的 cache 都建好了,再切走不可惜吗?」).

answered() is now given the usage's CacheWrite beside CacheRead (both
already parsed at that call site for every route: Anthropic, Chat's
cache_write_tokens / cache_creation_input_tokens, Cursor, Command Code,
plugins), and affine counts read + written against cacheWorth. The stick
keeps cacheWrite in memory and in affinity.json (`cacheWrite`, omitempty);
a file from before has no such field and reads as 0, so an old stick is
judged by its read alone, as before. The trace's Affinity carries
CacheWrite, and the Routing page's "cache" and "no-cache" explanations say
what was read and what was written (en, zh, zh-TW, ja, de).

Not covered: a vendor that caches without reporting a write (OpenAI's
automatic prefix cache, Gemini) still reports CacheWrite 0 on a first turn,
so its second turn may still move. Noted in gateway-routing.md.

Docs: docs/subsystems/gateway-routing.md (affinity bullet), docs/reference.md
(step 6 of how magpie picks an account).

Run:
- TestAffinityKeepsACacheJustWritten (new): an Anthropic Messages upstream
  streaming cache_creation_input_tokens 3000 / read 0; the second turn is
  kept as "cache", also across a restart (affinity.json reloaded); 600+600
  is kept, 300+300 moves as "no-cache". Broken by hand twice and watched
  red: the old `st.cacheRead < cacheWorth` (written: why no-cache), and
  stickOf not reading CacheWrite from the file (restarted: no-cache).
- routing-affinity-cache-write.test.cjs (new): chromium and webkit, 1100
  and 420 wide, en/zh/zh-TW/ja/de, 20/20 pass; red on the old routing.js
  and i18n.js. i18n-keys.test.cjs and routing-account-identity.test.cjs
  pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows for
  internal/gateway.
- go test ./internal/gateway/...: all pass except
  TestAgentGoneInTheRetryPause/group_replan, which failed in two full runs
  at load average 150-380 and passes alone (-count=3); its fixed 100ms
  sleep before cancelling assumes the pause has begun. Filed as #2175; it
  never reaches the affinity path this changes (a first request).
- go test -timeout 40m ./... at load ~300-377: 50 packages ok; agent and
  gateway hit the 40m package timeout (no test failed before it); gui's
  TestSetAnswersWhileDevinAndProvidersHang (#1375) and
  TestMainWindowCorners (#1936) failed, both filed load reds.
  internal/agent rerun alone: ok (1008s at load ~200).
- Not tried against a real Anthropic account.
2026-10-14 21:05:26 +08:00
yetone 4e9335c96c plugin: Windows on ARM downloads Bun's native windows-aarch64 build and runs plugins, not "Bun has no build for windows/arm64" (#2183, EdwinDigital)
bunTargetFor turned windows/arm64 away, so magpie-windows-arm64.exe
listed a plugin as on while its host never started, and its providers
never showed. Bun publishes bun-windows-aarch64.zip (1.4.2 and later),
so windows/arm64 now maps to it, with no baseline suffix (arm64 has no
baseline build). Its SHA-256 a7a16b87…0cfd is added to bunSums, taken
from Bun 1.4.2's SHASUMS256.txt, so the download is still checked and
can come through a mirror. The provider-plugins page says so.

What was run (macOS arm64, sandbox HOME, private GOCACHE):
- TestWindowsOnArmGetsNativeBun (new): with windows/arm64 stubbed,
  Bun() downloads bun-windows-aarch64.zip from an httptest release and
  runs it; the checksum is the official one. Old bun.go: FAIL
  "bunTarget = "", Bun has no build for windows/arm64".
- TestBunTargetForMusl gains windows/arm64 and now checks every
  target has a checksum; TestBunDefaultSums and TestBunTarget list
  bun-windows-aarch64. Both FAIL on the old code.
- go test ./internal/plugin/ ok; gofmt -l clean; go vet darwin,
  GOOS=linux -tags nogui, GOOS=windows clean;
  GOOS=windows GOARCH=arm64 go build ok.
- Downloaded the real bun-v1.4.2/bun-windows-aarch64.zip: SHA-256
  matches, it holds bun-windows-aarch64/bun.exe, a PE32+ Aarch64 binary.
Not tried: a real Windows ARM64 machine (the Windows box is x64), so
the plugin host starting on that bun is not verified.
2026-10-14 20:56:18 +08:00
yetone d1c485f7e9 agent: a model at max without xhigh tells Claude Code it has xhigh, so Ultracode shows on GLM, DeepSeek and Kimi in Claude Desktop
leesunrise2364 on Discord: Claude Desktop on magpie has no Ultracode effort,
which cc-switch had, and Ultracode is what turns on dynamic workflows.

Desktop 2.7032.0 shows Ultracode only when the model's effort options
include xhigh and Claude Code takes it. magpie lists a model with known
levels to Desktop as mythos-magpie-<n>, whose options include xhigh, and
tells Claude Code what each model can do in CLAUDE_CODE_MODEL_CAPABILITIES.
That value said only the levels magpie knows the model has. GLM-5.3
(low/high/max), DeepSeek V4 (high/max), Kimi K3 and the like reach max
without xhigh, so they were written as "effort,max_effort", and Claude Code
refuses Ultracode there: "Ultracode isn't available on <model>". cc-switch
names its models as real Claude ids, which Claude Code already knows have
xhigh.

A model Claude Code doesn't know whose levels reach max now also gets
xhigh_effort. The gateway already runs xhigh at max for such a model
(fitEffort: a tie goes up), so no level the model doesn't take is sent.
Claude models Claude Code knows are unchanged: Opus and Sonnet 4.6 still
get no xhigh, as Claude Code's own table has it. Models that top out at
high, or have no known levels, are unchanged too.

Tests: TestClaudeModelCapabilities gets v/glm (low/high/max) and v/top
(high/max), both now "effort,xhigh_effort,max_effort", while
v/claude-opus-4-6 stays "effort,max_effort". TestClaudeCapabilitiesSync's
w/b (low/max) now has xhigh_effort. TestFitEffort covers xhigh to
[high,max] going out as max. With the change turned off by hand, both
agent tests go red on exactly those values.

Run:
- Real Claude Code 2.1.299 in a sandbox HOME, gateway mode
  (CLAUDE_CODE_USE_GATEWAY=1), `-p '/effort ultracode'`, with the value
  magpie's own code wrote for v/glm-5.3 at low/high/max
  ("v/glm-5.3=effort,xhigh_effort,max_effort") printed "Ultracode on (this
  session only): dynamic workflows on every task". The old value
  "effort,max_effort" printed "Ultracode isn't available on v/glm-5.3".
  The same pair was run for Desktop's id mythos-magpie-7, with the same
  two results.
- gofmt -l is clean. go vet passes for darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test ./internal/agent passes when run alone (1110s at load ~250),
  and so do the caps and fitEffort tests.
- The full go test ./... ran twice at load average ~300.
  - The first run hit internal/provider's 10m timeout (#2051).
  - The second run (-timeout 30m) had these reds:
    - internal/agent and internal/gateway passed 30m as whole packages;
    - TestAgentGoneInTheRetryPause/last_one_left (#2175's sibling);
    - TestMainWindowCorners was killed at its deadline (#1936).
  - None of these is in code this commit touches.

Not tried: a live Claude Desktop. The packaged app won't start on a
sandbox user-data dir, and the live Desktop config is not to be touched.
So Desktop's effort menu showing Ultracode was not seen. It rests on
Desktop's renderer code (the Ultracode gate needs xhigh among the options
and the claude_code_workflows capability) and on the Claude Code probe
above.
2026-10-14 20:51:01 +08:00
yetone 22512cde53 provider, gateway: rest-cap off never rests a provider's keys after an unknown failure (Kismet Alan on Discord)
A relay or account pool fails now and then with errors that say nothing
of why (a 5xx, a dropped connection), and the next request often goes
through. Every such failure rested the key or account a minute, doubling
up to 10, and `rest-cap` could only move that cap (1 minute at least;
`off` read as `default`).

`magpie provider rest-cap <id> off` (provider.RestCapOff, restCap: -1 in
providers.json) now has a failure that says nothing of why (failOther)
rest nobody and not count toward the backoff: restAfterMarked returns a
Rest by "off" with no time left. What says why still rests as before: a
401 or 403, a model not served (restID), an account's window full, a
rate limit (magpie's own 30-minute cap; RestCapOr treats off as unset),
quota, credit, a restriction. `rest-cap <id> 30s` is turned away and names
1m and off (the first rest is a minute already). The Routing page tells a
try rested by "off" as not resting (one new string, zh/zh-TW/ja/de).
No "fail N times before switching" counter: a failed try already moves
the same request on to the next key or member, so a count would only
keep requests on a failing upstream longer.

Run:
- TestRestCapOff (gateway), TestRestCapCmd (cli), TestOwnRestCap: pass;
  each goes red with the change taken out by hand (the early return
  disabled: "#1 500: rests 59.99s by backoff"; restMinutes in place of
  restCapMinutes: "off: <nil> 0").
- routing-rest-off.test.cjs: 20/20 (chromium, webkit; 1100, 420; en zh
  zh-TW ja de); red 10/10 with the "off" case renamed.
  routing-wb-restricted 20/20. rest-try-now and routing-model-rest fail
  a varying few under load average 200-420 here, and fail more on
  origin/main 331c27703 run at the same time; neither reads "off".
- gofmt -l clean; go vet darwin (provider, gateway, cli, gui), GOOS=linux
  -tags nogui and GOOS=windows (provider, gateway, cli).
- go test ./... with pipefail, sandbox HOME: every package ok except
  agent, gateway and library, which hit the 10m timeout under load
  average ~200 (no test hung: each stack shows a different test seconds
  in). Rerun with a longer -timeout: library ok (603s), gateway ok
  (1572s) and agent ok (1457s).
Not tried: a real relay; the change is in the rest bookkeeping only.
2026-10-14 20:49:20 +08:00
yetone 5ccc05afe7 gateway: a plugin's non-streaming Responses request is relayed streamed and given back whole, so Grok's x_search runs (plugins#112, Watchyourback)
Plugin accounts only stream (Account.Stream), so a stream:false request
was translated: parsed to the IR and rebuilt. The Responses parser keeps
only function and web_search tools, so x_search never reached the Grok
plugin, and Grok answered "let me look that up" without searching. The
rendered reply also hardcoded "tools": [], dropped
usage.server_side_tool_usage_details, and dropped web_search's open_page
item. Watchyourback's capture of the plugin's fetch showed this (no tools
field, input wrapped into message[], store:false); CodeAlex52's code read
agreed.

Now a plugin's request on Responses that asked for one body is relayed
like a streamed one (gathers, used by serve's relay decision and by
passthrough):
- It is asked with stream:true, and the stream goes through the relay's
  usual tidies.
- The client gets the `response` of the stream's response.completed (or
  response.incomplete) as one application/json body. Its output is
  filled from response.output_item.done items, or else the streamed
  text, when that event's output is empty (gathered.go).
- A non-200 goes back as before.
- A whole reply goes back as it came.
- A stream that fails, or ends without its last event, is a 502, as a
  translated one is, never an empty 200.
- Usage is counted from the stream, as for a streamed relay.

Left as it was:
- Messages: its stream has no event holding the whole reply, so
  gathering it means assembling the message from deltas. That is not a
  simple sibling.
- Subscriptions magpie signs in to itself (ChatGPT backend, Qoder,
  MiMo...): their own code fits their requests, and their fakes end in a
  response.completed with no output. A first version that covered every
  stream-only account broke 7 Codex/ChatGPT-API tests, so it was
  narrowed to plugins.

TestGrokPluginGetsNamespacedTools now expects the namespace's freeform
custom tool to be left out (grokBody), as the built-in and the streamed
plugin already did. The translation had offered it as a function.

Tests (fake grok plugin through the plugin host):
- TestGrokPluginNonStreamKeepsHostedTools: upstream SSE with a
  custom_tool_call, tools [x_search] and server_side_tool_usage_details.
  Asserts the plugin was asked stream:true with tools [x_search]; the
  client gets application/json with the custom_tool_call, message,
  tools and details; usage is recorded at 50/7.
- TestGrokPluginNonStreamEndedShort: no response.completed gives 502.
- TestGatheredTextOnlyStream: deltas only.
Each was broken by hand and went red:
- the relay condition reverted: "the plugin was offered null";
- the missing-completed check removed: 200;
- the text fallback removed.

Run: gofmt -l; go vet ./internal/gateway on darwin, GOOS=linux -tags
nogui and GOOS=windows; go test ./internal/gateway -count=1 (ok, 1400s,
load ~200).
Not tried: a real Grok account or the real grok plugin; the reporter's
allowed_x_handles case.
2026-10-14 20:25:21 +08:00
yetone e1dcd1e1d7 tune: a compaction window advised never makes you wait longer on compactions, and says the wait (HirotaNagai on X)
Tuned for you advised the compaction window by tokens alone, so a smaller
window that compacts far more often could be advised however long each
compaction keeps the user waiting.

What changed
- sessions: a call now carries how long a compaction took (Call.Compact).
  Claude Code's compact_boundary line gives compactMetadata.durationMs,
  which goes on the first call after it that isn't an error. Codex compacts
  by a call of its own (the token_usage_record a compacted line names), and
  that call's own time is the compaction's. Older rollouts with no such
  record stay untimed. callCacheVersion is now calls-v13.
- tune: with 3 or more compactions timed for a model (minTimed), Facts.took
  is their median in seconds, and each window's Point.wait is its
  compactions x took. When compactions are timed, the advice never takes a
  window that compacts more often than the current one. Of the windows that
  don't, it takes the cheapest, and of those within 3% of that (sameCost)
  the one that compacts least. Tokens and seconds share no unit the files
  measure, so magpie doesn't trade one for the other at a guessed rate. The
  token-cheapest window is reported (cheapest, wait_cheapest) so the user
  can pick it. A model with fewer than 3 timed compactions is advised as
  before, with no wait shown.
- GUI (Usage > Context): when timed, the advice is labelled
  "Tokens + wait". The explanation says what a compaction took, the wait at
  the advice against the window now, and the cheaper window that would wait
  longer (if it saves 3% or more). The caveat says tokens and waiting only.
  The picker shows each window's wait, with "Fewest tokens" on the
  cheapest. Untimed rows are unchanged. The new strings are in zh, zh-TW,
  ja and de.
- docs/subsystems/agent-wiring.md describes the timing sources and the
  rule.

What was run
- go test -tags nogui ./internal/sessions ./internal/tune ./internal/gui
  ./internal/agent pass.
  - internal/agent ran before the rebase. It took 1416s under a load
    average of 120-300 and passed with -timeout 40m (the default 10m timed
    out mid-suite). Its Tune/Compact/CacheTTL tests pass on their own.
  - sessions, tune and gui ran again after rebasing on origin/main
    331c27703. fcd6f3519, the head this was pushed onto, touches none of
    these files.
  - internal/gui's TestProviderListReadsSettingsOnce failed 1 of 3 runs
    under load (7.0s against its 2s bar). It passed 6 of 6 on this branch
    and 9 of 9 on origin/main 4048ead7f, and it doesn't touch this code.
    Filed as #2185.
  - TestCallsClaudeCompactTook and TestCallsCodexCompactTook check the
    timings, also after Reset.
  - TestCompactTimedWaitsLeast checks the advice from 1M, 600K and 150K.
    With the timed rule disabled it fails ("advised 260000 makes 36
    compactions, more than 4 now").
  - TestCompactUntimedUnchanged checks that 2 timed compactions give the
    same advice as none, with no wait.
- GUI: context-tune, i18n-keys and context-window pass, 97/97 in Chromium
  and WebKit, in en/zh/zh-TW/ja/de at 360 and 1100 px. The new timed test
  fails against the old assets ("Fewest tokens" where "Tokens + wait" is
  expected).
- gofmt -l is clean. go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./... are clean.
- Real data, from copies of the owner's 4 Codex rollouts and 8 Claude
  transcripts in a sandbox HOME:
  - Compactions took 28-46s (opus-5-5), 85-139s (fable-5-1) and 52-121s
    (Codex gpt-5.6-sol).
  - gpt-5.6-sol keeps 230K. Before this change it was advised 70K: 44%
    fewer tokens, but about 3.5h of waiting against 30m.
  - opus-5 moves 200K to 190K, with 6% fewer tokens and the same wait.
  - Untimed models are unchanged.

Not tried: the live app with real accounts. The replay assumes a
compaction takes the same time at every window, since the files only time
compactions near the window the user ran with.
2026-10-14 20:03:53 +08:00
yetone 8ea4fec90a tui: w changes a custom provider's base URLs (luluxiu_1_4392 on Discord)
On Linux, with no window, the TUI had no way to change an API-key
provider's base URL: w only moved a local server's address or a preset
with an endpoint, and for a provider of the user's own it only pointed
to `magpie provider set <id> url=…`.

w on a provider with no preset now asks each base URL it has (Chat,
Responses, Anthropic, Gemini) in turn, prefilled with the one there now;
Enter alone keeps one. Only http(s) addresses with a host are taken, a
trailing / is dropped, and only the URLs that changed are saved, the
balance cache forgotten. A vendor preset is still asked at its own
address, and the footer already said "w address".

TestTUIAddsARemoteMagpieWithItsAddress asserted w asks nothing on the
custom provider "a"; its vendor case now uses a DeepSeek preset.

Run:
- TestTUIEditsACustomProvidersBaseURL: one URL changed and saved
  without the trailing slash, a bad URL refused, a two-URL provider with
  one kept and one changed, Enter Enter = unchanged. With the new branch
  disabled it fails ("w opened "" (mode 0)").
- go test -tags nogui ./internal/tui/ (the full run caught the old
  assertion above, now updated).
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: the TUI by hand in a real terminal on Linux.
2026-10-14 19:47:16 +08:00
yetone ef0c515eb0 provider: a sub2api or new-api account query left without its token asks the key's query instead (lx_78654 on Discord)
The editor's "Use …/api/v1/user/profile" sets the Balance URL to the
sub2api panel's account query, which only the login JWT can ask. Its
Remove button clears the token but not the URL, so the profile query was
then asked with the key, refused with 401, and the Usage card said
"Allowance unavailable" for good.

keyQueryOf now asks the same panel's key query when the Balance URL is
an account query (sub2api /api/v1/user/profile, new-api /api/user/self)
and no token is set: /v1/usage and /api/usage/token, with the key, their
own default field unless the user wrote another. The saved URL is left
as set, so pasting a token again asks the account query again. A
provider whose Headers carry its own Authorization or Cookie is asked as
set. It covers every reader: the Usage page and `magpie quota`
(KeyBalances), the editor's Check balance, routing's key windows
(sub2APIKeyLimits), and `magpie provider <id>`, whose "from" line now
says the query actually asked (BalanceQuery).

Run:
- TestAccountQueryWithoutTokenAsksTheKey (httptest sub2api + new-api):
  JWT, removed, JWT again; new-api without token; custom field kept;
  account query never asked with the key; own Authorization kept.
  With keyQueryOf a no-op it fails with the reporter's 401 card.
- Sandbox CLI (scratch HOME, fake sub2api on 127.0.0.1): old binary,
  after `provider set sub2 balance.token=`, `magpie quota` shows
  "401 Unauthorized…"; new binary shows "$7.25 left", from /v1/usage.
- go test -tags nogui ./internal/provider/ ./internal/cli/ ./internal/tui/,
  and internal/gateway's balance, allowance, quota and key-limit tests.
  The full `go test -tags nogui ./...` passed every other package;
  internal/gateway and internal/agent ran out of time (10m, then 40m)
  with the machine at a load average of ~300-370, the tests running at
  the deadline seconds old, so not a hang; neither run finished.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: a real sub2api or new-api account; the GUI not clicked
through (no asset changed, it reads the same KeyBalances).
2026-10-14 19:47:16 +08:00
yetone 0506f011d7 agent: a Codex reaching the gateway from another machine is never joined beside its ChatGPT sign-in (#2145, lazydao)
A Codex in a WSL distro under NAT (or with MAGPIE_ADDR pinned beyond
loopback) signed in to ChatGPT was joined beside its sign-in: it sent
its ChatGPT token to <gw>/backend-api/codex, and from another machine
the gateway takes a named key alone, so every request was a 401.

chatGPT() is now false when onAnotherMachine(at.gw()): such a Codex is
wired as one with no ChatGPT sign-in, magpie as its provider with gwKey()
(the LAN sharing key). One of its own models picked still goes straight
to OpenAI on its sign-in, as it does for a Codex with no sign-in.

Run: TestCodexBeyondLoopbackNotJoined (new; fails on the old code with
the joined config), go test -tags nogui -count=1 ./internal/agent (975s,
ok), gofmt -l, go vet darwin / GOOS=linux -tags nogui / GOOS=windows.
A first version forced magpie API under NAT and broke
TestWSLCodexProvider (own model refused); this one keeps that path.
Not tried: a real WSL distro under NAT with a ChatGPT-signed-in Codex.
A NAT Codex already joined is rewired on the next connect or model pick.
2026-10-14 18:44:45 +08:00
yetone a4d580fa24 gateway: a group skips Antigravity for the system prompt it just turned away (#2156)
Antigravity answers Claude Code's and the Agent SDK's system prompt (the
x-anthropic-billing-header line, "built on Anthropic's Claude Agent SDK")
with 429 "Resource has been exhausted" whatever quota is left (#666).
magpie already tells it as prompt_turned_away, rests nobody and hands it
on, but each Claude Desktop turn in a group waited on the same refusal
first (#2156: 429 in 1073ms, then cursor/composer-2.5 200).

Now, once Antigravity has turned such a request away (any of the three
paths that set holdWriter.turnedAway), for agForeseeing (6h) after, the
candidate loop skips an Antigravity candidate for a request that carries
the line, when someone is left after it (antigravityForeseen). The skip
goes in Fallback with the hint, sets `other` as the asked path does, and
changes no account state. The last one left is still asked and told the
400 with the hint. A request without the line (titles, Codex) still goes.
An old refusal foresees nothing, so a block Google lifts is noticed. The
lines are still neither rewritten nor hidden (#666). The stamp is per
Server, in memory.

TestAntigravityTurnedAwayRestsNobody's "asked first again" half now
checks it with a turn without the line, since one with it is foreseen.

Run:
- TestAntigravityTurnedAwayIsForeseen: fails with the skip turned off
  ("Antigravity was asked again for the prompt it just turned away"),
  passes with it; TestAntigravity* -count=3 green.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- go test -tags nogui ./... in a sandbox HOME at load average 140-220:
  everything green except 10m timeouts in agent, cli, gateway, library,
  provider and TestSetAnswersWhileDevinAndProvidersHang (#1375, noted
  there); those six packages rerun with -timeout 45m: all ok.
Not tried: the skip against the real Antigravity account (the refusal
itself was reproduced with a real account before: 400 with the line,
200 without), nor Windows/Claude Desktop as the reporter uses. No GUI
change.
2026-10-14 18:41:56 +08:00
yetone b75e21be31 agent: the Qoder app counts as Qoder again, found by the status file it writes to ~/.qoder (#2138, xiaozicoder)
xiaozicoder's Windows 11 has the Qoder app and the Qoder CN app
(Qoder-win-x64-user.exe, Qoder-CN-win-x64-user.exe from qoder.com and
qoder.cn) and no qodercli, and since v0.1.1220 magpie's Agents page lists
no Qoder at all. Qoder-win-x64-user.exe is the Qoder app (com.qoder.app,
qoder-app/releases/latest.yml at 0.4.7), not the Qoder IDE. Its app.asar
runs Qoder's CLI as its agent (qodercli 1.1.64's worker runtime, config dir
.qoder / .qoder-cn, QODER_CONFIG_DIR, with BYOK config management), so
~/.qoder/settings.json's providers.magpie reaches it. It writes the
enabledPlugins of its bundled qoder-context plugin to settings.json, which
alone stopped counting in the same change, so the app's Qoder was lost.

The app also writes .qoder-app-status.json (-canary-, -dev- for its other
channels) into ~/.qoder, or ~/.qoder-cn for the China product (the map is
in its app.asar; this Mac's Qoder.app 0.4.3 wrote one). Agent gets sign, one
more sign the agent is here for a dirShared folder, and Qoder's (both
builds) is that file. The JetBrains plugin's folder of #1495 has none, so it
still isn't Qoder.

Run: TestQoderAppIsQoder (both builds: plugin-only settings.json not
detected; each of the three status files detected; the status file with no
settings.json detected; a folder of that name not) red on the old code
(Qoder CN subtests fail), green now; TestQoderSettingsFromAnIDEPluginIsNotTheCLI
still green; go test ./internal/agent -count=1 -timeout 45m ok (1576s, the
machine at load ~350; a first run hit the default 10m package timeout mid
TestCodexAgentsV1WarnsWhenCodexOwnV2IsOn at 1s, not a hang). gofmt -l
clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean. A
nogui build's `magpie ls` in a sandbox HOME (PATH=/usr/bin:/bin) with
~/.qoder holding the plugin-only settings.json and a copy of this Mac's real
.qoder-app-status.json, and ~/.qoder-cn the same with a qoder-cn status,
lists Qoder and Qoder CN.
Not tried: the Qoder app on Windows itself, and whether its agent takes
magpie's provider from settings.json in practice (would need a live
~/.qoder changed).
2026-10-14 18:21:44 +08:00
yetone 1a33d22cca agent: an omp outside magpie's PATH (bun's ~/.bun/bin) is still found and asked its version on Linux and macOS, so its models offer max (whqtian on Discord)
whqtian: "ubuntu 24 版本的 omp 最大推理级别,还是xhigh,win版和 wsl版好了". omp
gets max in models.yml only when its version is known to be 16.4.0 or
later (ompTakesMax). The version comes from cliBin → binAt, which looks in
the user's tool folders (proc.FindTool: ~/.bun/bin, npm prefixes, every nvm
Node, mise, fnm ...) only on Windows. Elsewhere it uses the PATH magpie
was started with, and only the GUI and `daemon install` widen that. Under
`magpie serve`, web, tui, the CLI or a service, an omp installed by bun in
~/.bun/bin read as no version, so max was turned into xhigh. 31626c154
fixed only WSL's probe script, and Windows already had the fallback, which
is why only native Linux stayed on xhigh. cliBin now falls back to FindTool
on every system. proc.Version reads the npm package.json first, so it
doesn't need bun on PATH.

Verified:
- TestOmpVersionOffPath (a bun-layout omp 18.9.1 in a temp HOME, with
  PATH set to an empty dir) fails without the change (version "") and
  passes with it.
- Reproduced in Docker ubuntu:24.04 with real bun and omp 18.10.4, PATH
  without ~/.bun/bin, provider a/sol with efforts low..max, then
  `magpie omp a/sol`. The old linux/arm64 nogui build wrote efforts up to
  xhigh; the new one writes max. Control: the old build with ~/.bun/bin
  on PATH also wrote max.

Checks: gofmt -l is empty. go vet passes for darwin, GOOS=linux -tags
nogui and GOOS=windows. The GOOS=windows build passes. go test -tags nogui
-count=1 ./... was run under a sandbox HOME.
- The machine's load average was 200-360, so agent, gateway, library,
  plugin and provider ran out of the 10m timeout. Rerun with -timeout
  45m -p 2, all five pass.
- TestRefreshInvalidationCancelsStaleCall (plugin) and
  TestCopilotSecretToolUsername (provider) failed once under that load
  and passed on the rerun. Neither package depends on this change.

docs/subsystems/agent-wiring.md says where an off-PATH CLI is looked
for.

Not tried: the .deb GUI on a real Ubuntu desktop, or the reporter's exact
install.
2026-10-14 18:17:38 +08:00