Commit Graph
720 Commits
Author SHA1 Message Date
yetone ff2e6e2314 gateway: Cline's daily limit on one free model rests that model alone, until the time it names, not the whole key (#1398, wuasakura)
Cline answers a free model's daily cap with 429 "Daily free limit reached
on model X. Try again in 23h 59m". failure() reads "daily" as quota, so
the whole key rested for 15 minutes and every other free model on the
account was refused without being asked; the reporter saw the account
sent to the back of the list after one model's limit.

The limit is per model by Cline's own words, and Cline's client treats it
so (CLINE_FREE_MODEL_LIMIT_MARKER "free limit reached on model" and the
"try again in" reset parse in cline/cline sdk errors.ts). So for a Cline
provider (ClinePinnable: ClinePass, a cline.bot host, the Cline plugin)
that refusal now rests restID() (that model) for the time it names
(By "resets"). Another vendor's same words, and a Cline 429 that doesn't
name a model's limit (5-hour/weekly, "Rate limit exceeded"), rest the key
as before. No per-provider toggle: it would make account-wide 429s hit
the account once per model, the risk-control pattern the gateway avoids.
The Cline plugin's "usage limit reached: <body>" keeps the words (checked
with node on its failure() for all three body shapes), so moved users get
it too with no plugin change.

Run on 95e7c6bcc (origin/main) + this change:
- gofmt -l internal/gateway: empty. GOOS=darwin, linux and windows
  go vet -tags nogui ./internal/gateway/: ok. Before the rebase (at
  69d7ee33a) also go vet ./... for darwin, linux nogui and windows, and
  darwin, linux nogui and windows builds: ok.
- Full suite: SUITE_LINE
- internal/gateway package: left to the batch suite. At 69d7ee33a the
  first full run was green in every other package and red in gateway only
  through the leak below (fixed since); later runs died on a pruned
  shared cache, a 30m timeout under load ~100, and a kill for disk.
- go test -run 'TestCline' with -count=3 -shuffle=on: ok (at 69d7ee33a).
- Broken by hand: with routing.go at HEAD both new tests fail; the
  end-to-end one answers mimo with 429 "ClinePass: Daily free limit ...
  (out of its allowance: not asked again before ...)", the reporter's
  symptom. With the duration parse off: "rests 14m59s by quota, want
  23h59m by resets".
- The first full run caught the new test's rest leaking through
  restingUntil into TestClinePinsDeepSeek; the test now clears it on
  cleanup.
Not tried against a real Cline account (none here); the fixture is the
literal message from Cline's own tests.
2026-10-15 23:08:00 +08:00
yetone 92ac1c878e search: the web search MCP server has a web_fetch tool that reads a page by its URL (#2286, blackrion)
An agent that mounted magpie's web search over MCP (Cursor, Claude Desktop)
found pages it couldn't open: it has no fetch tool of its own. web_fetch
(url, max_chars, offset) reads one.

- The URL is the agent's, so the page is downloaded the way a caller's
  image is (publicClient): public addresses only, every resolved address
  checked and pinned, redirects (at most 5) checked the same, a request
  from this computer included; only http and https. 30 s and 5 MiB at most.
- HTML is decoded from its charset (x/net/html/charset; golang.org/x/net
  added) and given as Markdown: title, headings, lists, links made
  absolute, code and pre; script, style, hidden elements dropped. Other
  text as it is; anything else, or a 4xx/5xx, is the tool's error.
- 20000 characters by default (at most 100000) from offset, with the
  offset the rest starts at.
- Each call reserves the gateway key's limit, as a search does.
- The tool description is neutral (names neither magpie nor a vendor).
- GUI: the MCP row's text names both tools (en, zh, zh-TW, ja, de).
  Docs: gateway-routing's MCP section, README (en, zh-CN).

Run: go test -tags nogui ./internal/gateway -run 'WebFetch|SearchMCP';
GOOS=linux/windows go vet ./internal/gateway; gofmt -l clean. GUI:
search-mcp, i18n-keys, gui-ja, gui-de, gui-zh-tw 32/32 (chromium +
webkit). Broken by hand: webFetchClient = http.DefaultClient turns
TestWebFetchOnlyPublic red (the local test server was reached).
Tried by hand (a throwaway test, not committed) against go.dev/doc,
en.wikipedia.org/wiki/Magpie and http://github.com/yetone (redirected to
https; links come out by name, not the pinned address: the first try gave
https://216.239.34.21:443/..., fixed by taking each redirect's URL from
CheckRedirect), and an httpbin redirect to 127.0.0.1, refused.

Full suite: SUITE_LINE
2026-10-15 23:08:00 +08:00
yetone ec13d1162a search: the search APIs are dragged into the order they are asked in, and each switches off without losing its key (#2286, blackrion)
The search APIs were asked in the order they were added, and the only way
to keep one out of the chain (to try another alone, or rest one whose
credit is nearly spent) was to remove it and paste its key again later.

- provider: SearchAPI.Off; SearchAPIs() leaves an API switched off out, so
  neither a model's search nor the web_search MCP asks it. SwitchSearchAPI
  keeps key, URL and place; SetSearchAPI keeps Off. ArrangeSearchAPIs puts
  them in the vendors' order, refuses an unknown or twice-named vendor, and
  keeps one not named after them. RestoreSearchAPIs now puts a backup's
  APIs in the backup's order (one only here after them), so a restored
  order and Off come back as they were; sync already mirrors the list.
- GUI: each API's row and its keys' row are one unit, dragged off its
  buttons with dragRows (as routing's groups, #779) or moved with Alt+↑/↓,
  renumbered at once, focus kept, redrawn as saved if the order is
  refused. A lib-switch per row posts {vendor, on}; one off is dimmed and
  says Off; Search first with counts only APIs that are on. The row's
  buttons wrap instead of running past a 420px window.
- CLI: magpie search off|on <api>, move <api> <n>; the list says off.
- POST /api/settings/search-api takes {arrange} and {vendor, on}.
- Docs: gateway-routing "The search APIs' order, and one switched off",
  gui-shell, README (en, zh-CN).

Run: go test -tags nogui ./internal/provider ./internal/cli ./internal/gui
./internal/gateway (TestSearch*) ./internal/backup ./internal/davsync;
GOOS=linux/windows go vet of the touched packages; gofmt -l clean.
GUI: search-order.test.cjs 16/16 (chromium + webkit, en/zh/ja/de,
1100/420), and search-api, search-first, search-instead, search-keys,
search-mcp, searcher-pick, i18n-keys, gui-ja, gui-de, gui-zh-tw 100/100.
Broken by hand: SearchAPIs without the Off filter turns
TestSearchAPIOrderAndOff and TestSearchCLIOffAndMove red; the GUI
counting off APIs for Search first turns search-order red.
Full suite: SUITE_LINE
2026-10-15 23:08:00 +08:00
yetone 4ad929fd4d gateway: a native compaction a fallback seals is recorded to it, and its next turn goes there with the compaction, not answered 200 without it (#2271, JasonBuildAI)
With native compaction on for a provider, Codex's compaction_trigger
goes to any candidate whose wire carries it, a fallback included. The
compaction watcher recorded the writer only when the candidate that
answered had native compaction on itself (`if s.compactsNatively(...)
{ sealedBy = &c }`), so a fallback's seal went unrecorded. The next turn
carrying it then either went to another provider, which refused the
foreign item, and magpie dropped it (withoutCompaction, guarded only by
`checkpoint == nil`) and answered 200 without the compacted history; or
went to the fallback translated, since keepsCompaction kept a sealed
compaction only for a provider set to compact natively, and the
translation left the item out.

Fix:
- the writer is recorded whoever answered: the watcher exists only when
  the trigger was kept, so whoever answered sealed it;
- keepsCompaction also relays a sealed compaction to the provider
  recorded as its writer (checkpointOf), whatever its own setting;
- checkpointError no longer says "native compaction is on for <writer>",
  which isn't so for a fallback;
- docs/subsystems/gateway-routing.md says so.

Test: TestNativeCompactionFallbackSealStaysWithItsWriter (fa native,
falls back to fb, native off, which seals; a third provider). Broken by
hand, each part fails it:
- recording only native writers: the other provider answers 200 with
  the seal dropped;
- keepsCompaction ignoring the record: the writer's next turn (Codex's
  shape, offering web_search) goes translated without the seal;
- the old wording: the error says native compaction is on.

Run on the rebased head (origin/main plus #2274 and this):
go test ./internal/gateway/ -count=1, gofmt -l, go vet -tags nogui for
GOOS=darwin/linux/windows ./internal/gateway: see the ready note; all
green before this was handed over.
Full suite: SUITE_LINE
2026-10-15 23:08:00 +08:00
yetone 51d5b8d0b2 gateway: a Codex compaction's summary cut short or 429'd halfway fails over and rests the account, and one that keeps failing is held, not asked every 18s (#2274, huangzuomin)
Codex on antigravity/gemini-3.8-flash with context_management's
experimental mode asked magpie for 1169 summaries in 6 hours (8.44M
billed tokens), ending in 502 "compaction: the model wrote no summary".

Cause, in three parts:
- serve's holdWriter let the summary's stream through at its first
  words, so Antigravity cutting it short ("the reply ended before it was
  complete"), or a 429 "Individual quota reached" after some of it,
  reached codexCompact as a 200 with an error: no failover, no rest.
- codexCompact took a summary that ended `incomplete`, or a body with
  no response at all, as one.
- Codex's async compaction (codex-rs async_compaction) starts a
  background compaction at every step while the conversation is over its
  threshold and drops a failed one silently, so the history never
  shrank and each step paid for the whole conversation again.

Fix:
- codexCompact marks its request askWhole; serve then holds the summary
  stream to its end (holdWriter.wantWhole). A cut, an error event or
  `response.incomplete` anywhere in it fails over to the next candidate
  like a failure before content and rests the account as that would; a
  model that reached its output limit rests nobody.
- With nobody left, the cut/incomplete summary is a 502 saying so, never
  the words before the cut.
- compactFails (codex_compact_guard.go): after 3 failed summaries in a
  row of one conversation (prompt_cache_key) on one model, each within
  5 minutes, the next is answered 400 at once (Codex doesn't retry a
  400) naming the last failure, until 5 minutes pass. A summary clears
  it; 401/403 aren't counted. Decision: a 400 is the only answer Codex's
  remote compaction stops on, and a per-conversation hold costs a user
  whose model recovers at most 5 minutes, while the loop cost tokens.
- docs/subsystems/gateway-routing.md says so.

Run (worktree at origin/main 69d7ee33a plus this):
- go test ./internal/gateway/ -count=1: ok (1054s).
- TestCodexCompactCutSummaryFailsOver (Responses cut / quota halfway /
  incomplete, Chat quota halfway), TestCodexCompactCutSummaryIsNoSummary,
  TestCodexCompactKeepsFailingIsHeld: fake upstreams, no network.
- Broken by hand: hw.wantWhole = false fails every FailsOver subtest
  (the spare is never asked, the cut text comes back); dropping the
  incomplete check fails IsNoSummary/incomplete; held() always false
  fails KeepsFailing (the model asked a 4th time).
- gofmt -l: clean; go vet -tags nogui GOOS=darwin/linux/windows
  ./internal/gateway: clean (on the rebased head with #2271).
Full suite: SUITE_LINE
Not tried against Antigravity itself.
2026-10-15 23:08:00 +08:00
yetone 8a1b5916f3 sessions, usage, gui: one read of every call at a time, the Codex effort built once and kept, and the Sessions page asks for an overview once, so the app no longer grows to 85 GB (#2278)
On a long history (the reporter's: 68k call files in calls-v15, 415 MB;
42 MB usage.jsonl; 75k calls in 7 days), the app's main process grew to
85 GB in about 90 minutes and the gateway froze. `magpie serve` alone held
83-153 MB for 20 minutes (the reporter's follow-up), so the growth is in
the app's Sessions path:
/api/sessions/overview -> usage.CodexModelEffort -> LedgerOfAt ->
sessions.Calls(all history).

Why it grew:
- CodexModelEffort's cache key changes on every gateway write, and it
  never kept an answer when usage.jsonl was missing or grew during the
  build. So every /api/sessions, overview, /one and /manage ask with a Codex
  session rebuilt the all-history ledger, gob-decoding every shard (only
  64 stay in memory).
- Nothing joined concurrent asks.
- The page's 15s reload asked for an overview again while the last one
  was still under way, so slow asks piled up.

What changes:
- sessions.Calls and the new AgentCalls go through sharedCalls. An ask
  while the same read is under way waits for it and gets a copy, and
  reads run one at a time.
- AgentCalls(since, "codex") reads Codex's files only. pruneCalls still
  sees every file.
- CodexModelEffort is built from Codex's calls plus the gateway's records.
  Only those name a Codex actor, and TestCodexModelEffortIsTheWholeLedgers
  checks the answer equals the whole ledger's on a mixed Claude + Codex +
  gateway fixture.
  - One build per period at a time. An ask during a build gets the last
    answer for the same home (root), or waits if there is none.
  - The answer is kept when usage.jsonl is missing or grows during the
    build.
  - At most 8 periods are kept.
- page.js: sessOverview shares one promise per query, so the filter's ask
  and the 15s reload's ask for the same overview send one request.
- docs/subsystems/gateway-sessions.md says this.

Reproduced (temporary test, not committed): a sandbox HOME with 62k
Claude Code session files, 5.9k Codex rollouts and 100k gateway records.
Sessions routes in-process, 4 rounds x 6 concurrent asks
(overview?days=0 and /api/sessions), a usage record appended every 300ms:
  before (2b0037f41): 7m39s total, slowest ask 2m01s; 66264 MB allocated
    (2761 MB per ask); peak heap in use 4620 MB, peak Go sys 6274 MB,
    peak RSS 5325 MB
  after:              20.4s total, slowest ask 7.1s; 20728 MB allocated
    (863 MB per ask); peak heap in use 1168 MB, peak Go sys 1487 MB,
    peak RSS 1415 MB
Cold warm-up (index plus every shard) was 21m before and 18.5s after on the
same home. The after run reused the shards on disk, so it is not a
comparable number.

Tests, each red on the old code:
- TestConcurrentCallsShareOneRead: 8 reads, not 1. It also goes red when
  the join is broken by hand.
- TestCodexModelEffortConcurrentAsksBuildOnce: 8 builds.
- TestCodexModelEffortAnswersLastWhileBuilding: 3 builds.
- TestCodexModelEffortKeptWithoutLogAndAcrossAWrite: 2 builds.
- sessions-overview-once.test.cjs: 2 overview requests, not 1. That is
  chromium and webkit; en, zh, zh-TW and ja at 1100/900px, de at 420px.
  It was red with the old page.js served.
TestAgentCallsReadsOneAgent and TestCodexModelEffortIsTheWholeLedgers pass
on both versions.

Run:
- gofmt -l: clean.
- go vet -tags nogui for darwin, linux and windows: sessions, usage,
  gui. Before that, the whole tree for linux and windows.
- go test -race on ./internal/sessions/ and ./internal/usage/.
- go test of internal/sessions, internal/usage and internal/gui at the
  rebased head (on 95e7c6bcc): green. gui was red once, in a run whose
  output was cut, at load ~100; it was green on two reruns.
- Full suite: SUITE_LINE
- GUI: the 13 files that ask for sessions/overview, at the rebased head,
  in chromium and webkit: 198/198. Before the rebase, those plus every
  usage*.test.cjs,
  in chromium and webkit: 749 pass. The 24 failures are usage-fold
  (#2163) and usage-agents-hide (#2276). The same 24 fail with the old
  page.js on 2b0037f41, and both are filed.

Not tried: the real app on the reporter's data; an hour-long run.
2026-10-15 23:08:00 +08:00
yetone d4244d5c19 gateway: a thinking budget the provider's Extra body adds is sent to Opus 5.5 as adaptive thinking, as an agent's is
forwardOnce turned a thinking budget into adaptive thinking for a Claude
that takes no budget (adaptiveThinking), then merged the provider's Extra
body (#1604). A budget written there, {"thinking":{"type":"enabled",
"budget_tokens":2048}}, went to claude-opus-5-5 as written, and Anthropic
answers that with 400. When the Extra body changed an Anthropic body, it
is fitted again (adaptiveThinking, then withoutRefusedShapes for the
display), so it goes as the agent's budget does. Found while looking into
(rc.44), not this.

TestExtraBodyBudgetFittedToAdaptiveModel: a fake that refuses
thinking.type enabled with Anthropic's words, Extra body with a budget,
a client sending no thinking. Broken by hand: with gateway.go reverted it
fails with that 400; with the fix, one request, thinking
{"display":"summarized","type":"adaptive"} and an effort.

Run at this head (rebased on origin/main 95e7c6bcc): gofmt -l clean;
go vet -tags nogui ./internal/gateway for darwin, linux and windows clean;
go test -count=1 ./internal/gateway ok (sandbox HOME). No real Claude API
call was made.
Full suite: SUITE_LINE
2026-10-15 23:08:00 +08:00
yetone 5ca37ef86b tray: Settings › Menu bar cost off shows magpie's today and 7-day totals as tokens alone, in the menu bar and its tooltip (BussanQ on Discord)
BussanQ asked for the menu bar's today card with the token count only.
A new Settings › Usage › Menu bar row, "Menu bar cost" (On by default,
segs, every OS, shown with or without cards since the no-card tooltip
says the cost too), saves settings.TrayNoCost. Off, trayMoney drops a
total's cost and its count of unpriced calls before trayTotalCard and
trayIdleTip see it, so the macOS cells and title, and the tooltip on
macOS, Windows and Linux, say the tokens and requests alone. A relay's
or subscription's balance card is money itself and stays. TrayNoCost is
per computer (KeepOwn, beside the other Tray* fields), and a change
redraws the tray (api.go). Translated in zh, zh-TW, ja and de.

Run:
- TestTrayNoCost (internal/gui): broken by hand (trayMoney a no-op) it
  fails with label "Σ47M · $128 | Σ6.3M · $3.40+", want tokens alone,
  plus the tooltip and idle tooltip.
- TestSync (internal/davsync) now sets TrayNoCost on one computer; with
  TrayNoCost left out of KeepOwn it fails "b's menu bar: … TrayNoCost:true".
- tray-cost.test.cjs: Chromium + WebKit, en/zh/zh-TW/ja/de, widths 1100
  and 420, Mac/Windows/Linux and no cards: 22/22 pass. With trayNoCost
  dropped from the prefs it fails "a save of another setting keeps the
  cost off". Also green: i18n-keys, tray-bird, tray-logos, tray-totals,
  tray-usages, tray-usage-redraw, quota-pace, tray-inuse.
- gofmt -l clean; go vet ./... and -tags nogui for GOOS=darwin, linux,
  windows clean.
- go test ./internal/tune ./internal/gui ./internal/settings ./internal/davsync
  green at this head, rebased on origin/main 95e7c6bcc.

Full suite: SUITE_LINE
2026-10-15 23:08:00 +08:00
yetone 035c259a6d tune: Codex's compaction windows run to the model's own window or 1M, not the largest prompt seen (zhemu on Discord)
zhemu: Codex Desktop on a CLIProxyAPI provider's 1M GPT model, Settings ›
Long conversations at 750K; Usage › Context › "Other window…" stopped at
~412K. tuneOf took Codex's window as max(272K, the largest prompt seen),
so tune.Compact capped both the offered windows and the user's own value
at the largest prompt (~412K), whatever the model's window or the
user's setting.

Now codexWindow reads the window from magpie's catalog: a model with a
known window (typed or catalog) is offered up to it, and "now" is the
window magpie tells Codex (Settings' long-conversation value or the
model's own compaction, as codexcat writes it), 750K for zhemu. A model
whose window magpie doesn't know caps nothing short of 1M, and a mix
with one unknown is unknown. Codex's own models keep 272K or the
largest prompt. Claude Code is unchanged: only Claude models get the
advice, and other vendors' models use magpie's own window.

Run:
- TestTuneWindowsAreTheUsers (internal/gui), a custom provider with an
  unknown window, 1M and 400K, on Codex and Claude Code. Old code:
  "Codex on cpa/gpt-cpa-open: windows offered up to 410000; want
  1000000" (and for 1m). Broken by hand: told dropped → "now 0, want
  750000"; window=0 for unknown dropped → the mixed case fails.
- TestCompactUnknownWindowCapsNothing (internal/tune): old code "no advice".
- gofmt -l clean; go vet ./... and -tags nogui for GOOS=darwin, linux,
  windows clean.
- context-tune.test.cjs (Chromium + WebKit): 70/70 pass.
- go test ./internal/tune ./internal/gui ./internal/settings ./internal/davsync
  green at this head, rebased on origin/main 95e7c6bcc.

Full suite: SUITE_LINE
2026-10-15 23:08:00 +08:00
yetoneandNorethSea b00da3860c usage: a past cycle shows its own whole-window estimate, and a reset ends a dry run (#2009, #2010, NorethSea)
Ported from NorethSea's fork (abed2e224) and re-derived on main.

What it does:
- A known reset ends a dry run (a stretch where a window read 0% left), even
  when the next poll sees the refill later. A stale dry reading taken after
  its own reset no longer extends the run. Calls from the reset on are not
  treated as "maybe paid from credits".
- A refill observed later than reset minus span
  (QuotaPoint.StartsCycleAfter, the boundaries history sampling keeps)
  starts what is reckoned. Calls before a fixed-deadline refill stay in the
  cycle before it. A first reading is not a reset.
- Picking a past cycle in Usage > Allowances > Trends > Cycle asks
  GET /api/usage/quotas/history/holds once per selection
  (quotaCycleHoldsOf). The route asks no vendor. HistoricalWindowHolds
  reckons each window at its own last reading in the cycle, using the
  ledger and readings from before that reading. "Loading..." shows while it
  is pending. An answer for a cycle no longer picked is dropped. The card's
  Refresh, or an asked read, reckons again. The estimate's tooltip names the
  window's start and the reading's time.

Changed from the fork:
- After a run closed at its reset, the fork reset lastLeft to zero. A
  window that ran dry again before its next reset then opened a run from
  time zero, which hid every window's estimate, the weekly one included.
  The next run now starts no earlier than that reset.
  TestWindowHoldsDryAgainAfterReset covers it (red with the fork's line).
- The fork narrowed the live card's Span to the observed refill. Span also
  feeds provider.WithWindowStarts, so the window's Pace would have moved.
  withSpansOf puts the card's spans back after reckoning. A span assertion
  in TestWindowHoldsUsesObservedRefillStart covers it (red without it).
- The fork's historical snapshot dropped the card's Balance. That slipped
  past the gate a live card has (holdsBounds), so a card that tells a
  balance got past-cycle estimates. Balance is now kept. Covered in
  TestHistoricalWindowHoldsUsesEachWindowsOwnReading (red without it). The
  fork's fixture had a Codex card with a Balance, which no Codex card has.
- Main has since added HoldsWhy (#2045). The fork's own "Whole: not enough
  reliable data" line and its .quota-holds-unknown CSS are left out. A past
  cycle uses main's holdsUnknownLine and its reasons, as a live card does.
  A window with neither an estimate nor a reason shows nothing, where the
  fork showed its unknown line.
- withRecordedWindowStarts is ported to main's holdsBounds(start, end, why).
- quota-refresh-order.test.cjs's VM harness now stubs quotaCycleHolds,
  which loadQuotas and quotaRefresh clear.

Left out: nothing else from the fork. Past prices aren't kept, so a past
cycle's cost uses today's API list prices (documented). Credits can't be
attributed per call, so none is attempted (documented).

What was run:
- gofmt -l: clean. go vet -tags nogui ./... for GOOS darwin, linux and windows.
- go test -tags nogui ./internal/usage ./internal/gui ./internal/provider:
  ok.
- Each of the three fixes above was reverted by hand, and its test went red.
- GUI, Chromium and WebKit:
  - quota-curve: 30/30. Also run at 1100 and 420 wide: 60/60 (all five
    languages).
  - Also: quota-*, i18n-keys, gui-de/ja/zh-tw, usage-card-refresh,
    usage-refresh*, usage-stale-answer, usage-remote-cards,
    usage-accounts*, usage-quota-head, usage-pack and usage-alert.
  - Reds: quota-count-wrap and quota-name-translated are red in WebKit,
    the same as on origin/main 707fbb249. Filed as #2228.
  - The GUI break-check (main's !sub.history gate put back) turns the new
    quota-curve test red.
- Full suite: SUITE_LINE

Co-authored-by: NorethSea <963979204@qq.com>
2026-10-15 23:08:00 +08:00
yetone 758a4084ee sync: LAN sharing stays as each computer has it, so turning it on at home no longer turns it on at work (Lullaby on Discord)
Settings.KeepOwn now keeps LAN (sharing on the local network), AllowIPs
(the addresses let in to it) and SessionTerminal (the Mac app a session
resumes in) from this computer whenever a sync, a join, a Restore, an Undo
or a backup file brings settings in. davsync's hashes blanks the same
fields, so flipping sharing is no change to push. A backup restored onto a
new computer leaves sharing off there: it opens the gateway to the
network, so it is turned on by hand, like the port and proxy.

The default sharing key is not per computer. It lives in the gateway-key
store, which rides the settings part with LANKey and LANKeyID, so every
computer holds the same key, and a second computer turning sharing on
takes up that key instead of making another one (configureLAN finds it by
LANKeyID or k.LAN).

Audit of Settings, what stays synced and why:
- already own: Window/WindowMaximised, UIFont/CodeFont, Proxy, Port,
  Dock/DockWindow, Lightweight, KeepAwake/KeepAwakeDisplay, Tray*,
  GatewayMode, NoWSLAgents, QuotaReads, NoAccountDiscovery,
  GatewayConversations.
- made own now: LAN, AllowIPs (the address list belongs to the network
  this computer is on), SessionTerminal (another Mac may not have the
  app).
- not in Settings: launch at login (internal/autostart, the OS's own
  setting) and the listen address (MAGPIE_ADDR, plus Port). Remote access
  through Tailscale etc. goes through those.
- still synced: CORSOrigins (pages and extensions the user uses, and each
  still needs a gateway key), OTel, Redact*, update settings
  (NoAutoUpdate, AutoRestart, UpdateMirror, ChinaMirror), alerts, model
  and agent choices, Theme/Lang/TextSize. These are the user's
  preferences, not facts about one machine.

Older magpie versions still take LAN from the bundle. Only new clients
ignore it.

Docs: sync-backup.md gets a "What stays on each computer" section, and
gateway-routing.md says AllowIPs is per computer. README and site docs
don't list what sync carries, and no GUI string does either, so they are
unchanged.

Run, on origin/main 95e7c6bcc + this change:
- gofmt -l internal/settings internal/davsync: nothing printed
- GOOS=darwin/linux/windows go vet -tags nogui on settings, davsync,
  backup, access, gui: exit 0 each
- go test -tags nogui settings, davsync, backup, access, gui: all ok
- before the rebase, on 226222118: go vet ./..., GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux
  go build -tags nogui, GOOS=windows go build: all ok
Full suite: SUITE_LINE

Broken by hand: with the three KeepOwn lines removed,
TestLANSharingStaysOnItsComputer fails ("work after joining: sharing on
the local network is true, want false", the same after a restore, "turning
sharing off at home pushed 1 times", "home after work turned sharing on:
... true, want false", plus the AllowIPs and SessionTerminal ones), and
TestLANSharingIsNoChange fails ("sharing on the local network changes the
settings part's hash"). With LAN alone dropped from KeepOwn, the LAN
checks and the hash test fail and the others pass. Restoring the change
turns both green.

Not tried: two real computers syncing through a real WebDAV, S3 or GitHub
folder. The test uses two sandbox homes and a fake WebDAV server.
2026-10-15 23:08:00 +08:00
yetone ef49011448 gateway: Stays: Auto keeps a conversation on Claude's 1-hour cache for the hour, not 5 minutes (#2302, j3r0lin)
affine called a conversation "cold" once its last reply was more than
cacheCold (5 minutes) ago, whatever the reply said of its cache. A Claude
reply that wrote with cache_control ttl "1h" (cache_creation's
ephemeral_1h_input_tokens, already parsed into Usage.CacheWrite1h; Claude
Code asks for it on a subscription) keeps that prefix for an hour, so the
next turn 5-60 minutes on lost its priority and could move to another
account or model that has none of the cache.

answered now keeps an hourCache on the stick: the tokens read plus the
1-hour write (Anthropic puts 1-hour breakpoints before any 5-minute one,
so what was read lies inside that prefix), and when. A later reply on the
same account and model that reads at least all of it starts the hour
again; one that reads less (moved, compacted) drops it. affine's "cold"
now needs both past 5 minutes and no warm hourCache (>= cacheWorth tokens,
within cacheHour). It is saved in affinity.json (cacheHour, cacheHourAt;
absent in older files, read as none). Sibling: keepsEffort, which lets a
group's effort drop only once the cache is lost, used the same 5 minutes;
turnRule now carries the same hourCache from ruleAnswered.

Vendors that report no 1-hour write never have an hourCache, so their
behaviour is unchanged; resting, spent, strict and the other reasons are
judged before this as before.

Tests: TestAffinityKeepsAnHourCachePastFiveMinutes (real server stack, an
Anthropic upstream reporting cache_creation: 1h write at 20 min -> cache,
at 59 min across a restart -> cache, at 61 min -> cold, 5-minute write at
6 min -> cold, a 1h write under cacheWorth -> cold), TestHourCacheAfter,
and two TestKeepsEffort cases. With affine's and keepsEffort's old
conditions put back, both fail ("an hour's write, 20 minutes on: ...
Why:cold, want cache"; "an hour's cache: warm at 20 minutes: false, want
true"); with the file's cacheHour left unread, the restart case fails.
Real data: the owner's usage.jsonl has 166 Claude subscription replies
with cache_write_1h > 0, e.g. cache_read 57901 + cache_write_1h 336, the
shape hourCache takes. Not tried live past 5 minutes against Anthropic.

Ran: gofmt -l, go vet -tags nogui for darwin/linux/windows on
internal/gateway, go test -tags nogui ./internal/gateway (full package).
Full suite: SUITE_LINE
2026-10-15 23:07:59 +08:00
yetone 3c921835d0 library: RTK switches on for OpenCode 2 with rtk 0.52 or newer, not "Not for OpenCode 2" (#2295, witt-bit)
The RTK tab blocked OpenCode 2 whatever rtk was installed: rtk's
OpenCode plugin used to be written for OpenCode 1 only, which OpenCode 2
refuses ("Plugin must export a default definition with an id and an
effect or setup function", rtk-ai/rtk#4311). rtk-ai/rtk#4187 (merged
10-12, first released in rtk 0.52.0, also in 1.0.0 and 1.0.1, the
reporter's) writes one default object with OpenCode 2's id and setup()
beside OpenCode 1's server(). Checked with gh: 0.52.0's and 1.0.1's
hooks/opencode/rtk.ts are byte-identical, 0.51.0's is the old named
export.

- openCodeBlocked: with OpenCode 2, blocked only when rtk is older than
  0.52 or doesn't say its version; the reason now says to update RTK.
  OpenCode 1 is unchanged with any rtk.
- openCodeHas: under OpenCode 2, an old plugin (no setup()) left from
  before an rtk update counts as off once the rtk here is 0.52+, so
  switching it on runs rtk init, which writes the new one over it. With
  an older rtk it still counts as on, so it can be switched off.
- GUI: the OpenCode row's tag is "Update RTK" with OpenCode 2 reasons
  (on: refuses this plugin, update or switch off; off: needs 0.52), in
  en, zh, zh-TW, ja, de; the "Not for OpenCode 2" strings are gone.
- docs/subsystems/library.md says the same.

What was run:
- Real binaries in a sandbox HOME (throwaway test, not committed):
  rtk 1.0.1 and 0.51.0 (aarch64-apple-darwin release tarballs) with the
  real OpenCode 2.0.25 on PATH. rtk 1.0.1: row not blocked, SetRTK on
  wrote an 8425-byte plugin with setup(), off took it out. rtk 0.51.0:
  blocked "OpenCode 2.0.25 needs RTK 0.52 or newer, and this RTK is
  0.51.0 …", SetRTK on refused, nothing written.
- Real OpenCode 2.0.25 in a sandbox HOME (its own service, stopped
  after): rtk 1.0.1's plugin logs "loading plugin" with no error;
  0.51.0's logs "failed to load plugin … Plugin must export a default
  definition with an id and an effect or setup function".
- TestRTKOpenCode2 rewritten (fake rtk writes each version's real
  plugin shape). Broken by hand three ways, each a FAIL: old rtk.go
  (blocked: "RTK doesn't support OpenCode 2 yet …"), stale-plugin rule
  dropped ("OpenCode 1's plugin under OpenCode 2 is listed as on"), gate
  at 1.0 ("rtk 0.52.0 blocked for OpenCode 2").
- New GUI test library-rtk-opencode2.test.cjs: every language, 1100
  and 420, on and off rows, Chromium and WebKit 21/21 each; red on the
  old client.js/i18n.js. gui-de, gui-ja, gui-zh-tw, i18n-keys and all
  library-*.test.cjs: 286/286 in Chromium and in WebKit.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags
  nogui ./internal/library; go test -tags nogui ./internal/library
  under a temp HOME with pinned caches, on the rebased head.
Full suite: SUITE_LINE
2026-10-15 23:07:59 +08:00
yetone e679f1106f cli: magpie plugin lists a plugin's tools and its page
The list said a gateway module's hooks, routings and onUsage, but nothing
for a plugin that gives tools (P4b) or a page (P4c), so such a plugin had
nothing under its row. Found in the combined P4 real-use run.

Tools are listed by their names on the plugin tools MCP server
(gateway.ToolNames), a page by its title and what it may read.

Run: TestPluginListSaysToolsAndPage, and internal/cli whole (ok). gofmt
clean; vet darwin, linux -tags nogui and windows = 0. Broken by hand:
without the tools line the test goes red ("aren't listed"), and without
the page line too ("isn't listed"). A `!e.Off` guard on the tools line
didn't change the test, since the host loads no plugin that is off, so
it was dropped.
2026-10-15 22:36:59 +08:00
yetone 3f913b3de6 plugins: a JS gateway plugin serves routings (strategies) and watches usage rows (onUsage); plugins/middleware is "JS gateway plugins" (P4)
A plugin's gateway module (magpie.middleware, or its alias magpie.gateway,
or a *.gateway.js file) may now export, besides onRequest/onEvent/onResponse:

- strategies: {name: (pool, seats, options) => order}. Each is a routing
  "<short name>/<name>", registered with routes.Register while the plugin is
  on and loaded and removed when it goes off or reloads. Seats are
  routes.Seat in camelCase JSON. 20ms each; it fails open: a throw, a timeout
  or a result that isn't an order of the seats means the listed order. The
  failure is counted and logged, rate-limited. A file's name is made into a
  routing-safe prefix.
- onUsage(row, options): gets an allow-listed usage row (no bodies, prompts,
  error text, sessions or request ids). The rows come from a bounded queue
  (1024) with one worker, off the request path; a full queue drops the row
  and counts it, and a request never waits. 250ms each.

plugins/middleware is renamed "JS gateway plugins", with a new Sub
(en/zh/zh-TW/ja/de). It registers usage.Observe(middleware.Points()). Off,
no JS hook, strategy or onUsage runs. InUse is unchanged.

providers.json keeps a routing of the form <plugin>/<name> as saved
(provider.PluginRouting) in provider and group Save, whether or not a
plugin serves it now. Before this, `group set g routing=pick/last`
stored nothing.

GUI: the settings state carries jsRoutings. Provider and group routing
pickers offer the served ones, marked data-feature=middleware. A saved
routing that no plugin serves now shows as it is, with a hint. The
Plugins page's line shows routings, how often they were asked, onUsage
rows and dropped rows. The CLI accepts `group set <id> routing=<plugin>/<name>`.
`magpie plugin` lists a module's routings and onUsage; a strategy-only
module had printed nothing after "gateway middleware".

Docs: docs/subsystems/gateway-middleware.md (Routings and usage rows,
limits, verification) and plugin-runtime.md (P4: community plugins at
every point). site/public/docs plugins.html in en, zh and ja has an
example: internal/middleware/testdata/spread.gateway.js, which
TestDocsExample runs.

What was run (worktree on 4df1ba0c6, -p 2):
- gofmt -l: clean. go vet on internal/{middleware,cli,gui,plugin,provider}
  and plugins/...: darwin, GOOS=linux -tags nogui, GOOS=windows; all
  clean, run after the last Go change.
- go test, after the last Go change: internal/middleware ok,
  plugins/middleware ok, internal/provider ok (210s), internal/cli ok
  (203s). Earlier in the work: internal/plugin ok (385s), internal/pluginrt
  ok, internal/gui (Go) ok (320s), and plugins/... ok. The first
  plugins/... run printed a bare FAIL line that `tail` cut off before its
  cause showed. The rerun was all ok; the cause is unknown.
- GUI, both engines (routing-*, group-*, builtins, i18n-keys, gui-de/ja/zh-tw,
  plugin-middleware): 1220 tests, 1204 pass, 16 fail.
  - routing-manual (4): mine. A group's own "manual" was offered a second
    time as a routing no plugin serves. Fixed in client.js withJS. The
    coordinator is rerunning routing-manual, keys-fold, group-fold,
    intent-entry and routing-js alone in both engines, so that rerun is
    not recorded here.
  - routing-model-rest: red alone too, and red on untouched 4df1ba0c6
    (3/20). It is #2115; I commented there with the webkit cases.
  - group-member-weight webkit de 420 is #2387.
  - group-from-model-add webkit zh: it passes alone 2 of 2. Under load it
    waits a fixed 2s for the save post. Filed as #2388.
  - routing-keys-fold (webkit zh/ja/de), routing-group-fold (goto timeout)
    and routing-intent-entry (browser launch timeout 180s) are load
    timeouts. The coordinator is rerunning them alone.
- routing-js.test.cjs (new) passed in chromium en and zh, before the full run.

Broken by hand, each test went red, then restored:
- the permutation check: TestStrategyFailsOpen;
- the queue's non-blocking send: TestOnUsageNeverBlocks ("Ledger waited
  2.04s");
- the allow-list: TestUsageRowAllowList;
- unregister on off: TestStrategiesServedWhileOn and
  TestStrategiesStopWithServe;
- the CLI pattern: TestParseRoutingStays;
- Observe in plugins/middleware: TestOnServesStrategies;
- PluginRouting in provider.go and in group.go: TestPluginRoutingKept;
- the prefix sanitizing: TestRoutingFromFileName;
- the CLI list line: TestPluginListSaysMiddleware;
- the GUI's data-feature mark and its unserved-saved entry: routing-js.

Real use: a sandbox HOME, the gateway served on 127.0.0.1:3682 by a
-tags nogui build, a fake vendor on 3681, and providers fa (key ka) and
fb (key kb) in group g. pick.gateway.js has strategy last (reverse) and an
onUsage that logs.
- `group set g routing=pick/last` stored it.
- A request to group/g reached the vendor with Bearer kb, and the
  "usage-row fb m in=5 keys=17" line was logged.
- `plugin off pick.gateway.js`: Bearer ka (listed order), no onUsage,
  routing still pick/last.
- `plugin on`: Bearer kb and onUsage again.
- `plugin builtin off middleware` says "in use and stays on", as InUse
  should.
- Not tried: the GUI against that gateway, or a real vendor account.
2026-10-15 22:36:59 +08:00
yetone 64b0f3a201 plugins: a community plugin's own page in magpie's window, shut in a sandboxed frame (P4)
A plugin's package.json may declare magpie.page {title, file, icon} and
magpie.permissions.reads. While the plugin is on, its page gets a tab in a
"Plugins" group after the built-in pages, drawn in an iframe sandboxed to
allow-scripts only (an opaque origin: no cookie, no storage, no parent).
Its files come from /_magpie/plugin/<token>/ (HMAC of the spec with a
per-process secret) under a CSP with connect-src 'none' and
frame-ancestors 'self'; a path that leaves the page's folder, a symlink
out, or an off plugin's token is refused. The window's postMessage bridge
answers only that frame (event.source checked) with theme and language,
the plugin's own options.get/set (throttled), and the reads it declared;
any other read is refused in the window and again by the server, and no
read carries a secret. /api refuses Origin: null and frame/iframe
fetch-dest requests (noFramedAPI), so the frame never reaches the GUI's
API even with the cookie. A page that throws or never says hello shows
the kernel's broken-page state with Try again. The Plugins page shows the
page and what it reads before the plugin is turned on.

Docs: gui-shell.md, plugin-runtime.md (P4 section), site docs en/zh/ja
with an example plugin; i18n zh, zh-TW, ja, de; fixture in
internal/gui/testdata/page-plugin.

Run (worktree at base 4df1ba0c6, -p 2, one package at a time):
- go test -count=1 -timeout 45m: internal/gui ok, internal/plugin ok,
  internal/pluginrt ok, plugins/... (budget groups middleware otel redact
  rotation search) ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.
- Playwright (chromium + webkit, 5 languages, narrow widths): plugin-page 4/4,
  plugin-kernel 4/4, builtins 4/4, i18n-keys, gui-de, gui-ja, gui-zh-tw 3/3,
  plugin-middleware 24/24, plugin-own-icon 22/22, plugin-options 22/22,
  plugin-local 8/8, plugin-agent 22/22, click-scroll 22/22.

Broken by hand, each went red: CSP without connect-src; apiFramed always
false; the server's read check removed; the noFramedAPI wrap removed from
api.go (red through the real Handler); inside() letting every path
through; CORP same-origin re-added; in JS the client read check removed,
the ev.source check removed, and allow-same-origin added to the sandbox.
Without the Array.isArray guard on /api/plugin-pages, plugin-kernel,
builtins and plugin-middleware/own-icon/options went red (their mocks
answer a non-list) - that was found by the run, then fixed.

Real use: built magpie, `magpie web` on 127.0.0.1:3472 (gateway 3471) in a
sandbox HOME with the example plugin added. curl: the page file loads
with the CSP and no cookie, traversal and a bad token are 404, /api with
Origin: null or Sec-Fetch-Dest: iframe is 403 even with the cookie, an
undeclared read 403, a declared one 200. Chromium and WebKit at 1100 and
420: the page draws its declared read, the probe's fetch/absolute
fetch/top access/undeclared read are all refused, an <img> of /api is
refused, no page errors. Real use found that a
Cross-Origin-Resource-Policy: same-origin header blocked the frame's own
files (its origin is opaque); it is gone and a test guards it.

Not tried: the desktop (Wails) window. Market cards of plugins not yet
installed don't show a page's reads. The Playwright suite mirrors the
CSP in a mock route rather than the Go server (the Go tests and real use
cover the server).
2026-10-15 22:36:59 +08:00
yetone 6ac7032b4b plugins: a community plugin's tools reach every agent through magpie's MCP server /mcp/magpie/tools (P4 tool point)
A plugin's OpenCode `tool` hook ({tool: {name: tool({description, args,
execute})}}) used to reach no agent. Now the plugin host collects each
loaded plugin's tools, turns their zod args (v3/v4 shape or object; a
raw JSON Schema is kept) into JSON Schema, and runs one on a `tool`
call: arguments checked against the tool's own zod first (defaults
filled, a wrong one named), execute raced against ToolTimeout (55s,
ctx.abort fires), the answer as text.

The gateway serves them as an MCP server at /mcp/magpie/tools
(tools_mcp.go, guarded by serveMCP as the search one, 4 MiB body):
tools/list names each <plugin short name>_<tool>, at most 64 chars,
a shared name numbered _2; tools/call holds the call to the calling
key's limit through reserveFor and runs it with the calling agent.
The built-in plugin `tools` ("Plugin tools", Essential) serves
gwtool.PluginTools; off, nothing is listed, a call says the plugin is
off and the host isn't asked. InUse counts plugins that are on and
gave tools, from plugin-tools.json, which the host writes after each
load (whole, only on change), so it never starts Bun; the gateway's
KeepFresh watches that note too. Tool answers go to the calling
agent only, so masking doesn't apply (said in the docs).

The Plugins page lists an on plugin's tools by their MCP names, with
descriptions on hover and a button copying the server's address; a
plugin of tools alone has no Provider chip and isn't said to sign in
to nothing. Not done: a Library featured opt-in entry; wiring is the
copied address.

Docs: docs/subsystems/plugin-tools.md (new), plugin-runtime.md's new
"P4: community plugins at every point" section with the tool row, the
README index, usemagpie.ai/docs/plugins#tools in en, zh, ja with an
example. Strings in zh, zh-TW, ja, de. Example plugin:
internal/plugin/testdata/tools.

Run at this commit's tree (base 4df1ba0c6), each package alone, -p 2:
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  over internal/plugin, gwtool, gateway, plugins/..., gui, pluginrt: ok
- go test ./internal/plugin -run Tool; ./plugins/...; ./internal/pluginrt;
  ./internal/gui -run 'Builtin|Plugins'; ./internal/gateway -timeout 45m
  -run 'ToolsMCP|ServingGates|OwnMCPRejects|SearchOnAndOff|KeyLimitsOnAndOff':
  all ok
- GUI, Chromium and WebKit: every plugin-*.test.cjs, i18n-keys,
  builtins: 461/461 pass; plugin-tools.test.cjs (new) covers en, zh,
  zh-TW, ja, de at 980 and 420 px

Broken by hand, each red, then restored:
- tools/list ignoring the gwtool gate -> TestToolsMCPOff
- tools/call ignoring the gate -> TestToolsMCPOff
- reserveFor removed -> TestToolsMCPHeldToKeyLimit (tool ran)
- collision suffix dropped -> TestToolsMCPServesPluginTools
- ToolsOn ignoring Off -> TestPluginTools
- host arg check removed -> TestPluginTools
- host timeout race not listening -> TestPluginTools (answered at
  5.3s by Go's backstop; the test now bounds it at 4s, and the first
  try at this break was a syntax error that proved nothing)
- GUI listing an off plugin's tools -> plugin-tools.test.cjs

Real use: a built magpie in a sandbox HOME (MAGPIE_ADDR 127.0.0.1:3491,
real Bun), the example plugin added with `magpie plugin add`. curl over
MCP: initialize, tools/list (4 tools, schemas), shout "HI HI (for
curl)", a missing argument as isError naming it, add {"sum":6.5}, fail
"it broke", a foreign Origin 403; plugin-tools.json written. Claude
Code (sandbox CLAUDE_CONFIG_DIR) `claude mcp add --transport http` +
`mcp list`: Connected. Not tried: a model calling a tool through a
real agent turn (no model in the sandbox). Binary and HOME removed.
2026-10-15 22:36:59 +08:00
yetone 2e2c890304 agent: Lody is detected by what Lody makes, its link only on loopback is guarded, and its row is tested in every language
Review of Leon Zhao's Lody import (the two commits before this):

- Detection: a bare ~/.lody or ~/.lody-oss another tool made counted as
  Lody. Now the home folder counts only with an entry Lody makes there
  (workspace-catalog.json, loro-repo, agent-binaries, code-collab-v2, all
  in the owner's real ~/.lody). A Lody.app counts only with an ai.lody.
  bundle id (the real /Applications/Lody.app is ai.lody.desktop, and
  registers the lody scheme) or a plist that isn't XML. Electron's data
  folder under os.UserConfigDir (Application Support / %APPDATA% /
  ~/.config, "Lody", "Lody OSS", "Lody Nightly") still counts as before.
  A never-opened install on Windows or Linux has no folder and isn't
  shown; said in agent-wiring.md.
- Security: TestLodyLinkCarriesNoSecret turns LAN sharing on and checks
  the link holds magpie-lody and never the LAN key, every endpoint is
  loopback http, and MAGPIE_ADDR pinned beyond loopback gives no link at
  all (0.0.0.0, 127.0.0.1 and [::1] still give one).
- `magpie lody add` with no link (a LAN-pinned gateway) said it opened
  Lody and opened ""; it now says why and opens nothing.
- Added *bool: every consumer re-read. The CLI and TUI use agent.Agent's
  func (nil-safe), the GUI reads a.added == null, and Cindy's false is now
  sent as "added":false. TestLodyImportHandoff also checks Cindy's row
  says false and Lody's leaves added out; the handoff test's ~/.lody
  holds a catalog file now and checks it is left byte for byte.
- The hint "Opens {name} to add magpie as a provider — confirm it there"
  was already translated in zh, zh-TW, ja and de (the import button's
  tooltip). import-row now runs in all five languages, asserts Lody's
  exact translated line and that no added/not-added wording shows, and
  checks both import rows fit a 420px window with no sideways scroll
  (waiting for the header's segments to settle after the resize, which
  overflow for ~300ms in WebKit en on main too).

Run (on origin/main 4a6bf80f4 + Leon's two; after rebasing onto
dcf292cc8, a routing-only CSS change, import-row, agent-layout,
group-editor-align and i18n-keys were run again in both engines, 47/47,
with the Lody/Cindy/Import Go tests in agent and gui, ok):
- go test -tags nogui -count=1 -timeout 45m ./... under a sandbox HOME
  (scratchpad dir, XDG_* there too, Go caches pinned): 64 packages ok,
  exit 0 (agent 607s, gateway 674s, gui 130s, provider 219s).
- gofmt -l .: clean. go vet: darwin ./..., GOOS=linux -tags nogui ./...,
  GOOS=windows ./...: clean.
- GUI, playwright 1.62.0, Chromium and WebKit: import-row 20/20 (5
  languages x added/not x 2 engines, 960/700/420px); i18n-keys, gui-de,
  gui-ja, gui-zh-tw, agent-layout, agent-connect, plugin-agent,
  agent-cli-missing, agent-connected-unfolded, agent-bulk-visibility,
  agents-hidden-last: 116/116.

Broken by hand, each went red, then restored:
- a bare ~/.lody counting again: TestLodyDetectionAndRegistration;
- any Lody.app counting: TestLodyBundle (com.example.lody, ai.lodyx.);
- the loopback switch removed: TestLodyLinkCarriesNoSecret (LAN-pinned
  addresses got a link);
- the key taken from agentKeyAt at a LAN address: the LAN key showed in
  the link, red;
- Cindy's false left out of state(): TestLodyImportHandoff;
- app.js's unknown-status branch taken out: import-row red in every
  language; the de translation removed: import-row de red.

Not tried: Lody opening the link for real (Leon ran Lody's parser), and
Windows or Linux Lody installs.
2026-10-15 21:21:42 +08:00
Leon Zhao c6bd4e9707 agent: let Lody confirm local provider imports
Offer Lody a versioned import link for Claude, Codex, Pi, DSH,
Kimi Code, Grok and Bub. Export only loopback endpoints and the public
magpie-lody token. Leave Lody data untouched and show a confirmation hint
when the app exposes no public import-status reader.

Verified: go test -tags nogui ./... in a temporary HOME with pinned Go
caches; native, Linux nogui and Windows vet/build; gofmt and diff checks;
17 Chromium/WebKit import-row and locale checks. The actual Lody parser
accepted all seven targets with IPv4, localhost, IPv6 and canonical ports.

Negative controls: removing registration fails
TestLodyDetectionAndRegistration with "Lody missing from Agents";
removing URL handoff fails TestLodyImportHandoff with
"Lody import was not handed to the desktop". Restored tests pass.

Desktop launch and Linux/Windows runtime behavior were not exercised.

Cherry-picked onto main (4a6bf80f4) from Leeeon233/magpie
feat/lody-integration (ab6c6dd27): README lists resolved with Lody after
Cindy beside main's new agents; /api/open keeps main's OpenURL error path
(#2043) and takes lody:// beside cindy://; the test's fake Windows
returns OpenURL's error as main's interface now does.
2026-10-15 21:18:41 +08:00
yetone 37fec12409 import: OpenCode's keys come in from its auth.json, Go's on OpenCode Go (@hu_xiaomi on X)
@hu_xiaomi on X asked whether magpie could pick up OpenCode Go's API key
by itself. OpenCode keeps what `opencode auth login` signs in to in
auth.json, in $XDG_DATA_HOME/opencode (~/.local/share/opencode when that
is unset, on Windows too). Its format and path were checked against
anomalyco/opencode v1.19.0, packages/opencode/src/auth/index.ts.

- OpenCode is now a source in the import picker (appReaders,
  import_opencode.go). An "api" key comes in on the magpie preset with
  the same id: opencode-go on OpenCode Go, opencode (Zen) on OpenCode
  Zen, and a vendor's key (openai, anthropic, deepseek, openrouter, ...)
  on that vendor's preset, the same way Alma's almaPresets work.
- auth.json keeps no address beside a key, so a key for a provider with
  no preset is listed and skipped ("it has no base URL"). Sign-ins
  (oauth: Claude Pro/Max, Copilot; wellknown: an enterprise server's
  token) are listed and skipped with the reason the picker already
  translates. No new GUI strings.
- OpenCode is read only when the user opens the picker. The Providers
  page's automatic discovery leaves it out (DiscoverSources, the `asked`
  flag), because the file holds every sign-in OpenCode has. magpie never
  writes to it. OPENCODE_AUTH_CONTENT is not read.
- presetAt: the first preset at a host won even when a later one matched
  the URL exactly. OpenCode Zen and Go share opencode.ai, so a Zen key
  would have landed on Go. An exact match now wins.
- importSources: a source whose stat fails with anything but not-exist
  (a folder magpie can't search) is found with an error, which means
  unknown. Before, it read as "Not found".
- The picker's tab shows OpenCode's own mark (icons/opencode.svg).
- docs/reference.md describes the source.

Not added: an "use the key OpenCode has" offer in the OpenCode Go add
sheet, because no other app has one there (no sibling to follow).

Run (macOS, go1.26.8, worktree at dd25997a4 before the rebase):
- go test -tags nogui -timeout 40m ./...: every package ok
  (63 ok, none failed; gateway 1806s, agent 1769s at load ~160-230)
- gofmt -l internal/provider internal/gui: clean
- go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...: clean
- GUI, playwright 1.62.0: import-opencode.test.cjs in chromium and webkit,
  en/zh/zh-TW/ja/de, at 900 and 390px: 20/20. import-collision,
  import-row, provider-discovery and key-import pass. login-import fails
  in chromium (fill/click timeouts) at load ~230. It fails the same way
  with HEAD's app.js (dd25997a4 = origin/main, just fetched), and #1307
  already tracks it.
- Broken by hand, each went red and was then put back:
  1. presetAt's old first-hit rule: TestImportOpenCodeAuth, Zen came in
     as opencode-go-2.
  2. no sign-in skip: TestImportOpenCodeAuth, anthropic's oauth entry.
  3. stat errors read as not found: TestImportOpenCodeAuthUnknown,
     unreadable folder.
  4. discovery reads OpenCode: TestImportOpenCodeAuth and
     TestOpenCodeWaitsForThePicker.
  5. XDG_DATA_HOME ignored: TestImportOpenCodeAuth, TestImportOpenCodeAuthUnknown
     and TestOpenCodeWaitsForThePicker.
  6. tab icon left at app-opencode.png: import-opencode.test.cjs.

Fixtures are auth.json as OpenCode v1.19.0 writes it
(JSON.stringify(data, null, 2), 0600), under a sandbox HOME and
XDG_DATA_HOME. Not tried: a real OpenCode install with a real key, and
the Windows box (the path logic is the same there; GOOS=windows vet only).
2026-10-15 19:20:09 +08:00
yetone a1f7b8c13f plugin: gateway key limits are the Key limits plugin on the gateway's budget point (P3)
The last P3 point, after observer, router strategy, middleware and tool:
the budget point (internal/gwbudget). A plugin serves a Limiter while it
is on; the gateway asks gwbudget.Limiting before any request of a key held
to a limit goes to a provider (reserveFor: the chat APIs' keyLimited, the
search MCP server and the vision one). A request without a key, or of a
key with no limit, never asks it.

It fails closed. A key with a limit and no limiter served gets 503
gateway_key_limit_off, X-Should-Retry false, nothing sent, and a rejected
usage row. With none served, Limiting first asks the gateway's refresh
(pluginrt.Refresh, at most once a second, never from inside one), so a
limit set a moment ago turns the plugin on for the request that needs it.
A limit reached is the 429 gateway_key_limit with Retry-After and
X-Magpie-Limit-Reset, as before.

plugins/budget serves internal/budget's limiter (budget.Limiter). It is
Essential and in use while a gateway key has a limit, so it can only be
off while none has; a keys file that can't be read is an error, so it
stays on. KeepFresh watches the keys file too. What a key has used and
has left (/v1/magpie/limit, the Gateway page, the CLI) and budget.Append
stay in the core, so the ledger counts a key's use the same either way,
and the key editor's limit fields stay, since setting a limit is what
turns the plugin back on.

The builtins GUI test wheels to the Routing row as it did to Usage's: the
new row puts it below the fold in WebKit, where the page puts back a
scroll that isn't the reader's (scrollOnPurpose).

Run at this head (on origin/main 9d97fd073):
- go test -count=1 -timeout 45m ./... at this head (after two runs cut short by a full disk): 63 ok, 1 red: internal/gui TestMainWindowCorners/macOS_26_SDK killed at its 40s deadline at load ~280 (#1936, no window change here); alone it passed.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, chromium and webkit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw pass
- TestKeyLimitsOnAndOff, TestVisionMCPHeldToKeyLimit, TestKeyLimit*,
  plugins/budget tests

Broken by hand, each test went red: reserveFor ignoring Limiting's error,
Limiting letting a limited key through with none served, the refresh
never asked, Apply serving nothing, InUse counting keys with no limit,
InUse swallowing a read error, the vision and search MCP servers not
reserving, a refusal answered as 503 rather than 429.

Real use (built magpie, sandbox HOME/XDG_CONFIG_HOME, gateway on
127.0.0.1:3594, fake vendor on 3593, two gateway keys):
- no key with a limit: `plugin builtin off budget` turned it off; the
  key's request was 200
- `gateway-key limit <id> day --tokens 3`, then a request at once: 200,
  and the plugin read "on, in use"; the next 200, then 429 "has used 4 of
  its 3 ... tokens for this day"; turning it off was refused, "in use"
- the key with no limit: 200; /v1/magpie/limit answered the spent day
- limit removed: turned off; the key's request 200; a limit set again and
  a request at once: 200, "on, in use"
Not tried: the 503 in real use. With a key limited, the refresh turns the
plugin on before the request is refused (a hand-set `enabled: false` in
plugins.yml read "on, in use"); the 503 is the test's.
2026-10-15 18:41:03 +08:00
yetone dd25997a45 codex: a client's access_programs and the account's extraBody reach the ChatGPT backend, and its refusal comes back as it said it (magpie-releases#18)
NonMirror (0.1.1239, OpenCode, codex/gpt-daybreak-blue-latest on a ChatGPT
sign-in): a top-level Responses access_programs never reached upstream,
and the codex provider's extraBody wasn't applied.

Cause:
- A Codex account is streamed upstream, so a whole (stream:false)
  Responses request and every Chat or Messages request is translated
  (parseResponses/parseChat -> Request -> buildResponses). Request had no
  field for access_programs, so the rebuilt body dropped it. Only a
  streamed Responses request, relayed through codexBody, kept it.
- WithExtraBody skipped every signed-in account, and withPicks didn't
  copy the providers.json ExtraBody onto the account.
- writeError rewrapped every vendor error with code and param null, so
  even a forwarded refusal lost what it was about.
- The backend refuses a program the workspace hasn't got inside a 200
  stream (error event, invalid_request_error, access_program_not_enabled).
  The whole-translated path answered that 502 api_error, and translated
  streams wrote it as api_error, which holdWriter reads as 502: the same
  request went three times, then to the other accounts, and every one
  rested.

Fix:
- Request.AccessPrograms (Responses and Chat), built into the Responses
  body as it came; a null is kept.
- A ChatGPT (Codex) account takes extraBody; store, tool_choice and
  include stay magpie's (codexOwned). withPicks keeps ExtraBody.
- writeVendorError keeps the vendor's error.code and error.param on the
  relayed, whole-translated and streamed-translated status-error paths.
- requestRefused: a Responses stream error/failed whose error type is
  invalid_request_error carries status 400 and the vendor's error
  (Event.Said). The whole path answers that 400 with code and param; the
  Chat, Anthropic and Responses encoders write its type/code/param
  (saidError). Read by the type, never by words.
- Codex CLI sends access_programs as a top-level object on its Responses
  request (codex-rs ResponsesApiRequest.access_programs); OpenAI's Daybreak
  guide documents the same field.

Run:
- New: internal/gateway/codex_access_programs_test.go
  (TestCodexAccessProgramsReachBackend, TestCodexAccountTakesExtraBody,
  TestAccessProgramsNullKept), passes -count=3.
- Broken by hand, each went red: buildResponses not emitting the field
  (probe answered 200, the reporter's symptom); extraBodyTakes' Codex case;
  withPicks' line; codexOwned emptied; writeVendorError ignoring the body;
  the continuation site alone; retryable(400) true (asked twice, rested);
  requestRefused returning nothing (502, asked 4 times, both accounts
  rested); saidError a no-op (streamed: asked 4 times, rested); the whole
  site back to 502 (same).
- go test -timeout 30m ./...: all 62 packages ok (gateway 1559s at load
  ~26; an earlier run at the default 10m timed out in gateway under that
  load, not a failure). gofmt -l clean. GOOS=linux and GOOS=windows
  go vet -tags nogui ./... clean.

Real account (sandbox HOME, own port 3486, copied auth.json with a dead
refresh token; owner's ChatGPT Pro account, model codex/gpt-5.6-luna):
- "__daybreak_forwarding_probe__": 400 invalid_value, param
  access_programs.cyber ("Supported values are: 'standard',
  'daybreak_blue', and 'daybreak_red'") on Responses whole and streamed,
  Chat whole and streamed. The backend says invalid_value, not the
  guide's invalid_access_program.
- standard: 200. null: 400 invalid_type.
- daybreak_blue (not enabled for this workspace): 400
  access_program_not_enabled with param on Responses and Chat whole, the
  error event with that code on Responses and Chat streamed; ~1s each,
  one try (was 3 tries and a 502 before this change).
- The next plain request was served 200 by the same account: nothing
  rested.

Not verified: the Daybreak model itself (not listed for this account),
so no 200 with daybreak_blue; OpenCode's own wire; the Messages route
against the real backend (fake backend only).
2026-10-15 16:51:31 +08:00
yetone 9d97fd0733 plugin: magpie's web search is the Search plugin on the gateway's tool point (P3)
The third P3 point after observer/rotation, groups and middleware: the
tool point (internal/gwtool). A plugin serves a tool by name while it is
on; the process serving the gateway gates on it (Gate in ListenAndServe),
and a process not serving the gateway (CLI, TUI) has every tool, as
before.

plugins/search serves gwtool.WebSearch. Off, magpie offers and answers no
search of its own: the stand-in web_search isn't given to a model that
can't search, the search MCP server and Codex's search in ChatGPT's place
say "turn the Web search plugin on", and neither a search API nor a Kimi
Code plan's own search service is asked. A vendor that searches by itself
is still sent its own web_search. It is Essential and stays on while a
search API is set up or a searcher is picked (InUse); a providers.json or
settings.json that can't be read counts as unknown, so it stays on.

Settings → Models' Web search section stays visible with the plugin off:
the plugin can only be off when nothing is set up there, and adding a
search API there is what turns it back on (as Privacy does for redact).

Run at this head (rebased on origin/main 35aa50cfb):
- go test -count=1 ./... (full suite): 63 packages ok, none failed
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, chromium and webkit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw pass
- TestSearchOnAndOff, TestServingGatesTools, plugins/search tests

Broken by hand, each test went red: canSearch ungated, searchesOwn
ungated, webSearch ungated, no Gate in ListenAndServe, Apply serving
nothing, InUse ignoring the searcher, SearchAPIsSet swallowing the read
error, the gate never released.

Real use (built magpie, sandbox HOME/XDG_CONFIG_HOME, gateway on
127.0.0.1:3592, fake vendor and fake Tavily on 3591):
- on with a Tavily API set: a plain chat model was sent Read + web_search;
  MCP /mcp/magpie/web-search returned the fake's result
- `plugin builtin off search` with the API set: refused, "in use"
- API removed, turned off: the plain model got Read only; a native
  Anthropic provider still got its web_search; MCP answered isError with
  "turn the Web search plugin on"
- API added back: the plugin read "on, in use" and web_search was offered
  again
Not tried: a real search vendor or a real Kimi plan (fakes only).
2026-10-15 16:45:51 +08:00
yetone 35aa50cfb3 zhipu: a GLM Coding Plan key refused 200 in the platform's envelope reads as refused, in the test, the gateway and the quota card (@xanahopper on X)
On a Coding Plan with a key Zhipu refuses, Test showed OpenAI 401 and
Anthropic 401 but Responses (https://open.bigmodel.cn/api/v1) a green
check, and the 5h/weekly windows showed only "Allowance unavailable".

Cause: /api/v1 (Zhipu's real Responses endpoint, docs.bigmodel.cn
coding-plan/tool/codex) and /api/monitor answer a refused key HTTP 200
with {"code":1000,"msg":"身份验证失败。","success":false}. probe (endpoint
Test, model tests, Detect) took any 2xx as ok, and the gateway handed
the 200 to Codex as a reply, so no failover and no rest.

- provider.ZhipuEnveloped: a 2xx JSON, non-stream, unencoded reply from
  open.bigmodel.cn or api.z.ai whose body is the envelope with
  success:false becomes {"error":{...}} under the status Zhipu's code
  table gives (1000-1005 401, 1113/13xx 429, 1220 403, 121x/1261/1301
  400, else 502). Anything else passes through unchanged (64KB cap,
  body restored). Applied in probe and in the gateway's forwardOnce.
- planquota: a refused key (envelope 1000-1005 or HTTP 401 from a
  Zhipu/Z.ai host) says "Zhipu didn't take this key (...): it has
  expired, was deleted, or is mistyped; paste a current one from <keys
  page>", and skips the team retry. The card shows it in en, zh, zh-TW,
  ja, de.
- docs: providers-accounts and gateway-routing rows.

Run at this head (before rebase, base 95e7c6bcc):
- go test -timeout 20m ./internal/gateway ./internal/provider: ok
  (343s, 93s). New: TestZhipuResponsesRefusalNotGreen,
  TestZhipuEnveloped, TestZhipuRefusedKeyCard,
  TestZhipuResponsesRefusalIsRefusal (zhipu and zai presets).
- Full go test ./...: every package ok except internal/gateway, which
  hit the default 10m timeout while the full GUI suite and another
  session's GUI tests ran beside it; alone with -timeout 20m it passed.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet on provider and
  gateway clean.
- GUI: glm-quota-error (new) and opencode-go-quota-error 20/20 in
  chromium and webkit, five languages. The full GUI suite ran once (under
  load) and exited 1; each of its 16 red files was rerun alone here and
  on an origin/main 03eb0633a copy of internal/gui: 10 pass on both;
  quota-count-wrap (1), quota-name-translated (1),
  refusal-retries-setting (2), usage-agents-hide (22), usage-fold (2)
  fail the same counts on both; routing-held-member fails 1 here, 2 on
  main. None touches quotaError's GLM line.

Broken by hand: ZhipuEnveloped returning res unchanged, and
zhipuEnvelope returning ok=false, turned the provider tests red;
reverting the gateway line turned TestZhipuResponsesRefusalIsRefusal
red; breaking the GLM regex in app.js turned glm-quota-error 0/5 in
chromium. All restored.

Not tried: no real Zhipu or Z.ai key, valid or expired. The refusal
bytes are from a curl of /api/v1 with a bad key; the reporter's
"令牌已过期或验证不正确" code is unknown (assumed 1000-1005 or HTTP 401,
both handled). A valid key's quota read with a real plan was not run.
2026-10-15 15:55:24 +08:00
yetone 03eb0633af library: an agent not installed is on no row but those of what it still has (@jiahao_jayden on X)
Library → Skills showed a chip for WorkBuddy on every row though it
wasn't installed ("一排有点密恐了"). WorkBuddy has no CLI and no detect
rule, so it counted as installed whenever ~/.workbuddy (or its
models.json) existed; that folder stays after the app is trashed, and
magpie itself writes models.json, mcp.json and skills/ there.

- agent: on a Mac WorkBuddy and WorkBuddy AI are detected by their apps,
  each by its own bundle id (com.tencent.workbuddy.mac,
  com.workbuddy.workbuddy-ai) in /Applications or ~/Applications
  (macBundle). Off a Mac the folder still counts, as before.
- library: an agent that isn't a target but still has skills, servers or
  hooks magpie gave it is held (Target.Gone). A sync takes edits from its
  copies and then only takes things out of it; Read lists it with
  gone: true while it has any, and not once it has none.
- GUI: a gone agent's chip is only on the rows of what it has, lit; a
  click takes it away. All, the How-per-agent sheet and the pickers leave
  it out; By agent lists it as "Not installed here" with Turn all on off.
  No layout change. New strings in zh, zh-TW, ja, de.

Run at this tree (macOS, sandbox HOME, Go caches pinned):
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build: ok.
- go test -tags nogui -timeout 30m ./...: all ok (59 packages);
  internal/gui rerun after the last string rename: ok.
- GUI: the 74 test files that open the Library, chromium and webkit:
  563/563 each. library-gone-agents.test.cjs (new; 1100px and 390px, en,
  zh, zh-TW, ja, de): 11/11 in both; i18n-keys.test.cjs: 3/3.

Broken by hand, each went red, then restored and green:
- old client.js: library-gone-agents fails "a chip for an agent not
  installed on a row it has nothing on".
- workbuddyHere's Mac branch falling back to the folder:
  TestWorkBuddyOnMacIsItsApp "no app, only the folders: WorkBuddy true,
  WorkBuddy AI true".
- syncSkills' Gone guard off: TestGoneAgentListedToTakeOut "a sync gave
  the gone hermes a skill again".
- held() returning nil: "hermes, holding a skill and a server, isn't
  listed as gone".
- the gone sync steps skipped: "hermes, holding nothing, is still listed".

Not verified: the reporter's machine; WorkBuddy detection on Windows and
Linux (unchanged, still by folder); other agents detected by folder alone
(zcode, alma, grok-app, air, hanako, morph, grok) are unchanged. WorkBuddy
AI.app is installed on the owner's Mac without ~/.workbuddy-ai, so it now
shows as detected there.
2026-10-15 14:52:51 +08:00
yetone 01c41e8ba2 library: a skill probe's download goes when it is probed again or 15 minutes are up, and one a magpie that quit left behind goes at the next probe (#2321)
ProbeSkills kept each GitHub probe's download, a magpie-skill-* folder in
the temp dir, cached for 15 minutes. An expired one went only at the
*next* probe, so a magpie that quit, or a test that ended, left it there
for good. One go test ./internal/library left 22. This machine's temp dir
had 5477, and with old test homes they filled the disk under a full run
(gateway tests failed "no space left on device").

- keepProbe: each cached probe has a timer that removes its folder when
  probeLife is up. A probe of the same input replaces it and removes the
  old folder at once, outside the lock.
- sweepStaleDownloads, at each probe: a magpie-skill-* in the temp dir over
  an hour old goes. No live one is that old, since a probe is kept 15
  minutes and a fetch takes seconds.
- internal/library's TestMain gives the tests a temp dir of their own
  (TMPDIR, and TMP/TEMP for Windows), ends the cached probes, and fails a
  run that leaves a skill download there. A test binary started again by a
  test keeps its parent's temp dir.

Run (on origin/main 8b89b2e36): go test -count=1 -timeout 60m ./... all ok;
gofmt clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.

Broken by hand, each went red:
- a replaced probe's folder kept (TestProbeDownloadEndsWithIt)
- no removal at expiry (TestProbeDownloadEndsWithIt)
- the sweep ignores age, or the prefix, or doesn't run
  (TestStaleDownloadsSwept)
- TestMain doesn't end the probes: "the tests left 16 skill downloads"

Not tried: the Windows box, though TMP/TEMP are set for it.
2026-10-15 14:19:00 +08:00
yetone 4ac4d9ba99 plugins: the gateway's middleware point; JS middleware and privacy masking are built-in plugins, masking fails closed (P3)
P3's third point (docs/subsystems/plugin-runtime.md). internal/gwmw has two
places, each with its own failure policy:

- Agent: a middleware on an agent's request in its own API and on its reply.
  serveAgent runs each registered one. The JS gateway middleware is the one
  there (middleware.Chain), registered by the new built-in plugin
  `middleware`. Its place, API, limits and fail-open are unchanged. InUse is
  middleware.On(). Off, no middleware runs.
- Masker: what goes to a vendor, masked, and the values back in what comes
  back. The new built-in plugin `redact` serves masking.Masker (in
  internal/masking, since settings imports redact). InUse is masking.Wanted.
  It fails closed: masking asked for with no masker serving, or a masker that
  panics, is a 503 "nothing was sent" at every call site that masked before
  (serve, count_tokens, embeddings and audio, transcriptions, images, video,
  search stand-ins and their queries, the Codex backend).

With no masker, or with no agent middleware while plugins.json has one on,
the gateway asks pluginrt.Refresh, at most once a second. A setting or
middleware added a moment ago serves the request that needs it.
pluginrt.KeepFresh also watches plugins.json now.

Run (on origin/main 95e7c6bcc + this change, with the next commit's two
test waits):
- go test -count=1 -timeout 60m ./...: all ok (gateway 682s, agent 617s)
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, Chromium and WebKit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw. builtins reaches the Usage row by wheel now, since the
  page puts back a scroll that isn't the reader's.

Broken by hand, each went red:
- masking fails open with no masker (TestMaskingOnAndOff)
- a panic isn't recovered (TestSafelyTurnsAPanicIntoAnError, TestMaskingOnAndOff)
- no refresh asked (TestServedRefreshesOnce, TestMaskingOnAndOff)
- the plugins don't register (plugins/redact, plugins/middleware
  TestOnServesOffDoesNot)
- InUse misses redactWords (plugins/redact TestInUse)
- maskedQuery fails open (TestMaskedQueryFailsClosed)
- middleware runs with the plugin off (TestMiddlewareOnAndOff/off)
- no refresh on a middleware miss (TestMiddlewareOnAndOff), want ignored
  (TestAgentsWantedRefreshesWhenWanted)

Real use, sandbox HOME, magpie serve and a fake vendor that echoes:
- redact off with nothing asked: sent as written
- redactWords written, request at once: the vendor got {{TERM_…}} and the
  agent got the word back; `plugin builtin off redact` refused while in use
- `magpie plugin add ./alias.middleware.js`: the next request is rewritten
  (200, was 404). Removed: 404 again.
  The first build left that request at 404 until a restart, since plugins.json
  wasn't watched. That's fixed here.

Not tried: a real vendor account; the Windows box.
2026-10-15 13:40:20 +08:00
yetone b1d02fa612 groups: the user's own routing groups are the groups plugin's, served only while it is on (P3 router strategy)
The groups plugin now owns the user's own routing groups at the router
strategy point. The groups magpie finds (auto-<model>, one model several
providers serve) stay core, as Smart does: a new install has groups off
under Essentials, and taking those would silently drop cross-provider
failover. planGroup and the walk over a group's members stay core too.

- provider.GateGroups / ServeGroups (group_serve.go): the gateway holds
  the gate while it serves; the plugin holds ServeGroups while on. Gated
  with none served, groupsIn drops every group not Auto, so FindGroup,
  GroupFor, the catalog and /v1/models go without them. The CLI and TUI
  are never gated. Nothing derived from groups is cached past a call, so
  a flip is seen by the next lookup.
- Gated and off, a lookup that finds a user group asks the gate's refresh
  (pluginrt.Refresh in the gateway) at most once a second, never
  re-entrantly, then looks again. Without this, `magpie group add` was
  404 for up to 2s until KeepFresh turned the plugin on (seen in the
  sandbox).
- plugins/groups and plugins/routing: InUse is provider.NamedGroups, the
  file's non-Auto, non-hidden groups read past the gate; an unreadable
  providers.json is an error, so the plugin stays on.

Run before rebasing onto 707fbb249:
- go test -count=1 -timeout 40m ./... : all ok (59 packages)
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean
- sandbox, real nogui binary + `magpie serve` + two fake upstreams:
  before add: group/auto-m listed, group/mine 404; right after
  `magpie group add Mine models=pa/x,pb/m`: group/mine listed and 200;
  after `group rm`: 404, auto-m still served.

After the rebase onto 707fbb249: vets (3 OSes) and go test of
internal/provider, internal/gateway, internal/pluginrt and plugins/...
all ok.

Broken by hand, each went red:
- groupsIn filter removed: TestOwnGroupsWaitOnThePlugin,
  TestGroupsOnAndOff/off
- NamedGroups swallowing the read error: TestNamedGroupsUnreadable,
  plugins/groups TestInUse
- Apply not serving: TestOnServesOffDoesNot
- refresh not called / not throttled / asked for Auto groups too:
  TestOwnGroupRefreshesTheGate
2026-10-15 10:42:23 +08:00
yetone 707fbb249d backup: a settings.json that can't be read stops a backup, an export and a sync, not carried as the defaults to every other computer (#2269, JasonBuildAI)
Collect read settings with settings.Load, which stands the defaults in
for a file that is there but can't be read, or doesn't parse with no
good .bak. A sync then pushed those defaults as "changed here", and
every other computer brought them in over its own theme, language,
text size, allow list and per-model settings; an export carried them
too. Collect now reads through settings.LoadChecked and stops with its
error, as it does for providers.json (9c54a560). The sync ends before
anything is sealed or pushed, and its status shows the error; the CLI
and the GUI's export show it. A missing or empty file is unchanged.

Sibling: library.Collect read any failed stat of library.json as "no
library"; only a missing file is that now, any other error stops the
backup. plugins.json (provider.Carried -> plugin.list) still reads as
no plugins when unreadable; bringing that in never removes a plugin,
so it is filed separately rather than changed here.

What was run:
- TestCollectStopsOnUnreadableSettings (new, internal/backup) and
  TestSyncStopsOnUnreadableSettings (new, internal/davsync: two
  computers on a fake WebDAV, a's file cut short with no .bak; a's sync
  errs with no PUT, the status says so, the server keeps a's settings,
  b keeps its own). Both FAIL on the old backup.go ("Collect read a
  settings.json that can't be read as settings: <nil> &{Theme:system
  ..." and "a synced a broken settings.json") and PASS on the new, on
  macOS and on the Windows box (cross-compiled binaries, sandbox home).
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  clean.
- go test -p 4 -timeout 40m ./... on macOS (origin/main 69d7ee33a plus
  these three commits, load average 15-27 from other suites): every
  package ok but internal/gateway, where TestMaxRPMTooLongIs429With
  RetryAfter got 200 (the window had passed under load; #1791, open,
  gateway untouched here). -run TestMaxRPM -count=3 passes on this
  tree.
- After rebasing on origin/main 226222118 (which touched
  internal/library): go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows clean; go test ./internal/update ./internal/pluginrt
  ./internal/backup ./internal/davsync ./internal/library
  ./internal/settings ok (library under -timeout 40m, 550 s at load
  average ~60).
Not tried: a settings.json held open by another Windows program, or a
real WebDAV/S3/GitHub server.
2026-10-15 10:10:18 +08:00
yetone c7830731ca sessions: a session nothing was said in, which the Sessions page lists, opens and exports instead of "no such session" (#2273)
ListAgent lists a session assemble calls empty (no title, nothing
counted), so it can be cleared away, but Find searched only List(0) and
Get, and both drop it. The row's conversation, Markdown and Terminal
routes all go through Find, so they answered "no such session" for a row
the page itself shows. A real case is Codex's Image Session Helper: a
rollout with session_meta, settings, task_started and turn_aborted only.

Find now falls back to get(), which reports a session's files were found
even when assemble calls it empty, and fills it in the way ListAgent does
(listed(): Resume, Carry, Transcript), so Find finds every session
ListAgent lists. Get and List are unchanged: an empty session still
isn't in the main list and Get still says ok=false for it.

Run:
- TestFindEmptySession (internal/sessions) and TestEmptySessionOpens
  (internal/gui), on a fixture made from the real aborted helper rollout
  (paths and ids redacted). Both fail with Find's fallback broken by
  hand (only taking ok sessions), and pass with it.
- gofmt -l clean; go vet for darwin, linux (nogui) and windows.
- go test -p 4 -timeout 40m ./... with pipefail, sandbox HOME, at
  2b0037f41 plus this change, with four other full suites running on the
  machine: every package green but internal/gateway, whose
  TestOTelFastRequestTranscriptDiscovery/true failed ("request must still
  have a cached discovery miss"). That is #1811, its 2s discovery cache
  window under load; this change doesn't reach that path (TraceSessionIndex
  reads headers itself, never Find or ListAgent). Run alone with -count=10
  with its sibling it passes 10/10. Noted on #1811.
- Real use: a dev-tagged build in a sandbox HOME holding a copy of the
  real empty rollout, sessions feature on. /api/sessions/manage lists it,
  /api/sessions/transcript returns 200 {"parts":[]}, /api/sessions/markdown
  returns 200 with the .md attachment.

Not run: real use on Windows or Linux; the GUI suite (no GUI asset
changes). Whether an aborted helper rollout should count as something
said, and so show in the main list, is left as it was.
2026-10-15 09:40:51 +08:00
yetoneandggbdpq 58651568b3 agent, sessions, provider: a state file that doesn't parse is kept aside, not written over as empty (#2263, ggbdpq)
applied.json, wsl.json and sessions-wsl.json were read as empty when they
didn't parse, and the next save wrote that emptiness over them. What
magpie had applied to each agent, the WSL distros and the WSL session
listing were lost with no copy. stash.json already kept a bad file aside
as .bad-<time>. Each of these now does the same through one helper,
lastgood.KeepUnparsed, instead of a copy per file:
- It does nothing when the file is missing or empty.
- When the file doesn't unmarshal into the reader's own type
  (lastgood.Into[T]), it copies the file aside (KeepBad).
- It stops the write when the copy can't be kept.

This also fixes the issue's claim about stash.json. Stash judged a file
with json.Valid, so `[]`, which a map reader takes as empty, was written
over unkept. Its failed copy was only logged, and the write went ahead
anyway. Both are fixed (TestUnreadStashArrayKeptAside), and
gateway-hidden.json uses the same helper.

Siblings found by going through every single-file JSON reader that takes
a bad file as empty and then writes it whole:
- stepfun-auth
- login-returns
- quota-history
- balance-history
- credits-daily
- Claude Desktop tiers
- plugin updates
- usage's computer id
- davsync's sync state

Each now keeps a bad copy. Caches that are rebuilt from the vendor are
left alone; docs/subsystems/providers-accounts.md lists them.

Run:
- gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui,
  GOOS=windows): clean.
- go test -tags nogui -p 4 -timeout 40m ./... with the other three
  commits of this push: see the last one's body.

Broken by hand: on the code before this, these fail:
- the issue's applied_keep_test.go and wsl_keep_test.go
- TestUnreadStashArrayKeptAside
- TestUnreadStateKeptAside (10 subtests)
- the gateway, usage, davsync and plugin _keep tests
TestKeepUnparsed and TestKeepUnparsedFailsWhenItCantBeKept cover the
helper.

I dropped a test, "not written when it can't be kept", for stash. It passed
on the old code too, because a read-only folder also stops the atomic
write.

Not tried: a real WSL distro.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 09:36:26 +08:00
yetoneandggbdpq 919c8b934a gateway: a second answer to one call is dropped on the way to Gemini and Responses (#2262, ggbdpq)
A client that answers one tool call twice sent Google a call turn with
more functionResponses than functionCalls, which Google refuses with 400,
along with every later turn of the conversation. The Chat and Messages
builds already keep the first answer (pairToolMessages, pairToolBlocks).
The Gemini build (buildCodeAssistSent: Google sign-in, Vertex, a custom
Gemini provider) and the Responses build (buildResponses) now leave the
second one out before they build, with the images it carried
(dropSecondAnswers). A call made again under the same id takes an answer
of its own, and the request itself is left as it was, since a fallback
builds from it again.

This differs from the issue's patch. It dedups across the whole history in
pairFunctionTurns, keyed by id, or by name when there is no id. Keying by
name drops a real answer to a second call of the same function. Keying by
id ignores a call made again under that id. The patch also left the
duplicate's images in the turn and didn't cover Responses. Also fixed:
parseGemini matched a functionResponse with no id to the latest call of
that name, so two calls of one function were both answered as the second.
Each now goes to the first call of that name still unanswered.
pairToolItems (relayed Codex bodies) already keeps one answer per call and
is unchanged.

Run:
- gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui,
  GOOS=windows): clean.
- go test -tags nogui -p 4 -timeout 40m ./... with the other three
  commits of this push: see the last one's body.

Broken by hand: TestGeminiDropsASecondAnswer,
TestSecondAnswerDroppedWithItsImages and
TestGeminiClientUnnamedCallsAnsweredInOrder fail on the code before this.

Not tried: against Google's or a Responses upstream's real API.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 09:36:25 +08:00
yetone 226222118a agent: on Windows Claude Code and Codex are never taken for uninstalled by their folder, so neither shows "CLI not found" with its settings hidden (#1482, edussss)
edussss (Windows 11) on 10-15: "昨天早上的版本还能找到,今天早上更新后又找不到了".
Their screenshot shows both Claude Code and Codex marked "CLI not found",
with no model or effort pickers. v0.1.1231 listed both.

Cause: d0fcb8bcd (#2177, in v0.1.1238). It made cliHeld declare a shared
folder (~/.claude, ~/.codex, ~/.cline) a leftover when neither the CLI nor
a known reader is here. The known readers are editor extensions under
~/.<editor>/extensions, Claude.app, Claude Desktop, JetBrains and Zed. Before
that commit a shared folder was never gone. The list was checked on a Mac
only. On Windows, other programs read these folders too: a Store app, an
editor run portable or with --extensions-dir, or a CLI on a PATH that only
a shell profile sets (fnm). The Agents page, the TUI, `magpie ls`, Install
another agent and the Library targets (all through CLIMissing) treated both
of the reporter's agents as uninstalled.

Fix: on Windows, cliHeld says "can't tell" for a shared folder whose CLI
isn't found. A shared folder is then never gone, as before v0.1.1238, and
as OpenCode and Goose already are off a Mac. A found CLI still holds it.
Agents whose folder only their CLI keeps (dsh, Hermes) are still gone on
Windows. The Windows-only branches in that path became unreachable and are
dropped: desktopdir.Installed in the claude case, and the Windows dirs of
jetBrainsHere and zedAgentsHere. goneOS lets a test judge for Windows on
any host. docs/subsystems/agent-wiring.md says so.

What was run:
- Windows box (Windows 11 x64), sandbox USERPROFILE/APPDATA/LOCALAPPDATA
  holding only ~\.claude\settings.json and ~\.codex\config.toml, PATH
  C:\Windows\system32 (the registry PATH has the box's real
  ~\.local\bin\claude.exe; there is no codex on the box):
  - `magpie ls` at v0.1.1231 lists Codex "gpt-5 · effort".
  - At origin/main 69d7ee33a it lists "Codex  CLI not found". That is the
    regression.
  - With this fix it lists "Codex gpt-5 · effort" again.
  - At main, a fake openai.chatgpt extension in ~\.vscode or ~\.cursor
    also kept Codex listed. So the extension check works on Windows, and
    the reporter's reader is something cliHeld doesn't list.
- agent.test.exe -test.run TestCLIMissing on the Windows box: all four
  pass (TestCLIMissing, Hermes, SharedFolders, SharedFoldersWindows).
- Broken by hand: with the Windows branch disabled,
  TestCLIMissingSharedFoldersWindows goes red for claude, codex and cline.
  Each is taken for gone and offered again as missing.
- gofmt -l clean. go vet -tags nogui passes for GOOS darwin, linux and
  windows.
- set -o pipefail; go test -p 4 -timeout 40m ./... on macOS at base
  69d7ee33a plus this change: all 55 packages ok, exit 0 (internal/agent,
  cli, gui, library and tui among them).

Not tried: the reporter's own setup. Their screenshot doesn't say what
reads their folders. The reply on #1482 asks for `where.exe claude`, the
install method and the magpie version.
2026-10-15 09:29:57 +08:00
yetone af9bd6c3e2 gateway, routes, plugins: the routings besides Smart are the rotation plugin's, on the gateway's router strategy point (P3)
The second P3 extension point (docs/subsystems/plugin-runtime.md). A
router strategy orders one pool of routes: a provider's accounts or keys,
or the heads of a group's members. The gateway still lists the pool and
keeps rests, affinity, rules, pins and failover; a strategy only orders.

- internal/routes: Seat, Strategy{Order, Exact, ByUse}, Register (stacks,
  the last serves), Find, Served, and Apply, which fails open: a strategy
  that panics or answers what isn't a permutation leaves the pool in its
  listed order, logged. Smart is the core's; Ordered, Rotate, LeastUsed,
  Pace and Weighted are routes.Builtin, moved out of the gateway with the
  rotate turns and the smooth weighted round (Round, MoveRound, Forget).
- plugins/rotation (Essential): registers routes.Builtin. InUse counts the
  providers and groups providers.json routes by one of them
  (provider.Routings), an unreadable file is an error, so it stays on. The
  gateway's KeepFresh watches providers.json too.
- Off, a routing no strategy serves is its listed order, and routingOf
  reads it as "order" wherever the core asks (a turn's mark, sinks, a
  rotate group's sessions, a group's heads, weightedKept).
- GUI: the routing pickers (provider editor, Routing page pools and group
  editor) mark the five as data-feature="rotation" (routingSegs), so off
  they offer Smart alone. i18n zh, zh-TW, ja, de.
- Docs: plugin-runtime.md router strategy section, gateway-routing.md
  (also drops a duplicated sentence about a lone key), reference.md.

Run in the worktree at this change (on origin/main fbfb76149):
- go test -count=1 ./... : 57 packages ok (gateway 587s)
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows
- GUI: full suite, chromium and webkit, every language: 9805 tests, 29
  red in 6 files. Each red alone the same way on origin/main bc470c6b6
  (just fetched): quota-count-wrap, quota-name-translated (#2228),
  refusal-retries-setting (#2258), routing-held-member (#2252), usage-fold
  (#2163), usage-agents-hide (#2276, from cf455ebd5). routing-save, builtins and
  rate-limited-sink pass in both engines.
- internal/gateway TestMain registers the strategies, so every routing test
  is the parity run with the plugin on; TestRotationOnAndOff turns it off
  (three Rotate sessions start k1,k2,k3 on, k1,k1,k1 off, no turn mark;
  Smart still served).

Rebased on origin/main 2b0037f41: go test ./... again, 56 packages ok at the
default timeout; internal/agent and internal/gateway passed with
-timeout 40m (1093s, 1039s: the machine at load ~17 with other sessions'
suites; the 10m panics stood in TestCodexAPIDisconnectStays and
TestCodexHeardWithinItsIdleTimeout, 1-2s in, no stack waiting on them).
Vets and gofmt clean again; routing-save, builtins, rate-limited-sink,
i18n-keys and the GUI files upstream changed pass.

Broken by hand, each test went red then restored:
- Apply's permutation check off: TestApplyFailsOpen
- Register's remove a no-op: TestRegisterStacks
- the plugin's Apply registers nothing: TestOnServesOffDoesNot
- InUse swallows providers.json's error: TestInUse
- routingOf passes an unserved routing through: TestRotationOnAndOff
- routingSegs not marking data-feature: routing-save.test.cjs "Smart alone"
2026-10-15 09:09:15 +08:00
yetone 2b0037f41d sessions: a Claude Code, Qoder or Cowork project folder, a session's folder or a Hermes profile behind a junction is read, not skipped (#2268, JasonBuildAI)
On Windows os.ReadDir lists a junction as ModeIrregular, neither IsDir
nor ModeSymlink, so a reader that goes into only IsDir() entries, or
IsDir() and ModeSymlink ones, walked past a folder kept on another drive
with a junction left in its place. ccFiles (Claude Code's own store,
Qoder's, Qoder CN's and Cowork's) skipped such a project folder whole, a
session's own folder (its subagents) and a workflow run's; HermesDirs
skipped such a profile. Sessions and Usage lost all of them, silently.
#2233/#2250 fixed walk roots (walkLinked); this is the entry check one
level in.

dirent.IsFolder is the one check now: an entry is a folder to read into
when it is one, or when it is a symlink or irregular entry that os.Stat
follows to a folder. A link to a file, a broken link and other irregular
entries are none. It follows only the entry asked about; none of its
callers recurses through one, so no visited set is needed.

Used at every reader of an agent's folder that picks entries this way:
- sessions: ccFiles' project, session-folder and workflow-run checks,
  HermesDirs' profile check, agyCallFiles' conversation check (IsDir only
  before, so even a symlink was skipped);
- agent: hermesProfiles and ompProfiles (IsDir only), so a linked profile
  still gets magpie's provider and its own row;
- library: desktopSkillRoots' org and account folders (IsDir only).
Left as they are, on purpose: WalkDir copies, hashes and deletes in
library and sessions/manage.go (they must not follow links), the
relocate code (it tells a link from a folder on purpose), library's
linkEntry (asks "is this a link", not "is this a folder"), magpie's own
folders (calls cache, gateway logs, OthersDir, backups, Bun, Devin
homes), and install/version detection (claudecode versions, VS Code
extensions, Desktop's folder name, Hanako's agents).

The issue's patch had sessions' own copy of library's linkEntry without
a Stat; this is a shared package and Stat-checked, so an irregular entry
that isn't a folder (a dedup or cloud placeholder file) isn't read as one.
docs/subsystems/gateway-sessions.md says how the readers treat links.

Run:
- New tests make real links, a junction (mklink /J) on Windows and a
  symlink elsewhere: TestIsFolder; TestClaudeProjectFolderBehindALink,
  TestClaudeSessionFolderBehindALink and TestHermesProfileBehindALink (the
  issue's), TestClaudeWorkflowRunBehindALink,
  TestAgyConversationBehindALink; agent's TestHermesProfileBehindALink and
  TestOmpProfileBehindALink; library's
  TestClaudeDesktopSkillRootsBehindALink.
- Broken by hand on macOS (IsFolder = e.IsDir()): all nine fail. Broken
  as before on the Windows box (IsDir() || ModeSymlink, no Stat):
  TestIsFolder and all eight reader tests fail there (e.g. "Claude
  session files behind a link: [], want [...]", "Hermes sessions behind
  a link: 1, want 2", "agy calls behind a link: 3, want 5"); with the
  fix all pass. Windows test binaries cross-built with go1.26.8
  (windows/amd64, nogui) and run on the box with a fresh sandbox
  USERPROFILE/HOME/APPDATA/LOCALAPPDATA/TEMP per run.
- Whole packages on the Windows box: dirent and sessions pass. usage,
  agent and library each have reds that fail the same with binaries
  built from origin/main 69d7ee33a: usage's
  TestDesktopSessionAccountMetadata (#1356/#1827), agent's
  TestFolderVarsAreListed (reads ..\gateway source the copied layout
  lacks), library's TestAgentsSkillsFolders,
  TestHooksCodexTrustMovesWithTheGroups and TestTargetsLeaveGoneAgentsOut
  (filed as #2275).
- gofmt -l: nothing. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./... and -tags nogui: clean.
- macOS: set -o pipefail; go test -p 4 -timeout 40m ./... on bc470c6b6
  plus this change: 56 packages ok, none failed. After rebasing onto
  origin/main 3a0b61275 (#2261's subagents, which touch sessions.go and
  the same doc): go test ./internal/sessions/ ./internal/dirent/ again.
2026-10-15 08:33:54 +08:00
yetone 3a0b61275f gui: the Sessions page nests subagents under their session and opens each one's conversation; Codex threads nest under their parent_session (#2261, infinitr0us)
Only main sessions sit at the top of the Sessions page now.

- A session with subagents shows an "N subagents" fold under its row. It starts folded.
  - Unfolding neither opens the session nor moves the page.
  - The rows are indented by the depth of the subagent that started them.
  - Clicking a row opens its conversation in place, via /api/sessions/transcript?sub=.
- Codex threads with a parent_session nest under that session, to any depth.
  - The parent chain is guarded against loops and capped at a depth of 8.
  - A thread whose parent isn't listed stays at the top.
  - A folder's count and its select-all include the nested threads.
  - Searching opens the folds that hold matches. Opening a nested session from elsewhere opens its ancestors' folds.
- New strings ("{n} subagent", "{n} subagents") in zh, en, zh-TW, ja and de.
- No native select and no left-border accent. The nested list is a bordered card.
- docs/subsystems/gateway-sessions.md describes the subagents field, the sub= route and the page.

What was run, at this head before the rebase (5618ade1e):

- internal/gui/tests/sessions-subagents.test.cjs (new): 40/40 pass in Chromium and WebKit, at widths 1100 and 420, in all 5 languages.
  - It checks the fold, the indentation and order, that the transcript is called with sub= and read once, and Codex nesting with a loop and a missing parent.
  - Its tidy check covers: no select, no left border, nothing wider than the page.
- Related GUI tests (sessions*, sess*, session*, i18n, routing-session, account-mask, click-scroll): 451/451 pass.
- Broken by hand, each restored afterwards:
  - Without nest(), the Codex test fails.
  - Without the fold, both tests fail.
  - Without &sub=, the Claude test fails.
- usage-agents-hide and usage-fold fail the same way on origin/main bc470c6b6, with or without this change. They are filed as #2211 and #2163.
- The full suite, go test -p 4 -timeout 40m ./... under a temp HOME at 5618ade1e with this change: green (exit 0).
- gofmt -l is clean. go vet passes for darwin, linux (-tags nogui) and windows.
- Real use: a sandbox magpie (temp HOME, ports 3486/3487) against read-only copies of real sessions.
  - Claude Code: the 5-subagent fold, and a real nested subagent indented one step whose conversation opened.
  - Codex: a real exec rollout pair, with the child's session_meta source rewritten to thread_spawn of the parent. Only the parent is at the top, and the child's details and conversation open in place.
  - Found on the way, and the same on main: a Codex Image Session Helper rollout is listed but can't be opened ("no such session"). Filed as #2273.

Rebased onto 69d7ee33a, whose new commits touch none of these files. Rerun at the rebased head:

- go test ./internal/sessions ./internal/gui: pass.
- sessions-subagents: 40/40.
- i18n-keys, sessions-* and claude-cloud-drift: 371/371.
- gofmt -l is clean.

Not tried:

- A real Codex rollout written as a subagent: none on this Mac, so the copied rollout above stands in.
- Real OpenCode children and real Kimi sessions.
- The GUI on Linux (WebKitGTK) and Windows.
2026-10-15 08:31:21 +08:00
yetone 69d7ee33ae agent: Codex with magpie as its provider (magpie API, or a ChatGPT account the app holds) no longer reads as joined beside its sign-in (#2267, isymbo)
isymbo's ChatGPT account ran out for the week, they set Codex's sign-in to
magpie API and picked DeepSeek, and the Codex app still showed "Codex 和
工作使用额度已用完" and sent nothing. The Agents row said "重开 Codex
后,/model 中既有它自己的模型,也有 magpie 的模型": the ChatGPT state
they had just left.

The config was right (model_provider = "magpie", magpie's catalog), but
the codex.joined mark from an earlier Join stayed, and Joined() read it
whenever openai_base_url was magpie's, which it also is with magpie as the
provider. Joined is now false while magpie is Codex's provider; the mark
itself stays, so Sync still puts Codex back beside the sign-in once the
account has room (codex.out), as before.

Why the app blocks: ChatGPT.app 26.1007.21159's two composer gates (FN in
app-primary and Cui/kui's hardBlocked in app-initial) both require the
app-server's getAuthStatus authMethod to be "chatgpt" and
rate_limit.allowed false. With magpie as the provider the app-server
reports no ChatGPT auth, so neither gate applies, but the app reads it
from the app-server it started with: it has to be quit and reopened. The
row now says "Reopen Codex, then pick any model in /model". Asked the
reporter to restart and, if it still blocks, for versions and config.

Test: TestCodexProviderIsNotJoined joins, picks a magpie model, sets
magpie API (provider, not joined, still wired), back to ChatGPT (joined),
held by the app (provider, not joined), room again (joined). Red with
Joined: joined ("magpie API: joined true").

Run, both commits together on 5618ade1e: gofmt -l clean; go vet ./...
for GOOS=darwin and windows clean, GOOS=linux clean on the 68 packages
that don't import Wails (the root, internal/cli and internal/gui need
cgo for Linux, which a Mac cross-vet can't do); set -o pipefail; go test
-p 4 -timeout 40m ./... green (rc 0).
2026-10-15 08:03:20 +08:00
yetone bc470c6b63 agent: Claude Code's own ANTHROPIC_MODEL comes back when magpie steps out
Wiring Claude Code in deletes env.ANTHROPIC_MODEL (writeTiers), because it
outranks a pick in /model. Unlike the tiers' models (#1050), the user's
own value was never stashed, so Disconnect or Claude Code's own model left
it gone for good. A Bedrock user like jw1dev keeps the Bedrock model id
there, so after the previous commit put the switch back, Claude Code would
come back on Bedrock without its model. ANTHROPIC_MODEL now joins
claudeOwnEnv: it is stashed raw beside the endpoint and token when first
routed from the user's own endpoint, put back by unroute, and forgotten
with the rest. A value an older magpie wrote, at its own key, is still not
kept (keyOurs), as before.

Run:
- gofmt -l: clean.
- go vet ./internal/agent: native, GOOS=linux -tags nogui, GOOS=windows:
  clean.
- go test -tags nogui ./internal/agent ./internal/gui: ok 4 times. One
  earlier run of the two together had internal/gui red, and only `tail -5`
  of it was kept, so the failing test's name was lost. It passed alone 3
  of 3 and with internal/agent 3 of 3. Nothing in internal/gui reads
  claudeOwnEnv.
- Targeted: ClaudeCloud, TestClaudeDisconnect, TestClaudePick, legacy,
  stand-in and T3 tests: ok.

Broken by hand: before the fix, TestClaudeDisconnect's new "own env
model" cases (with no settings model and beside one, [1m] kept; each by
Disconnect and by default) went red. The bedrock fixture of
TestClaudeCloudSwitchStepsAsideForMagpie now carries a Bedrock
ANTHROPIC_MODEL and compares the whole env after.

Not tried: WSL twins for real (the stash key goes through at.key as for
the tiers).
2026-10-15 07:41:30 +08:00
yetone 79fec406c6 agent, gui: a Claude Code provider switch (CLAUDE_CODE_USE_BEDROCK, …) steps aside while magpie is wired in and comes back after; one magpie can't take out is said (jw1dev on X)
jw1dev's ~/.claude/settings.json had CLAUDE_CODE_USE_BEDROCK=1. magpie wrote
ANTHROPIC_BASE_URL and its model ids beside it. Bedrock ignores the base URL,
so Claude Code went to AWS, Bedrock refused magpie's model, and magpie still
showed Claude Code as connected.

Claude Code 2.1.300's six switches (agentenv.ClaudeProviders: BEDROCK,
VERTEX, FOUNDRY, ANTHROPIC_AWS, ANTHROPIC_GOOGLE_CLOUD, MANTLE; on = 1, true,
yes or on, any case, trimmed):
- In a settings file magpie writes (user settings, WSL twins), a switch
  that is on is taken out on every route that writes the wiring: connect,
  model pick and Rewire/Reapply through writeTiers, and Sync. Its raw JSON
  value is stashed (claude.cloud.<var>, under the distro id for WSL). It is
  put back as written when magpie steps out (Disconnect, or the model set
  back to default), unless the user set it again since. AWS_*/GCP
  variables and a switch that is off stay.
- Where magpie doesn't write it (managed settings, ~/.claude.json's env,
  the login shell's env), Check names the variable, the cloud and the
  file. It reads them in Claude Code's own order: managed wins, then the
  user's settings, then ~/.claude.json, then the shell. Two notice
  templates, translated in zh, zh-TW, ja and de. The row's line and its
  Reconnect pill now show a drift detail through tNotice.
- proc.LoginEnv reads the switches but never sets them in magpie's env,
  and testenv unsets them.
- T3 Code: a switch is never carried onto magpie's instance. Its Check
  says when the user's ~/.claude settings have one on. That Check first
  checks the instance's ANTHROPIC_BASE_URL against the gateway (t3EnvOf),
  as every agent's Check must for TestDriftUnwiredEveryAgent,
  TestPortMovesEveryAgent and TestReverseProxyIsStillMagpie.
- Claude Desktop's Code tab runs with CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST,
  under which Claude Code ignores these switches in settings, so nothing
  changes there.

Run:
- gofmt -l: clean.
- go vet: native ./..., GOOS=linux -tags nogui, GOOS=windows: clean.
- go test -tags nogui ./...: every package ok except internal/agent, where
  t3code's first Check (cloud only) failed the three every-agent tests
  above. Fixed with the wiring check, then the whole internal/agent package
  was rerun: ok (368s).
- GUI, Chromium and WebKit, 102/102 each: new claude-cloud-drift (5
  languages, 1100 and 420px, file and shell notices), gui-de, gui-ja,
  gui-zh-tw, i18n-keys, agent-notice-lang, agent-proxied,
  agent-unreachable, cli-behind, menu-scroll, agent-connect,
  agent-disconnect.
- Sandbox HOME (scratchpad dir, live ~/.claude untouched):
  - Setup: real claude 2.1.300 with settings.json
    {CLAUDE_CODE_USE_BEDROCK:"1", AWS_REGION, AWS_PROFILE}, a magpie-cloud
    binary from this tree serving on 127.0.0.1:3487, a fake OpenAI
    upstream on 3486.
  - `magpie claude fake/fake-model` took the switch out and stashed "1".
  - `claude -p "say hi"` printed PONG-FROM-FAKE-UPSTREAM, and the fake
    logged POST /v1/chat/completions model=fake-model.
  - `magpie claude default` left settings.json byte-for-byte the same as
    before connect (cmp).
  - Control: the switch put back by hand beside the wiring (the reported
    state). Claude Code never reached magpie: the fake logged nothing.

Broken by hand, each went red:
- no dropClouds in writeTiers, then in Sync;
- putClouds returning at once, and putClouds writing over the user's own;
- no claudeCloud in Check;
- the T3 filter and the T3 Check;
- shellVars without ClaudeProviders;
- the tNotice calls taken out of the line and pill: claude-cloud-drift
  went 17 red.

Not tried:
- A project's .claude/settings.json(.local) isn't read, because magpie
  doesn't know where Claude Code runs.
- WSL and Windows were not run for real; tests only.
- Real Vertex, Foundry and AWS accounts.
- T3 Code and Claude Desktop with a switch, run for real.
- The drift shown in the real app window. The CLI has no drift output.
- The user's own ANTHROPIC_MODEL being lost across connect/disconnect is a
  separate gap, fixed in its own commit.
2026-10-15 07:41:30 +08:00
yetone 94bceea4d2 lessons: fold 10-14 04:16 to 10-15 07:30 (275 commits, v0.1.1229 to v0.1.1244)
New lessons: an origin exemption judges every Origin a browser can send
(#2242, #2256; seen 2x with the 10-10 rebinding case); a file another
process rewrites may be half-written; a pinned hash or new download
source is checked against the vendor and trusted as far as who can write
it; a fixed date in a test is checked against every clock the code reads
(3c4b4dc97 -> 21aa40285); a new field on a polled endpoint is costed at
the poll rate; a full run gives slow packages -timeout 45m; a community
layout PR is not merged on review alone (#1354).

Evidence added: five fixed-wait CI reds under the timing habit, unfiled
reds and a cancelled run that tested nothing, a second oversized squash
subject (seen 2x), "see the push" as a run record and plugins#56 under
the moved standards. ggbdpq's Watched row notes 94e3b3f52 and the
red-before/green-after fixes since.

Every cited sha was checked with git log; claims were checked against
their commit bodies. Ran: go test -tags nogui -count=1 -run
TestLoopGuardLeavesOrdinaryRepliesAlone ./internal/gateway (reads
LESSONS.md): ok. Docs only, no code.
2026-10-15 07:35:13 +08:00
yetone 5618ade1e6 sessions: each reply in a session's conversation names the model its own line in the agent's file names (#2253, cnlove7777777-art)
Usage -> Sessions' conversation said only "Assistant", so which model
wrote a reply couldn't be told, though the agents' files name it.

- sessions.Part gains model (omitempty), set on assistant parts only,
  from the part's own line: Claude Code's message.model (the model that
  answered; none for its "<synthetic>" lines), Codex's
  turn_context.model (the model the turn was sent to; a /model between
  turns moves the next turn), Pi's and omp's message.model, OpenCode's
  modelID and OpenCode 2's model.id.
- Kimi Code (its model is only on a usage.record written after the
  reply), Cursor (no model in the transcript) and gateway transcripts
  (GatewayTurn.Model is the model asked for, not the one that answered)
  name none. Nothing is guessed from nearby requests.
- The reader (sessions client.js) says it muted after the role, once a
  reply at its first part and again only where it changes inside the
  reply; the tooltip is "Model: <id>" (an existing string, translated).
  ledSaid takes the model as an argument, so the Usage page's
  per-request content, whose row already names its model, is unchanged.
  No layout change: one muted span in the existing header line,
  ellipsized at narrow widths.

Run:
- TestTranscriptModelClaude/Codex/Pi/OpenCodeV2/OpenCodeFiles: all five
  fail on the old content.go/transcript*.go, pass on the new.
- sessions-talk-model.test.cjs: 20/20 (chromium+webkit, en/zh/zh-TW/
  ja/de, 1100 and 420). Fails on the old app.js/client.js, and with the
  once-a-reply rule removed by hand (label every assistant part).
- sessions-talk, sessions-export, gateway-conversations,
  usage-ledger-content, usage-ledger-detail GUI tests: all pass.
- go test -tags nogui ./internal/sessions ./internal/gui
  ./internal/gateway: ok. gofmt -l clean; go vet -tags nogui darwin/
  linux/windows clean.

Full suite for this push (#2257, #2251, #2254, #2253) at 53677ed8d:
go test -tags nogui -p 4 -timeout 40m ./... with pipefail: every
package ok. (An earlier full run caught davsync's TestSyncLibrary and
profile's TestOldProfiles/TestProfileCarriesLibrary relying on a gone
CLI after #2254; their sandboxes now have the CLIs, in #2254's commit.)

Not tried: the real app against a live Codex rollout (fixtures follow
the lines the readers already parse for usage).
2026-10-15 06:07:43 +08:00
yetoneandggbdpq e413512d8e library: an agent whose CLI is gone (only its config folder left) is no Library write target, and nothing it already has is removed (#2254, ggbdpq)
After an agent is uninstalled, the Agents page shows "CLI not found"
(d0fcb8bc), but Library still offered it for skills, MCP servers, shared
instructions and rtk, and a sync wrote into a folder nothing reads.

- library.Targets() leaves out an agent whose CLI is missing
  (agent.CLIMissing: false for WSL, plugin and detect agents), so sync,
  the read view, market, instructions, skills and found servers all
  drop it at their one upstream.
- Takes() refuses a gone agent by name, so `library mcp add ...
  agents=hermes` says "Hermes Agent's CLI isn't installed here; nothing
  reads its MCP servers until it is installed again" instead of "every
  agent already has it".
- The guards that must still see a gone agent's files (projects'
  notGlobal for skills and MCP, instructions' own-file check) read
  everyTarget(), so a set kept in the agent's own file is still refused.
- rtk: a gone agent isn't offered rtk; one that still has the hook is
  listed so the hook can be taken out.
- Nothing a user wrote is removed: sync acts per target, so a gone
  agent's skills, servers and AGENTS.md stay as they are, and the client
  keeps agent ids it doesn't show.

Run:
- Sandbox HOME, real binaries: old wrote mcp_servers into a gone
  ~/.hermes/config.yaml; new refuses with the message above, exit 1.
- New tests TestTargetsLeaveGoneAgentsOut, TestGoneAgentKeepsWhatItHas,
  TestRTKLeavesGoneAgentsOut; each broken by hand (Targets check,
  Takes refusal, everyTarget in instructions, rtk gate) goes red.
- go test -tags nogui ./internal/library ./internal/tui ./internal/cli
  ./internal/gui: ok. Fixtures that relied on a gone CLI now place one
  (holdCLI, TestRTKHermesHome, TestRTKOffPath), and so do profile's
  and davsync's sandboxes, whose library syncs to claude and codex
  (TestOldProfiles, TestProfileCarriesLibrary, TestSyncLibrary went red
  in the full run without them).
- gofmt -l clean; go vet -tags nogui darwin/linux/windows clean.
- go test -tags nogui -p 4 ./... at the pushed head: see the last
  commit of this push.

Not tried: the real GUI with an uninstalled agent on a live machine.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 06:07:43 +08:00
yetoneandggbdpq c3bef99efd provider: magpie://import links take gemini=, and its host is named before adding (#2251, ggbdpq)
An import link could set chat=, responses= and anthropic= but not
gemini=, though the editor and the TUI take a Gemini base URL; a link
with only gemini= failed with "it needs chat=, responses= or anthropic=".
ParseImport now reads gemini= under the same base-URL rules, and the
error names it (ggbdpq's patch, with docs/reference.md and the en/zh
docs rows).

Its siblings that listed the three base URLs:
- the GUI's import dialog warned "Your prompts and this key will go to ;"
  with no host for a gemini-only link: it names the Gemini host now;
- the site's handoff page (site/public/import.html) left it out of
  "Sends to";
- the docs' link builder (en, zh, ja) had no Gemini field and didn't
  count it as a base URL; the ja docs lacked the table row, and all
  three said one of chat/responses/anthropic is required.

Run:
- TestParseImportGemini fails on the old importurl.go ("the link gives
  no base URL: it needs chat=, responses= or anthropic="), passes now;
  go test -run Import ./internal/provider/ ./internal/gui/: ok.
- import-link-gemini.test.cjs: 20/20 (chromium+webkit, en/zh/zh-TW/ja/de,
  1100 and 420 px); against the old app.js the warning reads "will go to
  ;" and it fails.
- docs builder (en/zh/ja) and handoff page in Chromium from file://: a
  gemini-only builder gives magpie://import?name=…&gemini=…, no errors;
  the handoff page lists gem.example under Sends to.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
Not tried: a real magpie://import click through the OS handler.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 06:07:43 +08:00
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