Commit Graph
1849 Commits
Author SHA1 Message Date
yetoneandggbdpq 766d2a9f54 gateway: a Claude turn sent again while its run is busy with it goes on from a copy of its session (#5405)
A client's connection dropped mid-reply and its request was retried,
with no cancel reaching magpie (#5405, margbug01: a gateway between
the client and the server magpie retried after "unexpected EOF"). The
run the first attempt resumed was still busy with the very turn, so
resume and unshelve found nothing, and the retry started a new Claude
Code told the whole conversation in one message: only Claude Code's
own system prompt and tools read from the cache, the rest (92K to 142K
tokens in the report) written again on every retry.

retryBranch, tried in start between unshelve and retire, finds a busy
run of the account whose last heard request is this one, message for
message, and starts the retry's run from a copy of that run's session
cut before the turn (cutReply at backLine/backMsg), told only the
turn, as a branch off a side question already is. The busy run is left
alone; when both park at the same key, keepIdle lets the older go.
nil, and the conversation told whole as before, when no run matches,
the client places its own cache marks, the run was or is being taken
back, it was started for this turn (nothing before the turn to cut
at), or the session can't be cut (logged).

Changed from ggbdpq's patch: it matched with follows, which also takes
a request that goes on past the busy run's turn; the retry is matched
by the heard request's key alone. A copy cut for an older run is
discarded when a newer one is taken, a failed cut is logged as the
patch's notes say, and a run with a reply id but no line yet is cut
by the reply, as branchAt does. The test waits for the busy run to
have heard the turn instead of sleeping 200ms, and stops the held
first attempt in t.Cleanup, so a failing assert doesn't leave it
running. The doc's "goes on to step 3" now says step 4.

Run (mote, -tags nogui):
- TestClaudeTurnSentAgainWhileItsRunIsBusyBranchesOffItsSession
  (print, interactive) -count=3: ok.
- Broken by hand: claude_subscription.go back to origin/main, test
  kept: FAIL in both modes, "0 runs branched, 2 started anew, want one
  of each". Restored: ok.
- TestClaudeTurnPastABusyRunsTurnIsNotBranchedOffIt (print,
  interactive): a turn sent past the busy run's own, with a reply the
  client has, is told whole (one message, or the interactive mode's
  transcript), not branched off the busy run. -count=3 with the other
  test: ok; -race -count=5 of both: ok.
- Broken by hand: the match back to follows: FAIL in both modes, "the
  turn past the busy run's was branched off it" (nextTurn gives its run only
  "now commit it", the turn and reply before it lost). Restored: ok.
- -run TestClaude ./internal/gateway/: ok 139s.
- -race -count=5 -run of the busy-retry, fork, side-question,
  given-up, rewind, unshelve and branch tests: ok 52s.
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  internal/gateway: clean.
- gofmt -l on both Go files: empty.

Not tried: a real Claude subscription with a real dropped
connection. The full suite runs after the push.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 10:04:01 +08:00
yetoneandggbdpq baf70992f6 usage: a call the vendor answered with another model is priced as the model that served it (#5340)
The ledger priced a call at the model asked for and fell back to the
model the reply named (Served) only when the asked-for one had no price
(#1498). That order is right for a relay that sells kimi-k3 as
moonshot-kimi-k3 and bills by the name it sold, but it also priced a
real substitution: claude-opus-5-5 asked, claude-opus-5 served. The
vendor bills for the model that ran. kaimo455's ledger had 836 such
rows, every one at the asked-for rate: $374.06 reported against
$493.28 at the served model's rate. gateway-key cost limits (KeySpent,
NewCoster) and budgets read the same pricer.

Pricer now prices a call the ledger marks swapped at the served model's
price. That covers a price the user set for the served model and every
other layer of BasePriceIn. A price the user set for the model asked for
still wins, 0 included (new provider.UserBasePriceIn is BasePriceIn's
user layer alone). When the served model has no price, the asked-for
one's stands. Renames, vendor aliases, serving names and region
deployments price as before, and rate windows still read each record's
own time. apiPricer, the API price behind a subscription window's whole,
follows the same rule: the served model's API price first, then the
asked-for one's.

Review changes on top of ggbdpq's patch:
- The swap is judged the way the ledger's Swapped column judges it: on
  the model id and on the name that went out (SentNameIn over the
  user's ModelWires). A model the user sends under the served one's name
  was answered as asked, so it keeps its own price. The patch judged the
  model id alone, so such a row was priced as swapped while the Requests
  page said it wasn't. The pricers' memo keys now include the effort,
  because the sent name depends on it.
- apiPricer (window holds) got the same rule. The patch left it on the
  old order.

Tests:
- TestLedgerPricesASwappedCallAsTheModelThatServed (patch, plus a
  ModelWires case) checks the ledger and the Requests page.
- TestLedgerPricesARenamedModelAsTheOneServed: the sol row (sol asked,
  kimi-k3 served, both priced) is a genuine swap, so it now prices at 3,
  not 2.
- TestHoldsPriceTheModelTheReplyNamed: claude-opus-4-7 answered by
  gpt-5.5 is priced at gpt-5.5's API price. Answered by an unpriced name,
  it keeps opus's.

Run on mote at this tree, on origin/main 4e7661adc:
- The three tests above: ok.
- Product files (ledger.go, window_holds.go, provider/models.go) put
  back to origin/main, tests kept: all three FAIL ("served luna:
  priced=true cost=10, want 33"; "sol: ... cost=2, want ... 3"; "a call
  answered by another model wasn't priced as that one: &{Input:5 ...}").
- servedInstead's sent-name check broken by hand (return true): the
  ModelWires case FAILs ("served luna: priced=true cost=33, want 10").
- go test -tags nogui -count=1 ./internal/usage/ ./internal/provider/
  ./internal/budget/ ./internal/otlp/ ./internal/middleware/: all ok
  (usage 44.9s, provider 158.3s).
- gofmt -l: clean. GOOS=linux go vet -tags nogui and GOOS=windows go vet
  of internal/usage and internal/provider: clean.

Not tried: a real ledger with Anthropic's refusal fallback. The rows in
the tests are built from the shape the reporter describes. The full
suite runs after the push.

#5340, kaimo455 (report, measurement and the proposed order)

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 09:57:18 +08:00
yetone 4e7661adce redact: an app's one-word name the model took for a person's goes as written
Reported by ylorn. on Discord (11-06): choosing apps in Alma, a question
about one app was answered with another's facts. Privacy Filter took the
apps' names (Cicada, Mimi, Phosphor, Parakeet, Muesli) for people's: in a
bare list of them, alone, and in the Markdown list of apps the assistant
answered with (probed on the real model: ~0.99 each). The follow-up
questions ("How about Mimi?", "Phosphor vs Parakeet") it did not flag, so
they went as written while the history held the names as placeholders;
Phosphor and Parakeet (8 bytes) then became known values and were masked
everywhere. The vendor could not tell which placeholder was which app.

Restore was not the cause: placeholders are a keyed hash of kind and value,
one per value, and restore maps each back to its own value in any case
(TestManyNamesRestoreEachToItself, a guard: it passes on the old code too).

personFits now lets one ASCII word go when what is around it says a thing
and nothing says a person (thingNamed, internal/redact/thingname.go): a
person's word beside it (my colleague, Hi, Mr, said, told) masks; a thing's
word beside it (using, switched to, the ... app, vs, apps like, 这个软件)
lets go; else its sentence decides (he/she/relations/greetings/said mask;
app/macOS/subscription/vs/软件 let go); else a list item among items that
speak of apps, or a text of capitalized names only, lets go.

Trade-off, by design: a single first name alone, or a first name in a
sentence that speaks of an app with nothing of a person ("Mimi uses the
app daily"), goes as written. A full name (John Smith), a Chinese name
(张伟), and a first name beside a relation, a greeting, said or a pronoun
are masked as before.

Run (mote, worktree at 84ad780b6 + this):
- go test ./internal/redact/... ./internal/pii/... ./internal/masking/...
  ./internal/otlp/... ./internal/sessions/... ./internal/settings/... ok
- go test -run 'Mask|Redact|Privacy|Person|Known' ./internal/gateway
  ./internal/gui ok
- TestMaskEval re-recorded with both real models (MAGPIE_EVAL_CACHE);
  only the 12 new cases' recordings are added, old entries kept as they
  were (mote's re-record drifted 4 AstrLink and 2 Privacy Filter entries
  by score; not taken in). New cases app-names, app-alone, app-markdown
  (real Privacy Filter flags), app-compare/vs/list/using/zh (model finds
  none; guard), app-and-person, app-and-full-name, app-and-zh-name,
  greeting (person controls).
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/redact ok.

Broken by hand:
- the personFits hook off: TestAppNamesNotPersons red 9/9,
  TestPersonBesideAppStillMasked red on the 3 apps, TestMaskEval red on
  app-names (5), app-alone, app-markdown (3) with the real recordings.
- thingNamed always true: TestPersonBesideAppStillMasked red on Mimi (x2),
  Laura, Daniel.

Not tried: a real Alma chat through the gateway with the model on; Windows
and Linux runs (pure Go string code, vetted for both); the full suite runs
after the push.
2026-11-06 09:28:25 +08:00
yetone 84ad780b65 gui: DeepSeek's image-files setting in the provider editor's Advanced (#5407)
matrix0487 on Discord (#feedback, 11-05) asked to change image-files from
the GUI: 8fbf8e0af made it CLI-only (`magpie provider set <id>
image-files=off`). The editor's Advanced now has an Images tick, "Upload
images once and send them by file id", on by default. It shows only where
the setting has effect: a provider on api.deepseek.com, the built-in
DeepSeek or a custom one with that base.

The rule has one source: provider.ImageFilesAt(to) (own key, no account or
plugin, Chat/Responses/Anthropic, host == provider.DeepSeekHost), and
TakesImageFiles for the editor. The gateway's dsFilesOn and forward's
dsSent setup ask ImageFilesAt instead of their own host checks.
/api/providers sends imageFilesOff and takesImageFiles; /api/provider/save
takes imageFilesOff as *bool, so a save that leaves it out keeps the old
value (CLI-set off stays off), false turns it on, true off. app.js sends it
only when the row is shown. Strings in zh, zh-TW, ja and de. app.js is 135
bytes under its base (four comments cut to one line); no budget raised.

Run on mote:
- provider-image-files.test.cjs: chromium + webkit, en/zh/zh-TW/ja/de,
  1100 and 420 wide, 60/60. Shown for DeepSeek and a custom
  api.deepseek.com base, hidden for another relay, toggling saves the
  field, CLI-set off shows off.
- i18n-keys, i18n-en-no-cjk, editor-advanced-align, editor-fold-clickable,
  provider-limit-rest, provider-image-files: 131/132; the red is i18n-keys
  "a plugin's words are its own" from other tests' strings ("View
  routing", "No session ID"), #5332 / #5327.
- go test -timeout 45m ./internal/provider ./internal/gateway
  ./internal/cli ok; ./internal/gui ok but TestMainWindowCorners, the
  macOS 27 red (#3949). TestProviderSaveImageFiles and
  TestCoreScriptBudget rerun after the comment cut.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Broken by hand, each red then restored:
- row condition `if (false)`: GUI red (chromium en 420).
- save field renamed: GUI red (webkit zh 420).
- imageFilesOff left out of draftOf: GUI red ("one set off from the CLI").
- the old keep-only save restored: TestProviderSaveImageFiles red
  ("ticked on in the editor, still saved off").
- host rule loosened to contains "deepseek": TestProviderSaveImageFiles
  red (api.deepseek.com.example.com offered).

Not tried: a real DeepSeek key or the real app; a URL edit on an unsaved
provider doesn't show or hide the row live (it follows the saved row's
flag).
2026-11-06 08:01:14 +08:00
yetone ef176e21f6 sessions: a Claude Code session moved with /cd is listed under its new folder
usrname1833 on Discord (#feedback, 11-05): after Claude Code's /cd the
session's file is in the new folder's .claude/projects directory, while
magpie kept showing the session under the folder it was started in.

What /cd does (Claude Code 2.1.316, read in the binary and run for real
in a sandbox CLAUDE_CONFIG_DIR against a fake API): relocateSessionTranscript
renames projects/<old>/<id>.jsonl and its <id>/ folder to
projects/<new>/, and appends {"type":"relocated","relocatedCwd":"<new>"}.
The lines from before keep the old cwd; a second /cd adds another line,
and the last one names the folder.

Cause: a Claude Code session's folder was its first line's cwd only, and
a relocated line went to the default case. Every place that groups or
resumes by folder (GUI, TUI, `magpie sessions`, stats, the resume
command's cd) reads Session.Cwd, so all of them showed the old folder.

- claudeLine reads the relocated line (ccRelocated): the last move's
  folder is the session's.
- A parse kept by an earlier magpie isn't read again when the file
  hasn't changed. One whose folder isn't the project folder the file is
  in (ccStale, with Claude Code's own name: non-alphanumerics as "-",
  past 200 cut and a hash added) is read again once. state.CdRead marks a
  parse made by this reader, and a kept one in its right folder is marked
  on the first refresh, so the name isn't worked out on every poll.
  parseVersions isn't raised: that would read every Claude file again.
- A glance (a long file's row before its first read) takes a relocated
  line in the last 64 KB too.
- Sibling, magpie's own project move (relocateClaudeJSONL): a /cd'd
  session was judged by its first cwd, so moving the folder it was moved
  to failed with "a different project cwd", and relocatedCwd was never
  rewritten. It now judges by the last move and rewrites relocatedCwd.
- docs/subsystems/gateway-sessions.md says how the folder is found.

Fixtures (internal/sessions/testdata/claude-cd) are Claude Code
2.1.316's own lines from that run, paths written as /w, without request
records, attachments and file snapshots.

Run (mote, at a754660b2 + this):
- go test -count=1 ./internal/sessions ./internal/tui ./internal/cli: ok.
  ./internal/gui: ok but TestMainWindowCorners/macOS_26_SDK, which is
  #3949 (macOS 27 on mote), not this change.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok.
  gofmt -l: clean.
- wsl-run go test ./internal/sessions: ok.
- win-run go test ./internal/sessions: the new tests ok; TestAgySessions,
  TestAgyRowOnly (#4115) and TestCCListingKeepsItsNames (#4925/#5277) are
  red on Windows the same on a754660b2 alone.

Red on the old code (a754660b2 with the new tests):
TestClaudeCdListedUnderNewFolder (under /w/projA, resume cd '/w/projA')
and TestClaudeRelocationAfterCd ("a different project cwd").

Broken by hand, each red: ccRelocated not called (ListedUnderNewFolder,
KeptParseReadAgain); ccStale always false (KeptParseReadAgain); the kept
parse not marked (KeptParseReadAgain); the glance tail skipping relocated
lines (TestClaudeCdGlance); relocateClaudeJSONL not resetting the first
cwd on a move, and not rewriting relocatedCwd (RelocationAfterCd).

No GUI file changed and the GUI tests stub /api, so no GUI test was run.

Not tried: the reporter's own files; the fixed build against a real /cd'd
session in the app (only the package's listing, Find and resume command
in tests); a /cd across WSL, or Windows paths beyond the vet and the
package run there.

Reported by usrname1833 on Discord.
2026-11-06 07:32:04 +08:00
yetone a754660b2a gateway: requests that come together spread over a pool's accounts (#5242)
Moody-Sin and Tericerice (#5242, magpie 0.1.3072 on Linux): an
antigravity provider with three accounts and affinity turn sent four
requests at once all to one account, under In turn and By pace alike,
each request with its own X-Magpie-Session.

Cause:
- Nothing counted the requests in flight when a request was planned.
  Pace (internal/routes/strategies.go:348) goes by pace, wallet and
  Tokens, all of which move only once a reply ends; a key's lane counts
  a request only once its try starts, after planning. Requests that came
  together were planned on the same figures and all went to the first.
- In turn's next turn (affinity.go:685 "new-turn" → after(), :937) reads
  a stick that moves only when an answer comes back, so a burst of turns
  of conversations already answered all went to the one next account.
- conversationID (gateway.go:9160 on origin/main) ignored
  X-Magpie-Session, so callers that named their own sessions but opened
  alike were one conversation and kept together.

Fix:
- burst.go: burstSpread, called in serve once the candidates are planned
  (gateway.go:3013), counts each request on the account it goes to until
  it ends, and puts first, among the accounts routing would as soon pick
  (burstAlike: In turn any ready one; By pace a pace within a tenth, no
  wallet told apart, none near its cap; Least used within a point), the
  one with the fewest in flight. A kept conversation (session, turn's
  stick, strict), a pin, a lead's account, a checkpoint and a new
  conversation leastHeld spread are counted where they are, not moved.
  Fallbacks, reserved, aside, resting, held, barred and capped accounts,
  other routings (Smart, In order, ...) and a group in a group keep
  their order. In a group, a member routed its own way is alike only to
  its own provider's. The one step covers direct models, groups, plugin
  providers and a remote magpie.
- affinityID: the stick key (stickKey), a group rule's key (ruleKey) and
  the sealed lead's stick read X-Magpie-Session after an agent's own
  session header. conversationID, which Kilo and a plugin are sent as the
  conversation, is unchanged, so the caller's session never goes
  upstream.
- docs/subsystems/gateway-routing.md says both.

Not done: putting a markedly slower account behind by its TTFT. A first
token's wait goes with the prompt's size and the vendor's queue more than
with the account, so a small sample would move turns away from a fine
account and off its cache; it needs its own design.

Run (mote, mote-run):
- go test ./internal/gateway -run 'TestABurst|TestBurst|TestMagpieSession|
  Kilo|Sealed|Rule|Stick|Affinity|Conversation': ok
- go test ./internal/gateway ./internal/routes: ok (654s, 0.3s)
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok; gofmt -l: clean
New tests (burst_spread_test.go): six at once over three keys, rotate
and pace × affinity turn/off/auto × x-session-id / X-Magpie-Session /
same body × fresh and warm; over a group of three providers and of one
provider's keys; behind a remote magpie; over a plugin's three accounts
(fake plugin, streaming); a kept session stays on one account; paces
{10, 9.5} spread and {10, 5} don't; three X-Magpie-Sessions in turn get
an account each under session affinity, and conversationID never
returns X-Magpie-Session.

On the old code every pace case went 6 of 6 to k1, and rotate's warm
cases 6 of 6 to the next account.

Broken by hand:
- reorder forced false: every pace case, rotate's warm cases, the group
  pace cases, the remote and the plugin tests red.
- !aff.Kept dropped: TestABurstKeepsAKeptConversation red
  (map[k1:2 k2:2 k3:2]).
- affinityID without X-Magpie-Session: TestMagpieSessionIsTheConversation
  red (map[k1:3]); the burst tests stay green, as the count covers them.

Not tried: real Antigravity accounts, a run on Linux, a real remote
magpie on another machine.
2026-11-06 07:05:37 +08:00
yetone 5ae0ed1ab0 claude warm-up: a week left out while the five hours run is one the account hasn't
koohoko5924 (v0.1.3057, Claude Enterprise): the account has only a
five-hour window, and the warmer kept warming a week it doesn't have
(state Idle, 189 tries). warmNow walks withExpected(q.Windows, expect),
which adds the 7-day window whenever a reading leaves it out, since
Anthropic leaves a window out until the request that starts it. But
any request starts every window a plan has, so a week left out while
the five hours are running is not a week waiting to start.

warmNow now marks such a window Absent (codex-warmup.json, compared in
mapsEqual) and sends it nothing (windowAbsent). The rule: the reading
leaves it out, the reading is whole (no partial window), a shorter
plan window is running (shorterRunning), and it was never seen with a
reset or use. A week seen running before, or left out of a partial
reading, is warmed as before. usageRead counts an expected missing
window as due only when no shorter window runs. withExpected itself is
unchanged: claudeWithUnstarted uses it for the card. Codex has no
expect list, so it is untouched.

Docs: providers-accounts.md gets the rule.

Run (mote, at this tree): go test ./internal/provider -run
'Warm|NotStarted|UsageRead|Claude|Codex' ok; gofmt -l clean.

Broken by hand: windowAbsent off and the old usageRead check:
TestClaudeWarmLeavesAWeekTheAccountHasnt red (12 "7 days" sends),
TestClaudeWarmStartsAWeekThatReset's "never read" warmed, and
TestUsageReadLeavesAWeekTheAccountHasnt told five-only@x. With the
seen/partial guard taken out, "reset" and "partly told" go red.

Not tried: a real Enterprise account or a real warm-up; the state is
the report's (Idle 189), rebuilt in the test.
2026-11-06 06:30:23 +08:00
yetone beba9e8a1f claude warm-up: the account it started is read again, its old reading keeping its time
koohoko5924 (v0.1.3057): after a warm-up the card said "just updated"
over windows read before it. claudeWarmedNow cleared the kept
reading's time (e.at) and kept its windows, so claudeReadAt gave nil
and readNow stamped them now. Nothing read the account again either:
claudeWindows' next read waits on when /usage last ran (e.tried),
which the warm-up left alone.

claudeWarmedNow now clears e.tried, which makes the next read due as
for an account never read, and keeps e.at, so until that read the card
shows the reading's own time. Codex's warmed hook only drops its cache
(its usage is a fresh API read), so it has no such sibling.

Run (mote, at this tree): go test ./internal/provider -run
'TestClaudeWarmedReadAgain|Warm|Claude' ok; gofmt -l clean.

Broken by hand: on the old claudeWarmedNow TestClaudeWarmedReadAgain is
red ("the kept reading's time is <nil>"); keeping e.at but not clearing
e.tried, red ("warmed, not read again", the 10% reading kept).

Not tried: a real warm-up on a real Claude account.
2026-11-06 06:30:23 +08:00
yetone 77031d5817 claude usage: a /usage panel with no window is no window started, and a failure says why
koohoko5924 (Discord #help, v0.1.3057, macOS): a Claude Enterprise
account with a five-hour window only. A manual refresh took ~5s and
gave the card no window and the error "Claude Code's usage showed no
usage figures: ▐▛███▜▌ … magpie-claude-work…": Claude Code's banner,
not a reason.

Claude Code 2.1.316's Usage tab (gi) draws a window only once
Anthropic's answer has it non-null, and a window is null until the
request that starts it. An idle 5h-only account's panel loads with
the session's cost, maybe the plan's credit bar, and no window. The
helper told that panel's words, joined from the top of the screen, and
the card took them as a failure with the banner first.

- claudetui: a panel that loaded (tabs, Session/Total cost, nothing
  loading, refreshing, stale or failed, no gateway Spend limit) with no
  "Current session"/"Current week" is told as NoUsageWindow ("No usage
  window has started"). The provider reads that as no window started:
  no error, the unstarted 5h window as for any account.
- claudetui: the two rate-limit errors gi draws ("Claude is temporarily
  limiting requests to the usage page (not your usage limit)…",
  "Usage endpoint is rate limited until …") are failures to load, like
  "Failed to load usage data": retried once, then told as an error with
  the panel's own "Error: …" text, never the banner. A panel with no
  window and no error is told from its tabs on, the session's cost
  lines left out.
- provider: "(not your usage limit)" no longer reads as an account
  refused (claudeDenied, at every place claudeUsageDenied judged a
  reading: the CLI parse, codex_switch, quota_last, subscription_usage).
  Counts ("Last 7d · 403 requests …") are taken out wherever they sit in
  a line before that check, as the panel's words come on one line now.
  A no-figures error keeps every line (600 runes), not the first clipped
  at 120.

Tests are built from 2.1.316's own strings (ko/gi/hi in the bundled
cli.js), drawn on the helper's 200x50 grid row by row. Guessed: the
exact bytes of a real Enterprise panel (not captured; no such account
here) and the credit bar's layout.

Run (mote, at this tree): go test ./internal/claudetui ./internal/provider
-run 'Usage|Claude|Shim|Quota|Codex' ok; go vet for claudetui, provider,
gateway; GOOS=linux -tags nogui and GOOS=windows go vet; gofmt -l clean.

Broken by hand (each red, then restored):
- the NoUsageWindow case off: TestShimReadsUsageWithNoWindow red in all
  three panels (told the panel's words as success);
- the provider's claudeNoWindow branch off: TestClaudeUsageNoWindowStarted
  red ("showed no usage figures: No usage window has started");
- claudeDenied back to claudeUsageDenied: TestClaudeUsageWhyKept red
  ("read as an account refused");
- usageFailed back to "Failed to load usage data" and the whole screen as
  the reason: TestShimToldWhyUsageFailed red in all three (the banner as
  the reason; the rate-limit panels told as no window), TestUsageNoWindow
  red.

Not tried: a real Claude Enterprise account; a real rate-limited panel.
2026-11-06 06:30:23 +08:00
qiqllandggbdpq b7631300ec claudetui: a successful interactive turn tells its account's allowance
Since the interactive mode replaced -p for Claude subscription turns
(43966a53, e5f66f8a, 10-31), a turn that succeeded told no
rate_limit_event, so NoteClaudeLimits never ran and the Usage page's
5h/7d figures moved only on a manual refresh (/usage). Only a turn that
ended in a <synthetic> API error told one, from its transcript row.

What changed:
- tap.js, when a main-class reply opens, also copies its
  anthropic-ratelimit-unified-* response headers into the {s, open}
  line as "h". It only reads them; the request to Anthropic is sent as
  Claude Code made it.
- tap.go (rateLimitInfo) turns them into the rate_limit_info -p tells
  (Claude Code 2.1.291): status plus unifiedWindows five_hour, seven_day,
  seven_day_overage_included (5h, 7d, 7d_oi), each only when both its
  utilization and reset are numbers, the reset rounded to a second.
- A streamed reply tells it just before its message_start, as -p does,
  so the bridge keeps it before the reply begins. A reply whose message
  was told whole from the transcript, or that never began one, keeps it
  for the turn's end (tap.settle). Only the latest is told: a kept
  reading from an older reply is never told after a later reply's
  (toldOf), whether the older one ended before or after the later one
  began, since NoteClaudeLimits keeps the last it hears.
- transcript.go: a <synthetic> API error settles the tap first, then
  tells its own rate_limit_info, so the error's reading is the newest.
- docs/subsystems/claude-subscription-bridge.md says all of this.
  The gateway is unchanged: it already turns a rate_limit_event into
  NoteClaudeLimits and limitHeaders.

Run at this head (base origin/main 6c201095):
- gofmt -l on the changed Go files: nothing
- go vet ./internal/claudetui/, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet: clean
- go test -count=1 ./internal/claudetui/: ok (62s)
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway/ -run
  'Claude|Tap|TUI': ok (60s)

Broken by hand:
- tap.go, tap.js and transcript.go at 6c201095 with the new tests: all of
  TestTapTellsReplyLimits, TestTapLimitsOfMessageToldWhole,
  TestTapErrorLimitsLast, TestShimTellsTapLimits and
  TestTapKeptLimitsNotAfterNewer (both subtests) red.
- keepLimits without `n > t.toldOf`: TestTapKeptLimitsNotAfterNewer/
  ended_after red (told 0.42 then 0.3). message_start without dropping an
  older kept reading: /ended_before red the same way.

Not tried: a turn on a real claude.ai account, so the headers were not
checked against a captured reply; Windows and WSL; the full go test
./... suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Review: chosen over #5012, which reads the same headers but emits a
rate_limit_event the moment its line arrives. That event can land while an
unstreamed message is pending, and the bridge settles that message early.
This one tells the limits just before message_start, keeps them for a cut
stream's end, and never tells an older reply's limits after a newer one's.
ddnio's real setup-token run on #5012 shows Bun's response headers are
readable there, the same thing this reads.
Run at the pushed head on mote, go1.26.8: go test -tags nogui -count=1
./internal/claudetui/ ok (83s).
Broken by hand: with the limits before message_start turned off,
TestTapTellsReplyLimits, TestShimTellsTapLimits and
TestTapKeptLimitsNotAfterNewer are red.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 05:54:00 +08:00
ggbdpq 3da58c3dfc fix(plugin): end ordinary RPCs' plugin work when their caller leaves (#4678)
A plugin model list's deadline and an ordinary RPC's cancellation released
only the caller. inTime raced the hook without stopping it, and host.go
marked only gatewayRequest cancellable, so a cancelled usage or providers
call never told the host: the plugin's task kept running, the host's
pending count kept it, and repeated reads left task after task alive past
their callers. Reported with an offline host-script reproduction that
shows abort reaching none of three pending usage tasks and five model
tasks outliving their deadlines.

The cancellation path a fetch and a gateway request already take now
carries ordinary RPCs too:

- host.go marks every call but init cancellable, so a caller whose
  context ends has the host told (the existing callAborting write), the
  way it already tells it of a stopped fetch. init is left alone: a start
  that overruns is stopped whole.
- host.js registers each ordinary RPC's AbortController; an aborted
  RPC's answer, nobody's then, is not sent.
- the handler is handed the signal: usage passes it to the plugin's
  auth.usage hook as its own options, and a model list's hook options
  carry it, with the listWait deadline aborting the same controller, so
  vendor I/O that supports stopping stops at the deadline or when the
  caller leaves, whichever comes first.

Sign-in renewal and its persistence are untouched: fresh() runs before
the hooks, and an aborted RPC's handler still finishes what it saves.

Refs #4678

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported, narrowed: an aborted ordinary RPC is no longer
answered "Aborted" at once and dropped from pending. It stays pending
until its handler ends, as on main. host.go's stop() closes the host's
stdin and then gives a renewing host up to stopRenewing to save the
rotated token; with the early done(), host.js's own `pending === 0 &&
closed` exit ended the process at once under a cancelled call whose
handler was still renewing or saving (keepSignedIn, set, signOut, a
usage hook mid-refresh). The Go side needs no answer: an aborted call
is released once its abort is written. The signal to the usage and
models hooks, and the listWait deadline aborting the models hook, are
kept as the patch had them.
TestCancelledCallKeepsTheHostTillItsHookEnds is new: a usage hook that
ends 600ms after its abort, then Settle() closing the host's stdin; the
hook's end must reach its trace.

Run on mote (darwin arm64, Go 1.26.8, Bun via testenv): go test -tags
nogui -count=1 ./internal/plugin/... ok 102.8s; -run Plugin
./internal/gateway/ ok 52.1s and ./internal/provider/ ok 13.3s.
Broken by hand: host.js and host.go at main, tests kept:
TestOrdinaryCallCancelTellsTheHost FAIL "the host was told of the
cancellation didn't happen", TestCancelledUsageReachesThePlugin FAIL
"the plugin's usage hook was handed a signal didn't happen",
TestModelListDeadlineTellsTheHook FAIL "the models hook was handed a
signal didn't happen". host.js as the patch had it (early answer):
TestCancelledCallKeepsTheHostTillItsHookEnds FAIL "the host left
before the hook ended; trace: {"signal":"live"}...".
Not tried: the reporter's replay.py against the built host, and a real
plugin's usage hook that passes the signal to its fetch. The reporter's
"host lives on after stdin closes with a task pending" row is unchanged
by design: that is the renewal safeguard.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 05:53:23 +08:00
ggbdpqandIkki c6d2bd3316 library: ZCode reads the shared skills folder too (#4987)
ZCode reads ~/.agents/skills beside its own ~/.zcode/skills, but it
wasn't among the readers of the shared folder: a skill kept there
behaved as if ZCode didn't have it — its chip unlocked, a tick writing
a second link into its own folder. It reads it as the others do.

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported: docs/subsystems/library.md now lists ZCode among the
readers of ~/.agents/skills, as Ikki6666's own branch (a23828e81) had it;
the reporter checked the published ZCode builds for a version boundary
and found none (#4987).

Run on mote (darwin arm64, Go 1.26.8): go test -tags nogui -count=1
./internal/library/ ok 76.5s; -run 'ZCode|Shared|Always' ok.
Broken by hand: "zcode" taken out of readsShared, test kept:
TestSharedSkillReachesZCode FAIL "zcode has a second link to it in its
own folder" and "zcode's own folder got it on the sync too".
Not tried: a real ZCode install reading the skill.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
Co-authored-by: Ikki <824310075@qq.com>
2026-11-06 05:41:29 +08:00
yetone acde144a7a providers: a vendor of embedding and rerank models alone is detected on /embeddings and /rerank (heatonz)
heatonz on Discord (#help, 11-05): a custom provider whose models are only
embedding and rerank models couldn't be added. Detect APIs ("检测协议")
picked the first listed model, an embedding model, and asked it to chat on
every API, so nothing answered.

- tiny: an embedding or rerank model (catalog.ServesOf) on Chat is asked
  where the gateway's retrieve sends it: the OpenAI base's /embeddings
  ({"model","input"}) or /rerank ({"model","query","documents"}). tested
  adds no extra body there, as the gateway sends none.
- detectModel asks each API a model that chats when the list has one, so
  a chat vendor's detection is unchanged. A retrieval model is a last
  resort on Chat only. Responses, Anthropic and Gemini say why they weren't
  asked (DetectModels too).
- testModel: a saved provider with nothing to chat with tests on a
  retrieval model its list keeps apart (LiveServing). testOne asks such a
  model on Chat and never moves it to another API.
- provider.ListAll is List with Serves models kept. /api/provider/list and
  the provider's JSON carry a `retrieval` count. The add form's Fetch models
  and the saved editor say "Only embedding and rerank models are listed.
  They need no pick: ask them on /v1/embeddings and /v1/rerank." in place
  of "the list is empty". One new string, in zh, zh-TW, ja and de.
- app.js stays under TestCoreScriptBudget with no raise: +42 bytes, paid
  for by two add-form comments cut.
- The gateway already routes /v1/embeddings and /v1/rerank to such a
  provider (#765, resolveRetrievalModel by prefix or KindGroup), so nothing
  changed there.

Run (mote, at this tree on origin/main 60fe6645a):
- go test ./internal/provider ./internal/catalog: ok.
- go test ./internal/gui: ok, except TestMainWindowCorners/macOS_26_SDK,
  which is #3949 (mote is macOS 27).
- go build ./..., go vet (darwin), GOOS=linux go vet -tags nogui and
  GOOS=windows go vet of provider and gui: ok. gofmt -l: clean.
- node --test, chromium and webkit: provider-retrieval-only (new: en, zh,
  zh-TW, ja, de, with and without retrieval models, add form and saved
  editor), provider-detect, provider-add-models, azure-endpoint,
  provider-listed-as, provider-add-gemini, i18n-en-no-cjk and i18n-keys.
  94 of 95 pass. The red is i18n-keys "a plugin's words are its own", red
  on origin/main 60fe6645a too (#5332/#5327).

Broken by hand:
- New tests on origin/main's code. TestDetectEmbeddingOnly red ("The
  model BAAI/bge-m3 does not support chat" on chat, 404 on the rest).
  TestTestEmbeddingOnly red ("no model to try"). TestProviderListBeforeSave
  red (retrieval = 0).
- Retrieval models not kept out of chat probes: the mixed-list case is red
  (bge-m3 asked beside glm-5).
- tested adding the extra body to /embeddings: red (prompt_cache_key
  sent).
- detectOne asking non-Chat APIs with a retrieval model: red (404 on
  /v1/responses).
- testModel's LiveServing fallback off: TestTestEmbeddingOnly red.
- provider-retrieval-only on the old app.js with the new i18n.js: the 5
  retrieval cases red, the 5 empty-list ones green.

Not tried:
- A real embedding/rerank vendor (heatonz's is unknown). Fake httptest
  servers only.
- The whole GUI suite.
- Windows and Linux test runs (vet only).
- Models whose ids don't say embed, bge- or rerank (gte-, e5-, m3e-,
  text2vec-, voyage-) are still taken as chat models. The /embeddings probe
  goes by the id, and a Xinference model_type isn't read.
2026-11-06 05:21:05 +08:00
yetone 60fe6645a9 claude: a caller's folder Claude Code would ask about is known before the run, and the session kept (sleepy_shibe)
sleepy_shibe on Discord (magpie 0.1.2996, Claude Code 2.1.318, own
account, interactive mode): message counts 36, 65, 85, 108, 128 for one
conversation. Confirmed at origin/main 74d1cda42: a caller's folder Claude
Code asked about was passed over for untrustedFor (10 min) only. Past
that, the next run went in the caller's folder again, claudeSessions
pointed at another project folder than the conversation's session in
magpie's folder, so `from` went nil and the run was told the whole
conversation; Claude Code asked about trust, startTrusted dropped
req.branch and started from nil in magpie's folder (the deferred
from.discard() had already removed the session), told it all again.

Now, for the own account in the interactive mode, each run first decides
as Claude Code does (untrustedHere -> claudeTrusts), from
hasTrustDialogAccepted in claudeProfilePath()'s .claude.json
(provider.ClaudeTrustedProjects; a missing file is nothing trusted, an
unreadable one unknown, which goes on as before). The rules are Claude
Code 2.1.316's, read from its bundled JS (UI/zh/jh/Y0/lr): the key of the
repository's main checkout (a worktree's is the checkout it was added
from), or any folder from the run's up to the git root and never past it
(a nested repository isn't trusted by its parent), every folder above
outside a repository; NFC keys, forward slashes on Windows
(claudeTrustKey, shared with claudeTrustKeys). An untrusted folder stays
in magpie's folder with its session; a folder trusted since is run in on
the next run. When Claude Code asks all the same, startRun keeps `from`
and startTrusted goes on from it in magpie's folder with the branch.

Run (mote, at this tree on 74d1cda42):
- go test ./internal/gateway -run TestClaude: ok (118s);
  go test ./internal/provider -run Claude: ok
- GOOS=windows and GOOS=linux go vet ./internal/gateway ./internal/provider: ok
- win-run go test ./internal/gateway -run TestClaudeTrust: ok
- real Claude Code 2.1.316 in a sandbox HOME + CLAUDE_CONFIG_DIR (dummy
  key, no account), tmux, 10 cases: repo/subfolder/parent-in-repo/
  worktree-of-trusted/worktree-itself trusted -> no question; worktree
  under a trusted parent, nested repo in a trusted repo, repo under a
  trusted parent, unrelated folder -> asked; outside a repo a trusted
  parent -> no question. All ten match claudeTrustedBy.
Broken by hand:
- untrustedHere returning passedOver only (the old choice):
  TestClaudeTUIUntrustedFolderKeepsItsSession/untrusted red (helper
  started twice) and TestClaudeTUIFolderTrustedLaterRunInAtOnce red (ran
  in magpie's folder).
- startTrusted dropping req.branch and starting from nil (the old
  fallback): .../unknown red (resumed a new transcript, not the
  conversation's session).
Not tried: the owner's real account or a real turn through the gateway
(no sign-in in the sandbox); Claude Code 2.1.318 itself (2.1.316 is
installed here); a Windows or Linux real Claude Code; the full suite
before the push (it runs after, through the suite lock).
2026-11-06 04:35:12 +08:00
yetone 8fbf8e0af6 gateway: DeepSeek's own API gets an agent's images once, by file id, not on every turn (#5407)
DeepSeek's API is stateless, so every turn re-sent every inline image in
the history. Now, on api.deepseek.com only (never a relay or another
base), for a model with "flash" in its name (deepseek-flash sees images;
deepseek-v4-pro reads them as "[Unsupported Image]"), each base64 data:
image goes up once through POST /files (purpose=user_data, expires_after
a day) with the candidate's own key, and later turns name it by file id:
- Chat: {"type":"file","file_id":…} (flat, as DeepSeek's vision guide);
- Responses: input_image with file_id in place of image_url;
- Anthropic: source {"type":"file","file_id":…} plus anthropic-beta
  files-api-2025-04-14.
Shapes checked against api-docs.deepseek.com files_api, vision,
responses_api and anthropic_api. The Anthropic guide names the "file"
source type and the beta; the field name file_id is Anthropic's Files
API's, which DeepSeek says it follows. Not confirmed with a real call.

Ids are kept per key hash + image sha256 in deepseek-files.json beside
providers.json (temp+rename, unparseable file moved to .bad), reuploaded
with under an hour left. One upload per image and key however many
requests want it; a request waits at most 8s for its uploads, and what
isn't up goes inline this turn. A failed upload leaves the image inline
and rests that key's uploads for 10 minutes. A 4xx naming a file-api id
or a missing/expired file forgets the ids, uploads again and asks once
more; refused again, the request goes inline. detail:low stays inline.
`magpie provider set <id> image-files=off` turns it off (kept on GUI
save). Doc: docs/subsystems/gateway-routing.md.

Run (mote, at this tree on 498b6419f):
- go test -run 'DeepSeek|DsFileGone' ./internal/gateway: ok; -race -count=3 ok
- go test ./internal/gateway ./internal/provider ./internal/cli: ok
- go test ./internal/gui: TestMainWindowCorners/macOS_26_SDK red, the
  known macOS 27 red on mote (#3949); nothing in gui's code path changed
  but a kept field on save
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok;
  go build ./... and GOOS=linux -tags nogui ok

Broken by hand, each red: host check removed (InlineElsewhere), switch
ignored (ImageFilesOff), singleflight off (FilesOneUpload), breaker off
(UploadFailsInline), key left out of the cache key (FilesPerKey and
others), beta not added (ImagesByFile/anthropic), retry off
(FileGoneUploadsAgain), store not read from disk (FilesKeptOnDisk), the
flash check removed (InlineElsewhere), the 8s wait cap removed
(UploadSlowGoesInline).

Not tried: a real DeepSeek key (none available in the sandbox), so the
exact refusal text for a gone file and the Anthropic file_id field are
unconfirmed against the live API. Not covered: a custom_tool_call_output's
images (walkImages doesn't read it); files aren't deleted (they expire in
a day).
2026-11-06 02:46:46 +08:00
yetone 498b6419ff claude: a turn Anthropic refuses in the interactive mode as a third-party app's is asked again as claude -p, and the agent's prompt is remembered
Raven (Discord #general): Cindy with Pi as its engine, routed through
group/auto to a Claude subscription, failed every turn with "Anthropic
refused an interactive-mode turn on claude-opus-5-5 as a third-party
app's", and the message told them to turn the interactive mode off in
Settings, which makes every request of every agent run as -p (about twice
the plan count).

Now, with the interactive mode on:
- a refusal carrying "Third-party apps now draw from your extra usage",
  met before a byte of the reply reached the client (stream head, or a
  whole reply with no parts), is asked again once as claude -p
  (redoAsPrint); the client sees only the -p answer;
- the agent's system prompt (sha256 of its first 2KB, billing header
  dropped, so Pi's trailing <cwd> doesn't change it) is remembered for
  12h, and its next turns go straight to -p (wantTUI, req.tuiRefused,
  clientCache.print) while every other agent stays interactive;
- a refusal after the reply had begun (keepalive sent, or text said) is
  not redone, so nothing is spent twice; the prompt is still remembered
  and the message now says magpie runs its next turns as -p: ask again;
- a -p run that is refused too fails as before ("run as claude -p"),
  once, no loop;
- the setting is untouched; with it off (claudePrintMode) everything is
  -p as before. The run is the real claude binary, nothing else changed
  in what is sent.

This reverses the #4503 call (fbbdf6e05, v0.1.2754: no automatic -p redo)
and the 10-31/11-01 "nothing ever runs as -p with the interactive mode
on", for this refusal only. The switch's foot, the Settings text (en, zh,
zh-TW, ja, de) and docs/subsystems/claude-subscription-bridge.md say so.

Run (mote, at this head rebased on 1100ed649):
- go test -run 'ThirdParty|TUIRefusal|ClaudeTUI|ClaudeSubscription|ClaudePrint'
  ./internal/gateway/ ok; Budget/i18n tests in ./internal/gui ok
- gofmt -l clean; go vet ./internal/gateway (darwin, GOOS=linux,
  GOOS=windows) ok; GOOS=windows go vet ./internal/gui ok. GOOS=linux go
  vet ./internal/gui fails in wails' cgo-only linux files on mote, the same
  on main, untouched here.
- GUI, chromium and webkit: claude-mode, claude-tui-setting,
  claude-quota-onboarding, mobile-web, i18n-keys, gui-zh-tw, gui-ja,
  gui-de: 57 pass, 6 fail in each engine; the fails are i18n-keys "a
  plugin's words are its own" (#5327, #5332) and mobile-web (#3952,
  #5013), the same 6 at origin/main 1100ed649 alone.
- Red on the old code: the new tests run against 1d704f819 all fail (400,
  the old "turn the interactive mode off" message).

Broken by hand: dropping len(col.res.Parts)==0 from the whole-reply redo
turns TestClaudeTUIThirdPartyRefusalAfterWordsNotRedone/whole red;
dropping the refusedTUI call turns ...PromptRemembered, ...AfterStart and
...AfterWords/stream red.

Tests use the real Pi 1.1.0 system prompt (testdata/workdir/pi-1.1.0.json)
with its cwd changed per conversation.

Not tried: a real Claude account (no refused turn reproduced against
Anthropic; the refusal text is the one the reporter's log and #4503
carry). A -p run continuing with tool results under a remembered prompt
(the wantTUI resume path) has no test of its own.
2026-11-06 01:20:14 +08:00
yetone 1d704f8190 codex: OpenAI's threads follow a provider of the user's at the top, where Codex resumes them
harris on Discord (the Codex app, after switching from CC Switch):
"This chat uses openai, but your current provider is custom. Switch to
openai to continue." CC Switch left its "custom" as config.toml's
model_provider, which magpie keeps since #4347, and Codex 0.166 resumes
a thread only on the provider it is on now. Every thread started on
OpenAI before was refused, and switching to OpenAI would refuse
custom's threads instead, so the user was stuck. Nothing moved them:
bringOver moves only onto magpie, bringBeside only from such a provider
onto OpenAI.

lendOwn (each Sync) moves OpenAI's threads onto that provider, as
bringBeside does the other way: in place at OpenAI's length, by the row
for a paginated thread, the last 30 days rewritten with a copy kept
otherwise. The ids go in stash codex.lent; giveLent returns exactly
those to OpenAI once Codex is on it again (CC Switch's official card),
keeps the record while Codex is on that provider or on magpie, and
drops it on any other. Nothing moves while a profile names openai,
after the user disconnected Codex, or from a distro's Codex.
TestCodexThreadsComeBackOffMagpie/by_hand expected an OpenAI thread to
stay on OpenAI with custom set by hand at the top, the stuck state
itself; it now expects it on custom. docs/subsystems/agent-wiring.md
says so.

Run (mote, go 1.26.8): go test -count=1 ./internal/agent/ ok (250s);
GOOS=windows, GOOS=linux and native go vet ./internal/agent/ ok;
gofmt -l clean.
Broken by hand: Sync without lendOwn, TestCodexOwnProviderTakesOpenAIThreads
red (thread left on "openai", rollout not on custom); without the
disconnected and profile guards, TestCodexOwnProviderLeavesOpenAIThreads
red for both cases.
Not tried: a real Codex app resuming a moved thread on a real relay;
harris's config.toml wasn't seen, so the "custom" here is CC Switch's
relay table as it writes it. A thread moved from the ChatGPT backend to
a relay carries its encrypted reasoning, which a relay on another
account may not accept; the thread then fails on the relay as a
switch to it by hand would.
2026-11-06 00:51:01 +08:00
yetone 845e324b13 liveagent: each model on its own API, and the request format the user picks stays (xiaoxiaofei)
xiaoxiaofei on Discord: "magpie 默认导入的是 message 格式的,要可以自定义请求格式".
magpie wrote one LiveAgent provider, "magpie", type claude_code with
api anthropic-messages, for every model. K-brain asks all of a
provider's models on the provider's one API (routing/client.go builds
the client per provider; PiModel.api is only validated), and LiveAgent's
settings lock an Anthropic provider's API: only an OpenAI provider
(type codex) has a request format to pick (ProviderModalView.tsx,
resolveProviderApi; K-brain settings_provider.go accepts
openai-completions and openai-responses). So the format couldn't be
changed, and a GPT served on Responses was translated from Messages on
every turn.

Now, as dsh's routes do (dshKinds), each model goes on the provider of
the API it is served on natively (catalog.Model.APIs):
- magpie: type codex, Chat Completions, baseUrl the gateway's /v1, for
  every model with no Responses or Messages API of its own (groups, Chat
  providers' models);
- magpie-responses: type codex, Responses, baseUrl /v1;
- magpie-anthropic: type claude_code, Messages, baseUrl the root (K-brain
  appends /v1; for OpenAI it appends only /chat/completions or
  /responses, hence /v1 there).
A codex provider is written with api and requestFormat, as LiveAgent's
settings write one; when the user switches it in LiveAgent, a sync keeps
their format (one LiveAgent doesn't offer goes back to magpie's). A
provider left with no model is taken out. A config.json from before (all
on one claude_code "magpie") is moved on the next sync: each model brings
its record (the user's display name) and whether it was turned off, and
a default/compact/task pick of it follows it to its new provider.
Disconnect takes all three out. Docs: reference.md, agent-wiring.md.

Run (mote, through mote-run):
- go test -tags nogui ./internal/agent -run '^TestLiveAgent|Key': all pass,
  new TestLiveAgentRequestFormat and TestLiveAgentFormatMove included.
- go test -tags nogui -timeout 45m ./internal/agent: ok (320s).
- GOOS=linux and GOOS=windows go vet ./internal/agent: clean; gofmt -l clean.
- K-brain 507f560 (the version LiveAgent af89ea7 pins), with Go 1.27.0
  on mote: config.LoadFile on the config.json magpie writes in
  TestLiveAgentRequestFormat loads it, and routing.ClientForProvider
  builds *ai.OpenAI at http://127.0.0.1:3425/v1 for magpie,
  *ai.Responses at /v1 for magpie-responses and *ai.Anthropic at the
  root for magpie-anthropic (a throwaway test, not committed).

Broken by hand (a copy), each turned a test red:
- the user's format not kept -> TestLiveAgentRequestFormat;
- no carried record from another provider of magpie's -> FormatMove;
- picks not following their model -> FormatMove;
- Responses models left on magpie -> both;
- an emptied provider not taken out -> FormatMove;
- turned-off not carried to the new provider -> FormatMove.

Full suite at c24915f04 (the change before this one), go test -timeout
45m ./... on mote: 86 packages ok, internal/gui red on
TestMainWindowCorners/macOS_26_SDK (#3949) and
TestPanelHiddenByWailsMarksPageOutOfSight (#5322), both filed, both
macOS 27 on mote.

Not tried: the LiveAgent app itself (its UI showing the three providers
and switching a format, then a real turn through the gateway); LiveAgent
on Windows or Linux; a real config.json of a user's.
2026-11-06 00:48:29 +08:00
yetone 814a625a24 usage: the top refresh reads saved Claude accounts again (#5380)
The tray panel's Allowances refresh said "Allowances refreshed" but a
saved, non-active Claude account kept its old reading: claudeWindows runs
Claude Code's /usage for a saved account only under savedRefresh, which
only that account's own card refresh sets.

Now a refresh of every allowance by hand asks usage/quotas?asked=1&all=1
(AskEveryClaudeUsage). It marks its ask generation in claudeEveryAsked,
and for claudeEveryFor (2 minutes) each saved account not read since is
read as its card's refresh would, under the same due check, the
30-second per-account floor and the same running holds. Opening the
Usage page or the Allowances tab (?asked=1 alone), the timed refresh and
every background read are unchanged, so nothing polls more. Callers:
the panel's top refresh (refreshPage "allowances"), the Usage page's
refresh and sidebar reload (refreshUsage -> loadQuotas("all")),
Routing's Read allowances, and the TUI's r. loadQuotas no longer lets a
lesser load on its way (an opening's asked read) swallow a Refresh.

Siblings: saved Codex accounts are already read anew on every asked
whole read (loginReading over HTTP after AskUsage clears the cache), so
Codex is unaffected. PlanQuotas and KeyBalances keep their 1-minute cache
on an asked read; left as is. The core scripts' budget is not raised:
the ~140 bytes are paid for by two loadQuotas/quotasOpened comments cut.

Run (mote, at 807341cdc on origin/main 5666cb049; rebased onto
505534992 after, which touches only internal/plugin and internal/proc;
the core script budget rechecked at the pushed head, 193 bytes under):
- go test ./internal/provider/ ./internal/gui/ ./internal/tui/ ok
  (TestMainWindowCorners/macOS_26_SDK red on mote's macOS 27, #3949;
  green when run with the -run set at the pushed head)
- go vet the three packages; GOOS=linux go vet -tags nogui and
  GOOS=windows go vet of them ok; go vet provider+tui in WSL ok; gofmt -l
  clean
- GUI, Chromium and WebKit, en+zh: refresh-page, claude-usage-asked,
  usage-refresh, routing-read-allowances, allowance-open-read,
  quota-refresh-order, usage-refresh-flight all pass. A wider set of 119
  files (quota*, panel-quota*, usage-*, allowance*, routing-read/account,
  menu-*, tray-*, i18n-keys) has reds in 6 files, identical at the parent
  commit and filed: i18n-keys #5332, menu-input-scroll #3402,
  tray-cell-click #5215, usage-agents-hide #3414, usage-fold #3415,
  usage-ledger #5048.
- New TestRefreshEveryReadsSavedClaude: an opening's ask runs nothing
  for saved accounts; a top refresh reads each anew; an unasked read and
  a plain asked read after it don't; rapid refreshes keep the floor; the
  every-ask lapses after claudeEveryFor.

Broken by hand: dropping "|| every" from claudeWindows' read turns
TestRefreshEveryReadsSavedClaude red ("top refresh read no allowance of
saved max@x.com"); the panel's refreshPage back on loadQuotas(true)
turns refresh-page's panel subtests red in both engines.

Not tried: a real saved Claude account's /usage run from the real tray
panel (the test fakes Claude Code's /usage per account directory); the
full GUI suite; the de/ja/zh-TW GUI runs (no string changed).
2026-11-06 00:35:39 +08:00
yetoneandbaijiu666 5055349922 plugin: a host ended ends what its plugin started, at any depth (#5402)
A plugin host was ended with cmd.Process.Kill(), the host alone. A
plugin that starts a browser or a daemon (magpie-magicrew-auth's
headless Edge behind a WAF) left it running with no parent: 620
msedge.exe (6.8GB) and 382 temp profiles (57GB) in an hour on one
Windows machine. Bun's own job ends its direct children with it on
Windows, but lets their children out, so Edge's gpu/renderer processes
lived on. On macOS and Linux nothing ended them at all.

The host now starts as a proc.Tree (new Output.StartTree): a session of
its own on Unix, a job (kill on close) on Windows. host.kill kills the
tree; stop (after stopWait, so EndHosts, Restart, a moved proxy, an
update) and the line-too-long path both use it. A host that ends by
itself is swept by the tree's Wait: the Unix group is killed, the
Windows job closed. Nothing outside the host's own session or job is
signalled, so magpie's own process group is never reached.

Ported from baijiu666's fix/plugin-host-tree (a8172a1), which called
proc.End then Process.Kill. Reviewed against it:
- macOS/Linux: proc.End is SIGTERM to the host pid alone, followed at
  once by SIGKILL; host.js has no SIGTERM handler and the host was in
  magpie's own process group with no session of its own, so nothing it
  started was ended. Red on mote and WSL, same as main.
- Windows: endTree walks living parents, so it covers the killed host
  but not a host that ends on its own (crash, process.exit) or one that
  leaves when its input closes; those were red on Windows too.
- Its test was Windows-only and checked a direct child, which Bun's job
  already ends: the new test checks a grandchild, through a real host.

Run (TestHostEndedEndsWhatItsPluginStarted: a real Bun host whose
plugin starts a child that starts another; subtests stop / killed /
own end):
- origin/main 125fd93ec: red 3/3 on macOS (mote), Windows (win-run) and
  Linux (wsl-run).
- baijiu666's host.go: red 3/3 on macOS and Linux; on Windows red on
  stop and own end, green on killed.
- this change: green 3/3 on all three; -race green on mote and WSL with
  TestEndHostsLeavesNoChild, TestHostReapedWhileItsChildHoldsStdout and
  TestHostRunsAsMagpieBun.
- go test ./internal/plugin ./internal/proc: ok on macOS and Linux; on
  Windows ok except TestPiPackage, red the same at 125fd93ec (no `sh`
  on PATH there; #4115).
- go vet: darwin, linux, windows (./internal/... for windows). gofmt -l
  clean.
Broken by hand: the old and baijiu666 trees above are the fix taken out.
Not tried: a real headless Edge plugin (magpie-magicrew-auth) on
Windows; a plugin reading /dev/tty (the host has no controlling
terminal now, as every proc.Tree child).

Co-authored-by: baijiu666 <198813975+baijiu666@users.noreply.github.com>
2026-11-06 00:34:42 +08:00
yetone c24915f04e library: LiveAgent in the MCP and Skills pickers (zero2sin)
LiveAgent was missing from the Library's MCP and Skill agent pickers
(zero2sin on Discord #feedback). It is now a target, written in its own
engine's formats, read from K-brain 507f560 (the one LiveAgent af89ea7
pins), not guessed:

- MCP: <data dir>/config.json.live-mcp.json (cmd/kn/backend.go,
  internal/mcp/live.go LiveSettings): {"servers":[{"id","enabled",
  "transport":"stdio"|"http","command","args","env" | "url","headers",
  ...}],"selected":[...]}. Streamable HTTP only, so SSE is refused.
  ${NAME} in env and headers resolves as K-brain's secret refs
  (internal/config/secret.go). The user's servers and their
  description/enabled/cwd/timeoutMs/policy/auth/... are kept; untouched
  servers are written back byte for byte (json.RawMessage). A non-empty
  selected gets magpie's server added (or it would have no tools) and
  taken out on remove, never the last one. With no file yet, K-brain
  reads config.json's "mcp" object (settingsFromConfigs), so the first
  write carries those servers over the way K-brain's own first save
  does. A new file is 0600 like K-brain's. A file K-brain itself could
  not parse is not written over.
- Skills: <data dir>/skills, as copies (Target.Copy): K-brain refuses a
  link in a skill's path (safePath) and ScanDetailed walks past one. A
  skill there loads only when picked in skills-settings.json
  global.selected (Manager.Effective), so syncLiveAgentPicks picks each
  copy magpie makes once (Applied.Picked), never again after the user
  unpicks it, and unpicks it when the copy goes. Names K-brain refuses
  (validManagedName) are never put in selected, since its next save
  would fail on them. Its built-in skills-creator/skills-installer are
  not offered for import.
- Not added: instructions (K-brain's brain.md is its own memory file).
  A server written while LiveAgent runs is seen at its next start (the
  app holds the list in memory and saves it whole).

Run (mote-run, at base 326e72f4c):
- go test -run LiveAgent ./internal/library/: 7 tests ok
- go test ./internal/library/... ./internal/agent/ ./internal/gui/:
  library ok, agent ok, gui FAIL only TestMainWindowCorners/macOS_26_SDK
  (#3949, macOS 27 on mote, no library code)
- GOOS=linux and GOOS=windows go vet ./internal/library/: clean;
  gofmt -l: clean
- node --test of 100 GUI files (library-*, *skill*, *mcp*, i18n-keys)
  in chromium and webkit: 1941 of 1946 pass. Red: i18n-keys "a plugin's
  words are its own" (two Go test files elsewhere say a plugin's word)
  and found-skill-pick-remove "en at 420px" in both engines; this change
  touches no GUI file.
- Rebased on origin/main 125fd93ec and run again there:
  go test ./internal/library/ ok; found-skill-pick-remove and i18n-keys
  red the same (en at 420px both engines; "a plugin's words are its
  own"), and red the same on a clean origin/main 125fd93ec worktree:
  filed as #5013 and #5327/#5332.

Broken by hand, each red: Copy=false (TestLiveAgentTarget,
TestLiveAgentSkills: a link); no syncLiveAgentPicks call (nothing
picked); re-picking every sync (TestLiveAgentSkills: xlsx picked again
after the user unpicked it); no built-in skip (found lists
skills-creator); no selected append (TestLiveAgentMCP); no config.json
seeding (TestLiveAgentMCPFromConfig); no chmod (0644); no name check
(TestLiveAgentSkillsNewSettings: My_Skill picked).

Not tried: a real LiveAgent app reading the written files (no LiveAgent
on mote or here); Windows and Linux test runs (vet only).
2026-11-06 00:26:59 +08:00
yetone 2df5d40ee3 usage: a ChatGPT API account's calls count in the same ChatGPT account's Codex window estimate (jctaoo on Discord)
A ChatGPT account signed in through Sign in with ChatGPT (chatgpt-api) and
to Codex draws on one plan's five hours and week. Only the Codex card reads
those windows, and its whole-window estimate (usage.windowHolds) keyed the
ledger's calls by provider + account, so the chatgpt-api calls were never
counted and the estimate came out low.

provider.SamePlanAccounts maps each chatgpt-api account to the Codex
account that is the same ChatGPT account, matched on the tokens'
chatgpt_account_id and chatgpt_user_id, both known and both equal, never
on a name: two Team seats of one email share the name and the user id,
not the account id. A token that names neither matches nothing, as
before. windowHolds (current and HistoricalWindowHolds) counts a matched
account's calls as the Codex account's, dry runs included. chatgpt-api
alone (no Codex account) is unchanged: its card reads no windows, so
there is nothing to estimate. Routing's caps and pace go by the vendor's
own reading of the windows and don't sum the ledger, so they are
unchanged; the per-provider account breakdown in the summary stays per
provider on purpose.

Run (mote, at this tree):
- go test ./internal/usage/ ./internal/provider/: ok.
  ./internal/gui/: TestMainWindowCorners/macOS_26_SDK red, the AppKit
  test filed as #3949 (macOS 27 on mote), untouched by this change;
  the rest ok.
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  internal/usage and internal/provider: ok. gofmt -l: nothing.
- quota-holds.test.cjs in Chromium and WebKit: 2/2 each (the GUI only
  renders the server's holds; no asset changed).
Broken by hand:
- remap removed in windowHolds: TestWindowHoldsCountsTheSameChatGPTAccount-
  ThroughTheAPI red, "whole 5 hours 2500 tokens, want 10000" and "the
  personal account holds 2500 tokens, want 10000".
- account id ignored (user id only) in SamePlanAccounts: red, "the Team
  seat holds 12500 tokens, want 5000" and "whole 5 hours 10000 tokens,
  want 2500" (token naming no account).
Not tried: a real chatgpt-api sign-in. No such account on this machine,
so whether OpenAI's Sign in with ChatGPT tokens carry chatgpt_account_id
and chatgpt_user_id (Codex's do, checked on the real Codex logins here)
is not verified; if they don't, nothing is matched and the estimate stays
as before. GUI suite in other languages not run (no strings changed).
2026-11-05 23:57:33 +08:00
yetone 2d6939ec64 gateway: Automatic draws with the newest GPT Image, and a ChatGPT account's shows as GPT Image (StarBits on X)
StarBits asked on X whether magpie draws with OpenAI's newest image model,
as the editor showed "gpt-image-2".

- AutoDrawer took the cheapest priced model. An OpenAI key lists
  gpt-image-2.5/2.6 with no price (models.dev prices gpt-image-2 only), so
  Automatic kept an older GPT Image. Now a GPT Image that a newer one set
  up supersedes is never picked (gptImageGenOf: version, then
  base/Sunburst > Flare > mini; dall-e and chatgpt-image-latest under all),
  and an unpriced one is costed as the newest priced one. Another kind of
  model that costs less still wins.
- A ChatGPT (Codex) account's backend ignores the model name (#1865;
  re-checked today with a real account: gpt-image-2, 2.6-sunburst,
  2.5-flare and a bogus id all drew the same 1536x1024 image), so it is
  never superseded, and its chip now reads its name "GPT Image" with the
  id as tooltip (/api/providers drawNames). Unticking still saves the id.
- docs/subsystems/gateway-routing.md says both.

Run (on mote, at this tree):
- go test -tags nogui -run 'AutoDrawer|GPTImageGen|Codex.*Image|ImageGen|Drawer|Draw'
  ./internal/gateway ./internal/gui: ok
- GUI: chatgpt-image-chip (new), image-models-hide, video-models-hide,
  group-pick-drawers, chromium + webkit, en/zh/zh-TW/ja/de, 1000 and
  360px: 100 pass, 0 fail
- gofmt -l: clean
- Full go test ./... -timeout 45m and Linux/Windows vet: running; record
  follows in the next commit or a comment.

Broken by hand: without the supersede filter TestAutoDrawerTakesNewestGPTImage
picks oa/dall-e-3; without the ChatGPT exclusion TestAutoDrawerKeepsChatGPTsOwnPick
picks oa/gpt-image-2.6-sunburst; with the chip label reverted the GUI test
is red.

Not tried: a real OpenAI key's live model list in the app.
2026-11-05 19:56:08 +08:00
ggbdpq db9d6a6107 gateway: a working-directory line a turn quotes is no caller's word, and a --bare run's CWD: is read (#4940)
What changed: workPlace reads the folder in two layers, as
clientNamedWorkPlace does. The caller's own layer - its instructions and
its {role: "system"} messages - is read whole: Claude Code's
" - Primary working directory:", a --bare run's "CWD: /x", pi 1.1's
"Current working directory:", Codex's and pi's <cwd>, OpenCode's <env>.
A turn of the conversation is read only for the forms a caller states in
one - <cwd>, <env>, and Claude Code's <system-reminder>, which says a
folder it moved to; a line a user message quotes ("Primary working
directory: /x" alone on its line, WardLu's P3) no longer names the
folder for a group's rule by folder, nor goes to a plugin's provider as
its WorkDirHeader. The last said still goes, wherever it sits: an agent
that moved says so after. The forms are workdir.go's own, wrapper-scoped
as the routing face pinned them; the bridge's clientNamedWorkPlace is
untouched.

Run:
- go test ./internal/gateway -run 'TestWorkDirTurnQuote|TestWorkDirBareCWD|TestWorkDirMoveReminder|TestTellWorkPlaceTurnQuote' -count=1
  RED before (the quoted line named the folder; CWD: named none), green after.
- TestWorkDirOfEachAgent, TestWorkDirOpenCode, TestWorkDirLastSaidAndOnlyByTheAgent,
  TestRuleByFolder unchanged and green - the agents' own shapes and the
  move reminder keep working.
- gofmt, go vet -tags nogui (darwin/linux/windows), go build -tags nogui
  (darwin/linux/windows), the new tests with -race: clean.

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported: not superseded by b9a45f59e, which fixed the
bridge's clientNamedWorkPlace and named workDirIn as the sibling left.
On mote, with workdir.go and the docs at the parent: TestWorkDirTurnQuote
IsNotTheCallerWord FAIL ("a quoted line in a turn overrode the caller's
own: /Users/me/quoted"), TestWorkDirBareCWD FAIL ("a --bare run's CWD:
is not read"), TestTellWorkPlaceTurnQuote FAIL (the plugin is told
%2FUsers%2Fme%2Fquoted); green with the patch. go test -timeout 45m
./internal/gateway ok, GOOS=linux/windows/darwin go vet -tags nogui ok.
Fixed: workdir.go was not gofmt-clean (the piDir alignment); gofmt -w
applied. Not tried: a real agent's request through a group's rule by
folder.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-05 18:31:17 +08:00
yetone 2f59545d29 gateway: a key not given a group listing alone is listed the members it may use (luckymanjc)
luckymanjc on Discord (#general, 11-05): on a second computer, through
Remote magpie, his three Codex accounts offered GPT-6-Luna alone, with
the key his Remote magpie uses held to "Codex 的全部模型" (codex/*),
GPT-6-Luna and the accounts. His screenshot of that key's picker, on the
host, offered GPT-6-Luna alone under Codex too.

Cause: a routing group listing alone (Group.Unlists, "the group alone")
keeps its members out of Catalog(), so out of /v1/models and the key
picker (/api/caller-keys/models), as the group stands in for them there.
Since d1cdce130 (11-03) that holds for subscription models again. But a
group of the user's own is never a key's unless the key names it
(kautism's rule, groupAllowed), so a key held to codex/* was given
neither the group nor its members: only the Codex models no such group
named were left, Luna here. The picker read the same Catalog(), so there
was nothing else to tick.

Fix: the group stands in only where it is given.
- provider.GroupStandIns: the models groups listing alone keep out, with
  the groups' ids (groupsKeeping, which unlistedByGroups now reads; a
  provider kept for routing groups alone is not among them).
- gateway keyListed: for a key that may use none of the groups standing
  in for a model and may use the model, the model is listed beside its
  provider's others; the list's own picks still leave one out. Every key
  list goes through it: catalogFor (/v1/models and what it feeds, the
  remote magpie's fetch included), /v1/models/{id}, the key's page,
  Codex's catalog and spawn choices. A key that names the group gets the
  group in place of its members, as before. Unrestricted callers are
  unchanged: the group alone, as the option says.
- The key picker offers those models after their provider's.
It is the same for every provider a group can list alone, not Codex
alone. Docs: reference.md, gateway-routing.md.

Tests (mote):
- TestKeyNotGivenTheGroupIsListedItsMembers (gateway): Free + Pro Codex
  sandbox accounts, a group listing sol/astra/terra alone. Unrestricted
  list: group, no members. The reporter's key (codex/*, codex/gpt-6-luna,
  both accounts): every Codex model, no group. A key of one member: that
  one. A key naming the group: group, no members. A Remote magpie on the
  reporter's key fetches every Codex model. Red on the old code (sol,
  astra, terra missing), green now.
- TestCallerKeyModelsOfferGroupKept (gui): the picker offers the kept
  models, beside their provider's. Red on the old code, green now.
- Broken by hand: dropping the "a group standing in is given" check
  turns the key-naming-the-group case red.
- go vet provider, gateway, gui; go test ./internal/provider ok;
  ./internal/gui all ok but TestMainWindowCorners (#3949, AppKit titlebar on
  mote's macOS, untouched here); ./internal/gateway -run
  "Key|Codex|Model|Remote|Group|Catalog|Spawn|Unlist|Caller" ok.

Not tried: the reporter's own host (his groups are inferred from the
screenshot: only Luna left under Codex in the picker); two real magpie
apps on two machines; real Codex accounts.
2026-11-05 18:28:38 +08:00
yetone 6d9fb7ef0f routing: a dsh request names the dsh session its first prompt was read from
changqiu4890 on Discord: Routing -> Requests showed dsh's requests with no
session id. dsh 0.2.1's pi-ai routes (openai-completions, anthropic), which
magpie configures, send no session header (pi-ai's session affinity is
withheld by dsh's compat gate), so a route had only its Conv, the hash of
its first user message. The Context page already found dsh's session by
that hash (dshConvs); the Routing page grouped by header session only.

pricedRoutes now gives a dsh route with no session of its own the dsh
session whose Convs hold its Conv (convOwners, shared with the Context
page's joinConvs), from an index rebuilt at most every 2s when a conv is
missing and every minute otherwise. Grouping and titles (dsh:<id>) follow.
A route with its own session, another agent's route, and a conv two
sessions share stay as they were.

Run (mote-run, this tree):
- go test -tags nogui ./internal/gui/ ./internal/sessions/: ok, ok
- TestRoutingDshRoutesNameTheirSession and TestContext*: ok
- GUI routing-sessions, routing-session-folder, routing-by-key, ctx-route,
  routing-day-window: Chromium 160/0, WebKit 80/0
- go vet darwin, linux (nogui), windows ./internal/gui; go build all three
- gofmt -l clean
Broken by hand: `r.Session = owners[k]` -> `_ = owners[k]`; the new test's
dsh chat and messages routes went red.
Not tried: a real dsh through magpie. A brand-new session's first request
shows no session until dsh writes its session file and the index refreshes.
The in-flight list (Active, concurrency endpoint) is unchanged.
2026-11-05 17:25:26 +08:00
yetone 4f624241f7 codex: the ChatGPT app left on "hit a snag" after an app-server restart is reopened when idle (#4550)
ysm119 on Discord: each Restart of Codex in magpie left the ChatGPT
desktop app on "ChatGPT 遇到了问题 / 请重试" till it was quit and opened
again. magpie ends the app's own app-server cleanly (code 0); a
signed-in ChatGPT 26.1021 then fails "Hosted AppServerManager identity
is not ready" on the one it starts, logs fatal_error_broadcasted and
shows the page. That is the app's bug; magpie now follows it up.

- provider/codex_app_crash.go: for 60s after every end magpie makes
  (the watcher's step, RestartCodexApp, RestartSwitchedCodexApp) the
  app's logs are read for a whole fatal_error_broadcasted line stamped
  after the end. On one, with no request through magpie since or in
  flight and no Codex turn opened since, the app is quit and opened
  once. Otherwise it is left as it is and logged. Where it can't be
  reopened (Linux, an app that didn't quit) the Agents row says
  "The Codex app hit an error · quit it and open it again" (appSnag)
  until the app-servers seen then are gone or the app is closed.
  Unreadable logs reopen nothing.
- agent/codex_app_crash.go: the logs as the app's file logger writes
  them (macOS ~/Library/Logs/com.openai.codex, Windows
  %LOCALAPPDATA%\Codex\Logs and the Store package's LocalCache, Linux
  $XDG_STATE_HOME/codex/logs; YYYY/MM/DD folders, tail-read, half
  lines dropped). The relaunch is the Agents row's: on macOS
  ChatGPT.app found by its bundle id, quit as ⌘Q does and opened once
  it has ended, never forced; on Windows codexAppReopen.
- GUI line in en, zh, zh-TW, ja, de; docs/subsystems/agent-wiring.md.

Run on mote (macOS) at this head on origin/main 08982805e:
- go vet ./internal/agent ./internal/provider ./internal/gui (darwin
  and GOOS=windows), GOOS=linux go vet ./internal/agent
  ./internal/provider; go build ./...; gofmt -l clean.
- go test ./internal/provider ok; go test -run
  'TestCodexApp|Restart|Reopen' ./internal/agent ok.
- go test ./internal/gui: red only in TestMainWindowCorners (#3949) and
  TestPanelHiddenByWailsMarksPageOutOfSight (#5322), AppKit window tests
  red on mote's macOS 27 and filed before this change.
- win-run and wsl-run: go test -run TestCodexApp ./internal/agent
  ./internal/provider ok (the macOS relaunch test skips on Windows, as
  TestWorkBuddySidecarOutlivesQuitOnMac does, #4115).
- node --test codex-app-snag, codex-app-out, codex-app-back, i18n-keys,
  i18n-en-no-cjk: chromium and webkit, every language, 980 and 440px.
  i18n-keys' "a plugin's words are its own" stays red for "View routing"
  (#5327/#5332, red on main since 73c98ebc2); this change added a word
  there and took it out again.
- Core script budget: under it, not raised.

Broken by hand, each red then restored:
- codexAppCrashStep's call removed: 4 provider tests red.
- the watch not armed in RestartSwitchedCodexApp:
  TestCodexAppRestartsWatchForTheErrorPage red; in RestartCodexApp:
  TestCodexAppRowRestartWatchesForTheErrorPage red.
- the turn and request checks off: TestCodexAppInUseAfterItsErrorPageIsLeft red.
- the snag not set: TestCodexAppSnagSaidTillTheAppRestarts red.
- the stamp's >= since check dropped, or a half-written last line kept:
  TestCodexAppCrashedReadsItsOwnLogs red.
- a wrong Store package path: TestCodexAppCrashedReadsEachSystemsFolder red.

Not tried: a real signed-in ChatGPT app reaching the identity-not-ready
page, and a real quit and reopen of the user's ChatGPT.app (the relaunch
is tested with faked process listing, quit and open in a sandbox HOME).
The log line and folders are read from ChatGPT 26.1021's
file-based-logger and the reporters' logs; a later app that renames
them reopens nothing, as before this change.
2026-11-05 17:24:53 +08:00
yetone 965ae78e1e gateway: a routing group draws on its own image member, Codex's tool too
changqiu4890 on Discord: the group smart-split has three Codex CPA chat
models, DeepSeek-V4.1-Flash and Codex CPA's gpt-image-2.5, and dsh,
Codex and Pi are set to it. Image requests went to other providers'
image models.

Two causes in magpie:

- drawingTries tried every member of a group named for a drawing in the
  order chat routing plans them, so the chat members came first.
  group/smart-split drew on cpa/gpt-6-astra, which was asked as a chat
  for an image, before it reached the group's image member. A group
  with members that make the kind (drawsModel, or servesKind for
  video) is now tried on those members alone. The fallback between
  them stays as it was.
- Codex's image tool drew on the provider that served the turn, else
  on Settings' pick. A group's image member was never used: a turn on
  DeepSeek, or on the relay, drew with Settings' model or with the
  relay's other GPT Image. codexDrawingProvider now also returns the
  routing group the turn asked for. When that group draws (GroupDraws),
  the drawing goes to its image member through resolveDrawing, which
  keeps the member's provider.

The reporter's Routing screenshot also shows explicit requests from a
client magpie names "Mozilla": x0-15/gpt-image-2.5, codex/gpt-image-2.5,
and bare gpt-image-1 and gpt-image-1.5. magpie routes a request that
names a provider to that provider, and a bare id to the first provider
whose Drawers list it. Nothing in such a request links it to the agent's
group, so this commit leaves those requests alone.

Tests:
- TestMixedGroupDrawsOnItsImageMemberOnly (new): the reporter's group
  shape on fake upstreams, with another relay listing gpt-image-2.5
  first. Red before the fix (drew on cpa/gpt-6-astra), green after.
- TestCodexDrawingTakesItsGroupsImageMember (new): red with the group
  branch turned off by hand (drew on chat/gpt-image-2), green with it.
- TestMixedGroupMakesVideoOnItsVideoMemberOnly (new): a guard for the
  video sibling. It passes with the filter turned off as well, because
  video's mediaMembers already keeps only video members (KindGroup).

Run on mote (mote-run) at this tree:
- gofmt -l
- go vet ./internal/gateway on darwin, GOOS=linux -tags nogui and
  GOOS=windows
- go test -count=1 -run 'Group|Draw|Image|Video|Media' ./internal/gateway
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider

Not tried:
- a real Codex CPA relay or a real dsh session
- the image MCP's default for a non-Codex agent set to a group: the MCP
  call carries no link to the agent's chat route, so it still uses
  Settings' pick
- chat routing to a group's image member when the member's provider has
  no picks: the member's provider is still the pinned one, and this
  commit doesn't change it
2026-11-05 17:04:16 +08:00
yetone a732f3c493 gateway: models of one API other than chat are grouped by id on their route (#5339)
XYenon (Discord) has the same embedding model at several providers and
asked why it isn't grouped the way chat models are. It wasn't even
listed: a fetched list dropped every embedding, rerank, speech and
transcription model, so "embed-1" on /v1/embeddings was a 404 unless a
hand-made group named it.

- catalog: a fetched list keeps those models, tagged with their API
  (Model.Serves, read from the id by ServesOf: rerank, embed/bge-,
  whisper/transcribe, tts-/-tts). Chat() and Live() leave them out, so
  agents' model lists, gateway keys and Routing's chat pickers never
  see them; LiveServing(id, kind) reads them. The live file says
  "kinded": true; a list fetched before this is fetched again once a
  run (autolist), with no schedule needed.
- provider: KindGroup(kind, ref) is made per request, never stored, so
  it is in neither Groups() nor Catalog(). Its id is
  auto-<kind>:<model> ("group/auto-embedding:embed-1"); its members are
  the providers that serve exactly that id for that API, in the order
  they were added, none off, decide-only, serving none, or with the
  model disabled.
- gateway: embeddings, rerank, speech, transcriptions and videos pick
  the group by route (mediaMembers): a bare id is a kind group when
  more than one provider serves it, the group's own id always; a
  hand-made group still works through offChatList. A group is of its
  own API: an embedding model's id on /v1/rerank is a 404.

Run at bd0f33828 + this change, on WSL magpie-desktop (mote was
running another session's full suite):
- go test -tags nogui -count=1 -timeout 45m ./internal/catalog
  ./internal/provider ./internal/gateway: ok, ok, ok (594s). The first
  run was red in three tests that held a fetched list to leaving its
  embedding model out (TestFetchArkMarksVideoModels,
  TestNvidiaModelScopeLiveList, TestTencentTokenHubList); they now hold
  it kept, tagged embedding, and out of catalog.Chat.
- 22 GUI files over the model lists and Routing pickers, both engines,
  every language (group-pick-drawers image-models-hide video-models-hide
  model-kind routing-kind agent-models agent-models-picker
  agent-model-groups agent-models-only-picked gateway-key-models
  gateway-key-groups group-from-model-add unlisted-models
  models-select-all-api provider-add-models provider-detect-models
  routing-rule-models panel-routing-pick fallback-group group-unlists
  settings-groups i18n-keys): 229 of 244 pass. The 15 reds are in six
  files that a control run of those six at bd0f33828 has red the same
  (14 of 56): #4389, #4964, #5332, #4616 and, new, #5357
  (routing-rule-models webkit 390). agent-models webkit zh's opacity
  0.998 was red here only, a fixed 250ms wait: #5358. No GUI asset is
  changed here; the GUI tests stub /api.
- on mote: TestProviderListBeforeSave (internal/gui; the add form's
  list keeps an embedding model out) and
  TestPiModelsAskedOnTheirNativeAPI (internal/agent), ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of catalog,
  provider and gateway on mote at this head, ok.

Rebased then on origin/main d620ff6b5 (one commit, internal/agent and
internal/sessions only), and b63b28958 (one mover min line) after; at
d620ff6b5 + this on mote: go build ./..., go vet
of catalog, provider, gateway, agent and sessions, go test
./internal/catalog and -run 'Kind|Fetch|Nvidia|Tencent|Serving' of
provider and gateway: ok.

Red on the old code: TestKindGroupsServeEachAPIByRoute (embed-1 404)
and TestVideoKindGroupByTheModelsID (404).
Broken by hand, each red, then restored:
- the fetch dropping serves != "" again: TestFetchKeepsModelsOfOtherAPIs;
- the once-a-run refetch forced off: TestKindlessListFetchedOnce;
- KindGroup's disabled-model check removed:
  TestKindGroupHoldsTheExactModel;
- LiveServing asked with "" (any kind): the rerank-by-embedding-id
  check gets 200 instead of 404.

Known gaps, not done here:
- The Routing group editor still offers only chat and image models, so
  a new hand-made group of different ids (bge-m3 / BAAI/bge-m3) can't
  pick kind models: #5352.
- A bare id whose every member is disabled is a 404, not a 403.
- Rerank, Qwen3-Embedding and bge models that sat among a provider's
  chat models before (textModel's words missed them) leave agents'
  lists now. A hand-made group naming one keeps serving.
- /v1/models lists no kind model; the Routing live view may show the
  raw kind id.
Not tried: real vendors' lists and routes; the full ./... suite at this
head (queued on mote after another session's run; reds get issues).
2026-11-05 16:22:31 +08:00
yetone d620ff6b54 codex: an old OpenAI thread follows Codex onto magpie by its row, and back at the Disconnect (Parry_Moody, Cyrus)
Parry_Moody and Cyrus on Discord: Codex on OpenAI through an API key
before magpie, and for two days the Codex app answered every older
conversation "继续聊天未成功: This chat uses openai, but your current
provider is magpie. Switch to openai to continue."

Cause, from Codex's source (rust-v0.167.0-alpha.3.1, same in 0.166.0):
every thread Codex 0.166 starts is paginated (history_mode 'paginated'
in its state-DB row), and for those thread-store read_thread takes the
provider from the row, never the rollout ("Paginated history may contain
only a suffix, so its display metadata lives in SQLite"). The app sends
thread/resume with modelProvider null (ChatGPT.app 26.1021, Kct in
app-shared), so the row alone decides, and load_for_resume refuses a row
other than the current provider. bringOver moved threads by rewriting
files: plain ones in place, packed ones only from the last 30 days and
128 MB a sync. An older or packed OpenAI thread kept an openai row.

Now sessions.RetagPagedCodexThreads moves every paginated thread on a
provider by its row alone: any age, packed or not, an id of any length,
no file read, written or copied. Each thread is held by its writer lock
(an open one stays: its writer would write the provider back), one
written to in the last minute waits, 200 rows a transaction. It runs
after the in-place relabel in bringOver, bringBack (so a Disconnect no
longer copies a whole paginated history to the trash), bringOfficial and
bringBeside, and giveBeside by ids (RetagPagedCodexThreadIDs). Legacy
threads keep the file path. The Sessions page lists a paginated thread
on its row's provider (codexPagedProviders, memoised on the DB and WAL
stamp), so it isn't offered a Move it had.

Run:
- real codex-cli 0.166.0 (npm latest) on mote in a sandbox CODEX_HOME,
  a fake Responses server: a thread started with OpenAI (API key,
  openai_base_url) is paginated, row openai; with model_provider magpie
  `codex exec resume` failed with exactly "This chat uses openai, but
  your current provider is magpie" (modelProviderMismatch). After
  magpie's RetagPagedCodexThreads on that home (a throwaway test calling
  it, not committed) it resumed and answered; the rollout still names
  openai. Reversed (magpie -> openai) with config back on OpenAI, it
  resumed again. The first retag try moved nothing: the rollout had been
  written <1 minute before, the ActiveWindow skip, as intended.
- mote: gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  for ./internal/sessions ./internal/agent; go test ./internal/sessions
  ./internal/agent: ok (sessions 20.1s, agent 194.4s) on mote, plus go vet on darwin, linux -tags nogui and windows

Broken by hand:
- RetagPagedCodexThreads returning nil (the old behaviour):
  TestCodexPagedThreadsFollowByRow red (250 packed 90-day-old threads
  "on openai, want magpie"), TestRetagPagedCodexThreads red.
- the writer-lock hold skipped: TestCodexPagedThreadsFollowByRow red,
  the open thread moved to magpie.

Not tried: the Codex app GUI itself (the app goes through the same
app-server thread/resume, whose modelProvider it sends null); Windows
and Linux runs (vet only). Codex rebuilds a row from its rollout when a
search listing reconciles it, which puts a retagged thread back on its
file's provider until the next sync; not seen, read from the source.
A legacy thread packed over 30 days still waits for Sessions' Move.
2026-11-05 16:11:14 +08:00
yetone bd0f338282 hermes: a Claude model goes on anthropic_messages, so cache_ttl 1h works; the user's api_mode stays (#5315)
cherish_onlyy (#5315): magpie wrote providers.magpie as chat_completions at
the gateway's /v1 for every model. On chat completions to a custom provider
Hermes sends no cache marks (anthropic_prompt_cache_policy gives
(False, False)), and the marks magpie adds for a Chat client last five
minutes, so prompt_caching.cache_ttl: 1h never reached the vendor. They set
api_mode: anthropic_messages and the gateway's root by hand and got 1h
writes; magpie's next sync or connect wrote chat_completions at /v1 back.

Hermes takes api_mode per providers entry, never per model
(_resolve_named_custom_runtime, hermes_cli/runtime_provider_custom.py;
aliases in config_providers.py's _API_MODE_ALIASES, transport read when
api_mode is absent). On anthropic_messages its adapter strips a trailing
/v1 and the SDK adds /v1/messages, and for a "claude" model on a
third-party gateway it puts its own system_and_3 marks at the configured
ttl (agent/prompt_caching.py, read at d914e233). So magpie now writes two
entries, as dsh already splits its routes:
- magpie: chat_completions at gw/v1, every model not on Messages;
- magpie-anthropic: anthropic_messages at gw (no /v1), the models whose
  native API is Anthropic's Messages and not Responses (hermesOnMessages).
model.provider follows the picked model (hermesRoute), in every profile;
a sync moves a Claude model magpie had set under "magpie" onto
magpie-anthropic, and drops that entry when no model is left for it.
Disconnect takes both out.

The user's own value: an api_mode or transport on one of magpie's entries
that isn't the one magpie writes there (by Hermes's aliases, so "openai"
is still magpie's chat) is the user's (hermesModeIn). It stays through
sync and pick, base_url follows it, and on "magpie" that entry then
serves every model and no magpie-anthropic is written, which is the
reporter's set-up exactly. magpie only ever wrote chat_completions into
providers.magpie, so nothing earlier is mistaken for the user's.

Tests:
- TestHermesClaudeGoesOnMessages: Claude on magpie-anthropic (mode, base
  without /v1, models), deepseek stays on magpie at /v1, Get/Check/Drift
  clean, a pick moves model.provider back, a bot profile too, Disconnect
  removes both entries from every profile.
- TestHermesSyncMovesClaudeOntoMessages: an existing connected config is
  moved on sync, and back when the provider goes chat-only.
- TestHermesKeepsTheUsersAPIMode: api_mode anthropic_messages at gw,
  transport: anthropic, codex_responses: each survives two syncs and
  two picks, base_url kept; api_mode: openai is still magpie's.
- internal/gateway TestHermesHourMarksReachTheVendor: a Hermes-shaped
  /v1/messages turn with 1h marks reaches the Anthropic upstream with
  every mark at 1h; the same turn on /v1/chat/completions goes at 5m.
  This one passes on the old code too: the gateway already passed the
  marks through; it guards that and records why the mode matters.

Run (mote-run, this tree):
- go test ./internal/agent/ -count=1 -timeout 45m: ok
- go test ./internal/gateway/ -run 'TestHermesHourMarksReachTheVendor|TestResponsesToClaudeMarksLastAnHour' -count=1: ok
- go vet ./internal/agent/ ./internal/gateway/, GOOS=linux and GOOS=windows: ok
- gofmt -l: clean
Broken by hand:
- hermesSplit returning (nil, false), the old one-entry behaviour:
  ClaudeGoesOnMessages, SyncMovesClaude and the openai-alias case fail.
- hermesModeIn never reporting the user's mode: all three
  KeepsTheUsersAPIMode cases fail at "sync".
Not tried:
- Hermes itself: it was not run (running it under a temp HERMES_HOME
  rewrites the live launcher); its behaviour is read from its source at
  d914e233. No real 1h cache write was measured against a vendor.
- Group models whose members are all Claude, and Claude Code sign-ins
  (no Native API), stay on chat_completions; GPT on codex_responses is
  #3080.
- Windows and Linux runs of the agent package (vet only).
2026-11-05 15:53:16 +08:00
yetone 465928bcce backup: the default backup folder says a reinstall takes it too; docs say how to keep magpie on another disk (two_2025.)
two_2025. on Discord asked to pick magpie's config folder: on Windows it
is on C:, and a system reinstall without a backup loses everything.
Two ways already exist and neither is said where the user looks:
automatic backups can go to any folder (Settings > Sync and backup >
Backup folder > Change...), but default to auto-backups inside magpie's
own folder, lost with it; and portable mode (a data folder beside
magpie.exe, internal/appdir) keeps everything on another disk. So no
new data-folder setting: moving the live folder would have to repoint
the library's links, agents' configs and a running gateway, and its
pointer would sit on C: and be lost on the same reinstall.

- AutoStatus reports inside: the backup folder is settings.Dir() or in
  it, letter case aside off Linux. The Backup folder row then says a
  reinstalled system or a lost disk takes these backups too, and to pick
  a folder on another disk or a cloud drive's (en, zh, zh-TW, ja, de).
  A folder picked elsewhere says nothing new.
- docs/start (en, zh, ja) #data-folder: pick a backup folder on another
  disk and restore from it after a reinstall, sync for the keys, or run
  portable from D:\magpie with a data folder beside magpie.exe.
- docs/subsystems/sync-backup.md names the field and the tests.

Run (mote, at this tree on origin/main 5db1b07ed):
- go test -count=1 ./internal/backup/ ./internal/gui/: backup ok; gui
  red only in TestMainWindowCorners/macOS_26_SDK (#3949, mote's macOS 27).
- node --test auto-backup, i18n-keys, i18n-en-no-cjk, sync-not-backup:
  49 of 50; the red is i18n-keys "a plugin's words are its own", red on
  main since 73c98ebc2 (#5327, #5332). auto-backup passes in Chromium and
  WebKit, 1100 and 420px, all five languages.
- node --test site/*.test.mjs: 84 of 84.
- GOOS=windows, GOOS=linux and native go vet ./internal/backup/; gofmt -l.
- Windows (win-run on xiaomi-gpu): go test ./internal/backup/ ok
  (TestAutoInsideMagpiesFolder with the upper-case path);
  ./internal/appdir/ red only in TestFoldersJoinedOnce (#4846, untouched).

Again at this commit, rebased on origin/main 435f04151 (mote): go test
./internal/backup/ ok; auto-backup.test.cjs 22 of 22 and i18n-en-no-cjk
ok.

Broken by hand: AutoStatus with inside always false makes
TestAutoInsideMagpiesFolder red ("default folder ... inside false");
the JS line dropped makes auto-backup.test.cjs red (webkit 1100px zh,
zh-TW).

Not tried: the real app on Windows with a backup folder on another
drive and a restore after a reinstall; a portable copy moved to D: from
an installed one (the docs restore a backup into a fresh portable copy
rather than copying the folder, whose library links point at the old
one). Full suite runs after the push.
2026-11-05 15:30:11 +08:00
yetone 435f041514 gateway: an account near its usage cap takes one turn at a time (dyzdyz010)
dyzdyz010 on Discord: two Claude Code accounts, each capped at 90% of its
five hours, Stop at the caps and Check usage near the cap on, and both
read 100%. Routing holds a capped account by its last reading. Turns sent
together (an agent's subagents, several agents) were each planned on the
same reading, so an account a point under its cap took every one of them,
and went as far past it as they used between them. Check usage near the
cap reads the usage again before planning, but every turn read the same
figure: each saw 89%.

- gateway (cap_near.go): within 5 points of a usage cap (carefulNear),
  an account takes one turn at a time. A turn that finds it busy goes to
  the next candidate first, the account moved behind them once; the last
  candidate waits for it. Once its turn comes capHeld judges it again, by
  what the reply before it said (codex.rate_limits, rate_limit_event), or
  by the usage read again when that reply said nothing (at most
  carefulWait). Held, it is passed over, or the agent gets the cap's 429
  when nobody is left. The cap is passed by one turn at most.
- A conversation kept on its account by Stays: Strict takes no turn there
  and goes on past the cap, as before. Neither does an account already
  held when its try begins, let in past its cap on purpose (a Codex reset
  spent for it, its credits).
- docs: gateway-routing.md's capHeld step, providers-accounts.md's cap
  sentence.

Run (wsl-run, magpie-desktop, Go 1.26.8):
- go test -tags nogui -run 'NearCap|FarFromCap' -v ./internal/gateway:
  the five new tests pass.
- go test -tags nogui -race -count=20 -run 'NearCap|FarFromCap'
  ./internal/gateway: ok.
- GOOS=linux go vet -tags nogui ./internal/gateway, GOOS=windows go vet
  ./internal/gateway: ok. gofmt -l: nothing.
- go test -tags nogui -timeout 30m -run
  'NearCap|FarFromCap|CodexNoCredits|Reset|Strict|Cap|Credits'
  ./internal/gateway: ok.
- go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider,
  at this tree rebased on 248853225: ok (gateway 604.9s, provider 90.9s).
- at the pushed head, rebased on 5db1b07ed: the vets ok, and -run
  'NearCap|FarFromCap|CodexNoCredits|Reset|Strict|Cap|Credits|Group'
  ./internal/gateway ok.

Broken by hand (each restored after):
- the whole near-cap block off (`&& false`): TestNearCapTakesOneTurnAtATime
  red (acct-1 took all 4 turns), the two wait tests never saw a turn
  waiting, and TestNearCapClaudeAccountsTakeOneTurnEach red (both turns on
  the account near its cap, the spare never run).
- nearCapAgain a no-op: TestNearCapReadsAgainAfterASilentReply red
  (200, 200).
- capHeld's second look off: TestNearCapWaitsThenHolds and
  TestNearCapReadsAgainAfterASilentReply red.
- the first full run, before the strict exception, had
  TestStrictAffinityGoesPastTheCap red: the strict conversation got the
  cap's 429. The second, without the held-on-entry exception, had
  TestCodexNoCreditsSpendsAReset and
  TestCodexNoCreditsResetAfterTheLastRefusal red: the account a reset
  was just spent for was held again. Both fixed in this commit.
- An unrelated red in the first run,
  TestZCodeTrialRefusalRestsTheTrialAlone/trial_edge_block ("no plugin
  signs in to zcode"), passes alone and was green in the last run; filed
  as #5335.

Not tried: a real Claude or Codex account near its cap; plugin accounts
(their caps go through the same candidate loop, untested here). One turn
alone can still pass a cap by what it spends: an Opus turn on a Pro plan
can take several points of the five hours.
2026-11-05 15:16:13 +08:00
yetone a2f7ed2e81 gateway: a hand-made group of embedding, rerank, speech, transcription or video models is served when its providers have picks
XYenon on Discord: a routing group of embedding models was a 404 on
/v1/embeddings. Picks are of chat models, so membersFound dropped every
member of a provider with picks as unpicked (#3911). 1d8658abc fixed this
for drawings with FindDrawingGroup. The sibling routes still used
FindGroup: retrieval (embeddings, rerank, speech, transcriptions and
translations, which all go through serveRetrieval) and /v1/videos.

provider.FindGroupAlso is FindGroup with an "also keep" test, and
FindDrawingGroup now wraps it. The gateway's mediaMembers keeps a member
that is not on its provider's chat list (offChatList), so a chat model the
user unticked stays out. mediaGroupFirst resolves the group's first such
member, because Resolve reads the agents' catalog and finds none of them.
The routing doc says the same.

Auto groups by kind (non-chat ids never reach autoGroups) are #5339 and
are not in this commit.

Run on mote:
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider:
  ok (gateway 823.6s, provider 180.0s)
- GOOS=linux and GOOS=windows go vet of the two packages: ok
- gofmt -l: clean
- No GUI file changed, so no GUI run.
- At the rebased head (on origin/main 2891ec7a7: 6 commits, balance_probe and
  others, none in group, retrieval or video code): go test -run
  'MediaGroup|VideoGroup|ImageGroup|Retrieval|Embedding|Speech|Transcri|Rerank|Group'
  ./internal/gateway ./internal/provider: ok; gofmt -l: clean

Red on the old code: with media_group.go removed and the three routes back
on FindGroup, TestMediaGroupOfProvidersWithChatPicks fails with 404 "magpie
knows no model "group/emb"" and TestVideoGroupOfProvidersWithChatPicks with
404 for "group/vid". In both, the members' providers have picks that don't
name the embedding/speech/video ids.

Broken by hand: offChatList made to return true lets the unticked chat
model in, and the test goes red ("a group of a chat model the user unticked
was asked: 400 ... chat-model is not an embedding model").

Not tried: a real vendor's embeddings or speech through a group (fakes
only), plugin-served embedding models, and the full suite (it runs after
the push).
2026-11-05 14:57:43 +08:00
yetone 24d315fa85 routing: the request list can be grouped By key, each gateway key's calls under its name
acezan (#help on Discord) asked to see API use on the Routing page the way
it shows each agent's, live and in the history. The list's group bar gets
a third button, By key, after By request and By session. It shows once
Settings has a gateway key (/api/caller-keys). Each head is the key's
current name (else the name the route kept, else its id), with its agents
dim beside it and the usual count, tokens, in progress and cost. Calls with
no key (from this computer, or kept before 75fb76186 named the key) go
under "No gateway key". A row's tooltip names its key too. The choice is
kept in localStorage (magpie.routingGroupBy), and the old
magpie.routingBySession still works. Text added in zh, zh-TW, ja and de.

click-scroll counted two group buttons and now counts three, with By key
hidden when there is no key. purpose-filter clicked .last() for By
session and now picks [data-by="session"].
reference.md and gateway-sessions.md describe By key and Route.CallerKey.

Run (WSL magpie-desktop: mote's disk is full, ld errno=28):
- routing-by-key.test.cjs: 20/20 in chromium and webkit, in en, zh,
  zh-TW, ja and de, at 1100 and 420. Red 20/20 with client.js and
  i18n.js at the parent (waits for By key).
- 254 Routing-related GUI files at concurrency 4. Every red was rerun
  serially, with this change and at origin/main 73c98ebc2.
  - Only purpose-filter and click-scroll were this change's; both are
    fixed above and green now.
  - The rest are red at main too, or flake there: #5045 call-headers,
    #4385 click-scroll wheel, #5049, #1745, #4689, #3402, #4623, #1937,
    #3773 idle-frame (10 frames, passes on rerun), plus routing-rule-*,
    zero-priced-free and others under #4121/#4400.
- Windows: go test ./internal/gui. Reds are #4115/#1827, plus
  TestPluginAgentMissingSaysSo and TestGatewayHeldByAContainer, red at
  main too and filed now as #5324.
Not tried: the real app, the whole GUI suite, the tray panel (no By key
there). A key renamed after a row was drawn shows its old name in that
row's tooltip until the row is drawn again.
2026-11-05 14:47:18 +08:00
yetone 464cc30f91 provider: a relay's found balance query is looked for again each day
A relay added by hand with no Balance URL has its balance found at
/v1/usage or /api/usage/token (248853225). What was found was kept until
magpie quit, so a relay that moved to other software went on being read
at a query that may now mean something else. A query found is now kept
24 hours and then looked for again. If the look finds nothing, the old
query stays when it turns the key away (401/403, so the card says the
relay refused the key instead of going) or the relay can't be reached.

BalanceFound tells the editor where the balance was found, so a wrong
amount can be put right (the GUI commit after this one).

Run on mote:
- gofmt -l: nothing.
- go vet, GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  ./internal/provider and ./internal/gui: ok.
- go test -count=1 -timeout 45m ./internal/provider: ok.

Broken by hand:
- A found query kept for ever again: TestFoundBalanceLookedForAgain fails.
- The kept-on-refusal case taken out: TestFoundBalanceKeptWhenTheKeyIsRefused
  fails.

Not tried: a relay that really moved to other software.
2026-11-05 14:46:23 +08:00
yetone 2488532257 provider: a relay added by hand finds its balance where relays tell it
The same relay user had added yylx.io by hand: no Balance URL, so no
balance anywhere until they deleted it and imported it from the relay's
site, whose link names the query (小鱼 of yylx.io, WeChat, 11-05).

A provider added by hand, or from a relay's preset, with a key and no
Balance URL, at no host magpie knows a query for, is now asked at its
base's origin: /v1/usage (sub2api, $remaining), then /api/usage/token
(new-api, $data.total_available / 500000), with the key's own auth and
headers, as balanceRead asks. A 200 whose field reads is the query. It is
kept in memory per origins and key (the key hashed), and so is finding
none, for 6h (5 min when the relay can't be reached), so a poll asks once.
Nothing is written to providers.json. The card, Check balance and
`magpie provider show` (BalanceQuery) read the found URL; none found is
no card, and the editor's "No Balance URL to ask".

Never asked: a vendor's or local server's preset host (api.openai.com,
api.anthropic.com, api.deepseek.com…), this computer, opencode.ai and
api.cline.bot, a plan whose windows are its card. The subsystem page has
the row.

Run (mote, go1.26.8):
- go vet ./internal/provider; go test -count=1 ./internal/provider: ok.
- The new tests: a sub2api relay read at $10472.14 with /v1/usage asked
  3 times over the probe, a Balance and a card poll; a new-api relay found
  after /v1/usage's 404; a relay answering HTML 200 everywhere has no
  card and is asked twice in all over two polls; the hosts left alone.

Broken by hand: with the probe taken out of balanceRead, the three
HandAdded tests fail (balance "" false; a card with no balance).

Before this, TestOpenCodeZenSaysItTellsNoBalance caught the probe asking
opencode.ai for OpenCode Go and a custom inference provider; those hosts
are left out now.

Real use (mote, sandbox HOME holding only the owner's yylx.io provider,
copied with its key, removed after): `magpie provider yylx-hand` (no
preset) and `magpie provider yylx` (鱼鱼连线's preset, Global region)
both show "balance $19.97 from https://global.yylx.io/v1/usage
$remaining".

Not tried: a real new-api relay; a new-api relay that routes unknown /v1
paths to its upstream.
2026-11-05 14:19:28 +08:00
yetone 2947685999 claude: an interactive run's calls keep the conversation they answered when their line comes late
kay20475 on X (magpie 0.1.3005, local magpie -> shared server magpie ->
Claude subscription, interactive bridge): a Claude Code sub-agent's
requests on one account read 99%, 6%, 6%, 99% from the cache; the two 6%
requests were 169.1k each, 35s apart, about 3s long with a short reply.
That is the shape of Claude Code's AgentSummary: every ~30s it sends the
sub-agent's conversation with its last results and "Describe your most
recent action in 3-5 words", while the sub-agent's own run has already
taken those results.

Cause. Such a request finds no run waiting on its calls and should go on
in a branch of the sub-agent's run's session (branch). branch takes it
only when the conversation stored on the call's line (callLine.told)
matches the one before the reply. park stored that only on lines it
already had. The interactive mode streams a reply first and reads its
session lines from the file afterwards (118-162ms after the call). So the
run parked before noteLines had the call's line, and the line came in
with no conversation. The next park then gave it the next request's
conversation. branch returned nil, and every AgentSummary (and every
fork directive) was told the whole conversation in a new Claude Code,
pasted as one text block. A single block can't match the cache beyond
the tools and system prompt, so 6%, and the next summary missed the same
way because its tail differs.

Fix. park also keeps the conversation for each call the client was shown
(r.shown), as a line with no uuid yet. noteLines keeps it when the line
comes, and branch skips lines with no uuid.

Test: TestClaudeForkBranchesOffTheLeadsSession/interactive now has the
fake write the call's session line after the reply's stream, once the
result is handed over, so after the park, which is the real order.
Broken by hand: with this test and the old claude_subscription.go on
mote, it fails ("told it whole", want "branched at line-...").

Run on mote at this tree (base 4cb7159f1): gofmt -l clean; go vet
./internal/gateway on darwin, GOOS=linux and GOOS=windows ok; go test
-timeout 45m ./internal/gateway (679s) ./internal/claudetui
./internal/claudebridge all ok. The fork/side-question/cut tests
-count=3 ok. The full ./... suite and the GUI suite were not run (no
GUI or other-package change).
Rebased on 351844594 (GUI only since 4cb7159f1): go test -count=1 -run
'Claude|Fork|Branch|Subscription' ./internal/gateway ok (77s) on mote.

Not tried: a real Claude Code AgentSummary against a real account. The
reporter's requests are matched by shape only (size, timing, short
reply). Ruled out: the remote-magpie hop. The bridge doesn't key runs on
headers (only anthropic-beta for safeguards), so losing
x-claude-code-session-id can't move a turn off its run. Not fixed here: a
sub-agent loop with no plain reply, told anew in the interactive mode, is
still pasted as one text, so a new run for it reads only tools+system.
2026-11-05 14:05:54 +08:00
yetone 4cb7159f18 routing: a ChatGPT account whose usage can't be read is asked, not starved
peterpark8527 on Discord: 11 ChatGPT accounts under Use before expiry,
one never used. An account whose wham/usage reading fails (or names no
window, or is held by "When I ask") stayed not known for good:
Use before expiry counted it a fresh week (FreshPace, ~0.6/h), behind
every known week being spent; Smart put it after every known account.
NoteCodexLimits only updated accounts already read, so its replies'
x-codex-* headers never made it known. Its week, once started by
magpie's own turns or warm-up, lapsed unspent. A simulation of 11
accounts over 4 weeks (Pace, Poisson load 30/60/90%) had it at 141 of
~1200 used at 30% load, losing 3406, while every known account was used.

- provider: a reply that tells an unread account's week makes it known
  from that (usedCache.heard), kept over failed readings, until a good
  reading tells it; a 5h window alone still makes nothing up.
- gateway: a Codex account not known, weighed against one known, is
  Learns, like Claude's: asked first once so its reply tells its week,
  and again an hour after its last answer if that told nothing
  (codexAnswered, codexLearnAgain). Of accounts none known the order
  stands, so no week is started before it is needed.
- docs/reference.md: Smart and Use before expiry say so.

Ruled out (by design or not starving): an unstarted Codex week lasts
until its first request, so last is right for it; ties go by decayed
tokens, not a fixed order; a 5h-only account goes by its 5h pace
(ahead); rests are time-bound with probes.

Run:
- wsl-run go test -count=1 -timeout 45m ./internal/gateway
  ./internal/routes ./internal/provider ./internal/middleware: provider,
  routes, middleware ok; gateway had 3 reds (TestAccountProxy,
  TestCodexDrawMovesToNextAccount, TestWeeklyPace's five-hours case):
  accounts none known reordered by answers earlier tests left in
  codexAnswered. Fixed by the known-peer gate above; then wsl-run
  go test -count=1 -timeout 45m ./internal/gateway ./internal/routes:
  ok (809s). The none-known guard's u00 line was added after that run
  and run alone on Windows (win-run -run TestUnknownCodexAccountIsAsked
  ./internal/gateway, with the reds above: ok).
- win-run the two new tests on the old code (73c98ebc2, stand-ins for
  the new names): TestNoteCodexLimitsKnowsAnUnreadAccount and
  TestUnknownCodexAccountIsAsked red.
- win-run go vet ./internal/provider ./internal/gateway ./internal/routes:
  ok; wsl-run go vet of the same: ok. gofmt -l: clean.

Broken by hand: learns' codex case returning false turns
TestUnknownCodexAccountIsAsked red; Allowances not applying heard turns
TestNoteCodexLimitsKnowsAnUnreadAccount red ("the next failed reading
forgot what the reply told"); dropping the known-peer gate turns its
none-known case red ("u01@x.com first, not the first listed").

Not tried: real ChatGPT accounts; the reporter's actual cause is not
confirmed (asked for version, quota, status, plan). Other ways one
account goes unused (90%/98% tiers, rested, model list, group, off)
need their answers. mote was not used: its disk is full.
2026-11-05 13:27:32 +08:00
yetone 73c98ebc20 gateway: a search API's or plan service's ask is routed and archived (axelburks)
axelburks on Discord: when magpie searches for a model through a search
API, the Routing page doesn't say which API answered, and Usage →
Requests lists the row but has no request archive, so the request and
response sent to the API can't be seen.

A model's search (searchWith) was already routed and archived. A search
API's ask (askSearchAPIKeys, a plugin's search hook, a signed-in search
API) and a plan's own search service (Kimi Code, GLM Coding Plan,
WorkBuddy, Codex's searchBy, and searchBy's Kimi branch, which wrote no
row at all before) only wrote a usage row.

Now every ask that writes a row goes through keepSearch
(search_archive.go): a done web_search route, agent magpie, For the
agent searched for, the API's name as model and its host as provider,
seated on the masked key or account; a Recent call with ring-cut
bodies; and with the request archive on, archiveOwn of the exchange as
sent. The row gets RouteID and Archive, which the Requests tab already
opens. Each ask has a searchWire in its context, filled where it is sent
(tapSearch tees the answer as read; the last exchange stands, so GLM's
MCP tools/call is the one kept). A plugin's search is noted as what
magpie handed the hook (key masked) and what came back (PLUGIN method).
The key is replaced by MaskSearchKey in path, query, headers and both
bodies before anything is kept; the archive's own scrub runs on top.
Bodies are kept up to RequestArchiveMaxMB (longer marked cut); archive
off keeps nothing on disk, the route and Recent call stay.

Run (mote's disk filled mid-work, see below; the rest on WSL
magpie-desktop via wsl-run):
- mote-run: go test -run 'Search|Archive' ./internal/gateway ok; GUI
  usage-ledger-search, routing-side-calls, request-archive-usage in
  chromium+webkit, every language and width: 38 pass.
- wsl-run: go test -run 'Search|Archive' ./internal/gateway ok; go vet
  ./internal/gateway ok; GOOS=windows go vet ./internal/gateway
  ./internal/gui ok; GOOS=darwin CGO_ENABLED=0 go vet ./internal/gateway
  ok; GUI usage-ledger-search, routing-side-calls, request-archive-usage,
  search-instead, search-mcp in both engines: 68 pass, 0 fail.
- gofmt -l clean.

Broken by hand: keepSearch's call commented out turns all five new
gateway tests red; taken()'s key masking turned off turns
TestSearchAPIAskIsRoutedAndArchived and TestSearchAPIKeyInQueryNotArchived
red. TestSearchRowKeepsRouteAndArchive (internal/gui) is a guard that the
row's RouteID and Archive reach /api/usage/requests; it passed on the
old code too.

Not tried: real Tavily/Brave/Kimi/GLM/WorkBuddy/Codex accounts (httptest
stubs only); Linux go vet of internal/gui (WSL lacks gtk4/webkitgtk);
web_fetch (search_fetch.go) and a vendor's own search (search_native.go),
which magpie doesn't send, are unchanged. Full suite runs after the push.
No GUI asset, API call or i18n string changed.
2026-11-05 12:40:35 +08:00
yetone 1826c4bd99 providers: a Remote magpie that is this magpie says so and is left out, unless kept (hanslin1666)
B uses A through a Remote magpie provider, and sync carries that
provider to A, where it points at A. Each of its models was one of A's
own, listed again beside it and taken by A's found groups, and a request
through it passed through A's gateway twice.

A fetch of a Remote magpie's list now reads its models' magpie_via: when
the magpie that listed them (the last entry) is this magpie's own
catalog.Self, remote-self.json keeps the provider id and the address it
answered at (noteSelf). Another lister, or a list with no via, takes
the record away; an empty list or a failed fetch changes nothing; a
provider moved to another address is not self until a fetch there says
so. The file is this computer's own, never in a backup or sync.

Such a provider is left out (SelfLeftOut in On, SwitchedOff and
remoteMagpies): not in /v1/models, the catalog or a found group. A
request naming one of its models, an agent's pick synced from B, is
served here with the remote's id taken off (ThroughSelf in Resolve and
ResolveRoute), once through the gateway. A 404 for it says why and how
to keep it.

The Providers row shows "This magpie" (greyed while left out), with the
reason as its title; the editor has a note and a "Use it anyway" tick
(KeepSelf, POST /api/provider/keepself). KeepSelf belongs to the user
and to this computer: Mirror and Restore keep the local value (false for
a provider new here), davsync's hashes blank it, and a provider save
keeps it. Strings in en, zh, zh-TW, ja, de.

Docs: providers-accounts.md (two magpies row), sync-backup.md (what
stays on each computer).

Run at this tree on origin/main 4e85cac01:
- gofmt -l: nothing. app.js 1,309,132 bytes (budget 1,316,874).
- mote: go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  provider, gateway, gui, davsync, catalog: ok.
- mote: go test catalog, davsync ok; gui red only in
  TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27); provider and
  gateway did not build there (mote's disk full, "no space left on
  device"), so they were run on:
- Linux (WSL magpie-desktop): go test -tags nogui provider, gateway,
  gui, davsync: all ok.
- Windows (xiaomi-gpu): go test -run 'RemoteSelf|KeepSelf|RemoteMagpie|
  Mirror|KeepLogin' provider, gateway, davsync: ok.
- mote: remote-self.test.cjs 16 of 16 (chromium and webkit, 1100 and
  420, en zh ja de), before the rebase; the rebase touched no line of it.

Broken by hand, each red, then restored:
- noteSelf a no-op: TestRemoteSelfRecord and
  TestRemoteMagpieThatIsThisOneIsLeftOut red.
- ThroughSelf a no-op: the gateway test red (404 for rem/own/m1).
- On() without SelfLeftOut: the gateway test red (listed, 2 passes).
- davsync hashes without the KeepSelf blank: TestKeepSelfIsNoChange red.
- Mirror without keeping KeepSelf: TestMirrorKeepsKeepSelf red.
- The row's badge removed: remote-self.test.cjs red (chromium 1100 en).
- The tick's onchange a no-op: remote-self.test.cjs red (webkit 420 zh).

Not tried: two real computers syncing each other (the case is built in
one process: the gateway test's Remote magpie is its own gateway);
the Linux and Windows apps' webviews; the whole GUI suite (mote's disk is full);
remote-self.test.cjs again after the rebase.
2026-11-05 12:37:30 +08:00
yetone 10f1e97883 search: a GLM Coding Plan searches its own models with the plan's web search MCP
young02036 on Discord asked for the GLM Coding Plan's Web Search MCP in
magpie's web search. The plan's key is given for that server, so magpie
now asks it with the provider's own key, with nothing to set up: a
Streamable HTTP session at <host>/api/mcp/web_search_prime/mcp
(open.bigmodel.cn or api.z.ai, docs.bigmodel.cn/cn/coding-plan/mcp/
search-mcp-server and docs.z.ai/devpack/mcp/search-mcp-server), the key
as a Bearer, initialize, one tools/call of webSearchPrime with
{"search_query"}, then the session's DELETE.

- provider.ZhipuCodingSearch: only a provider or key on the plan's
  /api/coding/paas/v4 (Zhipu's or Z.ai's host, or the zhipu/zai preset).
  A pay-as-you-go key isn't served by the server and never asks it.
  ZhipuSearches reads p.Keys itself, since KeysOn is counted per list and
  searchesOwn runs on every request. ZhipuSearchKeys lists the plan's
  keys, which are asked in turn.
- searchesOwn/ownSearch: the plan's own models search there first, as
  with Kimi Code and WorkBuddy, and fall to magpie's searcher and the
  search APIs when it fails. This happens only while Settings names no
  searcher (glmSearches): a searcher the user named still searches for
  every model, which is a value the user set.
- It is not offered as a searcher for other providers' models. A plan
  with the Responses base (/api/v1) already searches natively there
  (searchHosts, #660), and making it a no-model service would change the
  searcher those users have now.
- The reply's text is read as a list of results, a list in a JSON
  string, or a list under search_result/results/items/data. isError, or
  words with no results, is an error with the key masked. The query is
  masked as Settings > Privacy says (maskedQuery). Each ask is a request
  log row (logOwnSearch).
- No GUI change: the setting has no switch, the same as WorkBuddy's.
- docs/subsystems/gateway-routing.md has a section on it, and the
  searchesOwn lists there and in plugin-runtime.md name it.

Run (mote, at this tree):
- go test -count=1 ./internal/provider ./internal/settings
- go test -count=1 -run 'Search|GLM|Zhipu|Kimi|LoopGuard|Docs|Guard|WorkBuddy'
  ./internal/gateway: ok
- GOOS=linux and GOOS=windows go vet ./internal/gateway ./internal/provider:
  ok
- gofmt -l: clean

The tests use a fake server only and never reach the network:
- TestGLMCodingPlanSearchesForItsModels: Claude Code's literal WebSearch
  request to a plan's model. The fake gives an event-stream reply with
  a progress notification before the result, and a double-stringified
  result. Then a refusal, an unnamed versus a named searcher beside a
  search API, and a pay-as-you-go key.
- TestReadGLMSearch: each reply shape, and prose.
- TestZhipuCodingSearchAddress: hosts, presets, a plan key beside a
  pay-as-you-go one, a key that's off.

Broken by hand:
- With the old searchesOwn/ownSearch, TestGLMCodingPlanSearchesForItsModels
  is red: the model had no search, 400 "no search tool".
- With glmSearches ignoring a named searcher, the test is red at the
  named-searcher step: the MCP was asked and the named searcher wasn't.

Not tried:
- No real GLM Coding Plan key was available, so nothing was sent to the
  real open.bigmodel.cn or api.z.ai server. The docs give neither the
  tool's argument names nor its reply's shape. search_query and the
  result fields come from Zhipu's Web Search API and a third-party npm
  wrapper (web-search-zaimcp 0.1.2). If the real reply differs, a search
  falls to magpie's other searcher or the search APIs and says why.
- The plan's MCP quota, and how a spent quota is worded.
- A GUI hint in Settings > Web search.
2026-11-05 11:44:31 +08:00
yetone 2260390a01 gateway: a Gemini thought signature goes back only to the provider that gave it
mimi001234 on Discord: Pi (openai-completions) on auto/gemini-4-argon, a
group of google-vertex and google-aistudio-paid. Vertex AI served turns
1 to 14 and signed its calls; on turn 15 it answered 429, the group moved
to AI Studio, and magpie replayed Vertex AI's signatures from
gemini-signatures/. AI Studio answered every try with 400 "Corrupted
thought signature." A signature is the issuing backend's, and only it
takes one.

- The provider that gave a signature is noted beside it,
  gemini-signatures/<key>.by (noteSigner, written through temp and
  rename), wherever a reply is read: decoderFor (every translated path:
  Chat, Anthropic and Responses clients, plugins, search, continuations)
  and sigTidy (a Chat relay, and a Gemini client's reply relayed as it
  came, now only read, in native mode).
- Every request is fitted to its provider: ownSignatures in
  forwardTranslated, chatCallSignatures and geminiBodySignatures in
  passthrough. Another provider's signature goes as Google's documented
  skip_thought_signature_validator on a call, and not at all on text. A
  signature of no known provider (ids from before this change, a note
  that couldn't be written) goes as before.
- A 400 "Invalid/Corrupted thought signature" (signatureRefused) is asked
  again once without signatures at any upstream Gemini's signatures
  reach (signaturesReach), relayed too, not only Vertex AI translated;
  it rests no account (restAfterMarked) and lets a group go on to its
  next member (shapeRefused).

The signer is the provider id, not the account: two accounts of one
provider share signatures as before.

Run on mote (mote-run), the targeted run and vets at this change on origin/main 0e55a7593:
- go test ./internal/gateway -run 'Signature|Signer|Vertex|Gemini|Corrupted': ok
- go test -timeout 45m ./internal/gateway: ok (876s), at this change on
  bf60ea596; the only commit since, 47d583939, touches internal/library
- gofmt -l internal/: clean; go vet ./...; GOOS=linux go vet -tags nogui
  ./...; GOOS=windows go vet ./...; go build ./...: ok

Red on the old code (origin/main 0e55a7593 with the new test file):
TestSignatureGoesOnlyToItsSigner (turn 3: 400 "AI Studio: ... Corrupted
thought signature."), TestCorruptedSignatureTriedWithout and
TestCorruptedSignatureNotTheAccount (rested "backoff" 60s).
Broken by hand on the new code:
- chatCallSignatures without the foreignSignature check:
  TestSignatureGoesOnlyToItsSigner red (AI Studio asked twice: refused,
  then the retry).
- ownSignatures in forwardTranslated commented out:
  TestSignatureGoesOnlyToItsSignerTranslated red the same way.
- the passthrough retry turned off: TestCorruptedSignatureTriedWithout
  red with the 400.

Not tried: real Vertex AI and AI Studio accounts; a Gemini client's
request relayed to Vertex AI end to end (TestGeminiBodyKeepsOnlyItsOwn
covers the body and the noting only); Code Assist relays, whose replies
are not noted, so their signatures count as of no known provider.
2026-11-05 11:42:53 +08:00
yetone 47d5839397 library: sync and backup files carry the hooks
VincentChan on Discord (v0.1.3005) said part of the Library doesn't reach
his other computer through sync. Checked kind by kind what the library part
of a bundle carries: instructions (each set's text, a linked set's file text,
the agents ticked, each agent's own addition), MCP servers, skills and
subagents all go. Hooks didn't: library.Bundle had no field for them, so a
hook made on one computer never reached the other, by WebDAV/S3/GitHub sync
or a backup file.

- library.Bundle.Hooks (*[]*Hook): name, description, event, matcher,
  command, timeout, agents ticked. Collect always sets it, empty too.
  Applied.Hooks (the entries magpie wrote into each agent here) stays out:
  each computer writes them on the sync Put runs, beside the user's own
  hooks, and records its own entries, so an entry the user edited there
  stays theirs.
- Put replaces the hooks with the bundle's, so one taken out on one
  computer goes from the others. A nil list (a bundle from a magpie before
  this) keeps this computer's.
- check refuses a hook with no name, no command, or named twice. The event
  and agents are carried as they come: an event a newer magpie knows is a
  problem on the agent here, not a refused library.
- davsync: an empty list hashes as before the field, so upgrading with no
  hooks syncs nothing.
- The CLI's backup line counts hooks; the GUI's sync/export/import ticks
  say "instructions, MCP servers, skills, hooks and subagents" in every
  language.
- library.md and sync-backup.md updated, and they now name what stays
  this computer's own: projects, skill groups, CopySkills/SkillHow,
  SharedSkills, MCPHub.

Instructions: two sandbox computers through the fake DAV server carried a
named set and a change to it, a set linked to ~/.agents/AGENTS.md and a
hand edit of that file, both computers having their own text first, an
agent's own addition, and an agent installed after the first sync. All
reached the second computer's CLAUDE.md/AGENTS.md (exploration tests, not
kept). So no instructions change here; what VincentChan saw is not
reproduced yet.

Run (worktree at 0e55a7593; origin/main bf60ea596's two commits touch
none of these files):
- mote: go test -tags nogui ./internal/backup ./internal/davsync
  ./internal/cli ./internal/library ok; go vet -tags nogui for darwin,
  GOOS=linux and GOOS=windows on the four packages ok; gofmt -l clean;
  go test ./internal/gui -run 'TestCoreScriptBudget|Words|I18n|Builtins' ok
- GUI (wsl-run, Linux): i18n-keys, github-sync, s3-sync, sync-*,
  webdav-settings-refresh, library-backups-top, gui-de, gui-ja, gui-zh-tw:
  187/187

Broken by hand: with Collect not setting Hooks, Put ignoring them and the
hash not dropping an empty list (the old code), TestCarryHooks,
TestCarryOldBundleKeepsHooks, TestCarryNewerHooks,
TestBackupFileCarriesHooks, TestSyncHooks and TestNoHooksHashAsBefore
went red.

Not tried: a real WebDAV/S3/GitHub remote between two real computers;
Windows and Linux runs of the Go packages.
2026-11-05 11:29:20 +08:00
yetone 234903cb23 cli: magpie model api sets the API a model is asked on, as the editor's picker does (yew_fence_931206)
A relay with many models behind one key can now have each model's API
set from a script, not only in the provider editor's Names, prices &
levels ("API this model is asked on"):

  magpie model api <provider/model>... chat|responses|anthropic|gemini|auto
  magpie model api <provider/model>... --reset      (auto)
  magpie model api <provider/model>                 what it is asked on
  magpie model apis [<provider>]                    the settings; with a
                                                    provider, every model

It saves through provider.SetModelPrefs, the editor's Save, into
settings' modelAPIs, so a running gateway reads it on the next request
and the agents' model lists are told once. Choices are those the editor
offers (modelAPIs in app.js): the APIs the provider has a URL for, when
it has two or more; Vertex AI none. --help anywhere prints the usage. A
flag in place of a model, an unknown API, a model the provider doesn't
list, or an API it has no URL for is refused; several models are all
checked before any is written. A saved setting for a model the vendor
no longer lists can still be reset. Documented in docs/reference.md
("The API a model is asked on") and the gateway-routing page.

Run (mote, via mote-run, at this tree on 0e55a7593):
- go test -count=1 ./internal/cli/: ok (46.7s)
- TestModelAPICmd, TestModelAPIReachesTheRunningGateway: PASS. The
  second starts gateway.New().Handler() first, asks relay/mixed (chat
  completions), sets anthropic through the CLI, and the next request
  goes to /v1/messages; after --reset back to chat.
- gofmt -l: nothing; go vet, GOOS=linux go vet -tags nogui,
  GOOS=windows go vet of ./internal/cli; go build, GOOS=linux build
  -tags nogui, GOOS=windows build: ok.

Broken by hand:
- the model/api(s) cases taken out of modelCmd: both tests FAIL
  (unknown command "apis" / "api").
- each model written as it is checked instead of all checked first:
  TestModelAPICmd FAIL "a refused command wrote:
  map[relay/claude-y:anthropic relay/gpt-x:chat relay/mixed:chat]".

Not tried: a real relay account; the reporter's provider. The full
suite runs after the push.
2026-11-05 11:05:38 +08:00
yetone 0e55a75936 remote magpie: a request that goes round magpies pointing at each other stops after 8, and a remote that is this magpie lists its models once
Follows c2c991a5b (cdredfox's two magpies each the other's remote).
hanslin1666 (Discord) has the sibling: device B uses device A through
a Remote magpie provider, and S3 sync carried that provider to A too,
so A has a Remote magpie pointing at itself. Sync carries every
provider (backup.Collect, provider.Mirror), a Remote magpie included.

Two holes c2c991a5b left:
- A remote that is this magpie lists this magpie's own models through
  this one alone ([self]); c2c991a5b kept any via of only self, so
  rem/own/m1, rem/rem/own/m1, ... still grew a level a fetch until
  MaxVia. A via naming this magpie is now taken only when it is
  exactly [self]: the remote's own models, once (what the gateway's
  in-process remote tests need, and what hanslin1666 sees today).
- Nothing stopped a request at request time: a list fetched from a
  magpie older than magpie_via, or one cached before the update,
  could still route round. Each request magpie passes to a Remote
  magpie now says how many magpies it went through (X-Magpie-Hops:
  the count it came with + 1, 1 for an agent's own); one that arrives
  having passed catalog.MaxVia (8) is answered 508 Loop Detected with
  what to turn off, before any vendor or remote is asked. The count is
  read only from a magpie's request (its User-Agent, which needs the
  key anyway), and taken off every request as it arrives, so no vendor
  is sent it. It goes on every path that already passes the caller on
  (passOnCaller: chat, decide, draw, embeddings, video).

Run (mote, at this tree on c2c991a5b):
- go test -timeout 45m ./internal/catalog ./internal/provider
  ./internal/gateway -count=1 on Linux (wsl-run, magpie-desktop):
  catalog ok, gateway ok (590s), provider red only in
  TestClaudeAccountServesModelsListedSinceItsFetch, #3174, which this
  doesn't touch.
- go vet, GOOS=linux and GOOS=windows go vet of catalog and gateway
  (mote): ok. gofmt -l clean.
- The full suite at c2c991a5b (mote, -timeout 45m ./...): 86 packages
  ok, internal/gui red only in TestMainWindowCorners (#3949).

Broken by hand:
- the via rule back to c2c991a5b's: TestFetchLeavesOutWhatCameFromHere
  red (rem/own/m2 through [self self] taken).
- no hops set in passOnCaller and no check in withCaller:
  TestRemoteMagpieRequestLoopStops red (the remote told [ ] passes,
  200 not 508 at 8, the vendor asked).

Not tried:
- hanslin1666's or cdredfox's own machines.
- Paths to a remote that don't go through passOnCaller (the Codex
  socket and native passthrough) don't count hops; a loop through
  them is still cut by the lists.
- Hiding a Remote magpie that is this magpie, or keeping it out of
  sync on the machine it names: not done here (a third machine that
  syncs may want it); it now costs one extra local pass per request
  to it, and its models show twice.
2026-11-05 10:52:06 +08:00
yetone 1fd02d33ce agentplug: an agent plugin can pick the model its agent starts on in a second file (str_, PiG)
str_ on Discord (#help, v0.1.3005): PiG's row on the Agents page only
switched the model list on, where Pi's picks the model it starts on.
PiG, like Pi, keeps its providers in ~/.pig/agent/models.json and the
model a session starts on in settings.json (defaultProvider,
defaultModel; PiG's docs/site/docs/settings.md, startup_model.go). An
agent plugin could name a model key only in the one file connect
writes, so agent-pig 0.1.0 had to be connect-only.

An agent's descriptor can now say `startup: {config, format, model,
keys}`: the other file, the key that holds the model (the id without
magpie's prefix) and keys written beside it. With it the row gets a
model field as a built-in's does. Picking one of magpie's writes
connect's keys into config and the model and keys into startup.config,
each key kept aside as before; a model of magpie's picked in the agent
itself still reads as magpie's; a model of the user's own picked there
while magpie's provider is listed counts as connected (Beside), not
drift, and is kept on disconnect. Sync rewrites the list and leaves the
startup model where it is. Off, or `magpie <id> default` with the plugin
gone (RestoreGone), puts both files back. startup without connect, beside
agent.model, in config's own file, or naming the model key among keys
is refused. An older magpie ignores the field, so agent-pig 0.1.1
(plugins repo) stays connect-only there. Every other agent plugin
already names its model in its own config; pig is the only
connect-only one.

Run (mote):
- go test -count=1 ./internal/agentplug/: ok
- go test -count=1 -run 'TestPlugged|TestPlugin|TestRestoreGone|TestAgent'
  ./internal/agent/: ok
- go vet, GOOS=linux and GOOS=windows go vet of both packages; gofmt -l
  clean
- the four TestPluggedStartup* tests on the old code: red (the row had
  a provider field and only listed models)
- real PiG 0.5.3 (darwin-arm64 release, SHA256SUMS checked) in a sandbox
  HOME, models.json written by agent-pig 0.1.1's own connect and
  settings.json as startup writes it, against a fake OpenAI server:
  `pig -p` sent model deepseek/flash with the gateway key. With an
  enabledModels scope that leaves it out, PiG started on the scope's
  first model (said in the plugin's README).

Broken by hand: no startRestore in Unwire (TestPluggedStartupModel and
OwnPickKept red); no Beside (OwnPickKept red, "wired false").

Not tried: the GUI and the TUI with the real row (app.js unchanged; the
row is the model field every built-in has), Windows and Linux runs of
PiG, a real magpie gateway in front of PiG, a real vendor model.
2026-11-05 10:46:46 +08:00
yetone c2c991a5b3 remote magpie: two magpies each the other's remote no longer list each other's models back without end
cdredfox (Discord) saw 100-200% CPU while magpie used a remote magpie
over Tailscale, gone with the remote off. Their providers mask anyway
and their agent asks auto/ ids, so the earlier unmasked-group lead
doesn't explain it. What does: when A and B are each other's remote,
A's /v1/models (to another magpie) lists rem/<B's models>, B fetches it
as back/rem/..., lists that back to A, and so on: one level deeper on
every 10-minute fetch, without end. Each level is another member of
the found auto/ group and another route round the two machines, masked
again on each pass. On mote, two sandbox magpies in that setup went
from A: [auto/m1 own/m1 rem/auto/m1 rem/up/m1 rem/back/own/m1] to
[... rem/back/rem/back/own/m1, rem/back/rem/auto/m1 ...] after one
more scheduled fetch, and B had back/rem/back/own/m1. A request on the
loop route (rem/back/own/m1) cost A 1.07s CPU over 10 turns against
0.69s for own/m1.

The list a magpie gives another magpie now names, as magpie_via, the
magpies each model passes through, itself last. Each process has a
random id (catalog.Self). A fetched list leaves out a model whose via
has this magpie and another one (it left here and came back), or more
than 8 magpies. A remote that is this magpie itself (via only this id,
as the in-process tests set up) is kept. A magpie older than this sends
no via, and its list is taken as before: both machines need the update.
Stamped on every list a magpie gives: models(), its deciders, and the
drawer and video lists. A routing group's via is its members'
together, so A's auto/m1 holding B's auto/m1 (which holds A's) is left
out at B, and requests no longer go A -> B -> A through groups.
What a user of A loses: B's own auto/ group of a model when it holds
A's model (it reaches A again); B's own models stay listed at A one by
one, and A's group of the model holds them. The cached list keeps Via, so a model a remote served
through others keeps its path in this magpie's list too.

Run (mote, at this tree on 6abacd46c = origin/main):
- go test -timeout 45m ./internal/catalog ./internal/provider
  ./internal/gateway -count=1: ok (catalog 0.7s, provider 120s,
  gateway 670s).
- go vet those three; GOOS=linux and GOOS=windows go vet: ok. gofmt -l
  clean.
- Two sandbox magpies (CLI, nogui build) each the other's remote:
  after two scheduled fetches (18:14, 18:24/18:25) A lists auto/m1,
  own/m1, rem/up/m1 and B auto/m1, up/m1, back/own/m1, each fetch
  taking 1 model; the old build in the same setup went 3 -> 5 models
  on B's second fetch and kept growing (rem/back/rem/back/own/m1).
- go test ./internal/gateway again after the group change: ok (715s).

Broken by hand:
- the loops check in live.go off: TestFetchLeavesOutWhatCameFromHere
  red (back/own/m1 with [self peer] and a 9-magpie model taken), and
  TestRemoteMagpieListLoopsNoMore red (the remote's back/own/m1 taken).
- models() without the magpie_via line: TestRemoteMagpieListLoopsNoMore
  red (own/m1 and rem/up/m1 listed through []).
- viaOf giving a group nil: red (auto/m1 listed through [self], not
  [peer self]).

Not tried:
- cdredfox's own two machines; it isn't confirmed yet that their remote
  also has this machine as its remote. If it doesn't, this isn't their
  cause.
- A loop through a magpie older than this one (no via: still grows
  until both are updated).
- The full suite (runs once after the push).
2026-11-05 10:26:14 +08:00
yetone 681a472cab agent: a Codex thread started during the takeover comes back to OpenAI once it is quiet, not hours later (nb5p on Discord)
nb5p on Discord (v0.1.3001, Codex app): after Send greyed out, Retry in
Codex did nothing. The model picker and Send spun, the same dialog came
back a few seconds later, and the model field read "model unavailable".

With the ChatGPT account Codex is signed in to used up, magpie makes
itself Codex's provider (codex.out), so a turn sent then starts a thread
saved with model_provider "magpie". When the account has room again,
Sync puts Codex back on OpenAI, and its deferred bringBack moves magpie's
threads to OpenAI. It skips a thread written to in the last minute,
which is the one the user was in, and leaves it "for the next Sync".
Nothing schedules one, though: Sync runs on a catalog change, which can
be hours away. The app then can't resume that thread on the provider it
is now on ("This chat uses magpie, but your current provider is
openai", the string still in the Codex the app bundles), so each Retry
failed the same way.

bringBack now asks whether a thread is still on magpie because it was
being written to (sessions.CodexThreadsBusyOn: the state databases' rows
on magpie whose rollout changed within ActiveWindow). If one is, it asks
for one more Sync after ActiveWindow+5s. Only one wait is pending at a
time.

docs/subsystems/agent-wiring.md says so beside bringBack.

Test: TestCodexTakeoverThreadComesBackOnceQuiet. The takeover is on, and
a thread on magpie is written to now. The account comes back, and the
thread stays on magpie while it is written to. A later Sync is asked
for, and that Sync, with the thread quiet, moves it to openai. No other
Sync is asked for after that.

Broken by hand: with the bringBack hook turned off (`if false && ...`),
it fails with "no later Sync asked for" (5.3s). Restored, it passes.

Run on mote at this tree (base 8eb219354, origin/main fetched, nothing
new):
- the new test with -race -count=3: ok;
- go vet ./internal/agent ./internal/sessions for darwin, for linux
  -tags nogui and for windows: clean;
- go build ./...: ok;
- gofmt -l: clean;
- go test ./internal/agent ./internal/sessions: ok.
The full suite at the pushed head is in the report.

Not tried: the real Codex app at the moment an account runs out and
comes back. The resume failure is read from the Codex source and the
string in the app's bundled codex, not seen live. A thread the app keeps
writing to for minutes on end waits one more round each time; that case
was not timed. Nor was a thread the app keeps open with its writer lock
held after it goes quiet: MoveCodexThreads refuses that one too, and
CodexThreadsBusyOn looks at the time only, so no further Sync is asked
for it.
2026-11-05 08:23:05 +08:00
yetone 3d0d790606 codex: the Codex app left on an account that runs out is restarted onto the one Codex is signed in to (nb5p on Discord)
nb5p has two ChatGPT accounts in magpie, B first. The Codex app showed A,
and once A ran out Send was grey for every model, magpie's and another
provider's too.

Cause: magpie's switch back to the first account (or to the account
Codex is kept signed in to) leaves the Codex app's app-server running
unless "Restart the Codex app to follow" is on. The app-server keeps the
account it started on (CodexAppStale), so the app stayed on A while
auth.json said B. magpie read only B, which had room, so nothing moved,
magpie never took over, and the app-server was never restarted: the app
greyed Send on A's allowed false for good.

Fix: on each full look of KeepOnAnAccountWithRoom,
restartCodexAppLeftOnSpent reads the account the app is left on, and
once that is held (codexHeld) marks a spent switch (codexAppSwitched
true), which codexAppStep restarts past the RestartApp tick, as a switch
off a used-up account already does. Once per app-server left.

Run (mote, at this tree):
- go test ./internal/provider -count=1: ok
- TestCodexAppLeftOnASpentAccountIsRestarted: user switches to A, magpie
  switches back to B and leaves the app running, A still has room
  (nothing ended), A runs out with B's room (app-server 7 ended), next
  look (not ended again).
Broken by hand:
- codexAppSwitched(true, false) commented out: red, "ended [], want the
  app-server left on the used-up account".
- the once-per-app-server check off: red, "restarted again: [7]".
Not tried: the real Codex app on a real account running out; the call
in KeepOnAnAccountWithRoom's loop is covered by reading, not by a test.
2026-11-05 07:51:09 +08:00