Commit Graph
1457 Commits
Author SHA1 Message Date
JoeyWu-tech bec9df0888 sessions: a provider move leaves a thread a Codex has open (#3751)
#3751's second half; 67b12956 fixed the half about lengths. A Codex
thread moved to another provider, by the Sessions page's Move
(MoveCodexProvider, #887) or as Codex steps off magpie (bringBack's
MoveCodexThreads), has each of its rollouts written whole into a temp
file that then takes its place. The move took no Codex lock and left
alone only a thread written to in the last minute. A Codex that resumed
the thread (the app-server, as run below; a resumed TUI too, by Codex's
source) keeps its rollout open to append to for as long as it has the
thread, so what it wrote after a move went into the file the rename had
put aside: a turn the upstream answered was in neither the rollout nor
what Codex sent after its next resume.

moveCodexPaths now holds the thread as Codex holds one it writes to,
archives or deletes (rollout/src/writer_lock.rs, acquire; thread-store
holds it through a whole archive, unarchive or delete): under
thread-writer-locks/.coordination.lock it makes and locks
thread-writer-locks/<thread>.lock, then lets the coordination lock go
and keeps the thread's lock from before a file is copied to the trash
until the thread's row in the state database has moved. Letting go takes
the lock file away under the coordination lock, as Codex's guard does. A
Codex that resumes the thread meanwhile is turned away by Codex itself
("already has an active writer"), so the files and the row move together
and a rollback is written under no Codex. A thread a Codex has open is
left as it was: its files, their time and its row, with no copy kept.

Its error, "a Codex has the session open", is ErrActive too, so it goes
where a thread written to in the last minute goes: MoveCodexThreads
leaves it for its next call, and the Sessions page's reply marks it
active, so the page says "{title} is still being written to; close it in
Codex and try again in a minute" ("{n} sessions ..." for several), in
en, zh, zh-TW, ja and de. No new words and no GUI file changed: app.js
grows 0 bytes. There is no CLI for the move. The minute is the page's
own: codex exec lets the thread go as it exits (the interactive TUI
wasn't tried), but Codex 0.164.0's app-server keeps a thread loaded, and
held, until 30 minutes after it went idle with nothing showing it
(thread_unload_delay_secs, 1800 by default), or until it ends. So a
thread the Codex app has shown can be refused for up to half an hour
after it is closed there, or until the app quits. Those words are left
as they are (#3986).

A Codex home without thread-writer-locks (a Codex from before them)
has no lock to take, and its threads move as before, with the
last-minute check alone. None is made there: PortCodexRollouts reads a
home with one as one whose Codex holds its threads, and would then
rewrite rollouts under a Codex that doesn't. A lock folder that can't
be read, or a lock file that can't be opened, refuses the move with
its error. The coordination lock is waited for at most 10s
(filelock.Wait), under storeMu and mu as the row's 5s busy_timeout
already is; not had by then, the thread counts as held, as in
editRollout.

editRollout, the port's writer, isn't used: it publishes one file under
the coordination lock alone, while a thread's files (a revert's, a
packed twin) and its row move together, and its edit can't refuse a
longer id in a paginated rollout as 67b12956's rewriteCodexProvider
does. rewriteCodexProvider is unchanged, so the padding and that
refusal stay as they were.

A thread bringBack leaves keeps its row on magpie, so the next bringBack
picks it again (codexThreadsOn) and moves it once its Codex has let go:
it isn't left for good. bringBack runs at Disconnect and in Codex's
Sync, which SyncCatalog runs: at the GUI's start, after a provider,
plugin or model list is saved or fetched, and when the catalog is
fetched again (catalog.KeepFresh, at least daily in the GUI and in
magpie serve). Until then the thread stays on magpie, as one written to
in the last minute does now, so for up to about a day while magpie runs.
At a Disconnect magpie also restarts the Codex app's app-server
(KeepCodexAppOnItsProvider, every 3s), which lets the thread go; when
that comes after bringBack's move, the thread waits for the next Sync.
When Codex goes back to openai, or another id of magpie's length,
RelabelCodexThreads first writes a plain rollout's provider in place,
held or not; MoveCodexThreads meets a held thread there only for what
that skips, a packed rollout mostly. For an id of another length it
moves them all.

RelabelCodexThreads takes no lock either. It writes the id over in the
first line, in place, so a Codex appending to the file loses nothing:
tried below, the turn after it was kept and the row stayed as it wrote
it. It is left as it is.

The port's paragraph in docs/subsystems/gateway-routing.md, where
67b12956 put the move's lengths, says so, and so do the comments of
MoveCodexProvider, MoveCodexThreads and bringBack.

What was run (tree d652ce94, on origin/main 74dcf40a, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- TestMoveCodexProviderLeavesAnOpenThread (new): a thread's writer lock
  held as a resumed Codex holds it. The Move is refused with ErrActive;
  the file, its time and the row are as they were, nothing is kept in
  the trash and no temp file is left. With the lock let go (its file
  left behind, as a Codex that ended leaves it), the Move goes through
  and the lock file is gone.
- TestMoveCodexProviderHoldsTheThread (new): looked at from a trigger
  on the row's update, as the Move writes the row, the thread's lock is
  held and the file names the new provider already; the lock file is
  gone after.
- TestMoveCodexThreadsLeavesAnOpenThread (new): two threads on magpie,
  one held. The other moves; the held one keeps its file and row, with
  no copy and no error, and the next call moves it once let go. A home
  without thread-writer-locks moves its thread as before, and gets
  none.
- The three with 74dcf40a's codex_provider.go: red, "err <nil>, want
  ErrActive", "as the row was written: no lock file", and both threads
  moved.
- -race -count=10, the three and every move and port test of
  internal/sessions (TestCodexProviderIn, TestMoveCodexProvider,
  TestMoveCodexProviderPacked, TestMoveCodexProviderKeepsBytePlaces,
  TestMoveCodexThreads, TestMoveCodexThreadsNone,
  TestPortCodexRollouts and its KeepsBytePlaces, LeavesAnOpenThread,
  LongerLine and RepairsForks, TestPortLineDropsClaudeBlocks,
  TestPortLineLeavesOthers): 16 tests, 10 runs each, ok. -race
  -count=3: internal/agent's TestCodexThreadsComeBackOffMagpie and
  TestCodexThreadsFollowMagpieIn (bringBack, bringOver) and
  internal/gateway's TestPortedCompactionReadsTheSame, ok.
- Broken by hand, each alone in a scratch worktree at this tree, the
  eight move tests run, each red:
  - no lock taken: all three new tests, as at 74dcf40a.
  - the row written for a thread left: both LeavesAnOpenThread tests
    ("its row moved to ..., its files didn't"), and MoveCodexThreads
    never finds the thread again ("after its Codex let go: [] <nil>").
  - the lock taken after the copy to the trash: both
    LeavesAnOpenThread tests ("a copy kept of a thread left as it
    was").
  - the lock let go after the files, before the row:
    TestMoveCodexProviderHoldsTheThread.
  - the error not ErrActive: TestMoveCodexProviderLeavesAnOpenThread
    ("err a Codex has the session open, want ErrActive") and
    TestMoveCodexThreadsLeavesAnOpenThread (the held thread's error
    returned, "thread ...: a Codex has the session open").
  - the lock file left when the move lets go: both
    TestMoveCodexProvider tests.
  - thread-writer-locks made in a home without one:
    TestMoveCodexThreadsLeavesAnOpenThread.
  The other move tests stayed green under each.
- Codex CLI 0.164.0, real, with gw-c's #3616 move-open harness: a
  sandbox HOME and CODEX_HOME, loopback only, a fake Responses
  upstream, and MoveCodexThreads from fake-provider to fake through a
  test binary built from each tree. Two turns on a thread T; a codex
  app-server resumes T (T's lock file appears in thread-writer-locks),
  waits 80s and has a turn; at 70s, the move.
  - 74dcf40a: the move moved T, file and row. The turn completed and
    the upstream got it, but the rollout has it 0 times, and Codex
    resuming T on fake sent turns 1 and 2 without it.
  - here: the move moved nothing, file and row on fake-provider. The
    turn is in the rollout (2 lines). With the app-server gone (its
    lock file gone) and the rollout a minute old, the move moved T
    (files 1, db 1), and thread-writer-locks had only
    .coordination.lock after it. Codex resuming T on fake sent turns 1
    and 2 and the turn the app-server had.
  Each tree ran twice: in the first runs the move after the app-server
  came within the minute after its turn, which left T here; the script
  now waits the minute out.
- Codex CLI 0.164.0, the same sandbox: with T's lock file made and
  flocked under the coordination lock by another process, as
  holdCodexThread does, codex exec resume T exits 1 with "thread/resume
  failed: thread ... already has an active writer" and sends nothing;
  once it is let go and the file taken away, the resume runs.
- Codex CLI 0.164.0, the move-open run with RelabelCodexThreads from
  fake to fak2 (one length) at 70s: T relabelled at once, the turn in
  the rollout (2 lines), the row still fak2 after it, and Codex
  resuming T on fak2 sent the turn.
- gofmt -l clean. tools/vetset.sh: go vet -tags nogui for linux,
  windows and darwin, go vet for windows, go build -tags nogui for
  linux and darwin, and go build for windows, exit 0 each; untagged
  linux vet and build exit 1 (no GTK or WebKitGTK dev packages on this
  box).
- go test -tags nogui -count=1 -timeout 45m ./... (log kept), Bun
  1.4.2: 68 packages ok and 8 red, sessions ok; each red on the list of
  reds already filed: agent (#3141, #3398, #3641, and
  TestWSLColdPlaceOpensNothing, #3924), davsync TestSync (#3420), edit
  and testenv (umask 077, #3640), gateway
  TestPluginToldWhereTheAgentWorks (#3675), gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649), provider TestCodexAppServersOnHome (#3906), then "close of
  synctest channel from outside bubble" (#3632), tui
  TestTUIFetchesSubscriptionModels/agent (#3919)
- On origin/main 1a804859 with this commit cherry-picked (a scratch
  worktree, not this tree): go test ./internal/sessions ok; go test -run
  Codex ./internal/agent, only TestCodexDriftReached red (#3398)
Not run: the GUI tests, i18n-keys among them; no GUI file changed.

Not tried: Windows, where magpie's lock is LockFileEx on one byte and
Codex's on the whole file (as for the port), and macOS; the Codex app
itself, whose app-server was driven over stdio here as the app drives
one; a thread of a Codex in a WSL distro moved from Windows, where the
lock taken may not be the distro's; a file system without locks, where
the move is refused as held.

Review (yetone, at this commit on origin/main bb5e68cea, go1.26.8):
- Checked against Codex's codex-rs/rollout/src/writer_lock.rs: acquire
  takes thread-writer-locks/.coordination.lock, creates and try-locks
  <thread_id>.lock and lets coordination go; its guard's drop takes
  coordination again, closes the file, removes it and lets go. The move
  does the same, and leaves a home without the folder alone.
- On main, the three new tests red on macOS (mote): "err <nil>, want
  ErrActive", "as the row was written: no lock file", both threads
  moved. With this change, ok.
- Broken by hand, each red: letGo called at once (HoldsTheThread);
  os.Remove dropped ("lock file is left", both MoveCodexProvider
  tests); threadOpen's Is false (LeavesAnOpenThread x2); the lock
  folder always made (MoveCodexThreads, "thread-writer-locks made where
  Codex keeps none").
- macOS (mote): go test -tags nogui ./internal/sessions
  ./internal/filelock ./internal/agent ok; -race -count=10 -run
  'TestMoveCodex|TestPortCodex' ./internal/sessions ok (at d0a61b856);
  gofmt -l clean; go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows for sessions and agent ok.
- Windows (xiaomi-gpu, win-run) and Linux (WSL magpie-desktop,
  wsl-run): go test -run 'TestMoveCodex|TestPortCodex'
  ./internal/sessions ok (at d0a61b856).
Not tried by the review: a real Codex CLI or app holding a thread
during a move, on any system; a WSL distro's Codex moved from Windows.

At the pushed tree (rebased on origin/main 7e0fe83d4), macOS (mote):
gofmt clean; go vet darwin, GOOS=windows and GOOS=linux -tags nogui for
sessions ok; go test -tags nogui ./internal/sessions ./internal/agent
ok; -run Budget ./internal/gui ok.
2026-10-31 18:52:01 +08:00
yetone 7e0fe83d4b provider: Listed as works for signed-in accounts and plugins (zeewell on X)
zeewell asked to list SuperGrok's grok/grok-4.6@500k as grok-4.6, and
Cursor, Devin and WorkBuddy models (all plugins) under ids of their own.
v0.1.2345's "Listed as" took ids only for key/relay providers
(takesModelIDs was p.Account == nil).

Why the restriction was there: the wire rewrite (Settings.Wires) turns
the request body's model back into the own id, but some code reads the
model by the vendor's id before that and got the listed one:
- plugin model lookup (pluginModel: the plugin's APIs, tiers, prices);
- the Claude subscription run (--model given to Claude Code);
- Code Assist/Antigravity variant choice (codeAssistBody, SentNameOnIn);
- account plan lists (fallback's Account.Lists, effort Levels/Tiers,
  AccountServes);
- moveModelRefs refused a provider with no providers.json entry, which
  is every plugin and account provider until a pick is set.
Each now translates with OwnModelID / the provider's ModelIDs, so the
upstream request still carries the vendor's or plugin's own id. Only a
decide-only provider refuses an id. The GUI box already follows
TakesModelIDs, so no GUI file changed.

Tests (red on the old code, each fix reverted by hand one at a time):
- TestModelIDRefused, TestModelIDAtAnAccount (takesModelIDs,
  AccountServes, SentNameOnIn);
- TestLocalModelIDAtAPlugin (Bun fake plugin: /v1/models, upstream
  path, X-Plugin-Model, body, usage; red on pluginModel and on
  moveModelRefs);
- TestLocalModelIDAtAnAntigravityAccount (codeAssistBody);
- TestLocalModelIDAtAClaudeAccount (claude got --model my-sonnet);
- antigravity pool test (fallback Lists, Levels).

Run on mote: gofmt clean; go vet darwin/linux/windows ok; go test
-tags nogui -count=1 -timeout 45m on internal/provider, gateway, cli,
gui, settings, access, usage, plugin: all ok except internal/gui's
TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll), red on main since
b09349d17 and filed as #4514. After rebasing on 140efc8f7 (nothing new
under provider/gateway) the ModelID/LocalModelID/Antigravity tests
ran again: ok.

Real accounts, sandbox HOME, dev build on 127.0.0.1:3486: magpie model
id set grok/grok-4.6@500k -> grok-4.6, grok/grok-4.5@500k -> g45big,
cursor/composer-2.5 -> my-composer, devin/swe-2 -> my-swe,
workbuddy/deepseek-v4.1-flash -> ds-flash. /v1/models listed the new
ids. Requests for grok/grok-4.6, grok/g45big, cursor/my-composer and
devin/my-swe each answered 200 "pong", served as the vendor's id
(grok-4.5-build for g45big); usage records the listed id as model.
Plugin tokens were not rotated (no diff with live).

Not tried: WorkBuddy's real request (its own sign-in answers 401,
unrelated); the GUI box not clicked; no full ./... suite, no GUI suite
(no GUI file touched).
2026-10-31 18:38:31 +08:00
yetone d8cf4f74f9 plugins: a plugin's package.json names its row with magpie.name (#4558, MYCF711)
A plugin installed from git whose package.json says
"magpie": { "name": "华为云 HUAWEI" } read as its dependency key
(magpie-officeace) on Settings → Plugins. Bun takes no non-ASCII key, so
a package outside the community's list had no way to show a readable
name. magpie.name was never read at all: #3608's route (MYCF711's branch
1cc33700) didn't reach main, so no release has it, git or npm.

plugin.InstalledName reads magpie.name from the installed package's own
package.json, beside magpie.icon (installedOwn, one parse for both): one
line of at most 80 bytes, no control or format characters (a bidi
override would show it as another name), else nothing. /api/plugins gives
each row it as ownName, and plugins.js's shownName takes it after the
community list's name and before the git package or the spec, so a
listed package is still named by the list. The row's page, the "is up to
date" status and every message that names the row (options, prefer, Update
all) go through shownName; a page plugin's sidebar tab takes it when the
page names no title (windowParts). It is never used to resolve a name and
never shown with the community badge. Not changed: the CLI's plugin list
(the dependency key, as the reporter expects), Discover's cards for
uninstalled GitHub/npm packages, and magpie.summary. Documented in
docs/reference.md and site/public/docs (en, zh, ja).

Run:
- mote: go test -timeout 45m ./internal/plugin/ ./internal/gui/ — plugin
  ok; gui red only in TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  the AppKit window tests killed at their deadline (TestPanelCloseHidesIt,
  TestPluginPageLoadsItsFilesInTheWindow, TestMainWindowCorners, …;
  #4125, #2645). The first three run the same red on origin/main 7aa67e9e5.
- mote: go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet on
  internal/plugin and internal/gui: clean. gofmt -l internal/: nothing.
- wsl-run (magpie-desktop): plugin-own-name.test.cjs, Chromium and
  WebKit, en/zh/zh-TW/ja/de at 980 and 420: 22/22. Every plugin*,
  plugins-*, agent-plugin*, account-plugin*, signin-paste-plugin,
  sidebar* and i18n-keys file (67): all green but i18n-keys "a plugin's words are its own" (#4524), plugin-card-update webkit en/zh (#3079) and plugin-github-filter webkit ja 420px (#4564, filed now), each red the same at origin/main 7aa67e9e5
- Rebased on origin/main 7b883cc61, mote: -run "Budget|OwnName|TestPluginsState|
  TestWindowParts" on internal/gui and internal/plugin: ok (core scripts
  under the budget, no raise).

Broken by hand:
- InstalledName returning "": TestPluginsStateGivesAGitPackagesOwnName red
  (ownName "", and the sidebar title magpie-officeace).
- shownName without e.ownName: plugin-own-name.test.cjs red, the row
  reads 'magpie-officeace'.

Not tried: the desktop window itself, and a real git repository with
magpie.name (the fixture is shaped from the reporter's installed
package.json: name magpie-officeace, version 0.2.4).
2026-10-31 18:30:39 +08:00
yetone 64cdb68035 accounts: import claude reads claude-swap's export (#4532)
StringKe (#4532) is moving from claude-swap (cswap 0.29.0) to magpie,
and `magpie accounts import claude` didn't read cswap's export. It does
now: parseLoginImport takes cswap's format-1 envelope ({version: 1,
swapVersion, encrypted, accounts: [...]}, read from cswap 0.29.0's
transfer.py) and cswapEntry reads each account's
credentials.claudeAiOauth and config.oauthAccount: email, account and
organization uuid, and the organization's name. The tokens are kept as
the file has them; magpie asks Anthropic nothing.

Refused, each with what to do: an encrypted export (decrypt with gpg -d
first), another format version, a Codex entry, and an API-key entry
(added as a key instead). An entry with no refresh token is accessOnly,
as for every other file. cswap's alias becomes the account's name in
magpie (importNames) when the account was added or updated, has no name
yet, and no other account is called that or signed in as it, so the
name stays a selector for one account (the previous commit's rule).

testdata/cswap_0.29.0_export.json is claude-swap 0.29.0's own `cswap
export` output, made from its source in a sandbox HOME in WSL with two
accounts and fake tokens (cswap's add step asked Anthropic once with
the fake refresh token, which it called dead; no real account was
involved).

Run (mote unless said):
- At this commit's tree (on origin/main 47173f593):
  gofmt -l clean; GOOS=linux go vet -tags nogui ./... and GOOS=windows
  go vet ./... ok; go test -timeout 45m ./internal/provider (ok 100.7s),
  ./internal/cli (ok 31.8s), ./internal/gui: red on 11 real-window
  AppKit tests killed at their deadline on mote over ssh (#4125, #2645)
  and TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main
  (#4514); none touches accounts.
- Rebased on origin/main 7aa67e9e5 (4 commits, none in accounts), then
  at the pushed tree: go test ./internal/provider (ok 163.5s),
  ./internal/cli (ok 55.8s), ./internal/gui -run 'Budget|I18n|Key'
  (ok), gofmt -l clean.
- TestImportCswapExport, TestImportCswapRefusals. Broken by hand, each
  red: no cswapEntry, no importNames, the taken-name check off (red on
  "the team seat took pro's name"), the encrypted check off, no
  organization name.
- CLI in a sandbox HOME in WSL: import of the fixture adds max@x.com and
  team@x.com, a second import says both are in magpie already, the alias
  "work" is team's name, `accounts forget claude work` picks it;
  `accounts import --help`, a missing file and an unknown agent each say
  what's wrong.
- On mote over ssh the same import added one account and failed the
  other on the Keychain ("Unable to obtain authorization", no GUI
  session there), and the failed one was still saved, so the second
  import called it "in magpie already". That's addLogin writing
  logins.json before signing Claude Code in, the same for every import
  and sign-in, not this change; not changed here.
- GUI: login-import in Chromium and WebKit on Linux (WSL), green.

Not tried: an export from a real cswap install with real accounts,
Claude Code running on an imported account, or cswap's encrypted export
decrypted and imported. A cswap account's plan (subscriptionType) isn't
carried: magpie reads it on the first usage read, as for CLIProxyAPI.
2026-10-31 18:22:02 +08:00
yetone a7b47d57ec accounts: removing the account Claude Code is signed in to switches it to another first (#4532)
StringKe (#4532): removing the signed-in Claude account was refused with
SignedInError, while Codex's switched away first. ForgetLogin now does
the same for Claude Code: nextOnForget picks another account (on first,
then one whose sign-in holds), SwitchLogin signs Claude Code in to it,
and only then is this one forgotten. If that switch fails, nothing is
removed and the error says why.

nextOnForget leaves out accounts Claude Code or Codex can't be signed in
to (switchable: not a setup-token account, not a Codex account held in
another folder). Claude Code is never signed out: when the account is
the only one it can be signed in to, it is kept, with
SignedInError{Only} (GUI code signed_in_only), which says to add another
account first or sign out in Claude Code. The GUI gives the signed-in
Claude row a Remove when another account it can use exists, and no
Remove or Sign out otherwise. Claude Code's own credential is never
deleted; forgetClaudeDir removes only the forgotten account's own
folder and its folder's Keychain item, and claudeHolders' check of
other records holding the same token is unchanged.

Tests: TestForgetLiveClaudeSwitchesFirst, TestForgetOnlyClaudeIsKept
(replacing TestClaudeInUseStillRefused, which held the old refusal);
codex-signout.test.cjs gets three Claude cases (Remove with another;
only + setup-token: no Remove, reason in zh/zh-TW/ja/de; the
signed_in_only refusal in en/zh).

Run (mote, sandbox HOME through the test helpers):
- go test ./internal/provider ./internal/cli, vet and gofmt at the
  stack head: in the next commit's body (one tree, same run).
- Broken by hand, each red: Claude not switched first
  (TestForgetLiveClaudeSwitchesFirst), Only left false, a setup-token
  account counted as another, nextOnForget unfiltered
  (TestForgetOnlyClaudeIsKept).
- GUI on Linux (WSL magpie-desktop), Chromium and WebKit: codex-signout,
  own-signin-remove, saved-signedout-remove, login-import, claude-signin,
  account-alias and i18n-keys all pass but i18n-keys' "a plugin's words
  are its own", red on main (#4524). On mote, codex-signout passed in
  Chromium; its WebKit launches were killed with mote at load ~25 under
  other sessions' suites (#4125), so WebKit's record is Linux's.

CLI in a sandbox HOME (WSL, file credentials): forget of the signed-in
account by its name switched Claude Code to the other (.claude.json then
says max@x.com); forget of the only one was refused with the message
above and left it signed in.

Not tried: a real Claude Code switch on removal with real accounts, or
in the CLI against a live ~/.claude (sandbox only).
2026-10-31 18:18:37 +08:00
yetone 149e763e9e accounts: a name you gave an account picks it wherever an email does (#4532)
StringKe (#4532): `magpie accounts switch claude work` failed when "work"
was the alias; accountNamed matched the email only.

provider.AccountByName resolves a name (magpie accounts alias) among an
agent's accounts. It refuses a name two accounts share, and a name that
is another account's email or email part, so a name never picks the wrong
account. It is used by:
- accountNamed: accounts switch/on/off/remove/alias/cap and the rest
  that take <email>;
- provider pool --accounts;
- accountRef (GUI and account-cap): the exact email first, then a name,
  so another account's alias never shadows an email;
- account-cap's display, through AccountRefOf (it filtered by email).

Run (mote, at this commit):
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok
  (104.9s, 33.2s).
- TestAccountsAliasPicksTheAccount, new: switch, alias, pool --accounts
  and account-cap by name; a shared name and another account's email
  refused. Red with each part removed by hand: the accountNamed call,
  pool's resolution, the clash check, the shared-name check, accountRef's
  name step.

Not run: the GUI suite (no GUI file changed); real accounts.
2026-10-31 18:18:37 +08:00
yetone 15b83901ac accounts: switch to the next account with room, or the one with the most left (#4532)
StringKe (#4532), comparing magpie with cswap 0.29.0: there was no "switch
to the next account", and when every account was past its line the
automatic switch stayed on the spent one, where cswap moves to the account
with the most room left.

- `magpie accounts switch <claude|codex> next` (provider.NextInOrder) takes
  the other accounts that are on in magpie, from the one after the account
  the agent is on, wrapping round: the first whose allowance is known and
  has room, else the one with the most room left, and says it is past its
  line. A saved Claude account not read yet is read first (readSpare), as
  the automatic switch's spares are. With no reading of any it refuses
  rather than guess; for any other agent it asks for the account by name.
- NextLogin (shared by Codex and Claude Code): when the account the agent
  is on is spent and every spare is past its line too, it moves to the
  spare with the most room left (roomLeft: the fullest stopping window's
  distance below the switch share, or the account's own cap when lower),
  when that has at least roomMargin (1 point) more than the one it is on,
  so two all but even accounts don't trade the agent each look. A held,
  failed or unknown reading is never moved to. One model's own window
  still counts for nothing, as before.
- docs: reference.md (the automatic switch and `next`; its "a Claude
  account magpie knows nothing of is not moved to" was stale since
  readSpare), providers-accounts.md's Used-up switch row, the en/zh/ja
  start pages' command table, `magpie help`.

Run (on mote, sandbox HOME through the packages' TestMain):
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok
  (144s, 44s), at this change's tree before the next commit's edits.
- TestNextLoginTakesTheMostRoomWhenAllArePast and TestNextInOrder, each
  over codex and claude with three accounts: green; red with the fallback
  taken out of NextLogin (the two "most room" cases, both agents) and with
  NextInOrder not starting after the signed-in account ("the one after
  it", both agents). The "none has more by the margin" case fails without
  roomMargin.
- Built the nogui binary and ran in a fresh sandbox HOME on mote:
  `accounts switch claude next --help` (prints the accounts help),
  `switch claude next` and `switch codex next` with no accounts ("has no
  other account that is on"), `switch gemini next` (asks for a name),
  `switch claude nxt` (no such account), `switch claude` (usage).
- gofmt -l clean. Cross-OS vet: run at the head of this stack.

Not tried: a real switch between real Claude or Codex accounts; the CLI
`next` with real saved accounts (the provider tests cover the choice).
2026-10-31 18:18:37 +08:00
yetone 6b8261029b routing: a request magpie put on another model says why (Neo)
Neo (Discord #feedback, Claude Desktop through the gateway) saw a
Requests row asking chatflowsai/claude-opus-5-5 served by AgentRouter's
gpt-6.1-sol, and read it as Claude asking for another provider's model
on its own. Claude Desktop names its own short requests (a title, its
connection check) on the first Claude-looking id in the list, here
chatflowsai's opus, and magpie keeps them on the chat's model by design
(desktopTurn, 51f66fe8b/13b4a29ab). The routing is right; the row never
said why the model changed.

Changed:
- Route gets Moved {to, why}, set wherever serve puts a request on
  another model before the trace starts: Desktop's tier, title, check,
  gone-model and side-turn moves (desktopMove returns the reason), the
  classifier and Claude tier stand-ins, the stand-in, Codex's turn and
  Privacy's mask route. A subagent's own move clears it (it has its own
  tag).
- Routing's list rows, replay, panel and story tag such a row "Title"
  or "Stand-in" and say why in the tooltip and story. Desktop's
  connection_check kind (da3c5e0c0) already explains itself, so it
  gets no second sentence (movedSays).
- zh, zh-TW, ja, de for the new strings; gateway-routing.md says it.
Not changed: codexFollowTo/codexMaskRoute still show the moved model as
asked.

Run:
- Full Go suite `go test -timeout 45m ./...` on mote at e30092847
  (before the rebase onto cae01311c): 79 ok; the one FAIL is
  internal/gui TestMainWindowCorners/macOS_26_SDK, #3949, same message.
- At 557c4f950 (on cae01311c), on mote: gofmt clean, go vet ./...,
  GOOS=windows go vet ./..., GOOS=linux go vet ./internal/gateway/...
  ./internal/usage/... (a whole-tree Linux vet needs cgo for Wails):
  ok. go test internal/gateway/... and internal/usage/... ok;
  internal/gui's reds are the AppKit windows killed at their deadline
  (#2645, #4125), TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestColdTurnsTaken (#4510), none of them Routing's.
- Rebased onto b1a1b950f (b52c39b65 changed routing/client.js): this
  head, on mote: gofmt clean, go vet ./internal/..., GOOS=windows go vet
  of gateway and gui, go test ./internal/gateway/... ok. Rebased again
  onto a511b11d8: go vet of gateway and gui, and go test -run
  'Desktop|Moved|Classif|StandIn|Subagent' ./internal/gateway/: ok.
- The full GUI suite at e30092847 was swamped by other sessions' suites
  (4771 browserType.launch 180s timeouts, #4125), so it tests nothing.
  mote's browsers were broken again (#4125), so the 208 GUI files that
  reach Routing or i18n ran on Linux (WSL magpie-desktop) at 557c4f950:
  2921 tests, 2823 pass, 98 fail in 37 files. Those 37 files at
  origin/main b1a1b950f: 76 of 428 red; at this head: 80 of 428, the
  differing ones the same tests in other languages or engines (rule
  drag/remove, rest-try-now, routing-flood, group-morph), filed as
  #4121, #4120, #4471, #2215, #3789, #3094, #2564. i18n-keys' one red
  is #4524 ("Unmarked", on main). At this head routing-moved-why,
  routing-session-title, claude-subagent-tag and i18n-keys: 83 of 84,
  the one is #4524.
- routing-moved-why.test.cjs runs en/zh/zh-TW/ja/de, both engines, at
  1100 and 420 wide.

Broken by hand: with `Moved: moved,` taken out of serve's Route literal,
TestClaudeDesktopMoveSaysWhy is red ("title's route moved <nil>, want
agentrouter/gpt-6.1-sol by desktop-title"); with origin/main's
client.js, routing-moved-why is red (0/2).

Not tried: a real Claude Desktop. Neo's earlier effort high-as-medium
report was not looked at here.
2026-10-31 18:05:17 +08:00
yetone a511b11d8b sync: an agent's model set back on a computer after a sync stays that computer's (hayden4608)
hayden4608 on Discord syncs two computers through GitHub, both with
Codex, and wants each one's Codex default model kept apart. Until now
the agents part carried every agent field ("codex.model", effort,
provider...) as one set: A's pick went up, B's sync brought it over B's,
B's pick went up again and A's next sync took it back. The two
computers fought, and the only way out was turning "agents' models"
off for every agent.

Now a sync that brings an agent field over this computer's value
records what it brought (Brought) and what it wrote over (Replaced,
only when that was picked here, not itself brought). If the user then
sets the field back to the value the sync replaced, the field is this
computer's own (Own): it leaves the hashes, a sync no longer brings it,
and a push keeps the server's value, so the other computer is not
changed either. Every other new pick is an ordinary pick and still goes
both ways, so a computer that changes the model for everyone (and
TestSyncAgentDefaults' reset) still reaches the rest. Nothing to set
up: the user's own act on this computer decides it, and a synced value
never overrides it again.

Settings > Sync lists the kept fields in one row ("Kept on this
computer: Codex model ...") with a "Follow the others" button
(davsync/follow), which brings the server's values on the next sync and
ends the keeping. Restore brings everything and ends it too. The row is
drawn only while sync and agents' models are on and something is kept;
plain row and button, no new layout. app.js grew 623 bytes; the budgets
are raised by that with a note.

Tests:
- internal/davsync/own_model_test.go TestOwnModelStaysOnEachComputer:
  two sandbox HOMEs (CODEX_HOME per computer) on the GitHub fixture.
  A picks a1, B joins and gets it, B picks b1 (goes up), A gets b1, A
  sets a1 back (own; the server keeps b1), B picks b2 + effort +
  provider (A gets effort and provider, keeps a1), A picks a2 and a
  Claude model (both go up, B gets them), A follows (gets b2), B's b3
  reaches A. TestNewPicksStillGoBothWays: alternating new picks always
  reach the other computer.
- internal/gui/tests/sync-own-fields.test.cjs: the row in en, zh,
  zh-TW, ja, de at 420px, no overflow, Follow posts once and the row
  goes, no scroll; no row without own fields or with agents off.

Broken by hand, each red: noticeOwn off (own_model_test:122); any pick
after a sync counts as own (TestSyncAgentDefaults and own test:106);
keepServersOwn off (:166); the bring ignoring Own (:146); withoutOwn
off in the hashes (:143, a notice); Follow off (:182).

Run at this head (rebased on 47173f593) on mote:
gofmt -l internal/davsync internal/gui clean; go vet ./..., GOOS=linux
go vet -tags nogui ./..., GOOS=windows go vet ./... ok; go test
./internal/davsync ok, ./internal/backup ok, ./internal/gui ok but
TestSettingsSaveKeepsWhatItDoesNotSend (#4514, red on main) and the
eleven real-window AppKit tests (dock, panel, tray, corners), which
time out on mote at origin/main 47173f593 too (#4125, #2645);
-run 'Budget|Sync|Backup|Settings' passes TestCoreScriptBudget.
GUI (node --test): sync-own-fields, sync-note-show, github-sync,
s3-sync, sync-other-kind, sync-not-backup, sync-auto-restore,
sync-usage-error, i18n-keys. Chromium on mote: all pass but
sync-not-backup and sync-usage-error, whose chromium.launch({channel:
"chromium"}) segfaults on mote at origin/main 47173f593 too; on the
WSL box (magpie-desktop) they pass, 25 of 25 with sync-own-fields.
WebKit on mote hangs on launch for every file, untouched ones too; on
WSL all nine files ran: 49 of 52, the reds being i18n-keys' "a
plugin's words are its own" (#4524, red on main) and the first
page.goto of sync-own-fields and sync-note-show at 5s under nine
files at once, which pass run alone (9 of 9).
Red on main and not from this change: TestSettingsSaveKeepsWhatItDoesNotSend
(#4514), i18n-keys "Unmarked" (#4524).

Not tried: a real GitHub repo and a real Codex on two computers; the
CLI has no follow command (only the GUI and Restore end the keeping);
Undo after a Restore doesn't bring Own back.
2026-10-31 18:01:04 +08:00
yetone fb9c176756 claudetui: Claude Code in WSL runs in its interactive mode too
A Claude Code found in a WSL distro (Windows has none of its own) was
always claude -p, the entrypoint the plan counts at about twice the
interactive mode's. Many Windows users run it there.

The Windows helper now runs wsl.exe in its pseudo console. The gateway
hands it MAGPIE_CLAUDE_TUI_WSL (claudetui.WSL, claudeCLI.tuiWSL): the
wsl.exe arguments up to Claude Code's (wslrun.Tool.Args, with
MAGPIE_WSL_RUN), the distro's mount, and the projects folder as Windows
reads it. That is the account's config directory, handed in through
CLAUDE_CONFIG_DIR/p, or the distro user's own ~/.claude/projects
through \\wsl$\<distro> (wslrun.Tool.Home, a new line in the probe;
wslrun.Tool.Windows). TERM is added to WSLENV, and an image's path is
pasted as the distro reads it (/mnt/c/…). The helper is the Windows
magpie.exe, not the /mnt/c/… path the MCP helper starts at; the first
real run failed on exactly that (fork/exec /mnt/c/...magpie.exe). The
gate keeps -p for a WSL Claude Code whose home is unknown, and, in the
distro user's own folder, when Windows can't stat \\wsl$\<distro>\<home>
(tuiWSLUnread): over ssh it can't (no 9P redirector), and the helper
would wait for a transcript it can't see. Doc updated.

Run:
- go test ./internal/claudetui ./internal/wslrun on mote and on Windows
  11 (xiaomi-gpu): ok. New: TestShimInWSL (image path, WSLENV),
  TestClaudeTUIWSL (projects folder both ways, wsl args), the home in
  the probe and Windows() in wslrun, the gate's two WSL cases, TestClaudeTUIWSLUnread.
- go test -run 'Claude|Refusal|Thinking' ./internal/gateway on mote: ok.
- go vet of claudetui, gateway, wslrun for darwin, linux, windows
  (-tags nogui, and the main package for windows); gofmt -l clean.
- Real account on xiaomi-gpu: a sandbox HOME gateway (3462) with no
  Windows Claude Code reachable (PATH trimmed, MAGPIE_TEST_SANDBOX so
  the registry PATH isn't read), the Claude Max account, Claude Code
  2.1.289 in magpie-desktop, haiku-5-5. Tree: helper -> wsl.exe ->
  claude on a pts in the distro, TERM=xterm-256color,
  CLAUDE_CONFIG_DIR=/mnt/c/..., no CLAUDE_CODE_ENTRYPOINT. One tool
  call, two in one message, text then a call, and two image turns: all
  right. Every transcript row "entrypoint":"cli", no "-p" line in the
  log, images noted as /mnt/c/.../magpie-claude-images-*/image-N.png
  and no folder left. Killing the gateway ended its four claude
  processes in the distro within 3s. The token wasn't refreshed; the
  copied credentials were deleted.

Broken by hand: shim.path returning the Windows path unchanged,
TestShimInWSL red; tuiWSLUnread ignoring the stat error,
TestClaudeTUIWSLUnread red.

Not tried: a WSL Claude Code run from the distro user's own ~/.claude
for real (only the account config directory ran; over ssh
\\wsl$\magpie-desktop is unreadable, so that run would be -p, and a
desktop session's \\wsl$ wasn't tried), a distro whose default user is root, a distro not sharing
Windows' loopback (wslrun.Tool.Host set), WSL1.
2026-10-31 17:29:01 +08:00
yetone f68ddca370 install.sh: a Linux desktop gets the desktop app, or the command that installs its WebKitGTK; --gui and --tui choose (shuhai)
shuhai on Discord: on a Linux desktop install.sh installed the terminal
build, and a desktop user expects the app. The script chose by
`ldconfig -p` alone, and on Debian a user's PATH has no /sbin, so
ldconfig wasn't found and every Debian desktop got the terminal build
even with WebKitGTK 4.1 installed. Without the libraries, the only hint
was a line mid-output.

Now, with nothing asked (curl | sh stays unattended):
- the libraries are looked up with ldconfig from PATH, /sbin or /usr/sbin,
  and in the usual lib folders when there is no cache (NixOS, Guix);
  GTK 3 is checked beside WebKitGTK 4.1, which brings the rest the app
  links (readelf -d of v0.1.2359's magpie-linux-amd64: gtk-3, webkit2gtk-4.1,
  soup-3.0, javascriptcoregtk-4.1, glib, X11, wayland-client, glibc);
- libraries there: the desktop app, as before;
- a desktop without them: the terminal build, and last in the output the
  distribution's command (apt/dnf/pacman/zypper/xbps/emerge from
  os-release ID and ID_LIKE), "run this again", or --gui. A desktop is
  DISPLAY, WAYLAND_DISPLAY, XDG_CURRENT_DESKTOP/XDG_SESSION_DESKTOP/
  DESKTOP_SESSION, XDG_SESSION_TYPE x11/wayland, the user's logind
  Display session when its Type is x11/wayland/mir (over ssh; logind
  falls back to a tty login, which doesn't count), or a session file in
  xsessions/wayland-sessions under XDG_DATA_DIRS;
- headless without them: the terminal build, with no desktop advice;
- --gui: the app even before its libraries, with the package to add;
  --tui (or MAGPIE_CLI=1, kept) the terminal build on a desktop too;
- musl (Alpine): always the terminal build; --gui refuses, since the
  app is built against glibc.
Docs: reference.md Install, README en/zh, docs start FAQ (en/zh/ja,
#linux-build).

Run:
- shellcheck -s sh: only SC2010 at the uninstall's `ls | grep`, there
  before this change. sh -n and dash -n clean.
- site/install.test.mjs (5 new tests): 19/19 on mote (macOS sh) and on
  magpie-desktop through wsl-run (dash); CI's site step
  (sh -n + node --test site/*.test.mjs) 58/58 on magpie-desktop and 58/58
  on mote.
- Red on the old install.sh: tests 16-19 fail (desktop advice, headless
  advice, --gui, --tui). With the logind Type check taken out by hand,
  the headless test fails on login "135 tty".
- Real installs on magpie-desktop (Ubuntu 24.04, XFCE, WSLg, /bin/sh =
  dash), `cat install.sh | env ... sh -s`, stdin a pipe, into a /tmp
  sandbox HOME/XDG dirs/MAGPIE_BIN_DIR, each removed after, v0.1.2360
  downloaded from the real feed and `magpie version` run:
  session with DISPLAY/WAYLAND_DISPLAY: desktop app + menu entry;
  env -i with PATH=/usr/local/bin:/usr/bin:/bin: desktop app (the old
  script gave the terminal build here, run the same way);
  an ldconfig whose cache lacks the libs + DISPLAY=:0, and the same in
  env -i (found by /usr/share/xsessions): terminal build + the apt line;
  that with XDG_DATA_DIRS=/nonexistent: terminal build, quiet; --gui
  there: desktop app + the apt line; --tui in the session: terminal build.
  The first run found the tty-login fallback (logind's Display=135 is
  this WSL user's pts session), fixed before commit.
- site/install.test.mjs on Windows (win-run): 0/19, the same 14 old
  tests too: the box has no sh for spawnSync; CI runs this file on Linux
  only.

Not tried: a real Debian, Fedora, Arch or openSUSE box, or a box without
WebKitGTK installed (simulated with a fake ldconfig); the package names
were checked against each index (Ubuntu noble, Debian bookworm, Arch,
Fedora mdapi, Tumbleweed oss, void-packages, Gentoo), not installed. The
installed app wasn't opened (only `magpie version`), to keep off ports
other sessions use there. Termux and macOS paths are unchanged and their
tests pass.
2026-10-31 17:27:55 +08:00
JoeyWu-tech d0a61b856a plugin: the pi tests keep the pinned pi's Bun cache between runs (#2865)
installPinnedPi's `bun install --frozen-lockfile` used the install
cache bunCommand names, which lies in the test's home. testenv makes a
new home for every go test process, so every run fetched pi's 118
tarballs before the host could start, inside the test's 4 minutes.
yetone saw TestPiPackage red at 86fef947e after 226s, most of it that
install, with gateway's tests run beside it on a Mac at load 26.

Now the install gets a Bun cache that outlives the home,
magpie-test-bun-cache-<uid>-<n> in os.TempDir() (pinnedPiCache), as
the last BUN_INSTALL_CACHE_DIR in its environment. The first run fills
it, and a run after that installs pi from it and asks npm for nothing.
Bun names each entry by package, version and registry, so a new pin,
or a run through another registry, fetches only what is missing. It
holds about 155 MB here. This is the first thing the tests leave
behind between runs, on purpose: testenv's own bound is the temp
folder (checkChild), so the folder is inside it, but it is outside the
test home, which goes when the run ends. agent-wiring.md's "Tests
never touch the real machine" now says so.

Why that folder:
- It is none of the user's own folders. testenv moves HOME, the XDG
  folders, APPDATA and LOCALAPPDATA into the sandbox, not the temp
  folder, and ~/.bun, ~/.cache and ~/.config/magpie are never named.
  Only the install's own process gets the variable, so the host and
  anything else a test starts never see it. The host keeps the home's
  cache, and pruneInstallCache, which prunes the app's cache, never
  touches this one.
- It is this user's. The uid is in its name, as Linux's temp folder is
  shared (macOS' and Windows' are the user's own). It is made 0700, and
  used only when it is a folder, not a link, that no one else has any
  permission on (not checked on Windows, where Go reports no real modes)
  and that this user can make a file in. One someone else made fails
  one of those, and the install then uses the home's cache as before.
  Root always uses the home's cache: root passes those checks in a
  folder another user made, and would run what that user put there.
- Its files are never old enough for a temp folder's cleaner. macOS
  takes files under its temp folder that went unread for about 3 days,
  and Bun doesn't notice a file missing from a cached package: it
  installs the rest, and pi doesn't load (shown below). So the folder
  is a new one every two days (<n> counts two day periods), the one
  before is kept for a run still using it, and older ones are taken
  out by the next run. The first run in a new period fetches pi again.
  TestPinnedPiCacheMovesOn checks the folder moves, the one before
  stays and older ones go.
- Two go test runs can share it. Bun unpacks each tarball into a folder
  of its own and renames it into the cache. When another install got
  there first, it swaps the two or removes the old one and renames
  again (move_to_cache_directory in Bun 1.4.2's extract_tarball.rs,
  written for concurrent installs sharing one cache; on Windows it
  retries the move). Two runs started at once on an empty cache both
  passed here.
- Bun's documented default on Linux is to hardlink the installed files
  to the cache (not looked at here), so a test that wrote into pi's
  installed files in place could change the cache. None does.

No assertion in the pi tests goes red when the cache is taken out: they
pass either way while npm answers inside their 4 minutes. What
regresses is the fetches, counted below; the times move with npm.

What was run (tree 93b344b1, on origin/main acdc85ac, go1.26.8,
linux/amd64, Linux 5.15, umask 077):
- npm's registry through a local relay (BUN_CONFIG_REGISTRY, Bun 1.4.2)
  that passes every request on at once and logs it, with `go test -tags
  nogui -count=1 -v -run <tests> ./internal/plugin/`, load 16 to 26,
  the cache folders removed first:
  - TestPiPackage alone: pass, 29.38s, 118 tarballs asked (no
    manifest). Run again: pass, 1.13s, nothing asked.
  - Then TestGatewayHookMixedPiPackage and TestPiPackage: pass, 0.92s
    and 1.04s, nothing asked.
  - Two TestPiPackage runs started at once: both pass (227.40s and
    115.58s), with every tarball asked twice (236 asked, 118
    distinct). A run after them: 1.13s, nothing asked.
- Broken by hand:
  - The cache not given to the install (the home's cache, as before
    this commit), the folder left full: TestPiPackage passes in 141.92s
    with 118 tarballs asked again.
  - One file of pi-coding-agent's cached package taken out, as a temp
    cleaner would: TestPiPackage red in 0.49s, nothing asked,
    `@earendil-works/pi-coding-agent isn't installed: add it as a
    plugin's dependency, or reinstall the pi plugin`.
  - The folder's name without its period: TestPinnedPiCacheMovesOn red,
    `after two days the cache is ".../magpie-test-bun-cache-<uid>-0",
    not a folder other than ...`. Older folders kept: red, `a folder
    four days old is kept (<nil>)`.
- go test -tags nogui -count=1 -timeout 45m ./internal/plugin/ (Bun
  1.4.2, npm direct): ok, 341 PASS lines counting subtests, 2 skip
  (TestFlowBigReplyProd wants MAGPIE_FLOW_BIG, TestRenewOtherHost is
  run by TestRenewOnceAcrossHosts). TestGatewayHookMixedPiPackage
  9.88s, TestPiPackage 1.08s.
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag
  on linux: exit 1 (no libsoup-3.0 or gio-unix-2.0 here).
- Not run again at this tree: -race and the full suite. This tree
  differs from tree f2b71fdd only in pi_test.go and agent-wiring.md;
  at f2b71fdd internal/plugin passed with -race, and the full suite
  had 79 packages ok, internal/plugin among them, and 7 tests red in 2
  packages, each filed: agent TestInstalledVersion,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141); gui TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie (#3649).

Not tried: macOS and Windows (their checks and cleaners were only
read), a run as root, a real temp cleaner, and the pi tests under a
load like yetone's.

Reviewed and run again by the maintainer at the stack's tree 45994757c
(this commit and the six beside it, on origin/main 90518de26), go1.26.8:
- mote (macOS, arm64): gofmt -l clean; go vet and go build for darwin,
  GOOS=linux -tags nogui and GOOS=windows (library, plugin, gui): exit 0.
  go test -tags nogui -count=1 -timeout 45m ./...: every package ok but
  internal/gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  internal/proc TestNoCommandBypassesProc (#4491), both red on main
  from b09349d17 and c59c547c5, in files this stack doesn't touch.
  go test -race -run 'TestWSL|TestTagged|TestPinnedPiCache' for
  library and plugin: ok.
- magpie-desktop (Linux, wsl-run; WebKit hangs on mote), Chromium and
  WebKit: every library-*, sync-*, s3-sync, github-sync and i18n-keys
  file, 4 at a time: 1003 of 1020. The 17 reds are in 6 files no commit here
  touches: i18n-keys ("Unmarked", #4524), library-chip-fan, -items,
  -mcp-health, -mcp-hub (#4483) and -mcp-tools. Those 6 alone, one at a
  time, at load ~60: 74 of 92 here, 77 of 92 at 90518de26 itself. Red
  in both: i18n-keys, -chip-fan and -items in WebKit, -mcp-tools in
  Chromium ja 420; -mcp-health green in both; -mcp-hub's WebKit case
  red here only, the case #4483 has red on main. -chip-fan and -items
  are #3072's and #4501's kind, WebKit under load.
- On macOS (mote), the pi tests twice in a row: TestGatewayHookMixedPiPackage
  21.41s then 0.96s, TestPiPackage 1.23s then 1.24s, and
  TestPinnedPiCacheMovesOn ok: the second run installs from the kept
  cache. It sits in os.TempDir(), outside a test's HOME, by design.
- The stack rebased on origin/main e4c784177 (main's 7 commits since
  share only docs/subsystems/agent-wiring.md with it, a line apart),
  with no conflict: on mote gofmt -l, go vet (linux nogui,
  windows), go test -tags nogui -count=1 ./internal/library
  ./internal/plugin ok and internal/gui's budget tests ok; on Linux
  sync-note-show and library-wsl-asleep, both engines: 92 of 92.
2026-10-31 17:03:55 +08:00
JoeyWu-tech 722ca104c0 library: the Subagents page lists a stopped WSL distro's agents, greyed (#4238)
While a WSL distro runs, the Subagents page lists its agents that take
subagents here (Claude Code, Codex and the rest of SubagentAgents) with
a greyed chip that says magpie gives subagents only to agents on this
computer, not yet to it in WSL. With the distro stopped, they were gone
from the page: subagentsView built its agents from the targets only, and
an agent in a stopped distro is no target (#3896).

As the commit before did for the Hooks page: subagentsView now also
lists each stopped agent of those kinds that the MCP and Skills pages
list from its shape (asleepView), with the reason it has while the
distro runs (wslNoSubagents, which subagentSpecOf now shares), so its
chip, a subagent's problem for it and the "magpie can't give subagents
to ... yet" line are the same, stopped or running. Nothing of the
distro is opened. One magpie never saw (unseen) isn't listed.

No WSL agent can be given a subagent yet, so there is nothing to keep
for Woken. No change to the page; nothing new to translate. The line in
library.md that named the pages leaving a stopped distro's agents out
(#4182, #4237, #4238) is gone with this.

What was run (tree e03c52f0, on origin/main ec5571d6, go1.26.8,
linux/amd64, Linux 5.15, umask 077):
- TestWSLStoppedSubagents (new): the Subagents page's WSL agents read
  while a FakeWSL distro runs (Claude Code and Codex, the kinds it
  lists, each with the reason), then with it stopped and its folder
  moved away: the same two, field for field. A subagent given the
  stopped Claude Code has the same problem for it. Nothing was written
  into the distro and FakeWSLRuns didn't move.
- Broken by hand, each alone: subagentsView skipping the stopped agents
  ("... while it is stopped: map[], while it ran: map[claude@wsl:...]",
  and the subagent with no problem for Claude Code); the stopped agents
  listed with no reason ("No:" empty against the running ones', the
  same problem missing).
- library-wsl-asleep, its new Subagents case beside the Hooks one,
  Chromium and WebKit, en, zh, zh-TW, ja and de at 1100 and 390px: a
  subagent's chips are Claude Code and the stopped Codex, Codex's
  blocked, asleep, aria-disabled, with the WSL reason as its tooltip,
  the line names it, a click on it sends nothing. As for Hooks, the page
  isn't changed, so only TestWSLStoppedSubagents catches the gap.
- GUI files, each alone, Chromium and WebKit, Node 22.22.1, Playwright
  1.62.1, DISPLAY unset: library-wsl-asleep 44/44 each, i18n-keys 4/4,
  library-subagents 6/6, library-hooks 6/6, library-gone-agents 11/11:
  142 of 142.
- go test -tags nogui -count=1 ./internal/library ./internal/agent
  ./internal/cli: library and cli ok; agent red in TestInstalledVersion,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir
  (#3141). go test -race -run TestWSL ./internal/library: ok.
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag on
  linux: exit 1 (no GTK headers here).
- go test -tags nogui -count=1 -timeout 45m ./... (Bun 1.4.2; 9m49s,
  load 20 at its start): 78 packages ok, and 8 tests red in 3 packages,
  each filed: agent TestInstalledVersion,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141); gui TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie (#3649); plugin
  TestGatewayHookMixedPiPackage ("starting plugins: context deadline
  exceeded", #2865, under load). The same suite on an origin/main
  ec5571d6 worktree right after (10m01s): the same agent and gui reds,
  test for test, and plugin ok there.

Not tried: a real distro, and the real app; FakeWSL counts the wsl.exe
-d commands run in the stopped distro (none).

Reviewed and run again by the maintainer at the stack's tree 45994757c
(this commit and the six beside it, on origin/main 90518de26), go1.26.8:
- mote (macOS, arm64): gofmt -l clean; go vet and go build for darwin,
  GOOS=linux -tags nogui and GOOS=windows (library, plugin, gui): exit 0.
  go test -tags nogui -count=1 -timeout 45m ./...: every package ok but
  internal/gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  internal/proc TestNoCommandBypassesProc (#4491), both red on main
  from b09349d17 and c59c547c5, in files this stack doesn't touch.
  go test -race -run 'TestWSL|TestTagged|TestPinnedPiCache' for
  library and plugin: ok.
- magpie-desktop (Linux, wsl-run; WebKit hangs on mote), Chromium and
  WebKit: every library-*, sync-*, s3-sync, github-sync and i18n-keys
  file, 4 at a time: 1003 of 1020. The 17 reds are in 6 files no commit here
  touches: i18n-keys ("Unmarked", #4524), library-chip-fan, -items,
  -mcp-health, -mcp-hub (#4483) and -mcp-tools. Those 6 alone, one at a
  time, at load ~60: 74 of 92 here, 77 of 92 at 90518de26 itself. Red
  in both: i18n-keys, -chip-fan and -items in WebKit, -mcp-tools in
  Chromium ja 420; -mcp-health green in both; -mcp-hub's WebKit case
  red here only, the case #4483 has red on main. -chip-fan and -items
  are #3072's and #4501's kind, WebKit under load.
- Broken by hand on mote: subagentsView skipping the stopped distro's
  agents turns TestWSLStoppedSubagents red.
2026-10-31 17:00:14 +08:00
JoeyWu-tech 0bd89a0237 library: the Hooks page lists a stopped WSL distro's agents, greyed (#4237)
While a WSL distro runs, the Hooks page lists each of its agents with a
greyed chip that says magpie gives hooks only to agents on this
computer, not yet to it in WSL. With the distro stopped, they were gone
from the page: hooksView built its agents from the targets only, and an
agent in a stopped distro is no target (#3896). So a hook's chips, and
the "magpie can't give hooks to ... yet" line, changed with whether WSL
was running.

hooksView now also lists each stopped agent that the MCP and Skills
pages list from its shape (asleepView), with the reason it has while
the distro runs (wslNoHooks, which hookSpecOf now shares), so its chip,
a hook's problem for it and the line are the same, stopped or running.
Nothing of the distro is opened. One magpie never saw (unseen) isn't
listed, as on the other pages.

No WSL agent can be given a hook yet, so there is nothing to keep for
Woken: the issue's "write a change once the distro runs" has no change
to write until hooks reach WSL. No change to the page, which already
greys a chip whose agent has `no` set; nothing new to translate.

What was run (tree fb979055, on origin/main ec5571d6, go1.26.8,
linux/amd64, Linux 5.15, umask 077):
- TestWSLStoppedHooks (new): the Hooks page's WSL agents read while a
  FakeWSL distro runs (Codex, Claude Code, Pi and OmO, each with the
  reason), then with it stopped and its folder moved away: the same
  four, field for field. A hook given the stopped Codex has the same
  problem for it. Nothing was written into the distro and FakeWSLRuns
  didn't move.
- Broken by hand, each alone: hooksView skipping the stopped agents
  ("... while it is stopped: map[], while it ran: map[claude@wsl:...]",
  and the hook with no problem for Codex); the stopped agents listed
  with no reason ("No:" empty against the running ones', the same
  problem missing).
- library-wsl-asleep, its new Hooks case, Chromium and WebKit, en, zh,
  zh-TW, ja and de at 1100 and 390px: a hook's chips are Claude Code and
  the stopped Codex, Codex's blocked, asleep, aria-disabled, with the
  WSL reason as its tooltip, the line names it, a click on it sends
  nothing. The page isn't changed, so this case pins what it draws from
  hooksView's answer and can't go red by a break in the Go code: only
  TestWSLStoppedHooks does.
- GUI files, each alone, Chromium and WebKit, Node 22.22.1, Playwright
  1.62.1, DISPLAY unset: library-wsl-asleep 33/33 each, i18n-keys 4/4,
  library-hooks 6/6, library-gone-agents 11/11: 108 of 108.
- go test -tags nogui -count=1 ./internal/library ./internal/agent
  ./internal/cli: library and cli ok; agent red in TestInstalledVersion,
  TestHowInstalled, TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir
  (#3141, a set that varies from run to run;
  three of them red at origin/main ec5571d6 in its suite too). go test
  -race -run TestWSL ./internal/library: ok.
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag on
  linux: exit 1 (no GTK headers here).

Not run at this tree: the full go test ./..., which ran at the
branch's last commit. Not tried: a real distro, and the real app;
FakeWSL counts the wsl.exe -d commands run in the stopped distro
(none). Not changed: the Subagents page (#4238, the next commit).

Reviewed and run again by the maintainer at the stack's tree 45994757c
(this commit and the six beside it, on origin/main 90518de26), go1.26.8:
- mote (macOS, arm64): gofmt -l clean; go vet and go build for darwin,
  GOOS=linux -tags nogui and GOOS=windows (library, plugin, gui): exit 0.
  go test -tags nogui -count=1 -timeout 45m ./...: every package ok but
  internal/gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  internal/proc TestNoCommandBypassesProc (#4491), both red on main
  from b09349d17 and c59c547c5, in files this stack doesn't touch.
  go test -race -run 'TestWSL|TestTagged|TestPinnedPiCache' for
  library and plugin: ok.
- magpie-desktop (Linux, wsl-run; WebKit hangs on mote), Chromium and
  WebKit: every library-*, sync-*, s3-sync, github-sync and i18n-keys
  file, 4 at a time: 1003 of 1020. The 17 reds are in 6 files no commit here
  touches: i18n-keys ("Unmarked", #4524), library-chip-fan, -items,
  -mcp-health, -mcp-hub (#4483) and -mcp-tools. Those 6 alone, one at a
  time, at load ~60: 74 of 92 here, 77 of 92 at 90518de26 itself. Red
  in both: i18n-keys, -chip-fan and -items in WebKit, -mcp-tools in
  Chromium ja 420; -mcp-health green in both; -mcp-hub's WebKit case
  red here only, the case #4483 has red on main. -chip-fan and -items
  are #3072's and #4501's kind, WebKit under load.
- Broken by hand on mote: hooksView skipping the stopped distro's
  agents turns TestWSLStoppedHooks red.
2026-10-31 17:00:14 +08:00
JoeyWu-tech 4ff086d1fb library: the Instructions page lists a stopped WSL distro's agents (#4182)
With a WSL distro stopped, the Instructions page listed none of its
agents: instructionsView built its rows from the targets only, and an
agent in a stopped distro is no target (#3896). So Claude Code, Codex
and the rest in WSL couldn't be switched on until the distro ran. And a
switch on the page sent the agents the page listed, so switching any
agent on or off while the distro was stopped took its agents off the
set, and the next sync once the distro ran took magpie's part out of
their files.

The same way c1da9ccda did it for the MCP and Skills pages: keepShape
keeps the instructions file's path in the shape (wsl.json, key
library:<kind>) while the distro runs. While it is stopped,
instructionsView lists its agents from that (asleepInstructions, asleep:
<distro>), switched on as library.json has them, with what each gets
besides, which is in magpie's own folder. The file itself isn't read:
its own lines, an edit to magpie's part and an override file aren't
known then, so the row says nothing of them, and Move its own and Write
again don't show. One switched on whose file magpie never saw (no path
in its shape, or a shape kept before this commit) is listed as unseen.
ReadInstructions, which the page reads after each instructions change,
lists them too, or the rows would go after the first switch. The TUI's
instructions picker sends the agents Read lists as on, so by its code it
had the same loss and keeps them now, with no change of its own (read,
not run).

A switch on one is kept in library.json, as any is. Takes accepts one
with a known file, so the CLI's `library instructions agents` records
it, and says on stderr that the distro isn't running (AsleepIn, as
before). Woken now watches a distro that Instructions.Agents names, or
whose agent still has magpie's part (Applied.Instructions), so a switch
on is written there once the distro runs, and a switch off is taken
out. Nothing is opened or run in the distro while it is stopped.

The page greys a stopped agent's row (icon as on the chips), shows its
path as text, not a button (showing it in Explorer opens the distro),
gives its switch the line's words as its tooltip and as the status after
a switch, and adds the one line per distro under the list
(asleepAsides, now given the page's own rows). An unseen agent's switch
is greyed out (aria-disabled), says why with the unseen chip's tooltip,
and sends nothing; every other switch keeps it on. No new strings: the
line, the unseen tooltip and "{agents} can be changed once it runs." are
c1da9ccda's, in en, zh, zh-TW, ja and de. The "keeps no user-wide
instructions file" line still leaves stopped agents out.

The MCP and Skills pages are the same, except that an agent seen with
an instructions file only (no MCP file or skills folder) now has a
shape: it is listed there as it is while the distro runs, among the
agents with no MCP servers or no skills folder, where before it was
listed only when unseen and named.

What was run (tree 7fd5f65a, on origin/main ec5571d6, go1.26.8,
linux/amd64, Linux 5.15, umask 077):
- TestWSLStoppedInstructions (new): Codex and Claude Code in a FakeWSL
  distro, seen running, then stopped with the distro's folder moved
  away. Both are on the Instructions page, asleep, at their files, Own,
  Edited and Override empty (Codex's AGENTS.md has a line of its own,
  counted once it runs), from Read and from ReadInstructions alike.
  Codex switched on while stopped is kept; Woken writes the shared text
  into its AGENTS.md once the distro runs. Stopped again and switched
  off, Woken takes the part out (the file is "Mine.\n" again). Nothing
  was written into the stopped distro and FakeWSLRuns didn't move.
- TestWSLStoppedInstructionsUnseen (new): Pi switched on in a distro
  stopped before magpie saw its file is listed on and unseen; Codex,
  never seen and off, isn't; Takes refuses it.
- Broken by hand, each alone, the two tests above run:
  instructionsView skipping the stopped agents: "a stopped distro's
  Codex isn't on the Instructions page", "Pi switched on while stopped:
  <nil>". distrosNamed without Instructions.Agents: "no sync once the
  distro ran" at the first start. distrosNamed without
  Applied.Instructions: the same at the second start, the switch off.
  ReadInstructions back on Targets(): "Read lists 15 instructions rows,
  ReadInstructions 11". Takes without instructions: "Takes while
  stopped: ... can be given instructions". keepShape without the path:
  Codex not on the page.
- library-wsl-asleep, its new Instructions case, Chromium and WebKit,
  en, zh, zh-TW, ja and de at 1100 and 390px: Codex's row greyed, its
  path a span, not the reveal button, its switch's tooltip the
  distro's line; Pi's switch aria-disabled with the unseen tooltip; one
  line naming the distro and Pi. A click on the path asks no reveal, a
  click on Pi's switch sends nothing, Codex switched on sends claude,
  Codex and Pi with the line as the status, and Claude Code switched off
  sends Codex and Pi. Broken by hand in the page, in Chromium: Pi's
  switch sending (all 10 red at the deepEqual of the posts with [] after
  Pi's switch is clicked), the path a reveal button again (all 10 red,
  tagName BUTTON for SPAN), no line (all 10 red, 0 .lib-asleep lines for
  1).
- GUI files, each alone, Chromium and WebKit, Node 22.22.1, Playwright
  1.62.1, DISPLAY unset: library-wsl-asleep 22/22 each, i18n-keys 4/4,
  library-instr-sets 3/3, library-instr-busy 6/6, library-linked-set
  11/11, library-alma-profile 6/6, library-gone-agents 11/11,
  library-items 9/9, library-mcp-hub 11/11: 166 of 166.
- go test -tags nogui -count=1 ./internal/library ./internal/agent
  ./internal/cli: library and cli ok; agent red in TestInstalledVersion,
  TestHowInstalled, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141, a set that varies from run to run;
  five of them red at origin/main ec5571d6 in its suite too). go test
  -race -run TestWSL ./internal/library: ok.
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag on
  linux: exit 1 (no GTK headers here).

Not run at this tree: the full go test ./..., which ran at the
branch's last commit. Not tried: a real distro stopped and started, and
the real app; FakeWSL counts the wsl.exe -d commands run in the stopped
distro (none). Not changed: the Hooks and Subagents pages (#4237,
#4238, the next commits), and the CLI's code for `library
instructions agents`, which already says on stderr that a stopped
distro's agent is written there once it runs.

Reviewed and run again by the maintainer at the stack's tree 45994757c
(this commit and the six beside it, on origin/main 90518de26), go1.26.8:
- mote (macOS, arm64): gofmt -l clean; go vet and go build for darwin,
  GOOS=linux -tags nogui and GOOS=windows (library, plugin, gui): exit 0.
  go test -tags nogui -count=1 -timeout 45m ./...: every package ok but
  internal/gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  internal/proc TestNoCommandBypassesProc (#4491), both red on main
  from b09349d17 and c59c547c5, in files this stack doesn't touch.
  go test -race -run 'TestWSL|TestTagged|TestPinnedPiCache' for
  library and plugin: ok.
- magpie-desktop (Linux, wsl-run; WebKit hangs on mote), Chromium and
  WebKit: every library-*, sync-*, s3-sync, github-sync and i18n-keys
  file, 4 at a time: 1003 of 1020. The 17 reds are in 6 files no commit here
  touches: i18n-keys ("Unmarked", #4524), library-chip-fan, -items,
  -mcp-health, -mcp-hub (#4483) and -mcp-tools. Those 6 alone, one at a
  time, at load ~60: 74 of 92 here, 77 of 92 at 90518de26 itself. Red
  in both: i18n-keys, -chip-fan and -items in WebKit, -mcp-tools in
  Chromium ja 420; -mcp-health green in both; -mcp-hub's WebKit case
  red here only, the case #4483 has red on main. -chip-fan and -items
  are #3072's and #4501's kind, WebKit under load.
- Broken by hand on mote, each red: instructionsView skipping the
  stopped distro's agents (TestWSLStoppedInstructions, "a stopped
  distro's Codex isn't on the Instructions page", and ...Unseen, "Pi
  switched on while stopped"); keepShape without Instructions (Codex
  not on the page); distrosNamed without Instructions.Agents ("no sync
  once the distro ran"). On Linux, client.js's asleep row back to
  pathLink with the unseen switch's guard gone: library-wsl-asleep's
  Instructions test red in both engines, 10 subtests each.
2026-10-31 17:00:13 +08:00
yetone 33a284497e plugin options: a switch a provider plugin declares is saved where the plugin reads it (plugins#550)
`magpie plugin options cursor '{"wire_trace": true}'` wrote the entry's
options in plugins.json (a middleware's ctx.options), while a provider
plugin's switches (auth.options, the editor's Plugin options) are read
from settings' PluginOptions (input.magpie.option). The command said
"options set" and Wire trace stayed off.

Now a key that the plugin declares as a switch for one of its providers
(from the providers last listed, else asked of the plugin host) goes to
PluginOptions for that provider, through settings.EditPluginOptions, and
a running host is handed it (SetProviderOptions, 5s, best effort). Only
true or false is taken for a switch. The other keys go to plugins.json
as before; set with switches only, a middleware's options stay, less a
switch written there before. `off` puts every switch back to the
plugin's default and clears plugins.json's options. Shown with no value,
each switch is listed with its value. docs/reference.md and the plugins
page (en, zh, ja) say so.

Run at this head on mote: go test ./internal/cli ./internal/settings
./internal/plugin ok; gofmt -l clean; go vet darwin and GOOS=windows ok;
Linux go vet -tags gtk3 in WSL (magpie-desktop) ok.
Broken by hand: no key read as declared, and both new tests went red
(PluginOptions empty, the old switch left in plugins.json).
Not tried: the real CLI against a running magpie with the Cursor plugin
installed; a plugin not listed yet (the host path) is not in a test.
2026-10-31 16:46:14 +08:00
yetone d83823d264 agent: a Claude Desktop Code tab session on WSL is told Desktop's window too (young02036)
young02036 on Discord: Claude Desktop 4.29.0 on Windows, a Code tab
session whose environment host is "WSL · Ubuntu", a magpie group of
Codex gpt-6.1-sol (500K) and Claude Opus 5.5 (1M) listed as
mythos-magpie-4247180078, and /context read "49.4k / 200k".

Cause: Desktop runs such a session on the distro's Claude Code, which
reads its user settings in the distro. Desktop 4.29.0's remote probe
reads them from `${CLAUDE_CONFIG_DIR:-$HOME/.claude}` there. Desktop sets
CLAUDE_CODE_MAX_CONTEXT_TOKENS only for Cowork (its bundle's one write of
it); a Code tab session gets the mythos-magpie id and no window. magpie
wrote Desktop's window, capabilities and Explore flag into Windows'
~/.claude/settings.json alone: desktopOn() was false for every
claude@wsl:<distro>. So the distro's Claude Code took the unknown id for
200K.

Fix: desktopOn() is true for a distro's Claude Code while this machine's
Desktop is on magpie (desktopSetsHere), so its Sync (desktopOnly when it
isn't on magpie itself, writeWindow when it is) writes the same values
into the distro's settings.json, and takes them out when Desktop leaves.
Turning Desktop on or off also syncs each running distro's Claude Code at
once; a stopped distro has no Sync (asleep) and is written on the first
catalog round after it starts.

Run:
- WSL (magpie-desktop, wsl-run), real Claude Code 2.1.289 in a sandbox
  HOME, `claude -p --model mythos-magpie-4247180078 /context`: no env in
  ~/.claude/settings.json gives "30.4k / 200k" and the unknown-model
  notice; CLAUDE_CODE_MAX_CONTEXT_TOKENS=500000 there gives "30.4k / 500k".
- New TestClaudeDesktopWSLContextWindow: a distro's settings.json gets
  1000000 and mythos-magpie capabilities with Desktop on, the user's
  model/theme kept, nothing before Desktop is on, all gone after it is off.
  mote and Windows (win-run) pass.
- Broken by hand: desktopOn returning false for a distro, the test is red
  ("the distro's window "", want glm's 1000000").
- win-run go test ./internal/agent -run 'TestClaudeDesktop|TestWSLClaude':
  only TestClaudeDesktopCarriesTheLanguage red, same at origin/main
  305c624ed on Windows alone (#4115).
- mote: go test -timeout 45m ./... at this tree (base 305c624ed):
  internal/agent ok (280s), 81 packages ok. Red, none touched here:
  internal/proc TestNoCommandBypassesProc (claudetui, #4491),
  internal/gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and the
  AppKit window tests killed at their deadlines on mote (#4125, #2645,
  #3949). GOOS=windows and GOOS=linux go vet ./internal/agent ok,
  gofmt clean.

Not tried: the real Desktop 4.29.0 on Windows with a WSL host session
end to end (the window read from the bundle and the distro's real Claude
Code, not a Desktop session); Claude Code 2.1.309 (the distro has
2.1.289). A session already open keeps the window it started with until
a new one starts.
2026-10-31 16:37:42 +08:00
yetone b52c39b65e routing: an account's row names the session it answers
connor_yang (Discord #help) asked that the Routing stage say which
session an account is serving next to its "answering…" / "answered this
request" status. The row now ends "· <title>", one line cut short with
the full title on hover, and only when the agent itself named that
session:

- Claude, Gemini and the other agents: sessions.Titles by agent:id, the
  same source the By session list heads use.
- Codex: its own name index (session_index.jsonl) by thread id.
- A Codex request whose parent the server inferred from prompt and
  reply fingerprints (parentMatched) shows nothing, since that parent
  is a guess. An untitled session shows nothing too.

Cost: no new server path. The titles come from the existing
/api/gateway/session-titles calls that refreshSessionNames already makes
every 15s and on focus. A session id the page hasn't seen is asked for
once (marked asked before the fetch, 300ms debounce, never two calls at
once), and the ask is skipped when a read since then already covered it
(namesDue). The per-second render only reads two maps. The title sits in
its own nowrap span, because the narrow stage (.max560/.max460) wraps
the status.

A Codex names reply silent on a session no longer clears the title
the trace brought. CodexTitles leaves unknown ids out, and returns {}
when the index can't be read, so the old loop turned a failed read into
"no title". With the earlier ask it also raced the trace: routing-sessions'
"title helpers belong to the named parent" went red 3 of 6 runs under
--test-concurrency=4 until this change, then 6 of 6 green.

Run:
- routing-session-title.test.cjs (new): engines x claude/codex x en, zh,
  zh-TW, ja, de x 1100/420px = 40 tests. Chromium 20/20 on mote.
  WebKit 20/20 on the Linux box (wsl-run, magpie-desktop). On mote even
  a bare webkit.launch() timed out at 60s under other sessions' load (21,
  67 pw_run processes), so WebKit there tested nothing.
- 16 nearby routing GUI files (answered-still, row-reuse, row-two-lines,
  stage-routes, sessions, reroute-title, tick-no-layout, live-patch,
  busy, served, js, steady, steady-garbage, session-folder, live-calm,
  request-model) in Chromium and WebKit on the Linux box, before the
  rebase onto 82b45888a. The reds that came back were compared with
  origin/main in a detached worktree:
  - routing-steady "requests coming in leave the routing groups" is red
    in both engines at main 03f609e3f (#3412).
  - routing-request-model's 5 WebKit cases are red at main 82b45888a,
    run alone (#4120 lists them).
  - routing-sessions "background memory groups" WebKit en is red at
    82b45888a, overflowing at 560px (filed #4538).
  - routing-sessions "title helpers" was mine; fixed above.
- After the rebase and the last edits, routing-session-title,
  routing-sessions, routing-session-folder and routing-rest-error
  (82b45888a's test, whose lines in client.js this change meets), three
  times per engine at --test-concurrency=4: Chromium 59/59 each time;
  WebKit 59/59 once, then 58/59 twice, the one red being #4538.

Broken by hand:
- titleOf without the parentMatched check (and the Codex name loop
  without it): the Codex cases go red, "a matched session's title is
  not shown".
- askUnnamed asking again on every pass: red, "asked 4 more times in 3s"
  (again on the final code).
- The silent-reply guard was not broken by hand on its own. What shows
  it is the title-helpers race above (3 of 6 red without it, 6 of 6
  green with it), not a deterministic test.

Not tried: a real app with a real agent's sessions, WebKitGTK in the
Linux app, and the whole GUI suite (it runs after the push).
2026-10-31 15:43:31 +08:00
yetone 7b09d2c951 provider: a model can be listed by an id of the user's at its provider, asked for by its own
zeewell on X (tweet 2116404121930432888): relays serve one model under
ids of their own (deepseek-v4.1-flash-1017, grok-4.6@500k). They want to
give each one their own id at the provider layer. magpie then lists,
routes, groups and finds groups by that id, and the upstream request
still carries the vendor's id.

Choice: a new per-model map, settings' ModelIDs
("<pid>/<local>": "<own id>"), served through the wire names that
already exist. ModelSameAs was not widened. It means "same as another
vendor's model": it lends specs and joins found groups. Making it rename
models everywhere would change every existing user's ids and refs.
ModelWires was not reinterpreted either, for the same reason. ModelIDs is
ModelWires turned round: a wire keeps magpie's id and changes the one
sent, and this keeps the one sent and changes magpie's. Settings.Wires()
merges each entry in as a wire name (wrapped by a "<pid>/*" wire). Every
place that sent a ModelWires name (gateway, usage ledger, request page,
UpstreamName, UpstreamNameAs) reads Wires(), so the upstream id needs no
new path. An explicit ModelWires entry for the same id wins.

- Listed by the local id: Available, liveIDs/liveByID, Serving and
  ListPrice translate through OwnModelID. /v1/models, agents' lists,
  Resolve, routing groups and found groups (auto/<local>, merged with
  every other provider serving that id) all see the local id.
- Only a provider of the user's own (Account == nil) takes one. An
  account's or a plugin's request is built from its list's id, which no
  wire reaches.
- Two variants of one provider given one id: the latest given it wins,
  and the earlier one is listed by its own id again. The CLI names it.
  The editor refuses two rows given one id in one save. A model of the
  provider's own id that a variant is listed by (plain grok-4.6 beside
  grok-4.6@500k) is not listed while the variant has it.
- The user's values are never overridden. SetModelID moves picks,
  contexts, fallbacks, groups' members/rules/fast/placed/off/weights/
  classifier/pick, the pickers' lists, every per-model setting
  (Settings.MoveModel) and gateway keys' models (provider.ModelMoved,
  set by access) to the new id, but only where nothing is under the new
  id yet. Agents' own files are not rewritten: an old provider/<own id>
  still resolves and is sent as it is. Group match patterns and key
  patterns stay as written.
- Key limits: a key held to either id passes for both (modelAllowed:
  the ref, OwnModelID, ListedModelID). Group members use the same check.
- Usage: model = the listed id, served = the vendor's id from its reply.
  The price is the own id's first.

CLI: magpie model id <provider/model> [<id>|--reset], magpie model ids.
GUI: Providers > a provider's editor > Names & levels > "Listed as",
beside Same as. It is staged with the editor's Save and taken back by
Restore default, in zh, zh-TW, ja and de. Accounts have no box.
Docs: providers-accounts.md, gateway-routing.md, and site start.html in
en, zh and ja.

Run (mote-run, at this tree rebased on 841326709):
- go test -tags nogui of internal/gateway, provider, settings, access,
  usage and cli: ok. internal/gui: ok but for
  TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main since
  b09349d17 (#4514, yiqiui's patch); its ModelIDs case passes.
- TestAutoVisionDoesNotBuildListsAgain: 457 allocations with 4 models,
  458 with 400 (main 459), searcherModel within its 50. Reading
  Shared() per list cost 3041; SharedModelIDs parses only modelIDs once
  per file change, the settings path is built again only when what it is
  built from changes, and Serving looks up the own id only when a key is
  listed to some model.
- TestCoreScriptBudget: raised by 1,178 bytes for the Listed as box,
  with a note.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet ok.
- GUI: provider-listed-as (en, zh, zh-TW, ja, de), provider-same-as,
  provider-detect in Chromium on mote and WebKit on the Linux box (mote's
  WebKit launch hangs, #4125): 9 of 9.
Broken by hand, each red: the wire name (wires), the list (list), a key
held to the own id (keyown), the key move hook (hook), liveIDs, liveByID,
moving refs (moverefs) and moving per-model settings (movemodel).
Not tried: a red for ListPrice's or Serving's own-id lookup; a real relay
with variant ids; Match patterns are not rewritten to the new id. The
full Go suite and the whole GUI suite are still running and their reds
get their own issues.
2026-10-31 15:04:44 +08:00
yetone 0407d69e84 provider: a group of Kimi models keeps always_thinking, dynamic tools and its default effort
jiabubu on Discord (#feedback): one Kimi Code model put in a routing group
so it lists first lost "always thinking" and "dynamic tool loading" in Kimi
Code, which the same model straight from its provider has. buildGroupEntries
never set AlwaysThinks, DynamicTools or DefaultEffort on a group (the Entry
comment said "a group has none of them"), so kimiModelTables wrote the
group's table without always_thinking and dynamically_loaded_tools, and
default_effort fell back to high.

groupSharedKimi now gives a group each of the three when every member's
entry says the same, and none of it when one member doesn't or has no
entry: a group request can reach any member (rule targets are members too,
ruledEntry's of()), so Kimi Code must not shape a request for a member that
can't take it. The capability words are Kimi Code 2.4.1's own
(catalog-runtime.ts capabilityFromDeclared), already written for direct
models; kimi-cli still gets neither.

Tests: TestGroupSharesKimiFacts (provider: all share, one without, efforts
differ) and TestKimiCodePlanCapabilities now writes a one-member group
"top" (the reporter's case: always_thinking, dynamically_loaded_tools,
default_effort max) and a group "mix" with a relay model (neither word).

Run on mote (mote-run, sandbox HOME):
- At 83a630d69 (on fbb1b36d1): gofmt -l internal/provider internal/agent
  clean; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
  go vet ./... ok; go test -tags nogui -count=1 -timeout 45m ./...: every
  package ok but internal/gui TestSettingsSaveKeepsWhatItDoesNotSend
  (#4514) and internal/proc TestNoCommandBypassesProc (#4491). Both fail
  the same at origin/main 841326709, just fetched; neither touches this
  change.
- At the pushed head (rebased on 841326709): go test -count=1 -timeout 45m
  ./internal/provider ./internal/agent ./internal/catalog ok.

Broken by hand: without the groupSharedKimi call, both tests go red
(group/top loses always_thinking and dynamically_loaded_tools and gets
high). With "any member" instead of "every member", both go red
(group/mix and the mixed auto groups get the words).

Not tried: a real Kimi Code session picking the group (the words are the
ones real Kimi Code 2.4.1 already reads for direct models), Windows and
Linux test runs (vet only), nested groups.
2026-10-31 14:59:44 +08:00
yetone 8413267097 catalog: a list's image/jpeg is an image, so OpenCode Go's models that see take images again (zeo9901)
zeo9901 (CC01CC) on Discord #feedback: "magpie 中 opencode go 所有的模型似乎
都无法实现图片输入了". Their screenshot is a routing group of DeepSeek V4.1
Flash at Open Design and at OpenCode Go.

Cause: OpenCode Go's own /models (https://opencode.ai/inference/go/v1/models,
the same at /zen/go/v1/models) lists what a model takes as media types:
deepseek-v4.1-flash's modalities.input is ["text","image/jpeg","image/png",
"image/gif","image/webp"], Gemini's adds application/pdf and audio/*, and so
on. catalog's live-list reader took the list word for word and asked for
"image", found none, and recorded ImageInput = false, an explicit answer.
entryFor puts a list's explicit answer over models.dev's (which says
image), so with a working Go key every Go model was text-only: a direct
pick had its image described or turned away with "model does not support
image input", a group member was sent it described or not at all, and
agents were told the models take text only. It used to work while Go's
list spelt modalities as models.dev does, or said nothing.

Fix: catalog.Kinds reads a modalities list as models.dev words it
(image/* image, video/* video, audio/* audio, text/* text,
application/pdf pdf, each once, an unknown word kept, nil stays nil).
imageInput and the live reader's InputModalities/OutputModalities go
through it, as do Codex's input_modalities, the labs rows and a decision
provider's listed facts (decide.go). A list saved before this, still
holding Go's media types and false, is mended when read (mendKinds), so
a user sees images from the first read after the update, not the next
fetch. A user's own Accepts images answer still wins.

Which OpenCode Go models take images, per Go's list on 2026-10-31:
deepseek-v4.1-flash, kimi-k3, kimi-k3.1-pro, kimi-k2.7-code, glm-5.3-flash,
qwen3.8-max, qwen3.8-flash, qwen3.7-plus, minimax-m3, minimax-m3.1-flash,
mimo-v2.6-flash, mimo-v2.6-pro, step-5-preview, gemini-4-argon, grok-4.7,
gpt-6-luna, gpt-5.6-luna, claude-haiku-5-5, muse-spark-1.2/1.3-contributor.
Text only: deepseek-v4-pro, glm-5.2, glm-5.3, hy3, hy4-preview,
longcat-2.0, beam-free, iceman-contributor-free.

Tests (fixture: four rows of Go's real list, read without a key, no test
reaches the network):
- TestOpenCodeGoMediaTypesSee (catalog), TestKinds,
  TestSavedMediaTypesListSees, TestListedFactsMediaTypesSee (provider).
- Broken by hand: Kinds returning its input unchanged turns all four red
  (deepseek-v4.1-flash, kimi-k3, gemini-4-argon "Images false"); the
  mendKinds call taken out turns TestSavedMediaTypesListSees red.

Run on mote at the working tree on 82b45888a (origin/main 82b45888a plus this change):
- gofmt -l internal cmd: nothing.
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  ./internal/catalog ./internal/provider ./internal/gateway: ok.
- go test -tags nogui ./internal/catalog ./internal/provider
  ./internal/gateway ./internal/agent -count=1 -timeout 45m: all ok
  (catalog 0.7s, provider 129s, gateway 665s, agent 203s).
  The docs paragraph was added after the run; no code changed since.
  The full go test ./... and the GUI suite were not run (no GUI file
  changed).
- Rebased onto ceeb73a0f (two commits outside catalog); at the rebased
  tree go test -tags nogui ./internal/catalog ./internal/provider
  -count=1 -timeout 45m: ok (catalog 0.8s, provider 98s).

Docs: gateway-routing.md, "A model that turns an image away".

Not tried: a real OpenCode Go request with an image (the only Go key here
has expired, and it isn't to be used). Not known: which agent and version
the reporter uses; Open Design's DeepSeek in the same group is a separate
provider and wasn't looked at.
2026-10-31 14:51:11 +08:00
yetone ceeb73a0f1 app: the desktop app writes its log to app.log; magpie log and Settings › About › Log find it
rayem1w on X (0.1.2330, macOS) was asked for ~/Library/Logs/magpie/serve.log
while chasing a Codex "hit a snag" through the gateway, and had no such
folder. Only the launch agent (magpie daemon install, written by launchd)
and a gateway magpie tui left running wrote a log; the app opened from the
Finder, the Dock or the Start menu logged to a stderr nobody reads, on
every system.

Now runGUI and runPanel (magpie, app, tray, panel, a window view, a
magpie: link) call applog.Start before gui.Run. It sends the standard
logger (the gateway, the plugin host, providers and Wails' error handler
all log through it) to app.log as well as stderr, and points
debug.SetCrashOutput at it so a panic's trace is there too:

  macOS    ~/Library/Logs/magpie/app.log
  Windows  %LOCALAPPDATA%\magpie\logs\app.log
  Linux    $XDG_STATE_HOME/magpie/app.log, else ~/.local/state/magpie/app.log
  portable data/logs/app.log

app.log, not serve.log: on a Mac launchd writes serve.log for the service,
another process. The file is 0600. At 5 MiB it becomes app.old.log (two
files at most); when another magpie (an update's new process) rotated it
already, it is only opened again; when it can't be moved it is emptied.
stderr goes first, through a writer that never fails, since io.MultiWriter
stops at a failed writer and an app opened from Explorer has no stderr.

Secrets: the log calls name header names and paths without queries; no
key or token was found logged (grep of log.Print* in gateway, provider,
plugin, gui, agent). scrub masks bearer/basic credentials, key/token query
parameters and sk-, AIza, gh?_ and JWT shapes anyway.

How a user finds it: Settings › About › Log, with the path, Copy and an
Open that shows its folder (POST /api/settings/log/reveal; the row is
hidden in magpie web, which writes no file). magpie log prints where every
log is (the app's, app.old.log, the service's, the tui's background
serve.log); --path the app's alone, -n N its last lines, -f follows it
across a rotation. Docs: reference.md, gui-shell.md, site start (FAQ "Where
is magpie's log?" and the CLI table) and privacy (files on your computer),
en/zh/ja.

Run:
At 227ce6074 on origin/main fbb1b36d1:
- mote: go test ./internal/applog ./internal/appdir ./internal/cli ok;
  -run TestCoreScriptBudget ./internal/gui ok; GOOS=windows go vet
  ./internal/... and GOOS=linux go vet -tags nogui ./internal/... ok;
  gofmt -l clean. GUI, chromium: about-log (5 languages x 1100/420, and
  no row without a log), about-website, i18n-keys: 24 of 25, the one red
  "a plugin's words are its own" ("Unmarked") is the same at origin/main
  fbb1b36d1 (#4524).
- WSL (magpie-desktop), webkit: about-log and about-website 21 of 21.
- Windows (win-run): applog, appdir, tui ok; cli ok but
  TestLibraryMCPHub's TempDir cleanup (#4140, mcp-npm, not this change).
- WSL full go test -tags nogui -timeout 45m ./... at the previous base
  03f609e3f: every package ok but reds that fail the same at origin/main
  03f609e3f alone: TestSettingsSaveKeepsWhatItDoesNotSend (#4514),
  TestNoCommandBypassesProc (#4491), internal/agent's install-detection
  tests (#4033, #3548), and TestCoreScriptBudget, which was this change
  (app.js 321 over): its comment is cut to one line and both budgets
  are raised by the remaining 124 bytes, with no room added.
- Broken by hand: with startLog left out of runGUI, TestTheAppWritesItsLog
  is red ("app wrote no log: open .../Library/Logs/magpie/app.log: no such
  file or directory"); with proc.UserPath taken out of openApp,
  TestGatewayStartsGetUserPath is red ("runGUI doesn't call
  proc.UserPath"). The guard now follows a start into a function or func
  var of this package, since the Wails start sits behind openApp for the
  test.
- Real use on mote: the GUI build, magpie app in a sandbox HOME, wrote
  ~/Library/Logs/magpie/app.log (0600) with its "started" line; magpie
  log and magpie log -n 3 printed it.
Not tried: the app opened from Windows Explorer or a Linux desktop
launcher for real (the paths are unit-tested per OS, the writer on
Windows and Linux); the full GUI suite (running on WSL after the push,
reds filed if they fail at origin/main too).
2026-10-31 14:45:22 +08:00
yetone fbb1b36d1f provider: the Claude keep-alive keeps off accounts, its reading, and its turn (#4532)
stringke read b48881f50 and 42c49e74d and left three notes on #4532
(issuecomment-6540015427). All three hold against the code:

1. Only accounts that were on were kept alive (claudeKeptAlive needed
   l.On). An account switched off as a reserve is still a sign-in the
   user kept for later, and Codex's keep-alive already renews saved
   ChatGPT sign-ins on or off. A run of Claude Code's /usage every eight
   days costs one local run and asks Anthropic nothing magpie doesn't
   already ask, so off accounts are kept too. Setup-token and signed-out
   accounts still aren't. The keep-alive never switches an account on.

2. The run's /usage reading was dropped (`_, err :=
   readSavedClaudeUsage`). The run now goes through the account's
   reading, the way a card's refresh reads a saved account:
   renewClaude forgets the account's minute-cached reading and calls
   loginReading with a keepingAlive ctx (asked, so nothing is held).
   claudeWindows runs Claude Code for it as for savedRefresh, past the
   30-second floor (the keep-alive is an hour apart at most), and keeps
   it in claudeUsage. loginReading keeps it beside the account and on
   disk (keepReading), and the new keepCardRead puts it on the account's
   card in the Usage cache with its history and the menu bar told, the
   way refreshCards does. A card the Usage page doesn't have isn't added.
   The run's own error comes back through the ctx, not the kept reading,
   so a failure is still told apart from a reading kept from before. This
   path doesn't bump the global ask generation, so Claude Code's own
   account isn't read again because of it.

3. A failed run held the hourly slot: still due, and with one renewal a
   look, the accounts after it never had theirs. A renewal that fails, for
   Claude and for Codex (the same loop had the same gap), now waits
   keepAliveRetry (6 hours, in memory) before the hourly look tries it
   again, and doesn't take the look's turn meanwhile. `magpie accounts
   refresh` (every 0) still tries it at once. A success clears it.

The help text, refreshAccounts' comment and providers-accounts.md say so.

Run on mote at 82b45888a plus this change: go test -timeout 45m
-count=1 ./internal/provider/... ./internal/cli/... ok; go test -race
-count=10 -run 'TestRenewLogins|WeeklyOnly|TestClaudeUsage'
./internal/provider ok; gofmt -l clean; GOOS=linux go vet -tags nogui,
GOOS=windows go vet and go vet of ./internal/provider/...
./internal/cli/... clean.

Broken by hand, each on mote:
- l.On put back in claudeKeptAlive: TestRenewLoginsKeepsSavedClaudeSignedIn
  ("renewed what wasn't due" with team@ missing), TestRenewLoginsKeepsClaudeReading,
  TestRenewLoginsFailedWaitsItsTurn and TestRenewLoginsLeavesClaudeSetupToken
  fail.
- renewClaude back to `_, err := readSavedClaudeUsage(...)`:
  TestRenewLoginsKeepsClaudeReading fails ("the account's reading: false").
- renewWaiting taken out of the loop: TestRenewLoginsFailedWaitsItsTurn
  fails at look 2 (the failed account took the turn again).

Not tried: real accounts and real Claude Code (fake runner, sandbox
HOME). The back-off is in memory, so a restarted magpie tries a failed
account on its first look. Codex's back-off is covered only through the
shared loop; there's no Codex-specific test for it.
2026-10-31 14:40:03 +08:00
yetone 03f609e3fd redact: a token count is not a secret (Discord, steven_4422; #3775)
steven_4422 in #feedback, with a screenshot of the Masking page: "total
number of tokens are masked as secret". Claude Code's system reminder
<total_tokens>1499872 tokens left</total_tokens> went upstream as
<total_tokens>{{SECRET_dkfgb3bf}} tokens left</total_tokens>, listed under
Secrets and found by the local model. #3775 had the same with AstrLink
Guard (<total_tokens>14902266).

Cause: the model labels the count `secret`; modelFits lets a hex run
(hexRe, which a run of decimal digits matches) through when secretCued
finds a key word right before it, and secretCued takes a cue anywhere in
the name before the value, with letters after it: the tag's name
total_tokens ends "token" + "s", so the count was "called a token". The
same held for "total_tokens": N, max_tokens: N and token_count=N.

Fix: a value of decimal digits alone that the model calls a secret is
masked only where the name right before it (then =, :, is, a tag's >,
quotes) ends with a key's, a token's, a password's or a PIN's word
(numberNamedSecret: api_key=, "token": , PIN:, user_pin=, 密码是,
<token>…). A name that runs on past the word counts what it names.
Rules are unchanged (numeric keys after key=/token: labels, phones,
ID numbers keep their own rules). The eval's token-count case now comes
out right for AstrLink Guard, so its #3775 marker is off.

Tests: TestTokenCountIsNoSecret uses the reporter's bytes in a Claude
Code user message's system reminder (the reporter's 7-digit counts, and
8-digit ones as Claude Code sends on a large window; the model's
len >= 8 secret check already let the 7-digit ones go, so the reporter's
exact values may have been 8 digits as read off the screenshot), plus a
usage object, max_tokens, token_count and "spin:". TestNamedNumber-
SecretStillMasked keeps api_key=, "token":, token is, PIN:, user_pin=,
password:, 密码是 and <token>…</token> masked.

Broken by hand: with model.go as on main, TestTokenCountIsNoSecret is
red for the 8-digit counts, total_tokens, max_tokens and token_count
(PIN:/user_pin= were not masked on main either; now they are).

Run (mote-run, base origin/main 93b31f5b7):
- gofmt -l clean; go vet ./internal/redact, GOOS=linux -tags nogui and
  GOOS=windows go vet ./internal/redact ./internal/masking ./internal/pii:
  clean.
- go test -timeout 45m ./internal/redact/... ./internal/masking
  ./internal/pii ./internal/otlp ./internal/sessions ./internal/settings
  ./internal/gui ./internal/gateway: all ok except
  - redact TestMaskEval: the token-count case's known issue was now
    fixed (marker removed, green after);
  - gui: TestCoreScriptBudget (green at 19594cc1c), TestSettingsSave-
    KeepsWhatItDoesNotSend (#4514, red on main, gui untouched here) and
    ten AppKit real-window tests killed at their deadlines on mote
    (#2645, #4125).
- Rebased on origin/main 19594cc1c: go test ./internal/redact/... ok,
  gofmt clean, TestCoreScriptBudget ok, #4514 still red there.

Not tried: the real local model (AstrLink Guard / Privacy Filter) on the
reporter's request; the gateway package was not run again after the
rebase (the commits in between touch usage, provider and the GUI).
2026-10-31 14:19:02 +08:00
yetone b48881f507 provider: keep idle saved Claude accounts signed in, by Claude Code itself (#4532)
#4532: a saved Claude account switched on but not needed for weeks
(switch-only) had nothing run on it, its refresh token sat idle, and it
was found signed out when the switch wanted it. Codex's saved sign-ins
already had a keep-alive (RenewLogins, every 8 days, one account an
hourly look).

The same loop now takes saved Claude accounts that are on, not Claude
Code's own, not added by setup-token and not already signed out
(claudeKeptAlive). For one that is due it has real Claude Code run
/usage in the account's own CLAUDE_CONFIG_DIR, the path a card's
refresh takes (readSavedClaudeUsage, inSavedClaudeDir), and
syncSavedClaude keeps whatever sign-in Claude Code refreshed. magpie
asks Anthropic nothing itself: no OAuth or usage endpoint, as removed in
9bf6d43527. A run that went through marks Renewed, so the account is not
run again for 8 days whether or not Claude Code rotated the token. A
refusal goes through NoteClaudeSignInFailure (and syncClaudeDir for an
emptied sign-in), so the row says to sign in again the way a request's
refusal does, and the keep-alive runs nothing more on it. A network
failure marks nothing. Anthropic's refresh-token idle lifetime is not
known, so the interval is Codex's conservative 8 days. The reading
itself is not kept as the card's cache.

`magpie accounts refresh` and its help say the Claude ones are renewed
too; providers-accounts.md describes it.

Run on mote at 93b31f5b7 (this tree): go test -timeout 45m -count=1
./internal/provider/... ./internal/cli/... ok; go test -race -count=10
-run 'TestRenewLogins|WeeklyOnly' ./internal/provider ok; gofmt -l
clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet of
./internal/provider/... ./internal/cli/... clean. The new tests also
passed with TZ=UTC and TZ=Pacific/Kiritimati.
Rebased onto origin/main 847f0c470 (a GUI-only change) and run again
at that tree on mote: provider and cli tests, gofmt, Linux and Windows
vet, all ok.

Broken by hand: with the Claude branch taken out of the loop's filter,
TestRenewLoginsKeepsSavedClaudeSignedIn and
TestRenewLoginsClaudeEmptiedSignIn fail ("renewed what wasn't due: []",
"emptied: []"); with the NoteClaudeSignInFailure call removed, the
refused case fails (Lapsed false).

Not tried: real accounts and real Claude Code; the tests use the
fake Claude Code runner and a sandbox HOME. Whether a /usage run makes
Claude Code refresh a token that is not near expiry is not known; the
run counts as the renewal either way. Left out (per #4532's scope):
per-model windows in the switch and caps, CLI commands, reset cards.
2026-10-31 14:15:52 +08:00
yetone 2eac916170 gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.

A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.

- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
  cost, readOnly} answers 201 with the secret once, no-store. GET lists
  the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
  [--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
  alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
  until/expired/issued by.

Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
  so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
  forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
  Such a request can already use every model with no key and run the CLI,
  so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).

An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.

An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.

Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.

Run at base 07a3312c5 (origin/main, fetched just before):
- mote: go test -count=1 -timeout 45m on access, budget, gwbudget,
  usage, cli, gateway, davsync, agent: ok.
- mote: internal/gui fails TestCoreScriptBudget (#4526),
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and ten AppKit window
  tests killed at their deadline (#4125, #2645). The first three fail the
  same at origin/main 07a3312c5 on mote. This change touches no GUI file.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; node --test site/*.test.mjs (49
  pass).
- win-run: access and budget ok. usage fails TestDesktopSessionAccountMetadata
  the same at origin/main (#1356). cli's TestLibraryMCPHub failed once on
  TempDir cleanup (#4140) and passed alone.
- Real binary on mote, sandbox HOME, port 47811: issued a 1m key with
  curl, read its limit, listed it, saw `gateway-key list` show "until",
  had a page's Origin refused 403, and after 62s /v1/models answered 401
  "the gateway key "sandbox-1" expired at …".

Broken by hand, each restored:
- no expiry check in Check: TestIssuedKeyExpires and
  TestIssuedKeyExpiresOnEveryRoute go red.
- no 401 for a refused key on loopback: TestIssuedKeyExpiresOnEveryRoute
  goes red (the expired key let in as no key).
- budget not counting CallerIssuerID: TestIssuedKeysSpendTheirIssuersLimit
  goes red (5 calls reached the upstream).

Not tried: a Responses WebSocket open across the expiry. The GUI shows
no expiry or issuer yet (issued keys look like plain keys until pruned).
A held issuer's /v1/magpie/usage shows its own rows, not its keys'. The
refused-key 401 doesn't count toward tooManyAuthFails. Issued keys sync
through davsync like other keys, with their expiry.
2026-10-31 13:44:29 +08:00
yetone 07a3312c53 library: sync and backup files carry the subagents
xixi_Sean_ on X asked why Sync leaves the Library's subagents out. There
was no reason: the library part of a bundle now carries them.

- library.Bundle.Subagents (*[]*Subagent): name, description, prompt,
  the skills and MCP servers named, the agents ticked. Collect always
  sets it, empty too. Applied.Subagents (which files magpie wrote here
  and their hashes) stays out: each computer writes the files into its
  own agents on the sync Put runs and records its own, so a file the
  user edited there, or one of theirs by the same name, stays theirs.
- Put replaces the subagents 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) is unknown and keeps this computer's.
- check refuses a subagent whose name isn't one (it is a file name in
  every agent) or comes twice; agent ids are carried as they come, so a
  newer magpie's tick for an agent this one can't give subagents to
  stays and writes nothing here.
- davsync: an empty list hashes as before the field, so upgrading with
  no subagents syncs nothing.
- backup files go through the same Collect/Put; the CLI's backup line
  counts subagents. The GUI's sync/export/import ticks say "instructions,
  MCP servers, skills and subagents" in every language.
- webdav-settings-refresh's "Agents" tick locator also matched the
  library tick's "subagents": it now asks for "Agents' models".
- library.md and sync-backup.md updated. Hooks still aren't carried.

Run (rebased on 0bf5adb11; Go runs at e0c57ffe2, same diff):
- mote: go test -tags nogui ./internal/backup ./internal/davsync
  ./internal/cli ok; ./internal/library -run 'TestCarry|TestSubagent|
  TestLocalServer|TestPutKeeps|TestPutSame|TestRestoreKeeps' ok
- wsl-run (Linux): ./internal/library ./internal/backup ./internal/davsync
  whole packages ok
- win-run (Windows): the same three, -run 'Subagent|TestCarry|TestLibrary|
  TestSyncLibrary' ok
- go vet -tags nogui for darwin, GOOS=linux and GOOS=windows on the four
  packages ok; gofmt -l clean
- GUI (wsl-run, Chromium + WebKit, every language): i18n-keys,
  github-sync, s3-sync, sync-auto-restore, sync-not-backup,
  sync-other-kind, sync-sign-in, sync-spin, sync-usage-error,
  webdav-settings-refresh, library-backups-top, gui-de, gui-ja,
  gui-zh-tw, settings-search, settings-sections: 170/173, then
  webdav-settings-refresh green after the locator fix. The one red left,
  i18n-keys "a plugin's words are its own" ("Unmarked" in
  plugins/routing/i18n.js), is on main already: #4524.
  mote ran five other GUI suites at load 18, where every WebKit
  github-sync case timed out at launch, so the GUI run moved to Linux.

Broken by hand: with Collect not setting Subagents and Put ignoring
them, TestCarrySubagents, TestCarrySubagentKeepsUsersFiles,
TestCarryNewerSubagents, TestBackupFileCarriesSubagents,
TestSyncSubagents and TestNoSubagentsHashAsBefore went red; with Put
treating a missing list as empty, TestCarryOldBundleKeepsSubagents and
TestBackupFileCarriesSubagents went red.

Not tried: a real WebDAV/S3/GitHub remote between two real computers;
the fake DAV server carries it between two sandbox HOMEs.
2026-10-31 13:14:16 +08:00
yetone 59546b3fdb gateway: Kimi Code's K3.1 Pro refusing reasoning none on Chat is asked again at its lowest (#3739)
7eleven.eth (Discord #feedback) hit "Kimi Code: K3.1 Pro does not
support disabled thinking mode. Please enable thinking and try again,
or choose another model." in ZCode. On Anthropic Messages, ZCode's
default format, this was fixed in 72e8d9fa6 (v0.1.2216): alwaysThinks
matches the wording, and the request goes again without
"thinking":{"type":"disabled"}, and without it from then on. The same
refusal on the Chat side was still handed back:

- a Chat client's reasoning_effort none, relayed (a ZCode provider set
  to OpenAI Chat, OpenCode's off variant): serve's retry for none
  matched only levels named, OpenRouter's mandatoryReasoning or
  effortRequired, and Kimi's words name no levels;
- a Responses or Chat client's none translated to Chat (Codex, Claude
  Desktop to a Kimi Code Chat endpoint): Kimi Code's catalog gives its
  toggled models none (reasoningOffProviders), so none went out, and
  forwardTranslated's retry read the same three.

needsReasoning is effortRequired, or for none and minimal alwaysThinks'
words, at both of those sites: asked again at the model's lowest
(onEffort), offRefused marked, so later requests go at it from the
start. Any other 400 still goes back as it came. Scoped by the
refusal's words, not by model name, so only a model that says it can't
stop thinking is changed.

Tests: TestKimiChatThinkingOffRefused (relayed and translated, Kimi's
literal sentence in Kimi's Chat error shape; turn 1 none then low, turn
2 low at once; a max_tokens 400 is not asked again).

Run (mote, macOS, Go 1.26.8, sandbox HOME by testenv):
- gofmt -l on the changed files: nothing.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: rc=0 each.
- go test -tags nogui -count=1 -timeout 45m ./... at this tree
  (0bf5adb11 + the change, origin/main unchanged since): 80 ok, two red.
  internal/proc TestNoCommandBypassesProc (claudetui/child_unix.go:32,
  #4491, untouched here) and internal/gateway
  TestRuleTimeWindowAtTurnStart ("a 5 b 2": a count changed between the
  check and its message; passes alone; filed #4528). Every thinking,
  effort, Kimi and mandatory-reasoning test in internal/gateway ok.
- Broken by hand: with needsReasoning back to effortRequired at both
  sites, both subtests fail with Kimi's 400 handed back; with only the
  translated site reverted, the translated subtest fails alone.

Not tried: the real Kimi Code endpoint (no account here), whether its
Chat endpoint answers none in these words (the Messages wording is the
reporter's; the Chat envelope is Kimi's usual {"error":{message,type}}),
a real ZCode session. Not changed: a Chat request with
"thinking":{"type":"disabled"} itself (no retry path reads it on Chat),
and #3739's second symptom (k3 losing thinking when
output_config.effort is asked).
2026-10-31 13:13:57 +08:00
yetone 79b4be4668 redact: a public IP goes as public-ip-<letters>, not a documentation address
akic404 on Discord (#feedback, 10-31): "ip的脱敏策略需要改进,会把公网ip直接
脱敏成内网ip,能不能沿用其他的方法用{ip:…}的代替". Since c2aad3db0 (10-28) a
masked public IP went as an address from RFC 5737's ranges (192.0.2.,
198.51.100., 203.0.113.). A 192.0.2. one reads as a LAN address to a
person, and every model knows the ranges: asked why ssh to the address
timed out, the models told the user they had an example address, not
their server's.

Now a public IPv4 or IPv6 address goes as public-ip- and eight lowercase
letters (public-ip-kvxqmrtz): visibly masked, still says it is public,
and a host name models ssh to. Same stand-in for an address every turn,
never shared, put back only as a whole name (no letter, digit, - or _
against it, no dot before it or before a name after it), in streamed
tool-call arguments too. A name with no dot reaches nobody if the vendor
tries it. A documentation address the user writes is no stand-in any
more, so it can't come back as someone's real address.

Run:
- Real models through the local gateway (deepseek-v4-pro, glm-5.3,
  kimi-k3, claude-sonnet-5-5, gpt-6-luna), two prompts each: "我的服务器
  是 X,帮我 ssh 上去看看磁盘" with a bash tool, and "阿里云服务器 X 从家里
  ssh 超时,是公网还是内网地址?最可能的原因?".
  - 203.0.113.147 / 198.51.100.147 / 192.0.2.183: ssh 5/5; diagnosis:
    4/5 (deepseek, kimi, gpt, glm) said "example address, use your real
    one", sonnet named it TEST-NET too.
  - {{IP_k3v9x2mq}}: ssh 0/5 (asked for the real IP, or grepped env);
    diagnosis fine.
  - public-ip-kvxqmrtz: ssh 5/5; diagnosis 5/5 security group or
    "public address", none said wrong/example address.
  - ip-kvxqmrtz (no "public"): ssh 4/5, but 4/5 called it an internal
    host name. Hence the public- head.
- On mote: gofmt -l, go vet ./internal/redact ./internal/gateway,
  go test -count=1 -tags nogui ./internal/redact ./internal/maskrec,
  and -run "Redact|Mask|Restore|IP|Privacy" ./internal/gateway: ok.
- Broken by hand: restoreAddr without its boundary check turns
  TestIPGoesAsAPublicIPName red; stand-ins made as 203.0.113.x again turn
  TestIPGoesAsAPublicIPName, TestIPv6GoesAsAPublicIPName,
  TestIPStandInsNeverShared and gateway TestRedactedKinds red.

Not tried:
- a real magpie build end to end with a real model (the gateway test runs
  the whole path against a fake upstream; the real models saw the
  stand-in text itself);
- the full suite, and Linux/Windows vet (no OS-specific code touched);
- an agent that resolves host names through a DNS search domain would
  look up public-ip-x.<domain> if a stand-in ever came back unrestored.
2026-10-31 11:48:21 +08:00
yetone e6b851b0fe update: magpie update in a terminal restarts the app with its gateway handed over
gaubeebangeel on X has an agent run the magpie upgrade at 4am and had
to give that agent its own provider: magpie couldn't serve it through
the upgrade.

Cause: `magpie update` put the new version in and printed "quit and
reopen magpie to use it" (a .app) or "updated to X" (a binary). The
running app never restarted, so the agent (or the user) had to restart
it by hand, and a plain restart closes the port and drops streams.

Measured before, on mote, a sandbox HOME `magpie serve` with a fake
upstream streaming 61 chunks at 100ms, restarted by SIGTERM + start:
- the stream was cut at chunk 15 of 61 (unexpected EOF); SIGTERM to exit
  took ~18ms, no drain;
- requests during the restart: 289 answered, 5 refused over 87ms.

Now `magpie update`, once the new version is in, POSTs it to the
running app's /v1/magpie/restart (gateway/restart.go). It is answered
only to a program on this computer over loopback; a LAN caller, a page
(Origin / Sec-Fetch) and another Host get 403. The updater's
restartBeside (gui/update_beside.go) restarts only when its own exe was
the one replaced (replaced() now also compares a .app's binary,
bundleExe), takes the version as ready without the feed, and runs the
same restart as Settings' AutoRestart: at once when it cuts nothing
short, else through waitIdle. On macOS and Linux that restart is the
existing SCM_RIGHTS handover, so the port never closes and in-flight
streams finish in the old process. The command prints what happened:
restarting (handing the gateway over), waiting for N requests, another
copy (current), magpie serve (unsupported), not running, or too old
(404: the first update into this version still needs a manual
restart).

Tests:
- TestUpdateInATerminalRestartsTheAppWithoutCuttingIt (darwin, linux):
  a stream through the gateway, the exe rewritten, magpie update's ask
  answered "restarting" with handover; the successor serves a request
  while the stream runs, the stream ends whole, the old one quits only
  after it. Red by hand with the route removed ("magpie update's ask:
  404").
- TestUpdateOfAnotherCopyLeavesTheAppBe, TestRestartAskedOnlyFromThisComputer
  (refused cases never reach the restarter), TestUpdateAsksTheRunningMagpieToRestart
  (each reply, a 404 magpie, none running).

Run at this tree:
- rebased on bdc1617be, at this head on mote: gofmt -l clean;
  GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...;
  go test -run 'TestUpdate|TestRestartHandsTheGatewayOver|TestHandoverNotMade'
  ./internal/gui ./internal/cli and -run 'TestRestartAsked|TestReadOnlyKey'
  ./internal/gateway: ok
- before the rebase (88ecae173), mote: go test -count=1 ./internal/gui ./internal/cli ./internal/gateway:
  gateway ok (535s), cli ok; gui FAIL only on filed reds: the real-window AppKit
  tests killed at their deadline on mote (#4125, #2645) and
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514), both red the same
  run alone at 88ecae173, and TestColdTurnsTaken (#4510, a race in
  full gui runs, not touched here)
- wsl-run (magpie-desktop, -tags nogui): TestRestartHandsTheGatewayOver,
  TestUpdateInATerminal..., TestUpdateOfAnother...: ok
- mote: gofmt -l clean; go vet gui/gateway/cli; GOOS=linux go vet -tags
  nogui ./...; GOOS=windows go vet ./...: ok

Not tried: the real GUI app end to end with a real `magpie update`
against a published release; Windows (no handover there: the restart
waits for an idle gateway and the port closes while the new version
starts, #4521); `magpie serve` / the daemon, which has no handover and
says to restart it the way it was started.
2026-10-31 11:39:04 +08:00
yetoneandggbdpq bdc1617bed routing: Accounts and keys count the whole day, not the last kept requests (#3351)
1234fsdc: the live Routing page's Accounts and keys said tried and
answered over the requests the page still keeps in memory, so on a busy
day the counts were a sliver of what Usage showed for the same accounts
and went down as old requests fell off. /api/trace/history (the read the
live page already makes every 15s) now carries `tallies`: per account or
key, today's tries, answers, fails by reason, models answered, the last
answer and the latest rest, read from routing/<today>.jsonl. The page
seeds the list with them and still takes the latest rest and readings
from the requests it keeps; a day looked at, or a purpose picked, counts
its own list as before. The note says "over today's requests" then.
Ported from ggbdpq's patch on the issue.

Changed from the patch:
- The patch parsed the whole day's file under history.mu on every look.
  A busy day's file is hundreds of MB (#3383) and saveRoute takes the
  same lock, so every 15s poll would stall the routes being written.
  DayTallies now folds in only the whole lines added since the last
  look (it keeps the offset, as History does); a line still being
  written waits for its end. It starts again when the day changes, the
  file shrank or was compressed, or the folder moved (another HOME).
- What it returns is a copy: the patch handed out the live tallies,
  and the JSON writer read a Fails map the next fold wrote.
- The latest name and rest go by the try's time, so no sort per look.
- docs/subsystems/gui-shell.md says how the counts are made and that a
  request done since the last look is counted at the next one.

Run on mote at this change on 394a92f0f. The pushed parent 5787d758a
adds usage, tray, redact and search changes and none of this change's
files:
- gofmt -l clean; go vet ./internal/gateway ./internal/gui for darwin,
  windows, and linux -tags nogui.
- go test ./internal/gateway -race -run 'History|DayTallies': ok.
- go test ./internal/gui -count=1 -timeout 45m: red in 11 tests, all
  red on main too. Ten are real-window AppKit tests killed at their
  deadline on mote (the same ten at 03f3e1528, #4125).
  TestSettingsSaveKeepsWhatItDoesNotSend is SearchAll on main (#4514).
  TestLiveHistoryTalliesTheWholeDay passes. At the pushed head, -run
  'Budget|Tallies': ok.
- GUI on WSL (wsl-run, Ubuntu 24.04, Playwright 1.62.0, Chromium and
  WebKit, every language each file runs):
  - The 229 test files that reach the Routing page, plus i18n-keys, at
    this change on 576b5dcbc (--test-concurrency=4): 3498 tests, 101 red
    in 31 files.
  - Those 31 files on main 03f3e1528: 94 red. With this change: 99 red.
    The same tests fail; which language or engine goes red changes from
    run to run (#4121, #4471).
  - Four of them run alone: 27 red on main, 21 with the change.
  - At 394a92f0f, routing-day-tallies, i18n-keys, account-weight,
    key-weight and routing-weight-chip passed. routing-columns' WebKit
    rows were red, as on main (#4520). Its fixture has no tallies.

Broken by hand:
- DayTallies re-reading the whole file each look (reset always true):
  TestDayTalliesFoldOnlyWhatWasAdded red, "a look after one route read
  101 lines, want 1".
- handing out the live tallies, no copy: red, "a tally handed out
  changed after: ... fails map[rate:3]".

Not tried: a real day's file of hundreds of MB. The first look after a
start still reads the whole day once under history.mu, as History's own
first read does. A real app beside a running gateway. Past days
are unchanged: still counted over their latest historyMax routes.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-31 11:29:38 +08:00
yetone 5787d758a7 usage: a search a provider's model runs with its own tool is a Web search row
cybercaius on Discord: with magpie's search APIs off, DeepSeek was asked
to search, and Usage › Requests showed nothing of it; its purpose list
had only All, Connection check and Unmarked.

DeepSeek searches by itself on its Anthropic and Responses APIs
(searchHosts): Claude Code's web_search_20250305 and Codex's web_search
are relayed as sent, and the reply carries server_tool_use and
web_search_tool_result blocks (#669), or web_search_call items. magpie
read only the reply's tokens. Its Chat API has no search tool, so a
Chat client's request there, with the searcher and the APIs off, gets no
search at all.

searchTally (search_native.go) counts what the reply shows: Anthropic's
server_tool_use blocks named web_search and
usage.server_tool_use.web_search_requests, the Responses API's
web_search_call items. What a stream named as it went (a block's start,
an item done, by id), what a whole reply or the stream's end listed, and
what the usage said are counted apart and the most is taken, so an item
named added, done and again in response.completed is one search. The
relay's usage sniffer and both translated readers feed it into an
unexported Usage.searches; after the request's own row,
logNativeSearches writes one row per search (at most 20): Source search,
Kind web_search, the request's agent, provider, host and model, status
200. No query is kept and nothing goes to telemetry: the rows ride the
probes' lane as the search API rows do (listed, counted nowhere, not
exported). An event is parsed for it only when it holds server_tool_use
or web_search_call.

The purpose filter needed no change: a search row's kind already gives
it Web search (TestSearchRowsListTheirPurpose guards that, and passes on
the old code too). The Requests tab shows the row with its model and
provider as it shows a plan's own search.

Run (mote, at this tree):
- go test -count=1 -timeout 45m ./internal/usage ./internal/gateway: ok
- go vet ./internal/gateway ./internal/usage, GOOS=windows and
  GOOS=linux go vet ./internal/gateway: ok; gofmt -l clean
Broken by hand:
- without this change TestOwnProviderSearchesAreLogged fails:
  "anthropic whole: 0 search rows, want 1"
- counting every streamed web_search_call event instead of the done
  ones by id: "responses stream: 4 search rows, want 2"
Not tried: a real DeepSeek account (the fixtures are #669's DeepSeek
reply and Anthropic's documented stream shape); the translated readers'
counting has no test of its own; no GUI file changed, so no GUI run.
2026-10-31 11:25:39 +08:00
yetone 5218119456 redact: every reply gets its values back, a turn that masked nothing too
yapechan123 (Discord) saw a table the model wrote come back as
{{PERSON_kb32hzkg}}、{{PERSON_iye66366}} and {{PERSON_isyrz5ih}}、
{{PERSON_j5kluh3x}}, all four in canonical form. Every way a placeholder
could come back unrestored was probed with those literal bytes, on each
protocol's stream split at every byte and at 1..7 runes, and whole:

- The gateway put no restoring writer on a reply when the request in
  hand masked nothing (redactedHits, redactedPromptHits returned early
  on n == 0). A vendor that holds the conversation (Codex's compacted
  history, a server-side session) answers with placeholders of earlier
  turns while the request carries no value, so they went back as
  written. Most likely the reporter's path. Now every reply on a masked
  route is read.
- Responses streams: each event's random "obfuscation" string could end
  like a placeholder start and take the stream's one held tail from its
  delta, so the placeholder after 、 stayed (4 of 140 text runs, 6 of
  tool args runs). The writer now holds a tail per string path and
  never for obfuscation or kept keys.
- Kept keys (name, type, data, status...) were never restored in a
  stream, so a Gemini functionCall args object {"name":"{{PERSON_…}}"}
  kept it. Every string is restored now but signatures, data: URLs and
  opaque blobs (sealedText).
- A whole body skipped restoring unless it held "{{", so a model's
  PERSON_kb32hzkg or {PERSON_kb32hzkg} stayed; heldIn looks for any held
  placeholder's hash.
- makeRoom let a random half of 200k values go though its comment said
  the oldest; now the least recently used half (touch on every mask and
  hit), so a value just masked is never the one let go.
- A binary reply (audio/, image/, video/, octet-stream, pdf, zip) goes
  through as it comes instead of being held.

Not fixed by design: values are in memory only (README's privacy
promise, TestNoValueOnDisk), so a placeholder from before a restart that
only the vendor still holds can't be restored. Masking switched off
later also restores nothing.

Tests (all red on d159314e3's code, green now, run on mote):
TestReporterTableRestoredOnEveryStream (responses-text 4, responses-tool
6 fails before), TestPlaceholdersRestoredWhereverTheySit,
TestFullValuesKeepTheNewest (499 of 1000 newest lost before),
TestBinaryReplyIsNotHeld, TestReplyToAnUnmaskedTurnIsRestored (gateway,
real stack: first turn masks an email, second masks nothing and the
fake vendor answers with the first turn's placeholder).

Run: gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./... on mote: clean. The full go test -tags nogui
-timeout 45m ./... on mote, one step before this head, found a nil
masker in redactedPromptHits with masking off (image drawing:
TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn, internal/cli's
image MCP); fixed here (m == nil returns as before). At this head
internal/redact and internal/gateway pass on Linux (wsl-run, 594s).
That run's other reds are outside this change: internal/gui
TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll) and
TestColdTurnsTaken, internal/proc TestNoCommandBypassesProc
(internal/claudetui/child_unix.go uses os/exec). The full suite runs
again at the pushed head after the tag.
Not tried: a real Codex compaction round trip with a real account, and
the reporter's agent (unknown).
2026-10-31 11:23:53 +08:00
yetone bfd4e9a5bf search: "Models that search by themselves" is always there, dimmed with why when magpie has nothing to search with
cybercaius on Discord, after v0.1.2309: "开关在哪个位置". They had turned
their search APIs off, so the row was hidden and couldn't be found.

The row is now always in Settings › Models › Web search. With no search
API on and no provider searching for other models, both choices are
disabled and dimmed (as the update rows are), and its line says why and
where to add one: "magpie has nothing to search with: add a Search API
above, or pick a provider under Searches for other models". Nothing else
on the page moves. zh, zh-TW, ja and de have the line.

Run:
- search-all (new case: a Search API turned off, provider search off, at
  560px: the row is there, dimmed, says where, both buttons disabled, a
  forced click saves nothing, nothing scrolls sideways), search-first,
  search-order, i18n-keys: WebKit on Linux (WSL), 36 pass; with
  searcher-pick, Chromium on mote, 46 pass.
Broken by hand: with the old settings.js, the new case fails in all five
languages.
searcher-pick in Chromium fails 1 of 2 runs at b09349d17 too (line 319, a
null box; #4274), and in WebKit on Linux at line 307 (#1745).
Not tried: the real app.
2026-10-31 11:06:41 +08:00
yetone 88ecae1738 routing: By weight spreads a subscription's requests over its accounts
rubbzha on X (tweet 2116346330625036794): a Claude Max account and a Pro
one signed in to one subscription should share its requests by how much
each allows. The provider editor's Routing now offers By weight for
subscription accounts as it does for keys. With it picked, each account
in use shows "Weight N · S%" beside its name, the key weight's chip, and
a click edits it in place (POST /api/provider/accountweight {id, account,
weight}). CLI: `magpie provider account-weight <id> [account [n|default]]`.

The weight is kept per account by its lower-case name
(Provider.AccountWeights), and is moved with a rename (moveAccountSettings).
The gateway's keyWeight reads it from the candidate, with no file read, so
the smooth weighted pick treats accounts as it treats keys: Stays keeps a
conversation on its account, and a resting account is passed over while
the others share its requests. The default is 1. Nothing is prefilled from
the plan, and 1 is stored as no entry, so a value the user set is never
overridden.

Re-derived: ROUTINGS' weight text and routingsOf (the editor), the Routing
page's MODES, provider-row options and its "why first" text for an account,
the routing and accounts subsystem pages, the start docs (en, zh, ja), and
i18n in zh, zh-TW, ja and de (i18n.js and plugins/routing/i18n.js).
app.js is 74 bytes smaller than before (a long comment cut, keyWeight
reused), so neither script budget is raised.

key-weight.test.cjs read #status before accountAction's second round trip
(/api/state) had written it. The same race is now waited on in both tests:
with a 400ms delay injected on /api/state, the old read is red and the
new one is green.

Run (rebased on 03f3e1528; then on ef8dfaa46, where the budget, i18n and
own tests were run again and passed: Budget|I18n|Weight Go tests,
account-weight, key-weight and i18n-keys GUI files 10/10):
- New tests, each red on the old code: TestSetAccountWeight,
  TestAccountWeightMovesWithRename (red with the moveKey line removed),
  TestAccountWeightSharesRequests (6/2 for weights 3/1; alternating with
  keyWeight forced to 1), TestAccountWeightCmd, and
  account-weight.test.cjs (chromium + webkit, widths 1000/560 and web 390,
  en/zh/zh-TW/ja/de; red on 3e5aa1151's assets: no By weight for accounts).
- account-weight, key-weight, routing-weight-chip, account-row-line GUI
  files on the Linux box: 24/24 after the status wait (23/24 before, the
  race above). On mote, 13 of 24 timed out launching a browser at load 24
  with 116 Playwright processes from other sessions (#4125).
- mote `go test -timeout 45m ./...`: every package ok except
  internal/proc's TestNoCommandBypassesProc (claudetui on main, #4491) and
  internal/gui's ten real-window AppKit tests killed at their deadlines
  under load (#2645, #4125). Neither touches this change.
- gofmt -l clean; go vet ./... (darwin), GOOS=windows go vet ./... and
  GOOS=linux go vet -tags nogui ./... ok on mote.
- Whole GUI suite on the Linux box: still running at push; reds are filed
  after.

Not tried: real Max and Pro accounts through the gateway; the Routing
page's own account row under By weight has no GUI test; the whole GUI
suite on macOS WebKit (mote was saturated by other sessions' suites).
2026-10-31 11:03:35 +08:00
yetone f63cf0bfc2 affinity: a DeepSeek conversation stays on its key past five minutes, as DeepSeek keeps it cached for hours
On X: "Claude code 通过 Magpie 链接 DeepSeek 缓存命中率只有 50% 怎么解决呀".

Measured with a real DeepSeek key, Claude Code 2.1.314 in a sandbox
HOME through a sandbox magpie (usage cache_read / in per request):
- one interactive conversation on one key, Anthropic path: 0% on its
  first request (13.7k system + tools), then 90–99% on every turn; the
  Chat path (a chat-only provider) the same, 90–99%;
- masking on (redact + personal + local model): 98–99%;
- left idle 7 minutes: 99%, 98%; left idle 26 minutes: 99% (14336 of
  14468);
- the misses are Claude Code's own requests: each session's first one,
  the title call, an Explore subagent's first (5.6k, 0%), the auto
  mode classifier's first (31.7k, 0%, and it misses again when Claude
  Code changes its rules in that prompt), and --resume, where Claude
  Code drops the thinking blocks from the history (76% on that turn).
  A session with auto-mode tool calls and a subagent came to 76%.

Cause in magpie: affinity treated every vendor but the ChatGPT backend
as cold after five minutes (cacheCold). With two or more DeepSeek keys
or accounts (or a group over them), a conversation paused over five
minutes was handed to routing again and could go to another key, which
reads none of it from cache. DeepSeek's kv_cache guide (read 10-31)
says an unused cache is cleared "usually within a few hours to a few
days", and the 7 and 26 minute pauses above read 98–99% back.

Fix: coldAfter gives DeepSeek's own API (api.deepseek.com, Anthropic and
Chat paths alike) an hour, deepseekCold, as chatGPTCold does for Codex.
A group's rules read the same window for keepsEffort. Other vendors,
Anthropic included, keep five minutes. Nothing sent upstream changes.

Run (mote):
- TestDeepSeekConversationStaysPastFiveMinutes and TestDeepSeekColdAfter
  red on the old code ("DeepSeek, 6 minutes on: why "cold" kept false";
  "DeepSeek's cold is 5m0s"), green with the fix, beside the ChatGPT
  cold, effort and affinity tests;
  at this tree, rebased on origin/main ef8dfaa46 (affine's
  new inOrder argument taken in);
- full suite (go test -tags nogui -timeout 45m ./...) started at the
  pre-rebase tree b7545c89a and still running when this was pushed, by
  the owner's rule not to hold a verified commit behind it; a red it
  shows gets its own issue;
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/gateway.

Not tried: a real move between two DeepSeek keys (one key here); a
pause past 26 minutes, so an hour is the docs' word plus that; other
prefix-caching vendors (Kimi, GLM, OpenAI-compatible relays) keep five
minutes, their unread TTLs unmeasured (#4515).
2026-10-31 11:02:36 +08:00
yetone d159314e35 gui: a hidden window's WebView2 goes on its low memory target on Windows
molamaker11 on X: "magpie后台占用快接近600MB了。win端 这个能优化一下吗。比如剔除一些动画".

Cause. On Windows the tray panel and the main window are both made at
start and only hidden when closed, so two WebView2 renderers, the GPU
process and the browser process stay up in the tray. They were kept at
WebView2's normal memory target, so a hidden window held what it last
drew: after the window had been open, the GPU process kept ~85 MB and the
main renderer ~70 MB. Animations are not the cost: hidden pages run no
layout or style (LayoutCount/RecalcStyleCount 0 over CDP), the JS heaps
are 5 to 8 MB each, and the Go process is ~40 MB private (liveHeap 25 MB).

Fix. lowWhileHidden (memtarget_windows.go) sets
ICoreWebView2_19::put_MemoryUsageTargetLevel to LOW on each hide and on a
page that comes while the window is hidden (both windows are made hidden,
and get no hide), and back to NORMAL on each show. The page stays loaded
and running, unlike lightweight mode, whose default the owner turned off
on 10-21 because reopening reloaded the page. The vtable slot is 120:
ICoreWebView2_19's vtable holds every inherited method, counted in
WebView2.h of SDK 1.0.2210.55 (a first build that used slot 4 called
get_Source and crashed at start). zoom_windows_arm64.go's reflection walk
to the controller is now chromiumPart, shared with it. macOS and Linux:
WKWebView and WebKitGTK have no memory target magpie can set, so
memtarget_other.go is a no-op.

Numbers. xiaomi-gpu, Windows 11, WebView2 156.0.4314.50, a release build
of each (-tags production,comlauncher -H windowsgui) in its own sandbox
profile with the same seeded sessions and usage (~248 MB of Claude
projects, 72 Codex rollouts, a 4.2 MB usage.jsonl), tray start. The whole
process tree (magpie plus msedgewebview2), private working set (Task
Manager's Memory column) / commit, MB:

                                       v0.1.2297     this change
  fresh tray, window never opened      205-209/316-332   81/323
  window open, every page clicked      304/482          236/467
  1 min after closing it               265/479           69/459
  5 min after closing it               ~203/~476         64/453
  idle 15-30 min later (sampled /5min) 200-214/474-481   -

  1 min after closing, by process: GPU 85 -> 2.6, main renderer 70 ->
  7.3, panel renderer ~50 -> 1.3, browser ~30 -> 6.2; magpie itself
  ~47 either way.

The commit charge barely moves: WebView2 trims the pages out of RAM to
the standby list and the page file rather than freeing them, so the
saving is RAM other apps get, not address space.

Reopening. Three trials, each window closed 3 to 5 minutes first, the
time for a view switch and two frames over CDP: the first trial took
901 ms on the first switch after reopening (v0.1.2297: 47 ms), then
12 to 31 ms; the other two trials were the same on both builds (first
frame 132 vs 131 ms, first switch 28 vs 30 ms, then 9 to 46 ms either
way).

Run: gofmt -l internal/gui (clean); on mote GOOS=windows go vet ./...,
GOOS=windows GOARCH=arm64 go vet ./internal/gui, GOOS=linux go vet -tags
nogui ./..., go vet ./..., go build; go test -timeout 45m ./... on this
tree (057c21b30, this commit with a draft message, on 91ffe5429): 80 packages ok, internal/gui and
internal/proc red. proc: TestNoCommandBypassesProc on
internal/claudetui/child_unix.go (c59c547c5, #4491). gui: ten AppKit
tests killed at their 30s bar on mote (#4125; TestDockJoinLeadsCommandTab,
TestPanelCloseHidesIt, TestCoveredWindowStaysUp and TestMainWindowCorners
red the same at 91ffe5429 alone) and TestSettingsSaveKeepsWhatItDoesNotSend
(#4514, red at 91ffe5429 too). This change adds no code to darwin; win-run go test ./internal/gui at this head: 6 red, the
same 6 at its parent 91ffe5429 run alone (TestGatewayHeldByAContainer,
#2107/#4115; TestLodyImportHandoff, TestImportStatusUnreadableIsUnknown,
TestAionUiImportRow, TestUpdateThatWontStart, #4115;
TestSettingsSaveKeepsWhatItDoesNotSend, #4514).

Not tried: a real user's profile with plugins (no bun/node host ran in
the sandbox) or signed-in accounts; an idle of many hours on the fix
build (#2515's 28h growth); Windows on arm64 (built and vetted, not run);
a WebView2 older than 1.0.2210, which answers E_NOINTERFACE and is
logged and left alone. No unit test: the call needs a live WebView2; it was checked on the box
by the numbers above. No GUI suite: app.js is unchanged.
2026-10-31 10:57:56 +08:00
yetone b09349d179 search: magpie can search for a model whose provider searches by itself too
cybercaius on Discord: "能否强制支持联网搜索的供应商模型走代搜 API". Nothing
did this before: a provider that searches by itself (Codex, Copilot and
Grok accounts on Responses, a relay marked Searches, the search hosts) was
always sent the client's web_search, and "provider search off" and
"Search APIs first" only order magpie's own search.

Settings › Models › Web search gets one row, "Models that search by
themselves": their own (as before, the default) or magpie's. On,
settings.SearchAll makes magpieSearches true while magpie can search
(canSearchFor), so searchedForIt and translate treat the model as one that
can't search: the searcher and the search APIs answer, and the provider is
sent no search tool. With nothing magpie can search with the provider keeps
its own, and the row isn't shown. magpie's own searcher request
(searchingKey) is never turned around. The value is set on its own
(POST /api/settings/search-all) and carried by a save of the rest of the
page, so app.js is unchanged and the core budget holds. With provider
search off and this on, the searcher's note says the APIs answer every
model.

Run:
- go test -run Search ./internal/gateway ./internal/settings; ./internal/gui
  TestSettingsSearchAllSetOnItsOwn, TestSettingsSearchProviderOff,
  TestSettingsPageSave*, TestCoreScriptBudget (on mote): ok.
- TestSearchAllTakesTheSearchFromAProviderThatSearches: on with no search
  API, relayed as sent with web_search_20250305; off, native and Tavily not
  asked; on, Tavily asked and no native tool sent.
- go vet darwin, linux, windows on gateway and settings, windows on gui; gofmt.
- GUI: search-all (new), search-first, searcher-pick, search-order,
  i18n-keys in Chromium (47 pass), en zh zh-TW ja de, 1100 and 560px.
  The WebKit run was still going at the push (owner: ship at once); any
  red it shows is filed.
Broken by hand: magpieSearches returning false, and without the
canSearchFor guard, the gateway test goes red; without the merge line in
api.go TestSettingsSearchAllSetOnItsOwn goes red ("a save of the page
dropped searchAll"); the old settings.js and i18n fail 15 of 20 GUI cases.
search-first now reaches its row before clicking, since the new row moved
it below the fold.
Not tried: real Codex, Copilot or Grok accounts with it on. Codex sign-in
turns relayed as sent (codexAsSent) and sealed relays keep the native
search; the Routing page's webSearchOf still says native.
2026-10-31 10:33:50 +08:00
yetone c420559fdf usage: a search API's asks, and a plan's own searches, are rows of the request log (#3528)
cybercaius on Discord: "能记录代搜 API 的用量信息吗,在使用过程中看不到它用了哪些代搜 API".
Nothing recorded which search API answered a search, how often, or whether
it failed.

Each ask of a search API (askSearchAPIKeys) and each search sent to Kimi
Code's or WorkBuddy's own search service (ownSearch) is now a row of
Usage › Requests, source "search" (usage.SourceSearch, kind web_search):
the vendor or plan, the host asked, ok / found nothing / refused / the
error, and the time. The row is a probe: it is listed, never counted in a
total or a chart, and never exported. Telemetry reads no usage rows, so
nothing is added to it. The query is not written: an error's text is
scrubbed of it (url.Error reduced to op and host, and the plain,
QueryEscape and PathEscape forms replaced). The Usage page badges the row
"Search API", or "Web search" under a plan's provider, muted.

Run (rebased on 3e5aa1151):
- go test ./internal/gateway ./internal/usage ./internal/settings
  ./internal/budget on Linux (WSL magpie-desktop): ok. With -tags nogui
  there the root package is ok; internal/cli and internal/gui were still
  running at the push (owner: ship at once), any red they show is filed.
- TestSearchAPIAsksAreLogged, TestSearchAPIFailureKeepsNoURL,
  TestOwnSearchIsLogged, TestWorkBuddyPluginSearches,
  TestSearchAPIRowsListedNotCounted; TestCoreScriptBudget ok.
- go vet for darwin, linux and windows on gateway, usage, settings; gofmt.
- usage-ledger-search.test.cjs in Chromium and WebKit, en zh zh-TW ja de,
  wide and narrow; i18n-keys.
Broken by hand: without logSearch the gateway tests go red; with the
query left in an error's text TestSearchAPIFailureKeepsNoURL goes red;
with IsProbe not naming search, the totals test goes red; the old page.js
fails the GUI test.
Reds the same at base 3e5aa1151, filed: usage-ledger, -chart, -ttft,
-open-settled (#3104, #4078, #3001, #4263, #4489); internal/agent on Linux
(#4033).
Not tried: real Tavily, Kimi Code or WorkBuddy accounts; the Routing page
shows no search rows; the whole GUI suite.
2026-10-31 10:32:00 +08:00
yetone 2f40cf4280 gateway: an In order group gives a conversation back to its first member at the next turn
yyhhyyyyyy on Discord made an Opus 5.5 group In order: an API key first,
a Claude subscription second, and 8 of 10 Claude Code requests went to
the subscription. With both healthy the plan is in order and every
request goes to the key. The cause is affinity: one failure of the key
(a 429, a 5xx, a rest) sent a conversation to the subscription, and Auto
affinity's "cache" kept it there at every turn after, since each turn
reads what the last wrote, while the key stood first and ready. A
provider's fallback already gave a conversation back (backToMain, "main");
a group's later member never did.

Now, in a group routed In order with Stays left on Auto, a new turn goes
back to the first ready member when that is another member than the one
that answered last (backToFirst, Affinity.Why "order"). Another key or
account of the same member, or a group in the group, keeps its own
affinity. Within a turn the conversation stays, on the reasoning the
later member sealed, as with "main". Stays: Session and Strict are the
user's own setting and keep it where it is. Smart and the other routings
keep it by its cache as before.

The Routing page says why it moved, for "order" and for a fallback's
"main", which showed no reason at all before (affWhy), in en, zh, zh-TW,
ja and de.

What was run (at the rebased head unless said):
- go test ./internal/gateway -run 'TestOrderedGroupGivesTheConversationBackToItsFirstMember|TestGroupMemberKeepsTheConversationOnceAnotherIsBack|TestFallbackGivesTheConversation|ChatGPTCold|LoginSwitch|LoneAllowance|Affinity' on mote: ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build on mote, before the rebase: all ok.
- GUI in WSL magpie-desktop, Chromium and WebKit, 1100 and 420 wide,
  every language: routing-affinity-order, routing-affinity-cache-write and
  i18n-keys 44 of 44 before the rebase; routing-affinity-order and
  i18n-keys again at the rebased head.

Broken by hand:
- the "order" case turned off (old behaviour): the new Go test fails,
  "answered by ssssssssss, want ssskkkkkkk" and why "cache", want "order".
- the Within and Session guards removed: "the key failed once" fails with
  skkkkkkkkk, and "Stays: Session" with skkkkkkkkk, want ssssssssss.
- client.js put back: routing-affinity-order 0 of 10 in Chromium
  ("order: goes in order not in").

Not tried: the reporter's own key and subscription (the subscription is
the test's fake Claude Code); that a failure of the key is what moved the
reporter's sessions is the likeliest cause the code shows, not confirmed
from their trace.

Full suite: go test -tags nogui -timeout 45m ./... on mote at the
pre-rebase head: 80 packages ok, two red. TestRuleTimeWindowAtTurnStart
("a 5 b 2") was this change: its group is In order, so turn 2 of "sess",
after the rule's hours, now goes back to a; the test now asserts that
turn's answerer and counts a 5 b 2. TestNoCommandBypassesProc
(internal/claudetui/child_unix.go:32) is red on main, #4491. At the
rebased head, go test ./internal/gateway -run
'Rule|Affin|Order|Group|Stay|Sticky|Cache|Turn|Fallback|Main|Cold|Login|Lone'
on mote: ok (107s).
2026-10-31 10:30:50 +08:00
yetone 03f3e1528b gateway: Qwen-Image and Wan 2.7 image models draw on DashScope's own API, so qwen-image-3.0-pro no longer draws nothing (judi0713)
judi0713 on Discord (v0.1.2288): qwen-image-3.0-pro draws when called
directly, but through magpie answers 502 "qwen-image-3.0-pro drew
nothing". DashScope documents its Qwen-Image and Wan 2.7 image models on
its own multimodal-generation API only (docs.qwencloud.com "Qwen-Image
text-to-image", and the Token Plan's "Integrate multimodal generation"):
a POST to <host>/api/v1/services/aigc/multimodal-generation/generation,
answered with the images at output.choices[].message.content[].image.
magpie sent them to the OpenAI images API at /compatible-mode/v1 and, on
its 404, to chat completions, whose answer holds no image it reads. Which
of the two answered the reporter is not seen from here.

Now, on a DashScope provider (dashScope(): Bailian, Model Studio, the Qwen
AI platform and Qwen Cloud, pay as you go and Token Plan, by preset or
host) a model named qwen-image* or wan2.7-image* draws there
(draw_dashscope.go, from drawImages):
- the prompt and any input images (data URLs) as one user message,
  parameters watermark false, n when over 1, size as W*H;
- every image of every choice is read; with none, the error says what
  DashScope said (message and code), the model's text, or the
  finish_reason;
- a mask or a ratio size is a 400 saying what to send instead, with no
  request made.
The root is the provider's Chat (or Anthropic) base cut at
/compatible-mode/, /apps/ or /api/v1. Every other provider and model is
unchanged (TestDashScopeDrawsScoped). /v1/images/generations and
/v1/images/edits both go through drawImages, and magpie's generate_image
MCP draws through those two, so all three are covered.

The fixtures are the documented response bytes, not a live answer.

Run (mote, at b06df2557 on 3e5aa1151):
- gofmt -l: clean.
- go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -tags nogui ./... -timeout 45m -count=1: every package ok
  (gateway 745s) except two reds already filed, in code this doesn't
  touch: internal/gui TestColdTurnsTaken (#4510) and internal/proc
  TestNoCommandBypassesProc (claudetui/child_unix.go, #4491).

Broken by hand: drawImages' dispatch made `if false && dashScopeDraws`:
TestDashScopeDrawsOnItsOwnAPI, TestDashScopeEdits and TestDashScopeSaysWhy
go red (the fake answers 404 off its native path).

Not tried:
- No real Qwen Cloud or DashScope account: no request reached Alibaba.
- The chat fallback's parse of a {"image": ...} part is unchanged.
- Older Wan text-to-image models (an asynchronous task API) and video
  are left as they were.
- No GUI change, so no GUI run.
2026-10-31 10:15:15 +08:00
yetone 0d5df496aa library: a server kept direct is given to Codex as its command, so Codex starts it in the thread's folder (#4382)
cuipengcx90 on #4382 (and nifengfanpan0853 on Discord): with cocoindex set
to direct, Claude and Pi start it in their own folder, but Codex on magpie
was still given `url = "http://127.0.0.1:3425/mcp/run/cocoindex"`. magpie's
/mcp/run (#3885) starts the command from home, so cocoindex answered "Run
`ccc init` in your project root". syncMCP now leaves a direct server out of
runVia, so Codex's entry is the server's command, args and env, as it is
for every other agent, with the hub on or off. runSpecOf, which serves
/mcp/run before a sync has recorded what it gave, no longer runs a direct
server either. A shared server is still run by magpie for Codex, as before.

No `cwd` is written: Codex's codex-mcp make_rmcp_client builds its
LocalStdioServerLauncher with the session's config.cwd as fallback_cwd,
used when the entry has no cwd (openai/codex 67f0994,
stdio_server_launcher.rs launch_server). RawMcpServerConfig takes command,
args, env, env_vars and cwd for stdio.

Siblings: runVia is the only place a command server becomes a URL
(runsFor needs fmtCodex). Every other format is given the command and
starts it itself; npxDirect (node in place of npx) and side (WSL image
server) keep it a command; magpie writes no cwd for any agent. Project
MCP files never went through runVia.

Run:
- TestRunDirectServerIsCodexsCommand (new): red on the old code with the
  issue's exact entry, `url = "http://127.0.0.1:3425/mcp/run/cocoindex"`,
  when the syncMCP guard was taken out by hand; red again with only the
  runSpecOf guard taken out ("before a sync /mcp/run would start the
  direct server true"); green with both.
- mote-run: go test -tags nogui ./internal/library (ok, at the rebased
  head 1a2ce7b8e), ./internal/cli ok, ./internal/proc FAIL
  TestNoCommandBypassesProc on internal/claudetui/child_unix.go, which is
  #4491 (on main, not this change).
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: all ok on mote.
- Real Codex: codex-cli 0.165.0 on mote, a sandbox HOME and CODEX_HOME, a
  config.toml entry shaped as magpie now writes it (command, args, env,
  no cwd) for a tiny node stdio server that logs its cwd. Run from
  ~/elsewhere with `codex exec -C <proj>`: the server logged
  cwd=<proj> K=v, the thread's folder, not Codex's own.

Not run: the full go test ./... (another session's full suite was on
mote; one per machine). No GUI change. Not tried: real cocoindex, Codex's
app-server (the desktop app) with a thread whose cwd differs from the
app-server's, and a real magpie sync writing the entry for a real wired
Codex (the unit test covers those bytes).
2026-10-31 10:14:03 +08:00
yetone 1a2ce7b8ef agent: a model picked in Claude Code's /model beside a Claude main runs at its own window, not 200K
young02036 on Discord put Codex Plus gpt-6.1-sol (500K) and Claude opus 5.5 (1M) in one routing group, with Context set to the smallest member's (500K). Each model picked on its own showed its window. The group showed 200K.

Cause: with the main model one of Claude's own, marked [1m], magpie tells Claude Code no window. Anthropic runs that model at its own window, so claudeWindow is 0 and no CLAUDE_CODE_MAX_CONTEXT_TOKENS is written. writePicker still lists every magpie model and group in /model. Claude Code 2.1.314 runs an id it doesn't know as Claude's at that MAX, and with no MAX at its own 200K. So group/mix and w/gpt-6.1-sol picked there ran at 200K.

Fix: pickerApart takes desktopPlan's path when four things hold:
- the main is a Claude model or a group of them;
- claudeWindow is 0;
- /model offers a row that is unmarked;
- that row isn't Claude's and has a known window.
desktopPlan also counts the picker rows (pickerRefs). The top MAX is then the largest window, and each smaller row gets its own modelSettings.<id>.autoCompactWindow. A group gets its smallest member's window, the same as every other agent; under Full window that is 500K uncapped.

Every other main is as before. A told window still serves a /model pick, and a main of no known window keeps the last one. Codex, OpenCode, DSH, Pi and the rest already list the group at 500000: they read the catalog's Context, which for a group is its smallest member's.

Real Claude Code 2.1.314, in a sandbox HOME against a fake Anthropic server, with `-p --model X "/context"`:
- old layout (no MAX): group/mix 200k, w/gpt-6.1-sol 200k;
- new layout: group/mix 272k, gpt 272k, glm 204.8k, claude [1m] 1m;
- new layout without the group's entry (Full window): group/mix 500k.

- go test -tags nogui ./internal/agent/: ok (289s), on the base before the rebase (576b5dcbc)
- at 3e5aa1151, after the rebase: go test -tags nogui -run 'Window|Picker|Context|TierEffort|Budget' ./internal/agent/: ok
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok
- gofmt -l: clean
- full suite (go test -tags nogui -timeout 45m ./...) at 3e5aa1151: still running at push, per the ship-immediately rule; any red gets an issue

Broken by hand: with pickerApart's term forced false, TestPickerModelsTheirOwnWindow is red with 10 errors ("a Claude main: group/mix in /model compacts at ""; want "272000"", MAX "" want 1000000, and so on). Earlier versions of the trigger turned five existing tests red (TestClaudeContextWindow, TestClaudeDesktopContextWindow, TestClaudeTierEffort, TestTypedWindowReachesCodexAndClaudeCode, TestLargestMemberTypedWindow), so the trigger is limited to a Claude main.

Not tried:
- the interactive /model switch (only `-p --model`);
- the reporter's real accounts;
- confirmation from the reporter that the agent is Claude Code.

Left alone, filed as #4509: a /model pick smaller than a non-Claude main's told window runs on the main's window.
2026-10-31 10:11:07 +08:00
yetone d35509b65b agents: a custom provider's picked API is the one its models are asked on, and a model named like a routing group stays plain (nb5p)
nb5p on Discord: (1) a custom provider set to Responses had its models
wired into dsh on magpie's Chat Completions route (`magpie`), so dsh sent
Chat and magpie translated; (2) in dsh's models, mygateway/gpt-6.1-sol was
"GPT-6.1 Sol" while mygateway/gpt-6.1-terra was "GPT-6.1 Terra · MyGateway".

Cause 1: Provider.Native never read BaseAPI, the API the user gave the
Base URL as. Detect fills in every API that answers, so a relay picked as
Responses also had a Chat URL, and Native returned Chat (out[0]). Native
now takes BaseAPI after the vendor rules (ResponsesFirst, MessagesFirst),
when the provider serves it. dsh supports it: dsh 0.2.1-rc.2 bundles
@earendil-works/pi-ai, whose KnownApi includes "openai-responses", and
magpie already has the `magpie-responses` route (dshKinds). Siblings
reading m.APIs from magpieModels move with it: dsh, Pi, omp, droid,
Grok Build.

Cause 2: provider.Labels counted collisions over models and routing
groups together. A model two providers serve gets an auto group with the
model's name, so the shown model collided with its own group and kept
"· Provider" (terra: served by a second provider too, hidden for dsh;
sol: one provider). Models and groups are counted apart now: a model
keeps its suffix only when another model reads the same, and a group
named like anything else keeps "· routing group". Labels feeds every
agent's list, so this holds for all of them.

Not changed: the gateway's usable() still orders a translated request
Chat first and doesn't read BaseAPI (#4508).

Tests (each red on the old code, broken by hand in a worktree on
origin/main: all new cases red; reverting only Native red on the route,
reverting only Labels red on terra's name; the old dsh output reproduced
the report exactly):
- internal/agent TestDshCustomResponsesProvider (new): both models on
  magpie-responses, none on magpie, named "GPT-6.1 Sol"/"GPT-6.1 Terra".
- internal/provider native_test: Responses picked beside Chat, Chat
  picked, Responses picked for a Claude where Messages is served, and
  Responses picked with no Responses URL.
- plainnames/plainown_groups/suffix_mode expectations updated to the rule.

Run on mote, at this change on 7fe191cec (the pushed head is the same
change rebased on a newer origin/main, 6f435677c; not re-run there):
go test -tags nogui -count=1 -timeout 45m ./internal/provider
./internal/agent ./internal/gateway ./internal/cli ./internal/gui:
provider ok 170s, agent ok 303s, gateway ok 797s, cli ok 53s; gui FAIL
TestColdTurnsTaken only (0.00s, a test race untouched by this change,
filed #4510). gofmt -l clean. Still running at push: TestColdTurnsTaken
-count=20 and GOOS=linux/windows go vet ./... on mote, and the test on
origin/main alone.

Not tried: a real dsh session against a real Responses relay; nb5p's
own providers.json (the second provider serving terra is inferred from
the suffix); the GUI suite (no GUI file changed); the full ./... suite.
2026-10-31 10:08:40 +08:00
yetone 3e5aa11519 provider: Qwen Cloud, Alibaba's international Qwen platform, is a preset with its regions and Token Plan (judi0713)
judi0713 on Discord (v0.1.2288) asked for Qwen Cloud (qwencloud.com).
Its keys are its own, made at home.qwencloud.com, and serve neither
DashScope's nor Bailian's hosts, so none of magpie's Qwen presets took
them.

Two presets, the way Alibaba's other pay-as-you-go/Token Plan pair is
modelled, because each key gets 401 at the other's host:

- qwencloud: pay as you go, sk-ws- keys, at
  https://{region}.maas.qwencloudapi.com/compatible-mode/v1 (Chat) and
  /apps/anthropic (Messages), in six regions named by their ids as
  Alibaba's docs name them: ap-southeast-1 (the default), us-east-1,
  eu-central-1, ap-northeast-1, cn-hongkong, cn-beijing. Catalog alibaba.
- qwencloud-token-plan: sk-sp- keys, token-plan.maas.qwencloudapi.com,
  Singapore only, with the plan overview's text models.

Endpoints, regions, key prefixes and the plan's models are from
docs.qwencloud.com ("Regions and endpoints" and the Token Plan
overview), not guessed. Responses is left out, as in the other
Qwen presets.

The gateway's dashScope() now knows both presets and the
*.maas.qwencloudapi.com hosts, so a Qwen Cloud stream gets the same
enable_thinking handling a DashScope one does. Import (presetAt), the
CLI's region= and magpie://import?preset=qwencloud&region=... map to it.
docs/reference.md, the CLI help and the site's import page (en, zh, ja)
name them. Region names are ids, so no string is new to i18n.js and
nothing in the GUI changed.

Run (mote, at 708213f65 on c272e5582; after it the commit was rebased on
876d477d7, which touches none of these files, and the new helpers' comment
was moved above bedrockRegions' doc comment, no code changed; at the pushed
head the provider tests below ran again, ok):
- gofmt -l: clean.
- go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -tags nogui ./... -timeout 45m -count=1: every package ok
  (gateway 804s, provider 205s) except two reds already filed, in files
  this doesn't touch: internal/proc TestNoCommandBypassesProc
  (claudetui/child_unix.go's exec.Command, #4491) and internal/update
  TestRelaunchOpenTriedAgain (TempDir cleanup not empty, #3881).
- At the pushed head: go test ./internal/provider -run
  'TestQwenCloud|TestQwenTokenPlan|Preset|TestParseImport': ok.
- No GUI change, so no GUI run.

Broken by hand:
- Preset ids renamed: TestQwenCloud red ("no preset qwencloud-token-plan").
- gateway.go's dashScope() back to main: TestDashScopeHosts red on the 5
  new Qwen Cloud entries; the maas.qwencloudapi.com.example case stays
  not-DashScope.

Not tried:
- No real Qwen Cloud key: no request went to qwencloudapi.com.
- The decision model (decide.go's bailianDecides hosts) doesn't know
  Qwen Cloud, and image models on these presets are the next commit's.
- The site isn't deployed by this commit.
2026-10-31 09:58:04 +08:00
yetoneandggbdpq 7fe191cec0 gateway: OpenCode Go's bare 400 (a model name, no error) is a 502 that rests nobody (#3740)
OpenCode's gateway answers some of s-leeq's turn-start requests with a
400 whose body is {"model":"deepseek-v4.1-flash"} and nothing else: no
error, message, code, type or param, nothing in or out, no reply id.
retryable() read it as the request's own fault, so a group stopped there
and a lone provider's turn ended on it, with a 400 nothing retries. Their
log ties it to the request, not the key: 30 of 214 requests carrying
~246K tokens of tools failed so, none of 420 under 1K, and the same
request was answered 200 some 13s to 25s after the first refusal.

openCodeBareRefusal (ported from ggbdpq's patch on the issue) reads a
400 from an OpenCode host whose body is a JSON object naming no error
field as the 502 it stands for (asBadGateway). A group asks its next
member; a lone provider is asked again within its patience (60s, with
replan pauses), which outlasts the reporter's window. Any 400 that names
something, a body that isn't a JSON object, and every other vendor's
400 go on as they came.

Changed from the patch:
- restAfterMarked rests nobody for this 502. The patch rested the key
  for fallbackCooldown in a group (a scratch test showed ocgo resting
  60s), over a refusal tied to request content: one heavy prompt would
  have set aside a key that serves every other request.
- The body is read through a 64KB limit and put back with a
  MultiReader, so nothing is cut; a body at the limit is left alone.
  The patch read it whole.
- TestOpenCodeGoBare400ToldAs502 asserts at least 3 asks, not exactly
  3: on current main the lone provider's patience asks 15 times.

Run on mote:
- At the pushed head (on c272e5582): gofmt -l clean; go vet
  ./internal/gateway for darwin, linux and windows; go test
  ./internal/gateway -run 'OpenCode|Rest|Fallback|Patience|Retry' ok (83s).
- On 576b5dcbc, before main took four more gateway commits
  (82ff88933..c272e5582): go test ./internal/gateway -count=1
  -timeout 45m ok (615.8s).
- TestOpenCodeGoBare400AskedAgain, ToldAs502, RestsNobody (new: a group
  of OpenCode Go and another provider; the first request's bare 400 is
  served by the other, the next request still reaches OpenCode) and
  TestOpenCodeGoError400Untouched pass.
- Before the rebase, the package was red only in
  TestClaudeCallerEnvironmentInAMessageIsTheLastGiven, which 576b5dcbc
  fixed on main since.

Broken by hand:
- rest exemption off (`if false &&`): RestsNobody red, "OpenCode asked
  1, the other 2".
- openCodeBareRefusal taken out of forwardOnce: AskedAgain, ToldAs502
  and RestsNobody red; AskedAgain shows the issue's exact 400.
- A real-time scratch test (refusals for 25s, 2.5s each, the real
  retryPause, lone provider) got its 200 after 32s, asked 6 times.
  Deleted after.

Not tried: a real OpenCode Go key or the reporter's DeepSeek Harness; the
bodies are the issue's bytes. A turn whose refusals outlast 60s still
ends, now as a 502 the client can retry.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-31 09:43:07 +08:00
yetoneandggbdpq c272e55825 gateway: any model's 8.0 in a call's arguments reaches the agent as 8, not only Grok's (#3152)
1024MrL's Codex, on opencode-go/muse-spark-1.3-contributor through the
gateway, had every tool_search turned away before it ran ("failed to
parse tool_search arguments: invalid number" over {"limit": 8.0}), and
exec_command the same ("floating point `2000.0`, expected usize").
grok_integral.go's whole-number rewrite (#1431) already fixes exactly
this, but it ran only when the model was Grok's.

Decision (delegated by the owner): the rewrite runs for every model,
not narrowed to Grok. Why:
- The defect is the model's, not a vendor's: Grok (#1431) and muse-spark
  (#3152) both write it, and no list of models would stay complete.
- The rewrite changes only a number written with a fraction of zeros and
  no exponent, to the same JSON number. Strict parsers break on 8.0
  (Codex's serde u64/usize/i32, Go's json into an int), while every
  float-typed field takes 8 (serde f64, Go float64, JS). The one visible
  difference is a Python client's json.loads giving int 8 for float 8.0,
  which any `number` schema allows.
- Strings, keys, other fractions (2.5, 2.50) and exponents (1.0e3) stay
  as written, held by integralCases' edges case.
- The reporter ran it end to end on Windows with real Codex 0.163 and
  muse-spark: 6 of 7 and 20 of 21 calls refused without it, 0 with it in
  two runs (thread, 10-23).
Gemini routes are left as they were: their call arguments are an object
the client decodes itself, and no report shows the shape there.

What changed:
- passthrough installs intTidy on every Responses, Chat and Messages
  reply; translate's Request.Grok and grokServed are gone, encoder wraps
  every reply in wholeEncoder and render runs wholeResult. grokModel
  stays for grok_schema.go.
- crTidy (glm-5.3-flash*'s stitched CR, #4256) now runs before intTidy,
  in the stream, the held-tail chain and the drain. With intTidy on every
  route, a whole reply it held went from its flush past crArgs, so the
  CR cure never saw it (added in this port: the patch's comment gave a
  different reason).
- intTidy's flush says a whole reply with no call marker as it came,
  without decoding it (added in this port), since every model's whole
  reply now reaches it.
- TestOnlyGrokCallsGetIntegers (which held the old scope) became
  TestOtherModelsCallsGetCodexIntegers; TestGrokCallsByUpstreamName is
  gone; TestToolSearchWholeFloatLimitGivesCodexIntegers is the report's
  shape; TestStitchedCRAndWholeFloatsBothGo (added in this port) holds
  both cures on a glm-5.3-flash route, whole and streamed. Its whole
  case reads the input's fields as written, not through a decode and
  encode, which would print 8.0 as 8 and pass on the old code.

Run at this head (rebased on 2c5d9101b, after #2580's held line in
passthrough's write), on mote:
- go test -tags nogui -count=1 -run 'TestWholeNums|TestGrok|
  TestOtherModelsCallsGetCodexIntegers|TestToolSearchWholeFloat|
  TestStitchedCRAndWholeFloatsBothGo|StitchedCR|TestCRLeavesHealthy|
  TestCRDropper|TestPluginStreamLargeReplies|TestQuietWholeReplyStreamed|
  TestTextWritten|TestChatStreamCut|TestPassthroughStream|TestNameless'
  ./internal/gateway: ok (61s).
- go vet -tags nogui ./internal/gateway on darwin, GOOS=linux and
  GOOS=windows: clean. gofmt -l: clean.
- At the review tree: the -run family above (without the last three)
  with -race -count=2: ok.
- Not run before the push: the whole gateway package and ./... (the
  package runs in the background after).

Broken by hand:
- gateway.go, grok_integral.go and ir.go back at origin/main, tests
  kept: TestToolSearchWholeFloatLimitGivesCodexIntegers fails "deltas:
  limit is 8.0 in {"query":"exa web search","limit":8.0}, want 8";
  TestOtherModelsCallsGetCodexIntegers fails "deltas: yield_time_ms is
  2500.0 ..., want 2500"; TestStitchedCRAndWholeFloatsBothGo fails in
  both subtests ("limit":8.0).
- the rewrite on every route but the old order (ints before crArgs):
  TestStitchedCRAndWholeFloatsBothGo/whole, TestChatReplyToolArgsLoseStitchedCR
  and TestAnthropicWholeRelayedToolArgsLoseStitchedCR fail with the
  stitched \r kept.

Not tried: a real muse-spark or Codex run by this port (the reporter's
runs stand in); a Gemini client. Risk not covered: a vendor that streams
SSE labelled Content-Type application/json. eventStream reads that as a
whole reply, and intTidy, now on every Responses, Chat and Messages
route, holds a whole reply to its flush, so such a stream would reach
the client only at its end, on every route rather than Grok's alone
(crTidy and chatWhole already hold such bodies on theirs). No vendor was
checked for it; a report of a stream arriving all at once points here.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-31 09:38:21 +08:00
yetoneandggbdpq df1c3dace3 gateway: a relayed stream cut mid-line sends no half event ahead of its error (#2580)
A passthrough stream the upstream reset inside an event (YonQua: Z.ai's
glm-5.3 under pi) sent the half event's data line on to the client, and
pi's SSE parser died on its JSON ("malformed server-sent event JSON")
before it reached the error event magpie appended after it (#2446 put
that event on its own line; the half line ahead of it was still there).

passthrough's write now holds a stream's last unended line back until
its rest arrives; only lines that ended go out as they come. A reply
that ends whole puts the held line out as it came. When a failure is
appended (streamFailure, or the finish_reason filled in for Gemini's
OpenAI-compatible API) the held line is dropped first, unless its data
parses (whole JSON, or [DONE]): that one is no half event and goes out
before the failure, as on main. A non-stream reply is written unheld.

Changes made to gua2100's patch (ggbdpq/magpie hunt/2580-midstream-reset
30288fe28), both regressions it brought, each red with the patch as
posted:
- a gathered stream (a plugin's Responses account asked for one body,
  plugins#112) returned before the held line was put out, so a stream
  whose response.completed had no newline after it became a 502 "ended
  before it was complete": TestGrokPluginNonStreamLastLineUnended.
- a reset after an event's JSON was whole but before its newline dropped
  that whole event, which main delivers:
  TestChatStreamCutAfterWholeEventKeepsIt.

Tests: TestChatStreamCutMidLineLeavesNoHalfEvent (gua2100's; severed
gained a Chat shape) red on origin/main 5c1ccec4a's gateway.go:
"passthrough_severed_test.go:190: a half event the upstream never ended
went to the client as data". The two above pass on main and fail on the
posted patch. Broken by hand: dropHalf's parse check made always true
(every half line kept), TestChatStreamCutMidLineLeavesNoHalfEvent red
again; restored, green.

Run at this head (rebased on 82ff88933), on mote: go test -tags nogui
-count=1 -run for the new tests and their neighbours
(TestChatStreamCut*, TestGrokPlugin*, TestPassthroughStream*,
TestPassthroughResponses*, TestLoopCutMidLine, TestGeminiCompat*,
TestTranslate*SeveredUpstream, TestStreamCut*, TestGeminiRelayEndedShort,
TestGatheredTextOnlyStream, TestPluginStreamLargeReplies, TestKeepalive*,
TestRequestBodyProgressRenewsIdleDeadline, and #1475's TestNameless* and
TestWhole* beside it) ok (27.6s); gofmt -l clean. At the review tree
(5c1ccec4a): go vet -tags nogui ./internal/gateway on darwin,
GOOS=linux, GOOS=windows clean. Not run before the push: the whole
gateway package and ./... (the package runs in the background after).

Not tried: a real Z.ai stream reset mid-line, a real pi client; a
translated route (the translators read events with readSSE and write
whole events of their own, so they don't forward a half line).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-31 09:34:29 +08:00
yetoneandggbdpq 82ff889338 gateway: a Chat tool call naming no function is dropped, not sent for the client to refuse (#1475)
AricRedemption on #1475: a long Qoder turn ended with an upstream tool
call whose function.name was no string, and the AI SDK refused the
whole reply ("Expected 'function.name' to be a string"), not retryable
and with the call already in the history, so every "continue" died
there while the gateway logged status=200 done=true. The parsers for
calls a model writes into its text already refuse a nameless one, but
calls an upstream made itself went out as they came.

A call whose function names nothing in a JSON string (absent, null,
another kind) is dropped on every path a relayed Chat reply leaves by:
a stream (chatTidy.nameless, its later fragments with it, and the id
mend no longer gives the dropped fragments an id back), a whole reply
(wholeNameless in chatWhole) and a whole reply given as the stream the
agent asked for (chatWholeEvents). A finish of tool_calls with no call
left ends stop. An empty string name goes as it came. Translated routes
are unchanged: their names are Go strings by construction.

Changed from gua2100's patch (hunt61-a-1475-unnamed-call, d851d922f):
- chatWholeEvents turned the finish to stop whenever any call was
  dropped, so a named call beside a nameless one went out with finish
  stop and the client ended its turn without running it; it now does so
  only when no call is left. The calls it keeps are numbered 0.. with no
  gap where a dropped one stood, and a call with no function object is
  dropped there too, as wholeNameless already did.
- chatWhole turned any whole reply ending tool_calls with no named call
  into stop, a reply that came with no tool_calls at all included; it
  now does so only when wholeNameless dropped a call.
New tests for both: TestNamelessCallBesideAGoodOneWholeAsStream,
TestToolCallsFinishWithNoCallsStaysWhole.

Run at this head (451c7e929 on 576b5dcbc), on mote:
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
  (528s). The first try at e53ba61f4 was red only on
  TestClaudeCallerEnvironmentInAMessageIsTheLastGiven, red 2 of 20 on
  origin/main too; fixed at its cause in 576b5dcbc, under this commit.
- go test -tags nogui -count=1 -run '^(TestNameless|TestNameAbsent|
  TestToolCallsFinishWithNoCallsStaysWhole|TestChatCallsEndToolCalls|
  TestEmptyCallID|TestStreamedCallGivenAnID|TestTextWritten|TestDSML|
  TestQuietWholeReplyStreamed|TestPluginTextWrittenCall|TestChatTidy|
  TestGeminiCompat|TestWhole|TestRelayed)' ./internal/gateway: ok.
- go vet -tags nogui ./internal/gateway on darwin, GOOS=linux and
  GOOS=windows: clean (at the review tree). gofmt -l: clean.
- Not run: go test ./... across every package.

Red on main: with chattidy.go, whole_stream.go and chat_call_ids.go
from origin/main, 7 of the 8 new tests fail, e.g.
TestNamelessCallStreamDropped "calls map[], finish \"tool_calls\"" and
TestNamelessCallBesideAGoodOneWholeAsStream "[{Index:0 ID:call_bad
...} {Index:1 ID:call_up ...}]" (TestToolCallsFinishWithNoCallsStaysWhole
guards unchanged behaviour and passes there).
Broken by hand:
- the patch's own chattidy.go and whole_stream.go:
  TestNamelessCallBesideAGoodOneWholeAsStream fails with
  "[{Index:1 ID:call_up ...}], finish \"stop\"" and
  TestToolCallsFinishWithNoCallsStaysWhole with finish "stop".
- the `calls = nil` clearing removed: TestNamelessCallWithoutAnIDStaysDropped
  "the call dropped for naming no function came back with an id".
- wholeNameless not called in chatWhole: TestNamelessCallWholeDropped
  "calls [{call_up ...}], finish \"tool_calls\"".

Not tried: a real Qoder subscription or the reporter's exact reply (the
report says replays came back well formed; fixtures are synthetic with
the shape the client's error names), a real AI SDK client. Not covered:
a relayed stream that keeps a named call beside a dropped one keeps the
upstream's index numbers, so a gap is left where the dropped call stood;
Responses and Anthropic relays (responsesWholeEvents,
anthropicWholeEvents, passthrough) forwarding a nameless function_call
or tool_use, which has no report.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-31 09:33:09 +08:00
yetone 9345318ff7 gui: Codex's Long conversations lines fit the core budget, no raise (zgjfjfl on Discord)
5c637f17b raised the core script budget from 1,537,356 to 1,537,669 for
Long conversations' two Codex lines. Size budgets are never raised, so
this puts it back at 1,537,356 and makes the lines fit under it. The
core is 1,537,351 bytes now, 314 less than at 5c637f17b.

- The server writes the config key list as the row shows it
  ("[profiles.work] key = value, ...", codexKeysText) in
  codexCompactKeys, where the page built it from codexCompactHeld's
  objects. The window's size comes formatted too (tokensSize, "128K"),
  under the "n" slot of the row's words, so the page passes the struct
  to t() whole.
- The two lines go through one helper. Their English words are shorter:
  "Codex's config.toml sets {keys}, read before Long conversations" and
  "Codex compacts {model} at 90% of its {n} window, before Long
  conversations; set a larger one in its provider's Context window". The
  zh, zh-TW, ja and de translations keep their words under the new keys.
- The row draws the same lines, button and drop as before.

Run, at origin/main a808c31a7 plus this change:
- mote-run: node --check app.js; go vet -tags nogui ./internal/gui for
  darwin, linux and windows; go test -tags nogui -run
  'TestCodexCompactHeld|TestCodexWindowUnder|TestCodexKeysText|
  TestCoreScriptBudget|TestI18n' ./internal/agent ./internal/gui: ok.
  gofmt -l: clean.
- wsl-run (mote's Playwright WebKit launch hung earlier today):
  codex-compact-held, i18n-keys, codex-async-compact, compact-at and
  compact-one-value: 64 of 64 ok, Chromium and WebKit, every language.

Broken by hand: codexKeysText without the profile turned
TestCodexKeysTextAndSize red with the profile missing from the line.

Not tried: the real app with a real config.toml after this change; the
full GUI suite.
2026-10-31 09:17:24 +08:00