Commit Graph
766 Commits
Author SHA1 Message Date
ggbdpq a786c51cb0 agent: a magpie-models.json that doesn't parse is kept aside, not written over or removed whole
What changed: #2263 gave magpie's state files whose reader takes an
unparseable file as empty the lastgood.KeepUnparsed copy-aside, and its
sweep named the files it covered. Codex's magpie-models.json was in
neither its covered list nor its cache exemption, and its reader has the
exact missed shape: codexcat.Keep (#1450) returns the new list for a
file it can't parse, and the next sync, model switch or stepping back in
wrote that over the file, ending the keys the user added by hand
(supports_reasoning_summaries and friends) with no copy. Stepping out
was worse: dropList took an unparseable file for one holding nothing of
the user's and removed it outright.

Now the three writers of the list go through writeOwnList, which keeps
an unparsed file aside (magpie-models.json.bad-<time>) before the write
and stops when the copy can't be made, and dropList keeps one aside
before it removes the file.

Run:
- gofmt -l internal/agent: clean.
- go test -tags nogui -p 2 -count=1 -timeout 25m ./internal/agent: ok
  (183s).
- TestUnparsedCodexCatalogKeptAside fails on the code before this ("the
  unparsed list was written over with no copy kept"); the ablation
  replays it against this commit's parent.
- go vet -tags nogui ./... for darwin, linux and windows ok; go build
  for the three ok (reviewer, at the batch head).
Full suite: go test -tags nogui -count=1 -timeout 45m ./... ok, every
  package (reviewer, at the batch head before #2424 was added).

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-16 00:16:43 +08:00
ggbdpq d830d460f0 provider: a refused keychain read is not asked again for ten minutes (#2408)
What changed: copilotCLISecret backs a denied keychain read off (10
minutes, "don't ask again at once"), but the two other readers of the
same family took every failure as an absent item and asked again after
their ordinary 10s TTL. On macOS a denied item prompts again on every
read, so a user who answers Deny once was asked again every 10 seconds
while Cursor's status or Claude's credentials were polled, and every 10
minutes only for Copilot (#2408's report is the Copilot face of this).

Now cursorKeychainToken and readClaudeKeychainItem (through
claudeCredential's cache) treat any `security` failure but 44 — the item
not being there, which asks nobody — as a read that may have shown the
user a dialog, and don't repeat it inside keychainDeniedTTL (10 minutes,
copilot's own pause). A sign-in or out in magpie reads afresh
(forgetCursorStatus, forgetClaudeCredential clear the pause), and a
fresh read in CursorToken is unchanged.

Run:
- gofmt -l internal/provider: clean.
- go test -tags nogui -p 2 -count=1 ./internal/provider: ok (72s).
- TestDeniedCursorKeychainReadIsNotAskedAgain and
  TestDeniedClaudeKeychainReadIsNotAskedAgain fail on the code before
  this (a refused read asked again 11s later).

Not tried: a real macOS keychain dialog answered no (a fake `security`
stands in for it); Copilot's own reader is unchanged.
- go vet -tags nogui ./... for darwin, linux and windows ok; go build
  for the three ok (reviewer, at the batch head).
Full suite: go test -tags nogui -count=1 -timeout 45m ./... ok, every
  package (reviewer, at the batch head before #2424 was added).

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-16 00:16:43 +08:00
yetone 682e4253bf gateway: a Gemini call's thought signature is kept on disk and its id carries a 16-character key, not the signature — ids were 3KB+ and broke a client's PostgreSQL index (#2411, liangxyz)
Since #687 a tool call Gemini signed went to the client with the signature
inside its id (<id>__ts<n>__<base64url>), so the client's next request
brought it back. A Gemini 3 signature is often 2–6KB, so ids were too: LobeHub
stores tool_call_id in a btree index, whose rows are capped near 2.7KB, and
the write failed.

The signature is now written to <settings>/gemini-signatures/<key>, the key
being 12 bytes of its SHA-256 in base64url, and the id carries
__tsk16__<key> (≈36 characters). Coming back, the file is read and its hash
checked against the key; a file gone or changed is no signature, and the
call goes to Gemini with skip_thought_signature_validator, as an id a client
shortened already did. A file is touched when it is read or written again
and pruned 90 days after its last use (at most once an hour, on a write);
temp files from a write cut short go after an hour. When the folder can't
be written, the signature still rides in the id as before. Ids made before
this (__ts<n>__, __tsr<n>__, __ts__) are still read.

Real use: a sandbox HOME magpie serve with the owner's Antigravity account
copied in, antigravity/gemini-3.8-flash-high, a two-turn tool call over Chat
and over /v1/messages: ids came back as call_659137__tsk16__cOTtfB5LubcVSNaX
(36 characters), turn 2 answered from the tool result, and the store file
(584 bytes) was born on turn 1 and touched on turn 2's read.
gemini/gemini-3-flash-preview answered 502 (Gemini CLI no longer
supported), unrelated. Not tried in LobeHub itself; asked on the issue.

Tests: TestFortyCharacterIDThroughGateway now keeps the real signature
through a 40-character id; TestLongSignatureGivesShortID (6.4KB signature,
id ≤ 64, round trip); TestKeptSignatureGoneOrChanged; TestUnkeptSignature-
RidesInTheID; TestOldSignaturesPruned. Broken by hand: keepSignature
disabled fails FortyCharacter and LongSignature; the hash check removed
fails KeptSignatureGoneOrChanged.

Ran: gofmt; go vet -tags nogui ./internal/gateway/ for darwin, linux,
windows; targeted tests -count=3.
Full suite: go test -tags nogui -count=1 ./internal/gateway/ ok (466.9s);
the rest of the suite ran green on the batch this is rebased onto
(386d341e7).
2026-10-16 00:16:43 +08:00
yetone a7a0122027 gui, gateway: the search grip's place is a class, not :has(), and Go no longer says the Routing plugin's words (batch GUI reds)
The full GUI run on this batch had two reds that are real, both from
commits in it:

- old-webkit "the styles hold up in Safari 15.0": 4b69460d1 (#2286)
  placed a search API's grip with `.search-unit:has(> .search-keys)`,
  which Safari before 15.4 can't parse. The unit now gets a with-keys
  class where its keys' row is added, as other rows in app.css do.
- i18n-keys "a plugin's words are its own": 7ff5f595e's test name
  TestArkDrawsUnmarkedOncePerImage and f9ccca71e's comments in active.go
  and left_in_flight_test.go said "Unmarked" and "answering…", which are
  plugins/routing's words. The test is TestArkDrawsWithoutWatermarkOncePerImage
  (the subsystem page renamed with it) and the comments say it in other words.

Run: node --test i18n-keys (3/3), search-order (16/16), old-webkit and
mobile-web alone; gofmt; go vet -tags nogui ./internal/gateway.
Not checked by a test: the grip's top under a unit with keys; the rule
is the same, only its selector changed.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone d6b045a7e7 usage: the Overview's lists fold under their headings and stay folded, the token totals can count the cache, and the Requests Tokens card wraps its cache count instead of cutting it (#2378)
The reporter asked for three things on the Usage page: fold Agents,
Models and Accounts from their titles and remember it (日常看账号维度
较多,都要拉到最底下); an option to count the cache in the token totals;
and the Requests tab's Tokens card cut its cache count off on a wide
window ("缓存 879…").

- Folds: each Overview list's heading (Agents, Models, Accounts, and
  Gateway keys beside them) is a .fold button with its chevron, the
  Gateway page's pattern. A click keeps the page still (backToReader).
  What is folded is kept per viewer in localStorage magpie.usageFolded
  (mountUsageFolds at the plugin's mount, showUsageFolds per render).
- Cache: the tokens tile's label is a pop-up (usageTokensPick, the app
  menu, no <select>) of Without cache / With cache, kept in
  localStorage magpie.usageWithCache. With cache, the tile, the chart,
  and every row's count and share add cache read and written
  (usageTokens), and the tile says the cache's count. Default unchanged.
- Cut count: a token line in parts (the Requests strip's Tokens card,
  the Overview's tokens tile) wraps between its counts and keeps each
  whole (usageParts, .parts); only a count wider than its card on its
  own is cut. The part spans undo .kpi span's label capitals.
- Strings in zh, zh-TW, ja, de. docs/subsystems/gui-shell.md bullet.
- mobile-web.test.cjs: until BASE_REF has mountUsageFolds, the
  desktop Usage comparison puts the new fold buttons and the pop-up
  back to their plain labels and compares the rest as before. That
  comparison caught the tile's line in the label's capitals and 5px
  taller; both fixed, and usage-overview-fold now checks them.

Run at this head (base dd25997a4), BROWSER=chromium and webkit each,
single files:
- usage-overview-fold (new, en/zh/zh-TW/ja/de at 1100 and 420 on the
  Overview, 1500/1100/420 on Requests; the ledger fixture is the
  reporter's numbers, zh in 万/亿 as they read them): 26/26 both.
- usage-accounts, usage-hit-rate, usage-ledger-fit, usage-ledger,
  usage-ledger-agent-middle, own-requests, mobile-web,
  usage-speed-count, usage-sum-whole, usage-head-steady, i18n-keys,
  click-scroll, number-units, gui-zh-tw, gui-ja, gui-de: all pass
  both engines.
- usage-agents-hide: 5 pass, 11 fail in both, "unhiding a row leaves
  the hidden line where it was", identical with this change taken out
  at dd25997a4: #2276, open.
Broken by hand, chromium, each red then restored: the .parts CSS gone
(9 red, among them zh 1500 cut at "缓存 8793.3 万"); folded lists not
hidden (11 red); the cache never counted (11 red, 8.1M vs 568M); the
parts' label-style reset gone (11 red, uppercase/600).
No Go changes, so no gofmt or vet. Not tried in the real app.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone b6fae8efd8 gateway: an advisor magpie leaves out takes its instructions and tool_addition with it, so the model no longer calls a tool it hasn't got (JackChou on Discord)
JackChou: "claude code 使用 advisor 返回找不到对应工具". Claude Code 2.1.300
(its request read from a fake ANTHROPIC_BASE_URL in a sandbox HOME, with
--advisor and a fake key) declares the advisor as the server tool
{"type":"advisor_20260301","name":"advisor","model":…,"defer_loading":true}
and also puts it in the conversation: a {role:"system"} message whose text
ends in "# Advisor Tool … call advisor BEFORE substantive work", and a
{"type":"tool_addition","tool":{"type":"tool_reference","name":"advisor"}}
block.

79f64f028 left the server tool out where the upstream can't run it (a
vendor's model, another provider's advisor) and every translation drops
server tools, but both left the instructions and the tool_addition in place.
The model was told to call advisor() and given no such tool, so it called it
as one of the agent's tools and Claude Code answered "No such tool
available: advisor"; on Messages the tool_addition also named a tool the
request no longer declared.

Where magpie leaves the advisor out, withoutAdvisor (passthrough) drops the
tool_addition/tool_removal/tool_reference naming it, and a message left
empty, and replaces the instructions (up to the end of their reminder or
text) with Claude Code's own "The advisor tool is no longer available;
disregard the earlier advisor instructions." parseAnthropic does the same to
the text on a translation. An advisor that is kept goes as before.

Run: TestAdvisorModelAsTheUpstreamNamesIt (now on the literal 2.1.300 turn
in testdata/claude-code-advisor-turn.json, environment text cut short) and
the new TestAdvisorLeftOutOnTranslation (chat, responses, gemini). Broken by
hand (withoutAdvisor given no names, parseAnthropic not rewriting): both
red, the two left-out passthrough cases and all three translations; green
restored. go test -tags nogui -p 1 -run
'Advisor|Deferred|BillingLine|Shape|Anthropic|ToolSearch|TurnSystem|Passthrough'
./internal/gateway ok. gofmt -l clean; go vet -tags nogui ./internal/gateway
for GOOS darwin, linux, windows.

Not tried: a running magpie with real Claude Code end to end, and a real
vendor upstream; the reporter's provider and model aren't known, so whether
theirs was the passthrough or a translated route is inferred.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone d98e17808b gateway: a refusal that comes as an error ends the try at once, is read across writes after content, and the high-risk message alone is one (#2400, Jichao)
Three gaps Jichao reported, each reproduced on origin/main 4a6bf80f4
with fake upstreams before the change:

1. An HTTP error or stream error event whose message is, whole, "The
   request was rejected because it was considered high risk" with no
   policy code was any failure, not a refusal: no refusal fallback.
   policyRefusal now takes that exact message (trimmed) as a refusal
   (highRiskRefusal). It reads only an error's own message field, so an
   answer that quotes the sentence stays an answer. The vendor that sends
   it isn't known (no wire capture; none of our code or docs has it); it
   says the request was turned away, so it rests nobody and goes to the
   next candidate under RefusalRetries, like every refusal.
2. A policy error event before any content (content_filter, coded) left
   the held try waiting for the upstream's EOF: with the connection kept
   open the request hung until the client gave up. Such an event is now
   eventRefusalError and stops the try as eventError does; a refusal's
   stop/finish marker (eventRefusal) is still read to the end for its
   trailing usage and terminator.
3. After content, refusalAfter skipped a write that didn't look like a
   refusal, so an "event: error" whose name and data came in separate
   writes was never noted (a coded content_filter too). Every write is now
   read; only an unfinished event's bytes are kept, so a reply's content
   isn't copied. refusalSays matches the bare word error for the named
   event. Nothing already sent is replayed.

Reference patch by Jichao (585836c on Jichao/magpie
fix/provider-refusal-errors), reviewed line by line and taken with
changes: refusalAfter no longer appends every write to a buffer, the
message is a named const with why, the doc line is rewritten, and the
split test gains a coded named error (red on main without the message
match). No new retries or fallbacks: everything goes through the
existing refusal path.

Run (darwin, sandbox HOME, -tags nogui -p 1):
- New tests on main without the fix: TestHighRiskErrorMessage,
  TestHighRiskErrorFallsBack, TestRefusalErrorDoesNotWaitForEOF (hung to
  the 10s guard), TestHighRiskErrorWhenRetryStops,
  TestHighRiskTextAndStartedReplyAreNotReplayed,
  TestHighRiskNamedErrorAfterContentRestsNobody,
  TestHighRiskErrorSplitAfterContent all red. With it, ok.
- Broken by hand, each red: no stop on eventRefusalError
  (TestRefusalErrorDoesNotWaitForEOF), the per-write prefilter back
  (TestHighRiskErrorSplitAfterContent), the message case off (the
  TestHighRisk* set).
- -run 'Refus|Refuse|Hold|Fallback|StreamEvent|Late|Policy|Safety' ok;
  -race on 'TestHighRisk|TestRefusalErrorDoesNotWaitForEOF|Refus|
  StreamEvent|Hold' ok.
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows ok.
Not run: the full suite, any real vendor.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone 6e17d58ebf usage: a top session only the gateway saw says "Gateway session", not "(no prompt)" with no folder (#2285)
The reporter's Usage › Sessions card listed seven Pi sessions on
deepseek-v4-pro as "(no prompt)" with no folder, and their routing group
has no DeepSeek. Those rows were gateway projections: Pi asked magpie for
deepseek/deepseek-v4-pro (every served model is in Pi's models.json), most
likely through a pi-subagents child, whose session file is in a temp folder
magpie never reads. The card gave no sign of that, so it read as Pi's own
sessions with an empty prompt, and our first reply took it that way.

The overview's summaries from MergeExternalStats now carry gateway: true,
as MergeExternal's list rows already did. The card shows "Gateway session"
where the folder would be, "(prompt not recorded)" as the title when no
text was kept, and a tooltip pointing to Record gateway conversations.
Strings in zh, zh-TW, ja and de. gateway-sessions.md says it.

Run in this worktree (a1f7b8c13 base):
- go test -tags nogui -p 1 -count=1 -run 'TestTopSessionsMarkWhatOnlyTheGatewaySaw|TestGatewaySession|Overview|Session' ./internal/gui/: ok
- go test -tags nogui -p 1 -count=1 -run 'External|Overview|Stats|Gateway' ./internal/sessions/: ok
- Gateway: true removed by hand: TestTopSessionsMarkWhatOnlyTheGatewaySaw red
  (the Pi record, provider deepseek, came back with cwd "" and title "",
  no gateway field), green with it back.
- sessions-overview.test.cjs: 28/28 in chromium and webkit; with the
  page.js change undone by hand, red in en and zh ("(no prompt)").
- i18n-keys, gui-zh-tw, gui-de, gui-ja (chromium): pass.
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows on
  internal/sessions and internal/gui: ok.
Not run: the full Go suite and the full GUI suite.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetoneandfangzhengjin 3f4186fd8e providers: a provider you added can skip its own host's certificate check, nowhere else (#2383, fangzhengjin)
A vLLM on the LAN, an Ollama behind a self-signed certificate or a
company CA can't be reached over https today. A custom provider now has
"Don't check its certificate" (Certificate, in its editor, shown while an
address is https), with a short risk note, in en/zh/zh-TW/ja/de.

Scope, enforced in Go, not only in the GUI:
- Only a provider the user added with their own base URL takes it
  (TakesInsecureTLS: no preset, no account, no Vertex, no subscription
  id). Save refuses it on anything else, and Via ignores a hand-set flag.
- It reaches the hosts of the provider's own base URLs alone
  (netproxy.WithUncheckedTLS): a redirect elsewhere, a models/balance/
  image URL on another host, and a nested request for another provider
  (With drops it) are still checked.
- Every route: it is set in Provider.Via, which the gateway's attempt and
  forwardOnce (count_tokens too), List, Test, Detect, balance, draw,
  embeddings and video all go through.
- The unchecked host gets its own cloned transport (the route key holds
  the flag), so the leave never reaches another request. An https://
  proxy is refused for it, because its TLS would be dialled with the same
  config and go unchecked too; http:// and socks5:// proxies work.
- The editor shows the saved value, Test/Detect/Fetch carry it before a
  save, and a save that omits it keeps it. Backup, export and WebDAV sync
  carry it (backup.Collect).

Rewritten from fangzhengjin's fork 749e82a25 rather than applied: it had
no Go-side limit to custom providers, set InsecureSkipVerify for every
host the provider's requests reached (redirects, other hosts, nested
requests) and for an https:// proxy's own certificate, never showed the
flag back to the editor (the next save cleared it), and didn't carry it
into Test/Detect/Fetch. Its transport cache key holding the flag is kept.

Run in this worktree (-tags nogui -p 1, sandbox HOME):
- go test -run 'TestUnchecked|TestWith|TestDispatch' ./internal/netproxy ok
- go test -run 'TestInsecureTLS|TestVia|Proxy' ./internal/provider ok
- go test -run TestInsecureTLS ./internal/gateway ok (chat, responses,
  anthropic, count_tokens, gemini against a self-signed server)
- go test -run 'TestProviderSaveInsecureTLS|TestProviderSaveKeeps|Typed'
  ./internal/gui ok
- go test ./internal/backup ok
- GUI provider-insecure-tls.test.cjs: chromium 30/30, webkit 30/30
  (en, zh, zh-TW, ja, de at 1100 and 420)
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows on
  netproxy, provider, gui, gateway, backup clean

Broken by hand, each went red, then restored:
- With not clearing the leave -> TestUncheckedTLSOnlyItsHost
- the https:// proxy guard off -> TestUncheckedTLSStillChecksItsProxy
- TakesInsecureTLS always true -> TestInsecureTLSNotForPresetsOrSubscriptions
- Via not setting it -> TestInsecureTLSOwnProviderOnly and all 5 routes
  of TestInsecureTLSEveryRoute
- backup field tagged json:"-" -> TestRoundTrip
- save not keeping an omitted flag, providerInfo not showing it ->
  TestProviderSaveInsecureTLS
- draftOf/asTyped not carrying it -> 2 of 3 GUI tests (en 1100 chromium)

Not tried: a real vLLM or Ollama behind a self-signed certificate; the
image, video, balance, embeddings and draw routes are covered through
Via, not each by its own test. The full suite was not run.

Co-authored-by: fangzhengjin <12680972+fangzhengjin@users.noreply.github.com>

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone dc8dcc85d1 provider: a custom Balance URL can be asked with POST, for an endpoint that answers only a POST (#2368, yaofeng)
A custom provider's Balance URL was always asked with GET, so a balance
endpoint that takes only a POST answered 405 and the card never showed.

- Provider.BalanceMethod ("" or GET, or POST with no body). It applies to
  the user's own Balance URL only; a vendor magpie knows is asked as
  before. balanceMethodOf refuses any other value before anything is sent.
- CLI: `magpie provider set <id> balance.method=POST` (GET clears it; any
  other value is refused and the saved one kept); `magpie provider <id>`
  shows "from POST <url>".
- GUI: a GET/POST segmented control (segs, not a <select>) beside the
  Balance URL in More endpoints, aria-labelled and titled in en, zh, zh-TW,
  ja and de. Check balance and Save carry it; a preset's save keeps it.
- No vendor preset or name is added. A string amount ("0.94306040") was
  already read by number(), so `$usd_balance` reads as any field does.
- docs/subsystems/providers-accounts.md says it.

Run:
- go test -run TestBalance ./internal/provider/: ok. New TestBalanceMethod:
  a POST-only httptest server, POST (any case) reads $0.94 from a string
  usd_balance, "" and GET are still GET (405 is an error), PUT, DELETE and
  a CRLF value are refused with nothing sent.
- go test -run TestProviderSetBalanceMethod ./internal/cli/: ok.
- Broken by hand: the request always GET turns TestBalanceMethod red
  ("asked GET, want POST"); balanceMethodOf passing any method turns it red
  (PUT and DELETE sent); the CLI taking any value turns
  TestProviderSetBalanceMethod red; the Check balance body without
  balanceMethod turns 20 of 21 balance-method.test.cjs cases red, and
  origin/main's app.js all of them.
- GUI: balance-method.test.cjs 42/42 (Chromium and WebKit, 1100 and 420,
  en, zh, zh-TW, ja, de, saved GET and POST: opens on the saved method,
  named and titled in the language, fits beside the URL with no page
  scroll, the other pick goes in the check and save bodies). Siblings:
  balance-parts, balance-field-default, balance-fix, catalog-hint,
  duplicate-pause, key-balance-card, local-address, provider-base-api,
  provider-auth-header, provider-gemini, provider-search,
  provider-url-each-api, gui-de, gui-ja, gui-zh-tw, i18n-keys: 250/250.
- Real use: the built binary in a sandbox HOME, a custom provider at a
  local server that answers GET 405 and POST {"usd_balance":"0.94306040"}.
  Default: "unavailable 405 Method Not Allowed"; balance.method=post:
  "$0.94 from POST …/api/check-balance $usd_balance", the server saw one
  POST with Content-Length 0 and the Bearer key; balance.method=PATCH
  refused. NanoGPT itself was not asked (no key here).
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.

Suite run here: HOME=<sandbox> go test -tags nogui -timeout 45m ./...: 62
ok, internal/gui FAIL only on TestSetAnswersWhileDevinAndProvidersHang
(a state took 11.97s, load ~180), open as #1375; it passes -count=2 alone.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone afb0ff7720 gateway: a tool Pi adds in a message of its own joins the request's tools on every route, once by name (#2322, deephbz)
Pi 1.2.0 with supportsMidConvoToolAdditions sends a tool it adds
mid-conversation as {"role":"system","tools":[...]} with no content and
keeps top-level tools as they were. parseChat read only top-level tools
and the Chat relay sent the message on as it came, so the tool could be
called on no route, and the tools-only message became an empty part of
the system text ("</cwd>\n\n\n\nUpdated ...").

liftMessageTools (message_tools.go) moves message tools into the
request's tools. handle does it for every Chat body, before serveAgent,
so the Chat relay, schema fixers, redaction, the prompt shown and
routing all see them; parseChat does it too for a body that never came
through handle. Each tool joins once by name and the first definition
wins (top-level, then the earliest message's), as liftAdditionalTools
and a tool_addition in withoutDeferredTools do. A system or developer
message that carried only tools is left out; one with content keeps
its place without tools. Message order is unchanged: the in-place
system message / inline-tools beta part of #2322 is not in this commit.
6312af989 (#2338, inline-only tool_addition joins tools) is not on
origin/main a1f7b8c13, so this builds on neither; the rule matches it.

Tests, from deephbz's literal Pi 1.2.0 request (last comment on #2322):
TestPiAddedToolReachesEveryRoute (Chat relayed to an OpenAI-compatible
upstream, Messages, Responses, Gemini, Codex), TestPiAddedToolOffered-
ToClaudeCode (the Claude subscription bridge's MCP tools.json, a fake
claude; skipped on Windows), TestMessageToolsFirstDefinitionWins.

Run (sandbox HOME, -tags nogui -p 1):
- go test ./internal/gateway -run 'TestPiAddedTool|TestMessageTools|
  Chat|Messages|AdditionalTools|Lite|Deferred|ExtraBody|Gemini|
  CodexAccessPrograms|Developer|ThinkingEffort|Kimi|DeepSeek|ClaudeRun|
  ClaudeSubscription|Strict|Prompt' -count=1: ok (75.8s)
- broken by hand: liftMessageTools a no-op -> every route subtest, the
  bridge test and FirstDefinitionWins red (tools [lookup_pantry], empty
  system relayed, "\n\n\n\n" in the system text); only handle's lift
  removed -> chat relayed red; only parseChat's lift removed -> the
  bridge test and FirstDefinitionWins red.
- gofmt -l internal/gateway: clean; go vet -tags nogui ./internal/gateway
  for GOOS=darwin, linux, windows: clean.
Not run: other packages, the full suite. Not tried with a real Pi or a
real upstream.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetoneandZhengJin cc09c5bd97 stepfun: a Step Plan sign-in is the provider's own, not its site's: two accounts on one site show their own windows (#2384)
stepfun-auth.json kept one platform session per site ("ai", "com"), so
every StepFun provider on a site shared it: bringing a sign-in to one
signed in all of them, two accounts showed the same windows, and signing
one out signed out all (fangzhengjin, #2384). Sessions are now kept by
provider id; the site, which platform is asked, is still the provider's
(StepFunSite). StepFunSignedIn, SaveStepFunSession, SaveStepFunPaste,
SignOutStepFun, stepfunNow and stepfunAsk take the id, and
stepPlanQuotas gives one card per signed-in provider, not one per site.

Nobody signs in again for the upgrade: a file still keyed by site is
given, on read, to the StepFun providers on that site (stepfunBySite) and
written back through the temp-and-rename write. One provider: it's
theirs. Several: each gets it, so nobody loses their windows, and the
user brings the other account's sign-in to the ones that are someone
else's. Those copies are one sign-in, so stepfunNow renews every entry
holding the same refresh token together; renewed apart, the platform
could end the token the first renewal replaced and sign the others out.
With no StepFun provider on the site yet (or providers.json unreadable)
the old entry waits as it is. A file that doesn't parse, or that holds an
entry of another shape, is read as no session and nothing but a new
sign-in writes over it, after lastgood.KeepUnparsed has kept it aside.

Every other place keyed by the provider follows: Delete drops its
session (a provider added later under the same id doesn't inherit it),
Rename moves it, and the GUI posts /api/stepfun/{id}/session and
/api/stepfun/{id}/signout, 404 for an id that isn't a StepFun
provider's (a site's name among them). Backup and sync never carried
stepfun-auth.json, so nothing changes there.

Built on fangzhengjin's stepfun-per-provider branch (996cf969e), which
rekeyed the session by id. Not taken from it: it made every existing user
sign in again, left Delete and Rename on the old keys (a renamed provider
lost its sign-in, a removed one's was inherited by a new provider of the
same id), let signout take any id, and its two-provider test checked
only the stored Account, never each provider's windows.

Run at this head (on origin/main a1f7b8c13), -tags nogui -p 1, sandbox HOME:
- go test ./internal/provider -run 'StepFun|StepPlan|UnreadState|Rename|Delete|PlanQuota': ok
- go test ./internal/gui -run 'StepFun|Provider|Route|Asset|Test.*Guard|I18n': ok
- GUI: stepfun-per-provider.test.cjs, chromium and webkit, en and zh: 4/4 ok
  (3 runs each)
- gofmt -l; go vet -tags nogui for darwin, linux, windows on
  internal/provider and internal/gui: clean
Broken by hand, each red: saving by site (TwoAccountsOneSite, plus the
old tests), no migration (OldSessionMoved), copies renewed apart
(renewed 2 times), Delete keeping the session, Rename not moving it,
SignOut writing with no session (UnparsedKept: written over as {}),
the old key not dropped, a partly-parsed file read (UnparsedKept),
the editor told by site and the signout route taking any provider
(TestStepFunSignInPerProvider), app.js posting the site
(stepfun-per-provider.test.cjs). Making the migration read providers.json
with load() instead of read() stayed green: an unread file gives no
provider to move to either way, so that case is covered by outcome only.
Not tried against the real StepFun platform: every test uses a fake.

Co-authored-by: ZhengJin <12680972+fangzhengjin@users.noreply.github.com>

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone 6ea3b78d4e agent: OpenCode gets <level>-fast variants of a Codex account's GPT models, sent as Codex's /fast; the user's own variants stay (#2379)
OpenCode has no /fast (jiz4oh). A ChatGPT account's own gpt-* model (not
a routing group; catalog.Model.CodexFast, set in magpieModels from
provider.CanFast) is written into opencode.json with each level again as
low-fast … xhigh-fast, or fast alone with no levels. Each asks
service_tier "priority" twice: as an option, which OpenCode 1's
@ai-sdk/openai-compatible sends as it is (read in v1.18.34's
transform.ts and the SDK's getArgs), and in extraBody, which OpenCode 2
sends while it drops an option it doesn't know. The gateway already
sends a Chat request's priority tier to chatgpt.com on Responses and
drops OpenCode 1's stray extraBody field. Other vendors' models, an
OpenAI key's GPT model and groups get no fast variants.

The models block was written whole, so a variant the user added to one
of magpie's models was wiped on every sync. openCodeKept (OpenCode,
DevEco, Air, OpenChamber) keeps a user's variant and one written over
under a name of magpie's; a variant exactly as magpie writes it is
magpie's, so one the model no longer has goes. agent-wiring.md says so.

Run:
- go test -tags nogui -p 1 -count=1 -run 'OpenCode|OpenChamber|Air|DevEco|Deveco|Variant|Theirs|Kept|CodexTier|MagpieModels|Fast' ./internal/agent/: ok
- go test -tags nogui -p 1 -count=1 ./internal/catalog/: ok
- go test -tags nogui -p 1 -count=1 -run 'Fast|Tier|Codex|OpenCode' ./internal/gateway/: ok
- New: TestOpenCodeCodexFastVariants (written config, user variants kept,
  stale one dropped, second sync byte-identical, relay/gpt-5.5 and
  codex/codex-auto-review without fast), TestOpenCodeVariants fast cases,
  TestOpenCodeFastVariantReachesCodex (Chat as OpenCode 1 and 2 send it,
  streamed and whole, against a fake ChatGPT backend: service_tier
  priority, effort kept, no extraBody; none without the variant).
- Broken by hand, each red: CodexFast never set; theirsKept back in
  place of openCodeKept; user variants not read; stale variants kept;
  extraBody not written; gateway's Chat parse not reading priority.
- Real use: the exact opencode.json the test writes, base URL pointed at
  a fake server, in a sandbox HOME, with opencode v2.0.25:
  -m "magpie/codex/gpt-5.5#xhigh-fast" sent reasoning_effort xhigh and
  service_tier priority; #medium sent no tier.
- gofmt -l clean; go vet -tags nogui for GOOS=darwin, linux, windows on
  internal/agent, internal/catalog, internal/gateway: clean.
Not tried: an OpenCode 1.x binary (read from source only), a real
ChatGPT account's priority tier.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone 39b9703e3f agent: a remote magpie's model an agent isn't shown, or isn't on the remote's list yet, is refused, not written as the agent's own and taken out of magpie (#2376, moonshardx)
Reproduced with two magpies under sandbox HOMEs: B on 127.0.0.1:3592 with
a relay and routing groups, and A on 3593 with B added as Remote magpie
(renamed to "home"), plus a second remote with the id "remote". Codex
(codex-cli 0.162.1) and Pi (1.1.0) were wired through A, and both ran real
turns on remote ids (group/, provider/ and multi-slash ones).

The cause: Spell left a value the field's picker didn't offer as the
agent's own. A remote's model is missing from the picker when magpie
visible keeps it from the agent, or when the remote added it after A last
fetched the remote's list (a key provider's list is fetched on Refresh or
RefreshEvery). For Pi, `magpie pi remote/group/smart` then wrote
defaultProvider "remote", defaultModel "group/smart", said "disconnected
from magpie: … is Pi's own", and Pi went to its own endpoint ("Your account
is not active"). Codex got model = "remote/group/…" with no catalog entry.
The rename itself was fine: `magpie provider set remote-magpie id=home`
moved Codex's and Pi's values, and the old id still routes through Was.

Spell now refuses (notOffered) a value that names one of magpie's models
the agent isn't shown, a model of one of magpie's providers not on its
list, or a group/… magpie has no group for, and says how to fix it
(magpie models <agent>, magpie visible <agent> all, magpie provider
refresh <id>). Every agent's model field goes through Spell (CLI set,
GUI /api agent set, aside, profiles). A model shown to the agent that a
field offers fewer of (Claude Desktop's tiers) is still taken, and so is a
value whose provider part one of the agent's own models uses.

Run:
- TestSpellRefusesMagpieModelNotOffered (Pi and Codex, visibility on the
  relay: hidden, unlisted and unknown-group values refused; shown and own
  values spelled as before). It fails with notOffered disabled by hand:
  all 8 refusals were spelled as given.
- go test -tags nogui -p 1 ./internal/cli/ (whole package; it caught
  Claude Desktop's tiers, so the hidden check is on the agent's shown
  catalog, not the field's options), ./internal/profile/ (whole package),
  internal/agent -run 'Spell|Pick|Connect|Visible|Rename|Pi|Codex|Set|Apply|Own'
  plus every test in the files that call Spell or Pick, and internal/gui's
  agent_connect, agent_models*, agent_model_order, agent_disconnect,
  agent_nomodels, aside_native, aside_offline and codex_agents_v1 tests:
  all pass.
- gofmt -l; go vet -tags nogui ./internal/agent for darwin, linux and windows.
- The built binary in the sandbox: Pi and Codex narrowed to "home" refuse
  remote/group/smart with the message and keep their config; an unlisted
  remote/group/newpool is refused; shown every model again, both take it;
  Pi's own anthropic/… still disconnects as before.

Not tried: the GUI picker (it only offers shown models; the GUI's set
endpoint now gets the error text). No GUI file changed.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone 4c07442d29 provider: a model no catalog prices is at the price its plugin lists, or $0 when the plugin says it is free; devin's mover needs 0.1.18 (太陽と向日葵 on Discord)
太陽と向日葵 on Discord: Usage no longer showed what calls through Devin
cost. Devin's own models (SWE-2, SWE-1.7 Lightning) are in no catalog,
and ListPrice read only catalogs. In the owner's ledger on origin/main,
devin claude-opus-5-5 and deepseek-v4-1-flash rows are priced and the
swe-1.7-lightning row is blank. Devin lists its own price for each paid
model in GetCliModelConfigs, and devin 0.1.18 (plugins 43d93b0) now gives
it as the model's cost. 0.1.18 also makes swe-2 free again: Devin's new
-lightning variants under SWE-2 had taken that away on 0.1.17.

After every catalog, ListPrice now takes the plugin's price
(pluginListPrice, an input or output above 0, read with plugin.Cost,
which now carries cache read and write). If there is none, a model the
plugin marks free (plugin.Model.Free) costs $0 (pluginFree). A catalog's
price is still kept over the plugin's, and a plugin model with neither
stays unpriced. The devin mover's min is raised to 0.1.18 (npm view
--prefer-online on registry.npmjs.org: 0.1.18). A row is added to
providers-accounts.md.

Run: TestPluginFreeModelCostsNothing (new) and
TestPluginCatalogPriceAndImages, -p 1: ok. Broke it by hand:
pluginListPrice off turns swe-1.7-lightning red; pluginFree off turns
swe-2 red. gofmt -l clean. go vet -tags nogui ./... for darwin, linux and
windows: ok.
Real use: a sandbox HOME with only the owner's Devin key, plugin 0.1.18
and this build.
- `magpie plugin list --json` on Devin's live answer: swe-2 free;
  swe-1.7-lightning 2.5/12.5 (cache 1); swe-2-high-lightning 1/5;
  claude-opus-5-5 4/20.
- `magpie usage --csv`: the 10-03 swe-1.7-lightning row is $0.000819,
  where origin/main gave none.
Not done: Cursor auto, Qoder's and WorkBuddy's own models have no USD
price from their plugins (they list credit multipliers), so they stay
unpriced unless marked free.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone dbf331211f agents: an agent plugin with no model key is connect only, a switch with no model picker (#2374, rocona)
A Raycast plugin wants magpie to write the gateway, the agent's key and
the model list, and leave the model to Raycast's own picker. agent.model
was required ("agent.model names no key"), and the row always had a
model picker whose pick Raycast never read.

An agent export without model is now connect only:
- its one field is provider, magpie or nothing, as an app whose one
  setting is magpie as its provider (ZCode); ListsModels is set, so the
  row has the model list button and no model picker; no new UI control
  and no new strings
- connect is called without model and only its keys are written; the
  stash, the restore on Disconnect, the agent's own key and Check work
  as before; Sync calls connect again on a catalog change
- such a module must export connect (else it doesn't load, saying why),
  and connect must return keys (else the connect errs and nothing is
  written), so the row never says connected with nothing written
An export with model behaves as before. Docs: the plugins page (en, zh,
ja) and docs/subsystems/agent-wiring.md.

Tests (internal/agent/plugged_connect_only_test.go):
- TestPluggedConnectOnly: one provider field, menu, connect without a
  model, no model key written, the user's key and theme kept, list
  follows a catalog change, Check sees a base moved by hand, off puts
  everything back.
- TestPluggedConnectOnlyWritesSomething: no connect is a load error;
  connect returning {} errs and writes nothing.
Broken by hand (only forced false and model passed): both FAIL.
The /api/state row for such an agent was dumped through gui.state() in
a temporary test: key provider, one magpie option, menu true, the same
shape as ZCode's. zcode-models, plugin-agent and agent-connect GUI tests
pass in Chromium and WebKit (46/46; every language, 1100/980 and 420).

Run at origin/main 9d97fd073 + this change and the #2373/#2372/#2374 commits beside it (one tree), -tags nogui -count=1
-timeout 45m: internal/agent, plugin, provider, catalog,
gui, gateway ok. gofmt -l clean; go vet -tags nogui ./... for GOOS
darwin, linux, windows clean.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone 3d63fc9cb5 gateway: an error in a stream already begun says its status and that it may be retried, so Pi asks again (#2372, zminds)
Once a group has sent the agent the stream's headers (the keepalive
while a member is slow), a later failure reaches the agent as an error
event in a 200 stream, with the member's words only: "no first token in
30s", "Upstream service temporarily unavailable", "521 status code (no
body)". Pi decides whether to retry from that text alone, and none of
these match its list, so the turn ended after one try where Claude Code
and Codex retried.

streamError, the one place every in-stream error passes, now runs the
text through saysPassing: for 408, 429 or 5xx whose text names none of
the words such agents retry on, it appends "(<status>: you can retry
your request)". A text that already says so, and a request's own fault
(400, 401, 404 ...), are left as they were. A response not yet begun
already carries its real status; unchanged.

Not done: an X-Magpie-Retryable header (can't be sent once the stream
has begun), and widening retryable()/passing() for relay wordings and
521-527 (overlaps the #2313 work on relay 400s).

Tests (internal/gateway/stream_error_passing_test.go, with Pi 1.2.0's
own allow and deny regexes as the reporter quoted them):
- TestStreamErrorSaysItPasses: the reporter's literal texts.
- TestGroupLastFailureInStreamSaysItPasses: a slow first member, a
  keepalive, then a last member's relay 503; the stream's error is one
  Pi retries. Broken by hand (Text: msg back): FAIL.

Run at origin/main 9d97fd073 + this change and the #2373/#2372/#2374 commits beside it (one tree), -tags nogui -count=1
-timeout 45m: internal/gateway, plugin, provider, agent,
catalog, gui ok. gofmt -l clean; go vet -tags nogui ./... for GOOS
darwin, linux, windows clean.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone 49639cd162 agents: a plugin signed in to, out of, or listing new models updates the agents' model files (#2373, 18565882223-beep)
After signing in to Trae CN (a plugin's subscription), Pi's models.json
kept the list it had before the sign-in, so Pi's picker had no trae-cn/*
model while settings.json named one. A plugin's sign-in change
(plugin.OnChange) only dropped what the gateway held; catalog.Changed
(SyncCatalog), which a provider saved runs, never ran for a plugin. Now
plugin.OnChange and a new plugin.OnListed (told when the host lists
providers/models other than the list kept, also across a restart) call
catalog.Touched, so every connected agent's own model list follows, Pi's
models.json among them, and a sign-out takes the models out again.

Not reproduced: the report's GUI pick leaving models.json's mtime
unchanged. GUI and CLI picks go through the same Agent.Pick, which writes
models.json in-process here. With this change the file is rewritten when
the plugin lists its models, not only on a pick. PiCode's providers.json
isn't wired by magpie at all; unchanged.

Tests:
- TestPluginSignInReachesPiModels (internal/agent): pick a model, sign
  Trae CN in, models.json lists trae-cn/kimi-k3-max; sign out, gone.
  Broken by hand (hold.go back to plugin.OnChange(Changed)): FAIL
  "models.json hasn't Trae CN's models after its sign-in".
- TestNewListIsTold (internal/plugin): a new list is told once, the same
  list or the one kept on disk is not. Broken by hand (listed() not
  called): FAIL "the first list: told 0 times, want 1".

Run at origin/main 9d97fd073 + this change and the #2373/#2372/#2374 commits beside it (one tree), -tags nogui -count=1
-timeout 45m: internal/plugin, provider, agent, catalog, gui,
gateway ok. gofmt -l clean; go vet -tags nogui ./... for GOOS darwin,
linux, windows clean.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone deffaed85e draw: Volcengine Ark's Seedream is asked as its images API takes it: watermark false, reference images as JSON, one request per image, a ratio as its 2K size or an error (JL on Discord)
JL (#help): magpie_image through a Volcengine Ark provider came back
watermarked, edits went as a multipart form, and n and a ratio size
were sent as for OpenAI. Checked against Ark's own doc, 图片生成 API
(https://www.volcengine.com/docs/82379/1541523, read 2026-10-15):
- watermark is a boolean, default true ("AI 生成" in the corner);
- image is a string or string[], a URL or data:image/<fmt>;base64,...;
  there is no edits endpoint, it goes to /images/generations;
- there is no n field (one image, or a group the model sizes itself
  under sequential_image_generation, which 5.0 pro/flash refuse);
- size is a tier (1K/1.5K/2K/3K/4K by model) or WIDTHxHEIGHT; a ratio
  is to be described in the prompt. The doc lists each ratio's 2K WxH;
  4.0/4.5/5.0 lite's 2K table is inside every model's pixel range (5.0
  pro's max 2048x2048x1.1025 too), so it is the one used;
- no quality, no mask; output_format png/jpeg and background
  transparent exist (5.0 models) and are passed when asked.

drawArk (draw_volcengine.go), reached from drawImages for any
ark.*.volces.com base (the preset's plans or a pay-as-you-go provider
added by hand): JSON body with watermark false and b64_json, images in
image, one request per image through eachDrawing, a listed ratio sent
as its 2K size and any other ratio a 400 saying to put it in the
prompt or give WxH, before Ark is asked. A mask is a 400.

Not tried against the real Ark API (no Ark key here); the fake server
follows the doc's request and answer shapes.

Run (worktree at origin/main dd25997a4, go1.26.8, -tags nogui -p 1):
- go test -run 'TestArk|TestIsArk' ./internal/gateway: ok. With the
  isArk branch in drawImages removed by hand: TestArkDrawsUnmarkedOncePerImage
  (one image, no watermark field), TestArkEditSendsImagesAsJSON (404 at
  /images/edits) and TestArkSizes (ratio sent, 200) red; restored, green.
- go test -run 'Image|Draw|Ark|ModelScope|Drawing|WorkBuddyDraw|Video'
  ./internal/gateway: ok (74.5s).
- go test -run TestLoopGuardLeavesOrdinaryRepliesAlone (reads the
  docs): ok.
- gofmt -l internal/gateway: clean. go vet -tags nogui ./internal/gateway
  for GOOS=darwin, linux, windows: clean.
- Not run: the full suite.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetoneandDony2050 7dc5cd8f08 provider: Codex keeping its sign-in in the macOS keychain is read and written there (#2367, Dony2050)
Codex 0.162 with cli_auth_credentials_store = "keyring" or "auto" saves
its ChatGPT sign-in to the keychain and deletes auth.json. magpie read
only auth.json, so it hid the Codex provider and every saved account.
Adapted from Dony2050's fcebfc322 (fix/codex-macos-keychain). The changes
from that branch are below.

What Codex does (codex-rs at rust-v0.162.1: login/src/auth/storage.rs,
config/src/types.rs, features/src/lib.rs). The item is service "Codex
Auth", account "cli|" plus the first 16 hex digits of the SHA-256 of the
canonicalised CODEX_HOME. Its value is auth.json's JSON on one line.
keyring reads only the item. auto reads the item, and falls back to
auth.json when there is no item or the item can't be loaded. Saves follow
the same order. With [features] secret_auth_storage on (the default on
Windows), keyring and auto use Codex's encrypted storage instead.

internal/provider/codex_store.go is now the one reader and writer:
- A keychain interface. The real one runs `security` the way Claude Code's
  item is read (keychainText, proc.CommandContext, 10s bound; errors carry
  no argv or output). Tests get a fake (isolate, CodexKeychainForTest).
- readCodexLogin follows Codex's rules on macOS. keyring with no item is
  signed out. keyring with a refused read is unknown (codexStoreError),
  never signed out. With the encrypted storage, on Linux and on Windows,
  keyring and ephemeral are unknown and auto is auth.json. A config.toml
  that doesn't parse reads auth.json as before.
- Reads are kept 10s, a refusal 10 minutes, and only one `security` ask
  runs at a time. Each read can be a Keychain prompt, and codexToken runs
  on every request.
- A refresh writes the rotated tokens back where they came from, with
  unknown fields kept, after re-reading the item.
- saveCodexLogin (switch, first sign-in) re-reads the store first. It
  refuses when the store couldn't be read, when config.toml doesn't parse,
  for ephemeral, and for a store magpie doesn't read. It never deletes
  auth.json; Codex cleans that up itself.
- deleteCodexLogin (signing the last account out) removes the item, then
  auth.json, as `codex logout` does.
- Routed through it: codexAccount, codexToken (it now takes the home dir),
  liveLogin, CodexAPIKeySignedIn, codexLoginAuth, the usage card's
  codexUntil, session identities, switchSavedLogin, addLogin, forgetLogin,
  and agent's codexChatGPT/Source (provider.CodexSignIn).
- savedButSignedOut now says what was found (codexSignedOutWhy): nothing
  in the item, an item macOS wouldn't give (allow it, or use file), or a
  store magpie doesn't read here (use file). This replaces ed6e27f5f's
  codexCredentialsStore and its single "magpie doesn't read the keychain"
  text.

Changed from fcebfc322: secret_auth_storage is honoured (the branch would
read and write the wrong item); there is no second keychain package; reads
are cached and a denial backs off (the branch spawned `security` on every
read); auth.json is not deleted after every keychain write; auto falls back
to the file only when there is no item; the tests use an interface fake on
every OS instead of a darwin-only PATH fake; codexChatGPT keeps its
meaning; a malformed config.toml doesn't hide a file sign-in.

Run (in the wt-2367 worktree, sandbox HOMEs only, no real keychain or
`security` run, nothing under ~/.codex):
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux and windows:
  clean.
- go test -p 1 -tags nogui ./internal/provider: ok (293s).
  ./internal/agent: ok (1291s). An earlier agent run hit the disk filling
  up (ENOSPC from other sessions' builds); it was rerun with room.
  ./internal/gateway -run 'Codex|Login|Account': ok (261s).
- Broken by hand. The keychain never read (keychainItem false):
  TestCodexSignedInInKeychain, TestCodexKeychainRefreshWritesItem,
  TestCodexKeychainSwitch, TestCodexKeychainAskedSeldom,
  TestCodexKeychainSignOut and TestSavedButSignedOut go red. saveCodexLogin
  ignoring a refused read: TestCodexKeychainSwitch red ("switched over a
  sign-in the keychain wouldn't give"). No cache:
  TestCodexKeychainAskedSeldom red (20 asks for 20 reads). agent's
  codexChatGPT reading auth.json only: TestCodexSignInInKeychain red.
- Not tried: an item Codex itself wrote. Codex writes it through
  keyring-rs, and its ACL may trust only codex, so macOS may prompt the
  first time magpie reads it, and Codex may prompt after magpie rewrites
  it (`add-generic-password -U`). An unanswered prompt is killed at 10s
  and reads as unknown. The reporter is asked to confirm on #2367, which
  stays open.

Landing: this goes on top of ed6e27f5f (in this worktree as its
cherry-pick 66cdde294) and replaces that commit's message.

Co-authored-by: Dony2050 <88673296+Dony2050@users.noreply.github.com>

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone ad312dfee9 zhipu: a 1308 or 1310's reset time, written with no zone, is read as Beijing's, and a held refusal says its time with the offset (Player on Discord)
Player reached a Remote magpie with a GLM Coding Plan key: "Z.ai:
[1308][Usage limit reached for 5 hour. Your limit will reset at 2026-10-15
20:12 (out of its allowance: not asked again before 17:12)". Z.ai's 1308
and 1310 ("Usage limit reached for N hour. Your limit will reset at
YYYY-MM-DD HH:MM:SS", bigmodel.cn "您的限额将在 … 重置") write the time
with no zone. It is UTC+8: code-yeongyu/senpi#3348 has a 1308 received at
2026-09-21T17:17:32Z saying 01:18:11, 39s later as UTC+8 and 8h later as
UTC; kodustech/kodus-ai#2104 and openclaw/openclaw#97764 show the same
zone-less form for 1310. resetsWhen reads only a time with its offset, so
nothing read it: the key rested quotaRest (15 min), the held refusal said
"not asked again before" a quarter-hour on (17:12, this magpie's local
time with no zone), and after it Z.ai was asked and refused again until
20:12 Beijing time.

- routing.go: zhipuResets/resetsZhipu read Zhipu's own words ("Your limit
  will reset at", "您的限额将在") then a whole date and a time to the
  minute at least, in UTC+8; not when a digit, colon or zone follows
  (cut in its seconds, or a zone of its own, which resetsWritten reads).
  resetsAt tries it after resetsWritten, so restAfter and keepRetry both
  see it, for the built-in key, a relay passing it on, and a Remote
  magpie's held refusal.
- heldClock: a held time is given as "20:12 UTC+8" (today) or
  "Oct 16 09:00 UTC+8", since its reader may be a Remote magpie's user on
  another clock. Siblings: the quota-held 429 (gateway.go), the capped
  window error (fallback.go), the spent searcher (search.go) and describer
  (vision.go), all of which wrote Local() with no zone.
- docs/subsystems/gateway-routing.md says both.

The "manual weekly reset" was Z.ai's weekly reset card, spent on Z.ai's
site (magpie only counts them, b69b0e810). It clears the weekly window;
the 5-hour window stays full, which is the 1308 Player got. Not a magpie
bug.

The held message's parenthesis is balanced in the code; Player's quote
was cut before the ")".

Run:
- TestResetsZhipu: Player's literal words (no seconds), Z.ai's OpenAI and
  Anthropic envelopes, senpi#3348's case (39s), kodus#2104's 1310,
  bigmodel.cn's Chinese raw and \u-escaped, a Remote magpie's held line;
  not read: cut in seconds/after the colon/in the minute/in the date, its
  own UTC/+00:00/Z, month 13, hour 25, past, over a week, WorkBuddy's
  words without offset, a date in passing.
- TestHeldClock in UTC+8, UTC and UTC-3:30, today and tomorrow.
- TestZhipuRestsUntilItsReset: a 1308 three hours off rests the key three
  hours (Retry-After), Z.ai asked once, and the held refusal names the
  time with its offset.
- Broken by hand: resetsZhipu taken out of resetsAt, TestResetsZhipu and
  TestZhipuRestsUntilItsReset go red (Retry-After "900"; held refusal
  "Z.ai reset at 20:12:53 … not asked again before 17:27 UTC+8", the
  reporter's bug); heldClock put back to Local().Format("15:04"), the
  end-to-end test goes red ("not asked again before 20:13").
- go test -tags nogui -p 1 -run 'Zhipu|Reset|Rest|Held|Quota|Cap|Spent|
  Searcher|Vision|Written' ./internal/gateway: ok.
- gofmt -l clean; go vet -tags nogui ./... on darwin, linux, windows: ok.
- The full suite ran out of disk on this machine (df / down to ~1 GB,
  45 "no space left on device" in agent, cli, davsync, gateway, gui,
  library, provider, sessions); it is not a record.

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 5c0049a38c agent: MothX is an Agents-page row, wired into ~/.mothx/settings.json, and Disconnect puts it back (#2353, zhenruyan)
MothX (oschina/mothx, formerly vibecoding; npm mothx-installer) reads its
providers and start-up model from one settings.json: $MOTHX_DIR, else
%APPDATA%\mothx on Windows, else ~/.mothx. This follows zhenruyan's fork
(#2353) and the jcode/Prime Agent pattern.

What changed
- internal/agent/mothx.go: the agent. Connect writes provider "magpie"
  (openai-chat at the gateway's /v1, key magpie-mothx, one entry per magpie
  model with reasoning, input, contextWindow, maxTokens, cost) beside the
  user's own providers, and sets defaultProvider/defaultModel; "thinking"
  is defaultThinkingLevel, narrowed to the levels magpie knows for the
  model (none → off). thinkingFormat "openai" makes MothX send
  reasoning_effort for every model; without it MothX guesses Qwen's
  enable_thinking/thinking_budget or DeepSeek's thinking from the model id.
  A thinkingFormat or headers the user put in magpie's block are kept.
  Model options: the user's own providers' models, the current built-in
  pick (deepseek-openai/…), then magpie's.
- Disconnect: settings.json is copied aside before magpie's first write
  (beforeMagpie) and put back byte for byte when nothing else changed; a
  file that wasn't there goes again. When MothX rewrote it meanwhile
  (/model, /statusline … global: SaveGlobalSettings marshals the whole
  struct), only magpie's provider, the pick and a providers object left
  empty go; the user's changes stay.
- Detection, the restart notice (mothx or vibecoding running; translated in
  zh-CN, zh-TW, ja, de), WSL distros (~/.mothx), MOTHX_DIR in agentenv and
  the WSL dir moves, CLI updates through npm mothx-installer.
- usage names its requests: the User-Agent is "Vibecoding Client/<ver>",
  matched by the alias vibecoding (usage.AgentOf takes the first word).
- GUI: the icon (upstream docs/assets/mothx-small.png, MIT).
- Docs: README en/zh lists, docs/reference.md (table row, provider-scoped
  list, notes), docs/subsystems/agent-wiring.md.
- Not in this commit: MothX as a Library skills target (its own goal).

Run
- go test -p 1 -tags nogui: TestMothX* (real first-run settings.json as
  the fixture; user keys, headers and thinkingFormat kept; no-op Sync and
  same-value Set leave bytes and mtime alone; Disconnect byte-identical;
  no-file round trip x2; changes while connected kept; MOTHX_DIR/Windows/
  WSL dirs; thinking levels), TestAgentOf, TestEveryNoticeIsTranslated,
  TestEveryAgentNamedByItsKey, TestWSLMore*; then ./internal/agent
  (1120s at load ~100; an earlier run hit the default 10m timeout inside TestReasonixConcurrentEditsAndSync at load ~50, not a failure), ./internal/agentenv, ./internal/usage: ok.
- Broken by hand, each red then restored: no take() (TestMothX and
  RoundTripNoFile red), user thinkingFormat not kept, thinkingFormat
  "openai" dropped, the vibecoding alias dropped (TestAgentOf: got
  "Vibecoding"), the empty-providers cleanup (KeepsWhatChanged red).
- gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui ./... clean.
- GUI (playwright 1.62.0, chromium and webkit): agent-notice-lang,
  models-add-and-icons, pi-default-note 30/30; a scratch check of the
  MothX row (icon loads, connect, notice in the window's language, fits)
  in en/zh/zh-TW/ja/de at 1100 and 420: 22/22.
- Real binary, MothX 1.3.104 (npm mothx-installer) in a sandbox HOME
  against a sandbox `magpie serve` and a fake OpenAI upstream:
  - `magpie mothx magpie/fake/echo-1` wrote the block; `mothx doctor`
    showed provider magpie, model fake/echo-1.
  - `mothx -P "Say PONG"` answered from the fake; usage.jsonl recorded
    agent mothx, provider fake.
  - Adding qwen3.7-plus to the provider live-synced the block (context,
    maxTokens, cost, reasoning). With thinking high, MothX sent
    reasoning_effort "high"; with thinkingFormat removed by hand it sent
    enable_thinking/thinking_budget instead, and `magpie provider refresh`
    put "openai" back.
  - The interactive TUI (tmux) started on "magpie | Qwen3.7 Plus · fake"
    and got the fake's reply; `magpie mothx effort medium` while it ran
    printed the restart notice.
  - `/statusline refresh 5 global` in the TUI rewrote the whole file
    (dropped reasoning:false, added responses:{…} to magpie's block);
    `magpie mothx` still read connected. `magpie mothx default` then left
    the original plus the user's refreshInterval, and (after the cleanup
    above) no empty providers.
- Not tried: Windows and WSL with the real binary; a real vendor key.

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 0f398c4895 gateway: a group member whose window can't hold the request isn't asked it (dgqyushen on Discord)
dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash (200K)
first in a group and a 1M DeepSeek subscription second, so that the
first 200K go free and past that go to the subscription.

The gateway fell over only on a refusal it reads as too long (#700,
withRoom/failOverflow, tooLongUnsaid past 1.2x the window). A vendor that
refuses a request just past its window without saying why (between 1.0x
and 1.2x) reached the agent as that error while the next member had
room, and every doomed request spent one against the free tier's limits.

roomy (fallback.go), in serve after rules, affinity, the image filter and
pinTo and before probeOne, estimates the request as the overflow path
does (estimate) and leaves out the candidates whose known window
(windowOf: Contexts, the catalog, ContextOf) is no larger, and their
order rows with them. It is a check before sending, not a retry. Kept:
a window not known, a body that doesn't parse, a single model, and a
request no candidate holds (the first is asked, its overflow told to the
agent to compact). A conversation stuck to the small member by affinity
moves once it outgrows it. count_tokens (a count on the first member) and
System One's decision models don't go through serve's candidate path and
are left alone; every generation route (middleware, classify, search,
vision, codex titles/backend, auto groups) goes through serve. No UI
change: a member left out is absent from the route's order.

TestPayloadTooLargeOverWindowTriesMemberWithRoom now expects the members
too small not to be asked at all (c only, one try).

Run:
- go test -tags nogui -p 1 ./internal/gateway -run
  'TestMemberTooSmallIsNotAsked|TestConversationOutgrowingItsMemberMoves|
  TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge': ok
- the overflow tests (TestPayloadTooLarge, TestOverflow,
  TestContextOverflow, TestEveryVendorsOverflow, TestCodexOverflowInGroup,
  TestStreamOverflow, TestRateLimitNotContextOverflow) with the new ones:
  ok
- gofmt -l clean; go vet ./internal/gateway (darwin); GOOS=linux and
  GOOS=windows go vet -tags nogui ./...: clean; go build darwin, linux,
  windows: ok.
Broken by hand: the roomy call in serve commented out:
TestMemberTooSmallIsNotAsked red (400 "FREE: Invalid request
parameters"), TestConversationOutgrowingItsMemberMoves red (free 2,
paid 0), TestPayloadTooLargeOverWindowTriesMemberWithRoom red (a 1, c 1,
2 tries); restored, all green.
Not run: the whole internal/gateway package (the run failed to build,
"no space left on device", the disk at 0 GB free) and the full suite
(left to the batch's run). Not tried against the real OpenCode Zen.
Known: the estimate is bytes/4, so mostly-CJK text counts high and a
member may be passed over a little early.

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 0dbb1a8490 library: subagents are written once and given to every agent in its own format, with what each agent can't bind shown (#2283, chuanchinatest)
The Library has a Subagents tab beside Hooks. A subagent is a name, a
description, a prompt, and the library's skills and MCP servers it uses.
magpie writes it to each ticked agent's user-level folder in that agent's
format, rewrites it on every change, and takes back only files it wrote.

Where each one goes (syncSubagents, subagentSpecOf):
- Claude Code: ~/.claude/agents/<n>.md, with skills and mcpServers
- Codex: $CODEX_HOME/agents/<n>.toml (name, description, developer_instructions)
- OpenCode: ~/.config/opencode/agents/<n>.md (mode: subagent)
- Gemini CLI ~/.gemini/agents, Qwen Code ~/.qwen/agents, Grok ~/.grok/agents,
  Cursor ~/.cursor/agents, Copilot CLI ~/.copilot/agents/<n>.agent.md
- Factory Droid: ~/.factory/droids/<n>.md, with mcpServers
Skills and servers are named only where the agent's file can name them.
The page says, per agent, which of the two it won't bind, and that only
the Cursor app reads ~/.cursor/agents (cursor-agent reads a project's only).
Agents in WSL and agents with no user-level folder are greyed out.

The user's own files: every file is recorded by the hash of what magpie
wrote (Applied.Subagents). A same-name file of the user's is never written
over (the agent gets a problem). A file the user edited is theirs from then
on: it is neither rewritten nor removed. A carried library doesn't carry
subagents yet (as with hooks).

The Library's tabs now wrap onto a second line rather than scroll a narrow
window sideways (eight tabs in German at 560px). library-servers-bulk's
window goes from 1000 to 1100px tall to keep its stated premise that the
whole list fits.

Run:
- gofmt -l, and go vet -tags nogui for darwin, windows and linux: clean.
- go test of internal/library, internal/gui and the packages that import
  internal/library, at this head: green.
Full suite: SUITE_LINE
- New tests: TestSubagentsEachAgentsFile, TestSubagentsLeaveTheUsersFiles
  (covers the user editing magpie's file and then a sync), TestSubagentCheck.
- GUI: library-subagents (new) passes in Chromium and WebKit, at 1100 and
  420, in en, zh, zh-TW, ja and de. Also all library-*, gui-ja, gui-de,
  gui-zh-tw, i18n-keys, images-library-way, skill-* and mcp-* tests pass.
  Greying out the WSL agent was broken by hand, and library-subagents
  went red.
- Real binaries in a sandbox HOME against a fake upstream: each one sees
  the subagent magpie wrote.
  - Claude Code 2.1.300: it is listed in the system prompt.
  - OpenCode 2.0.25: debug agents.
  - Grok 1.0.50: grok inspect.
  - Codex 0.162.1: spawn_agent's roles, with --enable multi_agent_v2. v1
    showed no spawn_agent with a custom provider.
  - Gemini CLI 0.63.0: <subagent> in the request.
  - Qwen Code 0.21.9: its agent types.

Not tried: Factory Droid and Copilot CLI (both need a sign-in; Copilot
stops on auth before it reads agents), and the Cursor app.
2026-10-15 23:08:03 +08:00
yetone c14842fbb7 routing: a try the gateway went on from says it went on, not that the agent got it (#2281, xishuchkui-code)
xishuchkui-code's Antigravity account answered 502 with an empty reply,
which doesn't rest it; the gateway went on to the next account and that
one answered. The Routing page's story said "answered 502 — an error
another account wouldn't fix, so Claude Code gets it" (换账号也无法解决,
Claude Code 收到此错误), and the account's row said "502 · failed ·
passed to Claude Code". Both guessed the outcome from where the try stood
in the order (not last, no rest, no retry), not from what the gateway did.

What came of a try is now read from the record. The gateway appends a try
to Route.Tries only as it asks it, so a later try is the request going
on; with none, the error ended the request, the agent's once the route
is done. No marker was needed for that. The one case the record can't
show is the `other` hand-back: the last try left, out of its allowance
after an earlier failure that wasn't one, while the agent is told the
earlier error (Discord, waroy). That try is now marked Try.Earlier.

Siblings in trySaid that guessed the same way:
- a try that went on with no rest: "answered {status}, and the request
  goes on to {next} … doesn't rest for it" (was "wouldn't fix … gets it");
- a resting try with nobody after it (the last key, #1772) said the
  request goes on to "the next"; it now says nobody is left and the
  agent gets the error;
- slow to begin with nobody left said it went on to the next; same;
- the Earlier try says the agent got the earlier try's error;
- a failed try with no next on a route still running says only what it
  answered.
The account row: "passed to {agent}" only for the route's last try once
it is done; a try the gateway went on from says "{status} · {fail} ·
went on to the next". Usage's request detail only shows the gateway's
"answered on a retry" counts and the CLI/TUI don't tell tries, so neither
changes. 6 new strings, in en, zh, zh-TW, ja and de.

Run at this head (rebased on origin/main 95e7c6bcc):
- gofmt -l . clean; go vet ./... on darwin, GOOS=linux -tags nogui,
  GOOS=windows: all 0.
- go test of internal/gateway and internal/gui under a sandbox HOME:
  ok on af9bd6c3e (gateway 600s, gui 123s). After the rebase onto
  95e7c6bcc, gui ok (608s); gateway ran out its 25m and then 30m
  -timeout with no test failed (the alarm caught TestTextWrittenCallWhole
  4s in), at load average ~100 with ~15 other go test runs going, and
  was not run again: free disk fell to 2.7G.
- routing-went-on.test.cjs (new): 20/20 in Chromium and WebKit, en, zh,
  zh-TW, ja, de, 1100 and 420. It fails on the old client.js with the
  reporter's own words ("…返回 502,换账号也无法解决,Claude Code 收到此
  错误。"), and with only the old row line put back it fails on
  "502 · failed · passed to Claude Code".
- TestCodexSpentGrokFailingIsTold now asserts Earlier; with the gateway
  line reverted it fails.
- routing-*, panel-routing*, gui-de, gui-ja, gui-zh-tw, i18n-keys in
  both engines, after the rebase: Chromium 513/514, WebKit 512/514
  (before it: 513/514, 510/514). WebKit's two after the rebase are
  routing-model-rest de ("the Opus row doesn't rest"), red on
  95e7c6bcc too (1 of 3 runs, alone; #2115 has it in Chromium). The reds are
  routing-held-member at 420 in WebKit (#2252; also 2-4 red per run on
  origin/main 707fbb249, alone, 4 runs) and routing-wb-restricted's
  wheel-scroll "button can't be reached" (#1905; 4/4 green alone on both
  this branch and main 707fbb249, alternated). routing-proxy and
  routing-shape asserted the failed member's tag, which only appeared in
  the wrong "passed to" row; the went-on row keeps it and both pass.
Not tried: a real Antigravity account answering empty; the fixture is
the reporter's case as the trace records it.

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 0fe7892320 library: shared instructions can be given to Alma, after the profile in its ~/.config/alma/USER.md (#2315, Jie211)
Alma had no instructions target: the library said it "has no user-wide
place for instructions". Alma 0.4.164's own main process
(out/main/index.js in its app.asar) does read one. Its main chat puts
~/.config/alma/USER.md into the system prompt as "USER PROFILE (your
owner/primary user...)", or a workspace's USER.md in its place. Alma's
prompt calls the file "your owner/primary user's profile (name,
preferences, habits - editable)". Its leading front matter (name,
telegram_id, discord_id, matched with ^---\n...\n---) is who its bots
answer to.

So Alma's target gets Instructions = ~/.config/alma/USER.md and a new
Profile flag:
- magpie's part goes after the user's, so the front matter stays first
  and Alma still finds its owner. Turning Alma off leaves the file as it
  was. A USER.md magpie made holding only its part is taken away again.
- ImportInstructions refuses a Profile target. Moving the user's lines
  out would take the front matter out of USER.md and put the owner's
  telegram/discord ids into every agent's file. The page hides "Move its
  own into the shared text" for it (AgentInstructions.Profile), and adds
  an aside in en/zh/zh-TW/ja/de. The aside says the file is Alma's
  profile of the user, and a workspace USER.md is read instead.

Not tried with the real Alma app. Its live ~/.config/alma was not touched.
What Alma reads was taken from its bundled source. Sub-agents are not
confirmed to read USER.md.

Tests (sandbox HOME, Jie211's own line as the shared text, a USER.md in
the shape Alma's setup writes):
- TestTakesAlma
- TestAlmaInstructionsKeepTheProfile: the front matter is still matched
  by Alma's own regexp after the sync; turned off, the file is the same
  bytes.
- TestAlmaInstructionsWithoutUserMD
- TestAlmaProfileIsNotImported
Broken by hand:
- the Profile check in ImportInstructions taken out:
  TestAlmaProfileIsNotImported goes red;
- Alma's Instructions path taken out: TestTakesAlma and
  TestAlmaInstructionsKeepTheProfile go red.

Ran (at the reviewed head, on origin/main 01c41e8ba): go test -p 1 -tags nogui ./internal/library ./internal/provider ok; library also ok in 5 of 6 -count=1 reruns after the rebase. The 1 red run came while ~1G of disk was free, and its output was not kept; the new Alma tests passed in every run. gofmt -l clean; go vet -tags nogui GOOS=darwin/linux/windows ok; node --test internal/gui/tests/library-*.test.cjs (33 files, chromium and webkit) 518 pass, 0 fail; library-alma-profile.test.cjs went red with the !a.profile guard taken out by hand.
Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 357ffac7be usage: a model's Same as prices its calls when no list does (#2344, liuweifeng)
A model a provider serves under its own id (a WorkBuddy kimi-k3-1, a
relay's renamed gpt) had no price unless the user typed one, even when the
user had already told magpie in the editor's "Same as" box which model it
is. Its calls showed no API-price cost in Usage, window holds had no price
to weigh, and `magpie model price` said unpriced.

Now, when neither the user's prices, the provider's list nor models.dev's
maker price covers a model, provider.SamePriceIn takes the maker's list
price of the model it is the same as (settings.ModelSameAs), and the
provider's price rate still applies. A price the user set, or a list that
prices the model, always wins; nothing is inferred without a Same as.
The same fallback is used by priceOf (Usage costs, re-priced when the
ledger is read, so past calls pick it up), usage's apiPricer (window
holds), the model editor's greyed list price, and `magpie model price`,
which names where the price came from. The "Same as" tooltip says so in
en, zh, zh-TW, ja and de.

Run:
- go test -p 1 -tags nogui ./internal/provider ./internal/usage
  ./internal/cli ./internal/gui (focused: TestSameAsPricesAnUnlistedModel,
  TestHoldsPriceTheModelItIsTheSameAs, TestModelEditorShowsTheSameAsPrice,
  TestModelPriceCmdSaysWhereThePriceCameFrom, plus the packages): ok
- GUI (chromium + webkit): provider-same-as, i18n-keys, model-price-edit,
  11/11 pass
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows: clean

Broken by hand, each went red:
- SamePriceIn dropped from priceOf: "kimi-k3-1 ... false; want $0.3"
- usage's apiPricer fallback removed: "wasn't its API price: <nil>"
- the GUI editor branch removed: "list <nil>"
- the CLI source line disabled: TestModelPriceCmd... FAIL
- the zh tooltip left untranslated: provider-same-as.test.cjs 0/2
A prefix-stripping branch passed when removed (MakerPrice already resolves
vendor-prefixed ids like moonshotai/kimi-k3), so it was dropped.

Not tried: a real WorkBuddy account's usage after the change.

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 0c0665126b quota: magpie quota --json and /v1/magpie/quotas tell each window's whole (holds / holdsWhy) as the Usage page does (#2333, zhenghaowen0967)
usage.WithWindowHolds reckoned a subscription window's whole (tokens, and
cost at API list prices) from magpie's own calls, or why it can't, but
only GET /api/usage/quotas and its refresh called it. magpie quota --json,
GET /v1/magpie/quotas and its ?kept=1 list showed name, used, remaining
and resetsAt only, so a script comparing plans had to rebuild the estimate
from the log without its guards.

Package provider can't import usage, so usage sets provider.ReckonHolds in
an init (like the other provider hooks). quotaReport, which QuotaReport,
KeptQuotaReport and RefreshReport share, runs it once over every card and
QuotaSpan carries Holds and HoldsWhy. The log is read through usage's
cached snapshot, so ?kept=1 (magpie statusline, every message) adds no full
read after the first. A key held to a budget, models or accounts and told
cards (#2216) is not told holds: they are reckoned from every call routed
through the account, other keys' too, so quotaScope.quotas drops them;
this machine and unheld keys get them.

The Balance guard in holdsBounds (a Codex account holding credits gets no
whole and no reason) is unchanged; it is answered on the issue.

Docs: reference.md's /v1/magpie/quotas section names holds/holdsWhy and
each reason; providers-accounts.md's Allowance row names the hook.

Run (sandbox HOME, -tags nogui, -p 1):
- New TestQuotaReportTellsWindowHolds (provider), TestQuotaReportsReckonByTheLog
  (usage, against a real usage.jsonl in the sandbox) and
  TestHeldKeyToldNoWindowHolds (gateway) pass.
- Broken by hand: the ReckonHolds call in quotaReport skipped → provider
  test FAIL "reckoned 0 times over 0 cards"; Holds/HoldsWhy not copied into
  QuotaSpan → FAIL "5 hours told no whole"; usage's init removed → usage
  test FAIL "provider.ReckonHolds isn't set"; quotaScope not clearing them
  → gateway test FAIL "a held key was told 5 hours's whole".
- go test ./internal/provider ./internal/usage ./internal/cli
  ./internal/gateway: ok.
- gofmt -l clean; go vet -tags nogui darwin, GOOS=linux, GOOS=windows on
  provider, usage, gateway: ok.
- Not run: the GUI suite (no GUI file changed), and against the owner's
  real accounts.

Full suite: SUITE_LINE
2026-10-15 23:08:02 +08:00
yetone d8d52c6e97 agent: Raycast is an agent magpie connects: a magpie entry in its Custom Providers' providers.yaml, magpie's models in Raycast AI's picker (lx_78654 on Discord)
lx_78654 asked on Discord: "agents能否加一个raycast".

Raycast AI takes models of the user's own as Custom Providers (Raycast
Pro, "Available on: Mac, Windows"), from ~/.config/raycast/ai/
providers.yaml in the user's folder on both systems
(https://manual.raycast.com/ai/custom-providers). Raycast watches the file,
so no restart notice.

What changed:
- internal/agent/raycast.go: a new agent, "raycast". One field, provider:
  connecting adds an entry, id magpie, to the providers list: the gateway's
  /v1 (OpenAI compatible, no /chat/completions), an api_keys alias holding
  magpie-raycast (Raycast's User-Agent isn't known, so its key tells it
  apart), and one model per magpie model with name, context and all five
  abilities said (Raycast assumes tools and vision off when left out):
  tools and system_message on, vision for a model taking images,
  temperature off for one that refuses it, reasoning_effort for one with
  effort levels. ListsModels: the model is picked in Raycast.
  - The list is edited as a yaml node, so the user's other providers, the
    top-level tools block (anchors too) and comments stay.
  - A key the user adds to magpie's entry or to one of its models
    (include_user_email, a description) is kept on a sync; a model gone
    from the catalog leaves the list. A sync with nothing to change
    doesn't write.
  - Disconnect takes the entry out, the list when it was the only one, and
    a file left with nothing in it (Raycast's providers.template.yaml is
    never touched). A providers key that isn't a list is refused and the
    file left as it is.
  - Detected by Raycast.app (com.raycast.macos) or the ~/.config/raycast
    folder.
- agents.go: registers it.
- icons/raycast.svg: Raycast's mark from Simple Icons (CC0), currentColor.
- docs/reference.md, docs/subsystems/agent-wiring.md, README.md,
  README.zh-CN.md: Raycast's row and its place in the agent list.

What was run:
- go test -p 1 -tags nogui ./internal/agent -run '^TestRaycast' in a
  sandbox HOME: ok. The fixture is the manual's LM Studio and tools
  examples, with comments and an anchor; the result is decoded strictly
  (KnownFields) into the manual's schema. Red by hand when I:
  - turned off the no-op check ("a sync with nothing to change wrote");
  - replaced the merge with magpie's entry alone (the user's
    include_user_email and a model's description gone).
- go test -p 1 -tags nogui ./internal/agentenv: ok.
- The whole ./internal/agent package didn't finish here: the first run hit
  the 10m default timeout at TestInstalledVersion with the machine at load
  ~110 (other sessions' suites), the second (-timeout 40m) ran 20 minutes
  with no FAIL and then stopped on "no space left on device" when the disk
  filled (0 GB free, not this run's files). It needs a run on CI.
- gofmt -l; GOOS={darwin,linux,windows} go vet -tags nogui ./internal/agent: ok.

Not tried with a real Raycast. On Windows it is found by the
~/.config/raycast folder only (its install path isn't verified). WSL isn't
covered.

Full suite: SUITE_LINE
2026-10-15 23:08:02 +08:00
yetone ecaa7e7dd7 gateway: a decision provider of several keys asks the next when one is out of quota, at /v1/systemone and as a classifier, in its routing's order (fflake33 on Discord)
A TypeSafe Jev provider with several keys never left its first key when that
one's quota ran out. serveSystemOne and the classifier (askClassifier → askJev)
always sent to p.Key, with no rest and no rotation. Only a decision group
failed over (serveDecisionGroup, askDecisionGroup).

Now the single provider goes the same way as a group:
- decideKeys plans its keys and accounts with s.plan, so Smart or In order,
  rests and barred keys apply. probeOne keeps only the resting one back
  soonest.
- serveDecideTries and askDecideTries (the group's loops, pulled out) ask
  each in turn. A retryable failure that isn't the request's own rests it and
  the next is asked.
- serveSystemOne keeps #905's limits. A gateway key held to some accounts is
  asked only on those (allowedCandidates), and gets 403 keyAccountsError when
  none serves the model.
- A provider whose every key is set not to serve the model is refused 403
  (barredError) instead of being sent on its first key.
- decideSeat is gone; the trace lists every key tried.
- docs/subsystems/gateway-routing.md says so.

Run: go test -p 1 -tags nogui -run 'SystemOne|Decid|Decide|Jev|Classif|
KeyAccount|KeyModel|Disabled|RemoteMagpie|Caller|Usage|Plugin.*Decide|
Barred|Rest|Probe' ./internal/gateway (ok, 124s).
TestDecisionProviderKeysFailOver (Smart and In order) refuses the first key
429 and checks:
- /v1/systemone answers 200 from the second, the trace has two tries and the
  first rests, and one usage row goes to the provider;
- the next request asks only the second;
- the same holds through askClassifier.
Broken by hand: with the old decide.go, decide_group.go and classify.go it
fails "systemone: 429 no capacity for k1" in both. The first version of the
reordering ran the barred check before the held-key one, and
TestGatewayKeyAccountsSystemOne caught the changed 403 message. The held
check now runs first.
gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui
./internal/gateway ok.
Not tried against the real TypeSafe API.

Full suite: SUITE_LINE
2026-10-15 23:08:02 +08:00
yetone e894443932 trae: a check-in Trae CN refused 9074 says Trae refused it and to check in in the Trae CN app, not that Trae pays only its own app (#1920)
#1920 showed Buddy Switch checking in third-party Trae CN accounts, so
"Trae CN only gives check-in credits to its own app" wasn't true. What is
known is that Trae CN answered the claim 9074 (当前参与用户太多). The
own-app outcome stays as it was (the day's answer, no Check in now), but a
Trae account (By "trae") now has its own text in every place it shows:

- GUI card and Settings line: two new keys in en, zh, zh-TW, ja and de
  ("Trae CN refused this check-in (9074: too many taking part); check in
  in the Trae CN app" / "Trae CN 拒绝了这次签到(9074 当前参与用户太多),
  请在 Trae CN App 里签到"). WorkBuddy keeps the shared own-app key.
- TUI line and cell, CLI: provider.TraeRefusedWords; the cell says
  "签到 refused by Trae CN (9074) · check in in its app".
- trae_checkin.go, workbuddy_checkin.go and provider-plugins.md comments
  and the claim's fallback message say the same. They also note the
  plugin side: since @magpie-community/opencode-trae-auth 0.2.14 the
  account the machine's own Trae CN client is signed in as checks in with
  the client's device id, read only. No id is made up or rotated (#1705).

Ran (worktree at origin/main 9d97fd073, -tags nogui, -p 1):
- gofmt -l internal/: clean. go vet ./internal/{tui,cli,provider} for
  darwin, linux and windows.
- go test ./internal/tui ./internal/cli: ok.
- go test -run 'Trae|Checkin|WorkBuddy' ./internal/provider: ok.
- GUI: usage-checkin.test.cjs and i18n-keys.test.cjs in Chromium and
  WebKit, en and zh: 31 pass, 0 fail.

Broken by hand:
- app.js's card without the Trae branch: the renamed usage-checkin test
  fails in chromium en/zh and webkit en/zh (4 of 4).
- pages.go's ownAppWords without the Trae branch: the new
  TestTraeOwnAppSaysTraeRefused fails.

Not tried: a real Trae CN account. No test checks the CLI line on its
own. The ja, de and zh-TW strings are checked only by i18n-keys.

Full suite: SUITE_LINE
2026-10-15 23:08:02 +08:00
yetone fa725d47cd gateway: a rule naming a group in the group that shares its models with one ahead of it sends the turn there, in that group's own order, not unready (#2361, davisjiahao)
davisjiahao's Parent held First (Alpha, Beta) and Second (Beta, Alpha), with
a rule sending every request to group/second. Each request came out
"use=group/second, unready=true" and First's Alpha answered; with Beta
failing, Second's own failover (Beta, then Alpha) never happened, as Beta
was never asked.

membersOff walks the group down and keeps each provider/model/effort once,
where it meets it first (so a request never asks one model twice), and
dropped every later place of it. Second's models were all First's, so a
rule naming group/second (named, ruleMembers) found none of them.

Each member now keeps its later places in Member.Also, each with its own
path, way down, Fast and At (where the walk met it, so a group's own models
come in its own order). A model is still asked once a request. A rule
naming a group has the models as that group does (Member.In,
membersNamed), sorted by that group's order, for the rule's own and its
Then members. Further down the turn, nestedRules looks at the rules of the
group the rule chose (homed, at the top and at each nested rule naming a
group), Fast and the first token's wait go by it (homeCands), the length a
held rule outgrows (memberContexts) counts it, and the catalog's rule
capabilities (ruledEntry) find it. A pause rule naming the later group
still leaves a shared model to the group ahead of it, as before.

Tested, in the gateway through New().Handler(), the reporter's config
with a token rule in place of the agent one:
- TestRuleNamesAGroupSharingModelsWithOneAhead: all ready, Beta answers,
  rule not unready; Beta 402, Beta then Alpha; both 402, two tries.
- TestRuleNamesAGroupSharingSomeModels: First (Alpha, Beta), Second
  (Beta, Gamma): Beta, Gamma, then Alpha.
- TestRuleGroupSharingModelsKeepsItsRulesAndTurn: Second's own rule picks
  Alpha (Nested shows second), and the turn's tool round stays there.
Broken by hand, each run with -run on the three:
- every source file put back: all three FAIL ("from ka", unready);
- no sort in membersNamed: WithOneAhead FAILs (Alpha first);
- nested rules given ms, not homed: KeepsItsRulesAndTurn FAILs (Beta,
  Second's rule never looked at);
- dedup off (the later place appended as well): WithOneAhead and
  SomeModels FAIL.
TestRuleNamesAModelAGroupInItHasToo (#625) passes. gofmt -l clean; go vet
-tags nogui ./internal/gateway ./internal/provider for darwin, linux and
windows ok. go test -tags nogui -p 1 -timeout 45m ./internal/provider ./internal/gateway: ok (263s, 518s, load ~30). A first run at the default 10m timeout ran out in internal/gateway under that load, in a TempDir cleanup, no test failing.
Not tried: an agent-matched rule against the installed binary (the rule's
match is the same code either way), and Fast differing between two groups
sharing a model end to end.

Full suite: SUITE_LINE
2026-10-15 23:08:02 +08:00
yetone 6e2aa8e321 agent: on Windows DeepSeek Harness is never taken for uninstalled by ~\.dsh alone, so it no longer shows "CLI not found" with no model to pick (#2300, yangkai2; #2304, wlj521)
From v0.1.1239 (d0fcb8bcd, #2177) an agent whose folder is here and whose
CLI isn't found shows "CLI not found" with its settings hidden. On Windows
dsh's folder is read by DeepSeek Harness Desktop too, which installs to any
folder and puts its dsh.cmd in one the user picks, and a dsh installed
through fnm sits on a PATH only a shell profile sets: magpie can't tell
those readers are gone, so ~\.dsh was taken for a leftover and the row
hid its model picker (both screenshots: 未找到 CLI). #1482 already made a
shared folder unknown on Windows; a folder an agent's desktop app reads
(desktopApps: dsh, and codex, already shared) is one too. On macOS and
Linux ~/.dsh with no dsh and no app is still gone (#843); Hermes, whose
folder only its CLI keeps, is still gone on Windows.

TestCLIMissingDshWindows: ~\.dsh as the desktop app leaves it, no dsh,
no app found; judged for Windows it isn't gone nor offered again, judged
for a Mac it is. It fails on the old gone.go (put back by hand: "dsh taken
for uninstalled on Windows, its settings hidden").

Run on this tree, on 6b7ea178d (#2279) over origin/main 707fbb249:
- gofmt -l: clean; go vet -tags nogui for darwin, windows, linux
- go test -p 1 -tags nogui ./internal/agent/: ok (857s)
Full suite: SUITE_LINE

Not tried: the reporters' own machines (how their dsh is installed is
asked on both issues); not run on the Windows box (the test forces the OS
switch, goneOS).
2026-10-15 23:08:02 +08:00
yetone 2a1637f4f6 agent: DeepSeek Harness Desktop is wired when installed but never opened, and found in any folder it was installed to on Windows (#2279, liangjinyuan-sihan)
DeepSeek Harness Desktop already reads magpie's route: its lib/main.js
(0.2.0-rc.2, the latest on its update feed, read from download.deepseek.com's
dmg and Windows installer) resolves $DSH_HOME, else ~/.dsh, and runs on
profiles/desktop, so the CLI's wiring applies. Three gaps remained:

- Installed but never opened, there is no ~/.dsh: the row wasn't listed,
  and connecting wrote the legacy config.yaml the app never reads. magpie
  now writes profiles/desktop/cordis.patch.yml from dsh's own template
  (PROFILE_PATCH_TEMPLATE) with its routes; the app's initProfile writes
  only missing files, so its first start keeps them. The notice says it
  starts on this when first opened (noticeDsh5, in all 5 languages).
  Disconnect before that first start removes what magpie made, when
  nothing else is there; afterwards only magpie's entries go.
- On Windows the installer lets the user pick the folder and registers it
  under HKCU\Software\1bf39983-50d0-5fe0-9ef4-cece76f67c5e InstallLocation
  (read from the NSIS script of dsh-latest-windows-x64.exe). magpie reads
  that, so a custom folder is found, and the Uninstall entry's
  DisplayVersion gives the version shown.

Tests: TestDshDesktopNeverOpened (pick on a never-opened app writes the
desktop profile, a user's key in .credentials.yaml and the user's own start
survive Disconnect, the app's first start is told apart),
TestDshDesktopRegisteredFolder (registry stubbed; exe must be there; WSL
twin has none).

Run on this tree, rebased onto 707fbb249:
- gofmt -l: clean; go vet darwin, GOOS=windows, GOOS=linux -tags nogui
- go test -tags nogui ./internal/agent/: ok (846s, loaded box)
- GUI, Chromium and WebKit: agent-notice-lang, gui-de, gui-ja,
  gui-zh-tw, agent-app-version, agent-cli-missing: 79 pass
Full suite: SUITE_LINE

Not tried: the real app was not run (Electron's userData isn't fully
redirected by a sandbox HOME); it was inspected statically (dmg mounted
read-only, app.asar extracted, NSIS header decoded). The registry reader
was not run on a real Windows install; the test stubs the registry.
2026-10-15 23:08:02 +08:00
yetone 7cad9a6185 agent: magpie's own files written during a sync with ~/.config a link are left alone, and the window's size saved after a resize no longer hangs the app for good (ylorn on Discord)
ylorn (v0.1.1250, macOS arm64, ~/.config a symlink): ~10s after every
start the GUI froze, beachball, CPU ~0, SIGTERM ignored. Their SIGQUIT
stack: the window's resize timer -> settings.Save (fileMu write lock) ->
edit.WriteAtomic -> the sync's filter keptAway -> gateway.URL ->
settings.Load -> fileMu.RLock, the same lock, forever.

Cause: edit.Filtered's filter sees every file written through edit while
a sync runs, from any goroutine, under whatever lock the writer holds.
keptAway read the settings (gateway.URL, and access.LANSecret through
ourToken) inside it, and skipped magpie's own files by a prefix check on
the unresolved ~/.config/magpie while WriteAtomic hands it the path
edit.Target resolved, so with a linked ~/.config settings.json fell
through to the settings read.

Fix (the class): what the filter needs of this magpie, the gateway's
address and the LAN key, is read before it is on (keeping(), kept.away,
kept.ours), so the filter takes no settings or access lock. magpieFile
compares magpie's folder as named and as EvalSymlinks resolves it, with
the written file's folder resolved too (for a file not there yet).

Siblings found: wslSaveLocked writes wsl.json under wsl's mutex, and the
filter's wslHost takes that mutex: with a linked config folder the same
self-deadlock on Windows (now skipped as magpie's own; the test covers
it). access.save writes keys.json under access.mu, which LANSecret took
inside the filter (now read before). No other prefix check against
provider.Path()/appdir gets a Target-resolved path; the filter is
edit.Target's only consumer of that kind. edit.Filtered's doc now says
the filter waits on nothing.

Run at this head (macOS arm64, go1.26.8, -tags nogui, -p 1):
- TestOwnWritesDuringASyncWithALinkedConfig (new; sandbox HOME with
  .config a symlink): on origin/main 35aa50cfb it fails with the
  reporter's stack (settings.go:972 <- keptaway.go:92 <- settings.go:1324).
- go test ./internal/agent (whole package, 810s): ok
- go test ./internal/edit: ok
- -race TestOwnWrites...|TestKeptAwayOnlyWhatIsSure -count=2: ok
- gofmt -l clean; GOOS=darwin/linux/windows go vet ./internal/agent
  ./internal/edit: ok

Broken by hand:
- magpieFile comparing the unresolved folder only (settings read kept
  out of the filter): red, wsl.json deadlocks in wslHost.
- the settings read put back inside the filter, own check fixed: green
  (settings.json is skipped as magpie's own before it); with the old
  check as well: red with the reporter's stack. The hoist is guarded only
  together with the own check.

Not tried: the real GUI with a linked ~/.config; the Windows box.

Full suite: SUITE_LINE
2026-10-15 23:08:02 +08:00
yetone f15542d2ea sessions: OpenCode 2 subagents show their type, and a Kimi Code subagent opens on its task, not a context chip (#2290, infinitr0us)
OpenCode 2.0.29 keeps a child session's agent in session_v2.agent and
titles it with the task alone, so ocSubagentTitle found no kind and every
OpenCode subagent row showed only its title and time. The kind now comes
from session_v2.agent when set (ocV2DB.agent, kept once found; a missing
column or NULL reads as none and isn't kept), and the "(@agent subagent)"
title split stays the fallback for older versions.

A Kimi Code subagent's own wire.jsonl starts with the task its parent
gave it, a turn.prompt whose origin is {kind: system_trigger, name:
subagent}; the transcript folded every system_trigger as context. In a
subagent's own wire (not agents/main) that prompt now opens as its first
user message (kimiTask). Other system triggers, and a "subagent" one in
the session's main wire, stay folded.

Fixtures follow the reporter's described shapes: ocMakeV2's real
session_v2 schema with agent 'explore' and a task-only title beside a
child with no agent and an older suffixed title; a 1.5-shaped subagent
wire (agentId, promptId, turnId) with the subagent trigger, a reply and a
background_task trigger, plus a subagent trigger appended to main.
No real OpenCode child sessions or Kimi Code subagents on this machine.
No GUI change: the Sessions client already draws a subagent's kind.

Run: TestOpenCodeV2SubagentKind and TestKimiSubagentTask fail on the old
subagents.go/transcript_kimi.go (no kind; user/context first), and
TestKimiSubagentTask fails with the agents/main scope check dropped.
go test -p 1 -tags nogui ./internal/sessions/ ok at the rebased head;
gofmt -l clean; go vet -tags nogui ./internal/sessions/ for darwin,
GOOS=linux and GOOS=windows.
Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00
yetoneandggbdpq 540454acec gateway: a turn on Codex's own ChatGPT sign-in is counted on that account, so the card's window holds see it (#2297, Edward4226, ggbdpq)
codexUpstreamOn wrote the relay's ledger row as Provider: call.Provider
("openai") with no account. The account card's window holds key rows by
codex + the sign-in's email (usage/window_holds.go), so every turn Codex
relayed on its own sign-in was left out: the reporter's 7-day window read
2.3M/$0.31 where its calls were 19.0M/$64.26.

codexServed (ggbdpq's patch) records such a relay as the codex account
signed in to, or the account compactOn signed it with. An API-key call
and a relay with no sign-in to name stay openai with no account. The
Routing view's seat stays OpenAI. loggedAnswers (#1367) still leaves the
relay out of a lead's answerers, as openai or as codex without a
"host as email". Rows already written are not rewritten.

On top of the patch: the relay goes out with the token Codex sent, which
is the sign-in magpie reads only when it is the same ChatGPT account. A
request whose chatgpt-account-id isn't the account auth.json here is
signed in to (a Codex in WSL, another CODEX_HOME) stays openai rather than
being put on this machine's account (provider.CodexSignedInAccount).
TestCodexServedNamesTheAccountThatSigned is back and covers it.

Run, go1.26.8 darwin/arm64, on 03eb0633a, -tags nogui -p 1:
- go test ./internal/gateway -run 'TestCodex|TestSealedTaskFromChatGPTLead|
  TestLoggedAnswer|Lead': ok (48.8s). The four new tests -race -count=3: ok.
- go test ./internal/provider -run 'TestSessionIdentit|TestCodex': ok;
  ./internal/usage -run 'Window|Hold': ok.
- go vet ./internal/gateway ./internal/provider for darwin, GOOS=linux and
  GOOS=windows: clean. gofmt -l: nothing.
Broken by hand, each red, then put back:
- codexServed always "openai": TestCodexOwnModelRecordedAsCodexAccount
  (Provider:openai, no account) and TestCodexServedNamesTheAccountThatSigned.
- chatgpt-account-id check dropped: TestCodexServedNamesTheAccountThatSigned
  ("another account's token: codex me@example.com").
- loggedAnswers back to provider == "openai" only:
  TestCodexOwnModelRecordedAsCodexAccount and TestCodexOwnRelayAnswersNoLead
  ("own sign-in answered a lead").
ggbdpq's own record (Windows, 38d25fe3/1d61458b on 01c41e8b): the same
tests red with codex_backend.go reverted, green after; -race -count=5;
vet/build for windows, linux, darwin.
Not run: the full suite, GUI, a real Codex sign-in.

Full suite: SUITE_LINE

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 23:08:01 +08:00
yetoneandcyh 7faf55778a gateway: OpenCode's DeepSeek is sent no deferred-tool blocks, and an inline-only tool definition joins tools (#2338, Emaj77)
Claude Code's deferred tools put tool_addition / tool_removal /
tool_reference blocks in a message. OpenCode Go's DeepSeek route answers
one defining a tool with a bare 422 "Upstream request failed: Endpoint is
unavailable.", which names nothing deferredRefused can learn from, so
every turn went out the same way and failed the same way. The reporter
checked it straight against opencode.ai/zen/go/v1/messages on 2026-10-15
(3/3 422 inline, 3/3 200 plain and with the definition in tools).

forwardOnce now drops the blocks for a Messages request to an OpenCode
host (p.IsOpenCode) whose model names deepseek, as it already did for Kimi
(#2042). Other OpenCode models and every other provider are sent the
blocks as Claude Code wrote them; no retry or fallback is added.

withoutDeferredTools assumed every tool was also in the top-level tools.
A tool defined only in a tool_addition's definition was dropped, so the
model could no longer call it; that held for Kimi too. Such a definition
now joins tools once, by name, a top-level definition of the same name
winning; ToolSearch's tool_reference inside a tool_result stays. A later
tool_removal is not applied to tools (out of scope, as before).

Run (go1.26 darwin/arm64, sandbox HOME, -p 1 -tags nogui):
  go test ./internal/gateway -run 'TestOpenCodeDeepSeekInlineTools|
    TestDeferredInlineDefinitionPreserved|TestKimiIsSentNoDeferredToolBlocks|
    TestDeferredToolBlocksRefusedOnceLeftOut|TestOpenCodeGoModelsGoOnTheirOwnAPI|
    TestRefsOnly|TestRefsSaid|Deferred' -count=1  -> ok, 14 pass
Broken by hand:
  - forwardOnce's condition put back to isKimi alone:
    TestOpenCodeDeepSeekInlineTools/go/deepseek-v4.1-flash fails with the
    reporter's 422.
  - withoutDeferredTools not writing tools back: both new tests fail
    ("inline definition was not preserved", "tools lost or duplicated").
gofmt -l clean. GOOS=windows and GOOS=linux go vet -tags nogui
./internal/gateway clean. Not run: other packages, the GUI suite (disk
had under 1 GB free); not tried against the real OpenCode Go endpoint through
magpie (the reporter's direct requests are the evidence).

Full suite: SUITE_LINE

Co-authored-by: cyh <2293985047@qq.com>
2026-10-15 23:08:01 +08:00
yetone 5ca897690f library: an instructions set linked to the file an agent reads is read without magpie's part, so it isn't written into itself until gigabytes (#2349, eachann1024)
instructions.md linked to ~/.claude/CLAUDE.md (or both linked to one
dotfile) made the set's text the whole file, magpie's part included.
wanted() read it as is, syncInstructions wrote it into that same file's
part, and split() only knows the first begin/end pair, so the part never
matched and each sync nested the whole file in it again: the file doubled
at every sync. linkable() refuses an agent's own file for a set kept in
the user's file, but the default set's instructions.md being a link went
around it.

- setText reads a set's text with every magpie part taken out; used where
  the set's text is read (wanted, the page, ImportInstructions, carry,
  setup snapshot/compare).
- own() takes out every part, and the end lines a part nested in itself
  leaves behind, so a file already grown comes back to the user's text.
- An agent whose instructions file is, links followed (realBelow), the
  file the set on is kept in gets no part; one written before is taken
  out, the file kept aside first. ImportInstructions refuses that agent.
- docs/subsystems/library.md: Instructions row.

Run (worktree on origin/main 03eb0633a, go1.26, sandbox HOME via the
package's sandbox()):
- go test -p 1 -tags nogui ./internal/library -count=1: ok (114s)
- gofmt -l internal/library: clean
- GOOS=windows and GOOS=linux go vet -tags nogui ./internal/library: clean
Broken by hand: with instructions.go, carry.go and setup.go put back to
origin/main, TestInstructionsSetLinkedToAgentsFile fails: CLAUDE.md
holds nested magpie parts after three syncs, codex gets them, the page's
shared text has them, and a 4-deep grown file stays grown.
Not run: the real app with a linked instructions.md; Windows (symlink
creation skips the test there without the privilege).

Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00
yetone 1242367020 gui: the menu bar's idle tooltip splits today's tokens into input, output and cache (NextCommit on Discord)
With no cards ticked, the tooltip said only "Today: 6.3M tokens". It
now says "Today: 6.3M tokens (912K in · 318K out · 5.1M cached)" over the
cost and requests, as the usage:today card's tooltip has since #1984
(trayTokens, shared by both; cached left out when nothing was cached).

Run: TestTrayIdleTip and the SNI tip case, updated. gofmt -l clean.

Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00
yetone 49d60394ef gui: the Mac's menu bar item shows its tooltip, which Wails never set there (NextCommit on Discord)
NextCommit (macOS, 0.1.1244) hovered the menu bar item for today's
tokens split into input, output and cache and saw nothing. Nothing was
shown at all: Wails v3.0.0-beta.24's macosSystemTray.setTooltip is a
no-op ("Tooltips not supported on macOS"), so neither the idle tip nor a
card's tooltip (usage:today already said "6.3M tokens (912K in · 318K
out · 5.1M cached)") ever reached a Mac. Linux has its own setTrayTip
(SNI); Windows keeps Wails'.

setTrayTip on the Mac now sets the status item's button toolTip on the
main queue (trayTipNative, mpTip in trayimage_darwin.go), returning false
while the item isn't up yet so it is tried again, as Linux's does.

Run: TestMacTrayTipIsSet (darwin, cgo): setTrayTip reaches the native
setter, false before the item is up, and a real NSStatusBarButton keeps a
multi-line tip whole. go vet: darwin (cgo, GUI) and -tags nogui for
darwin, linux and windows. Not tried: hovering the icon in a built app.

Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00
yetone 6f6b7d4077 gateway: a Codex request with web_search stays alive while its provider is queued, not cut at Codex's idle timeout (#2316, clxsh)
A request that offers web_search to a model that can't run it goes through
searchReply, which reads the provider's reply in rounds. That reader used
readSSE, so the provider's keepalives (": keepalive", response.in_progress)
were dropped, and relay waited for the first event past KStart before it
made the client's encoder. A provider queued for minutes sent the client
nothing but the holdWriter's comments, which Codex's idle timeout doesn't
count: it hung up at ~315s and asked again, losing its place in the queue.
The plain translated path has kept the client alive since #436.

Now askTranslated reads with readSSEAlive and, after keepaliveGap with
nothing else sent, hands its reader a KAlive event (nothing of the reply).
searchRounds passes it on without collecting it, the collector ignores it
(no reasoning block boundary moves), and relay takes it as the provider
being heard from: it begins the client's stream and sends the protocol's
own keepalive (response.in_progress, Anthropic's ping) when the client has
been quiet keepaliveGap. A provider that goes silent sends no KAlive, so
relayEvents' keepaliveLongest still ends the keepalives; an error before
any keepalive is still a status for the next account.

Test: clxsh's TestSearchQueueKeepsCodexAlive as filed (comments, progress,
cancel, silent). On the old code all four fail (pings=0 complete=false,
only comments reach the client); with the fix they pass, -count=3.

Run: go test -tags nogui ./internal/gateway -run
'Search|Keep|Alive|Relay|Zen|Draw|Probe|Held|Hold|Queue|Codex.*Stream|Translated'
ok (75s); gofmt -l clean; go vet -tags nogui ./internal/gateway on
darwin, linux, windows clean. Not tried against a real queued provider.

Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00
yetone b9e5c28997 gui: a Library MCP server magpie can't check for a variable only its agent sets shows not checked, not a red error (#2308, ASD-max)
Codex's host-only codex_app (codex-app-tools, imported into the Library)
names ${CODEX_APP_TOOLS_PIPE_PATH} and ${CODEX_MCP_NODE_PATH}, which only
the Codex app sets when it starts the server. magpie's check expands them
from its own environment, finds them unset and returns novar before
starting anything. The page painted that red, the same as a server that
exited or doesn't answer, so a working server read as broken. Its tooltip
already said magpie can't check it there.

A novar result is now painted as not checked: a grey ring and muted
words ("CODEX_APP_TOOLS_PIPE_PATH, ... not set"), the same tooltip. Other
errors stay red. The check itself is unchanged: magpie doesn't start
codex_app with Codex's pipe, as the reporter's own probe shows Codex
turns away a peer that isn't its signed binary
(untrusted-code-signing-identity), and it doesn't learn the pipe's path.

Run: library-env-refs.test.cjs (Chromium and WebKit, en/zh/ja/de at
440px) now also checks the novar status isn't "err" and isn't the red
colour; with client.js put back to HEAD it fails. library-env-refs and
library-mcp-health pass (16). Go tests not run (no Go file changed; disk
under 6G free).

Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00
yetone 206dc24cd5 gui: with the Sessions page switched off, a latest session on Usage unfolds its details, not a click that does nothing (#2311, betacatZ)
Usage › Sessions' latest sessions open on the Sessions page. With that
page switched off in Plugins › Built-in (the reporter's screenshot has no
"All sessions" beside the search, which is hidden the same way), the row
still looked like a link, with a chevron and a pointer, and a click
returned without doing anything.

Now, with Sessions off, the row is a button (aria-expanded) that unfolds
the session's details in place, as a top session's do: time, folder,
session id, the resume command, what each model spent, the file. One is
open at a time, Enter and Space fold it, and nothing scrolls. With the
page on, a row still opens there.

Run: internal/gui/tests/sessions-usage-off.test.cjs (new, 12 cases:
Chromium and WebKit, en and zh, 900 and 420px) passes; with page.js put
back to HEAD its 4 Chromium "off" cases fail and the "on" cases pass.
sessions-usage-open, sessions-paging, sessions-in-range,
sessions-overview and builtins pass (84). Go tests not run here (disk
under 6G free); no Go file changed.

Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00
yetone 75035fa202 gateway: Command Code's bare 400 (a trace id, no reason) hands a group's request to the next member, not ends it (#2313, lqisgod)
Command Code's Provider API answers some requests with
{"message":"invalid request error trace_id: <hex>","type":"invalid_request_error"}:
a 400 (a 422 the week before), no code, no param. retryable() read it as
the request's own fault, so a group stopped there and its later members
were never asked: six requests in a row on lqisgod's wb-flash group, while
the fourth member answered the same ~660K prompt that hour.

What it turns away is the request's size, not the key: lqisgod's A/B on
one agent conversation (~748K tokens of history and tool calls, same bytes
otherwise) answered 200 with max_completion_tokens 64000 and this 400 with
384000, the max output Command Code lists for the model, so history plus
asked-for output is over a limit below the 1M context it lists. Its own
tracker has more of the kind (CommandCodeAI/command-code#960, #976).
Another member whose model has room may take the same request, so it is
asked, as for a shape another API can take.

unsaidWords matches that message alone, as the vendor sends it, wrapped by
a client in front of it, or told on after a provider's name. It goes the
way shapeWords do (shapeRefused, retryable): the next member is asked once,
Command Code doesn't rest, and the last member's error reaches the agent.
No retry of the same member is added. Its overflow ("The input is longer
than the model's context length trace_id: …") and a refusal naming a param
aren't matched. The keyed "commandcode" preset and the moved plan go
through the same gateway decision.

Tested: TestGroupFailsOverCommandCodesBare400 (streamed group request,
reporter's literal body; the 422 and wrapped forms from #960/#952; overflow,
param and longer-message negatives). With fallback.go put back it fails:
"400 ... COMMANDCODE: invalid request error trace_id: ... (a 1, b 0)".
go test -run 'TestGroupFailsOver|Shape' ./internal/gateway passes.

Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00
yetoneandhhh2210 94c70a2dd9 gui: the tray's Allowances cards say "Resets 14:26", not a bare ↻ that read as a button, and each card has the Usage page's own refresh (#840, hhh2210)
In the tray panel the first reset deadline was drawn as "↻ 14:26": text
with no click handler, which reads as a refresh to click (hhh2210 clicked
it). It now uses resetText, "Resets 14:26" / "重置于 14:26", as the
Usage page does; the other windows keep "Weekly Oct 31".

The tray cards also had no per-card refresh. They now get the main
window's quotaRefresh, the same single-card API and response-order
guard, at the start of the line under the account (the deadline, the
error, "Unlimited", or a balance's name): opened as the card is hovered
or the button is focused, spinning while it reads, closed taking no room
(the balance row's flex gap is closed with it). renderPanelQuota puts the
focus back on the button after the redraw. A failed read keeps the
figures and says the error in the footer, as on the Usage page.

Based on hhh2210's fork commit 9ea883ffb. Kept: the reset label, the
refresh on every tray card kind, the focus kept through the redraw, the
test's fixtures. Trimmed for the owner's UI restraint: the always-visible
24px button and the new "Updated N ago" row on every card (now hover-
revealed in the existing line, as on the Usage page), and the new status
texts (reading / cached, no new data / refresh failed / Claude's 30s
interval), which the Usage page's own refresh doesn't have either. No new
strings: "Resets {when}" and "Refresh this card" exist in every language.

Run (macOS arm64, Playwright 1.62.0, Chromium and WebKit):
- panel-quota-refresh.test.cjs, rewritten for this behaviour: 20/20,
  en/zh/zh-TW/ja/de at 440 and 360px tray widths.
- Broken by hand, each red with its own message: the ↻ label back ("the
  deadline says 重置于, got ↻ 14:31"); no refresh in the deadline line
  ("has its own refresh"); no focus restore ("the redraw keeps the
  focus"); no .pq-card:hover rule (hover never opens it); the error card
  without one ("kimi has its own refresh"); without the .pq-bn margin the
  closed button moved the balance's logo ("relay's closed refresh moves
  nothing").
- 68 GUI files that open the tray's Allowances or the Usage refresh
  (every mode=panel file reading usage/quotas, usage-card-refresh,
  quota-balance-error, usage-remote-*, quota-read-at): 943/944. The one
  red, usage-fold chromium "the view didn't scroll" 184 !== 180, is red
  alone on origin/main 95e7c6bcc too and is filed as #2163.
- No Go change.

Full suite: SUITE_LINE

Co-authored-by: hhh2210 <hzy2210@gmail.com>
2026-10-15 23:08:01 +08:00
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