Commit Graph
1447 Commits
Author SHA1 Message Date
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
yetone 5c637f17b2 gui: Long conversations says what makes Codex compact before it (zgjfjfl on Discord)
zgjfjfl set Long conversations to "Compact at 544K", and Codex still
compacted every conversation at about 128K. The model is gpt-6-A, with no
context size set on the provider, on v0.1.2281.

Codex 0.165 compacts at min(model_auto_compact_token_limit, 90% of the
window). magpie writes the model's window into the catalog and writes
auto_compact_token_limit only when Long conversations is below that
window. Two things put Codex under 544K, and the row said neither:

- ~/.codex/config.toml's model_context_window or
  model_auto_compact_token_limit, at the top or in a profile, which
  Codex reads before magpie's catalog. The row now names each key, with
  its profile and value, and "Take it out" removes those lines
  (agent.CodexCompactHeld, DropCodexCompactHolds,
  POST /api/settings/codex-compact-held/drop). Nothing is removed unless
  the user clicks.
- The model's own window. gpt-6-A isn't in models.dev, so its window
  comes from the provider's own /models list (context_length). A relay
  that lists it at 128K makes Codex compact at ~115K, and no Long
  conversations value can raise that. The row now names the model Codex
  runs (agent.CodexModel, from config.toml's model and the picked
  profile) and the window magpie tells Codex, and says a larger one is
  set in the provider's Context window (codexWindowUnder).

Which of the two the reporter has is not known: their config.toml and
their relay's list weren't seen.

Run (worktree at origin/main a6951cc63, through mote-run):
- Real Codex 0.165 against a fake Responses server in a sandbox HOME:
  config.toml model_context_window = 128000 made it compact at ~115K
  with Long conversations at 544K; with the key taken out it didn't.
- go test -tags nogui -run 'TestCodexCompactHeld|TestCodexWindowUnder|
  TestCoreScriptBudget|TestI18n' ./internal/agent ./internal/gui: ok.
- go vet -tags nogui for darwin, GOOS=linux and GOOS=windows on
  internal/agent and internal/gui: ok. gofmt -l: clean.
- node --test codex-compact-held.test.cjs on the Linux box (wsl-run):
  20 of 20 ok, Chromium and WebKit, en/zh/zh-TW/ja/de at 900 and 420px.
  On mote Chromium was 10 of 10 ok; mote's Playwright WebKit launch hung
  at 180s for every test there, beside another session's full GUI suite.
  The first Linux WebKit run was red at 420px in en, ja and de: the test
  took scrollTop before Playwright's click scrolled the button into view.
  The button is now wheeled into view first (reader.cjs reach), and the
  check allows only the browser holding scrollTop under a shorter page.
- i18n-keys.test.cjs: 4 of 4 ok.
- A first GUI run was red in every file: the new block declared `box`
  twice in one function (a SyntaxError), so no row drew. Fixed before
  this commit. A rerun of codex-async-compact, compact-at and
  compact-one-value at this tree was cut short when mote's browsers
  stopped launching; codex-async-compact's five Chromium cases had passed
  by then. That run was stopped, not finished.

Broken by hand:
- CodexCompactHeld without the profile lookup: its test went red.
- codexWindowUnder forced to nil (`if true ||`): red at line 46.
- CodexModel without the profile lookup: red at line 52.
- The window line turned off (`if (false) hb.append`): codex-compact-held
  red in all 10 Chromium cases at the own line's waitFor.

Not tried: a real relay listing gpt-6-A, the reporter's config.toml,
WSL Codex configs, `codex --profile` on the command line, the Codex app.

Core script budget: 1,537,356 -> 1,537,669 for the two lines in Codex's
row, with the comment cut and no room added.
2026-10-31 09:03:01 +08:00
yetone 06c2c35d13 claude: the interactive mode's start is waited for, and a hung one goes to -p (#4504)
derrors (Linux Docker, 2 vCPU, v0.1.2281): every new Claude Code run
failed "Claude Code has not answered magpie's initialize request in 10s"
and the turn was 502 after 6 tries, while -p runs on the same account
answered.

Cause: the claude-tui-helper answers the bridge's initialize only once
the interactive Claude Code shows its prompt (claudetui.ready, up to
45s), or as -p after it falls back. The bridge gave it the 10s of any
control request and then ended it, so a Claude Code slower than 10s to
start was killed before its own -p fallback could run, and nothing was
marked: each try started the interactive mode again.

Fix:
- startRun waits tuiInitWait (claudetui.ReadyWait + 2x controlWait, 65s)
  for a TUI run's initialize, and gives up on the request's context.
- a helper that still answers nothing is ended, the machine is marked
  (claudetui.MarkBroken), and start runs the turn again as -p.
- claudePrintWhy goes -p at once while the mark holds ("the interactive
  mode failed to start lately"), so no helper is started.
- the mark counts failed starts in a row: 30m after one, doubled to a
  day (brokenFor), so a machine where it never starts waits about once a
  day. A start that shows its prompt removes the mark.
- the helper falls back at once when Claude Code asks how to sign in
  (a container signed in for -p only, CLAUDE_CODE_OAUTH_TOKEN), which
  it otherwise took for the prompt or waited 45s on.
Every other control request keeps its 10s; initialize is the only one
a TUI run is sent (cliControl's one other caller is setSafeguards,
and a run with safeguards or cache marks is -p).

Run (mote, at this tree):
- go test ./internal/claudetui/ (whole package) ok
- go test ./internal/gateway/ -run Claude ok
- GOOS=linux and GOOS=windows go vet ./internal/claudetui/
  ./internal/gateway/ ok; gofmt -l clean
- wsl-run (magpie-desktop, Ubuntu 24.04): go test ./internal/claudetui/
  ./internal/gateway/ -run 'TestShim|TestBroken|TestClaudeTUI|
  TestClaudeEndedRunSaysWhy|TestClaudeUnloadable' ok

Broken by hand (each red, then restored):
- TUI initialize waits controlWait, no mark, no retry (the old code):
  TestClaudeTUISlowStartAnswered 502 "Claude Code has not answered
  magpie's initialize request in 10s", the reporter's message
- TUI initialize waits controlWait only: marked broken, red
- no MarkBroken in the bridge, or no retry in start:
  TestClaudeTUIHungHelperGoesPrint 502
- no sign-in check: TestShimFallsBackToPrint/asks_to_sign_in timed out
- no clearBroken: TestShimStartClearsBroken red
- brokenFor not doubling: TestBrokenGrows red

Not tried: a real Claude Code in a headless container, or any real
account. Why derrors' Claude Code was slow or stuck is not known: the
sign-in screen is a guess from -p working where the interactive mode
didn't; the helper's line now logs the screen it stopped on. No full
suite.
2026-10-31 08:13:47 +08:00
yetone c59c547c5b claudetui: Claude Code's interactive mode on Windows, in a pseudo console
A Claude run on Windows was always claude -p, the entrypoint the plan
counts at about twice the interactive mode's. The helper now starts
Claude Code in a ConPTY there (child_windows.go): CreatePseudoConsole on
two pipes, CreateProcess with the console attribute and
STARTF_USESTDHANDLES with no handles. Without that flag a child takes
the helper's own standard handles (the bridge's pipes) and draws into
them, not the console. A .cmd claude is quoted by proc.Command as the -p
run's. Ending closes the console, then kills after 3s; the -p fallback
runs Claude Code as a child, as Windows has no exec. The pty code moved
to child_unix.go unchanged, and tui.go has no build tag.

Windows ends a run by killing its job, which no handler hears, so a
turn's images folder is now removed once its message is sent, and a
helper starting removes magpie-claude-images-* folders over an hour old
(dropLeftImages). The gateway's gate lets Windows through (WSL stays
-p), and the setting's text no longer says Windows is always -p
(en, zh, zh-TW, ja, de). Doc updated.

Run:
- go test ./internal/claudetui on macOS (mote), Linux (magpie-desktop
  WSL2) and Windows 11 26200 (xiaomi-gpu): ok. The fake Claude Code on
  Windows is a claude.cmd, its console made raw with SetConsoleMode.
  New: TestDropLeftImages, and TestShimPastesImages checks the folder is
  gone after its message.
- go test -run Claude ./internal/gateway on mote, and the TUI tests on
  Windows: ok.
- i18n-keys and claude-tui-setting (chromium and webkit, en/zh/ja/de,
  1100 and 420): 20 of 20 on the Windows box. On mote chromium passed
  and every webkit case timed out in browserType.launch, beside other
  sessions' GUI suites running for up to 20 hours (load 22).
- go vet -tags nogui of claudetui, gateway and cli for darwin, linux and
  windows; gofmt -l clean.
- Real account on xiaomi-gpu: a sandbox HOME gateway (port 3462) with
  the Claude Max account, real claude.exe 2.1.281, haiku-5-5. One tool
  call, two in one message, text then a call, and two image turns
  (twice): all right answers. 81 transcript rows, every one
  "entrypoint":"cli", no "-p" line in the log. Images noted as
  C:\Users\...\magpie-claude-images-*\image-N.png and no folder left.
  Killing the gateway ended its four resident helpers and claude.exe.
  The token wasn't refreshed; the copied credentials were deleted.
  (This ran before the 1809 check in start was added; the claudetui
  tests on Windows and GOOS=windows vet ran again after it: ok.)

Broken by hand: STARTF_USESTDHANDLES removed, TestShimTurnsInteractive
on Windows red (3 lines of 5 in 30s: the fake's drawing reached the
shim's stdout).

Not tried: an npm claude.cmd install with the real account (only the
fake .cmd), Windows 10 before 1809 (no CreatePseudoConsole: the start
checks for it and falls back to -p), a run ended mid-turn by the client
on Windows.
A stray "The system cannot find the path specified." showed once in the
Windows test output; it wasn't on the shim's stderr, and three reruns
didn't show it.
2026-10-31 06:10:00 +08:00
yetone c8f199695c gateway: DeepSeek's reasoning is held for a refusal after it; WorkBuddy plugin min 0.2.4 (plugins #540)
itspig (plugins #540): deepseek-v4.1-flash on WorkBuddy, through
group/tiered, reasoned ~5s, said "Sorry, I can't respond to this
question.", and ended finish_reason content_filter with 0 output tokens
under a 200. The try was recorded done/200, none of the 15 members behind
it was asked, and DeepSeek Harness failed "The model refused to complete
the request".

Two halves:
- workbuddy 0.2.4 (plugins 4883f94) takes the filter's canned line out of
  a streamed chat that ends content_filter with nothing else said.
- refusesAfterThinking now holds DeepSeek's reasoning too (as Claude's,
  GPT's and Gemini's), only while another candidate could answer: with it
  let through as it came, a refusal after it could never go to the next
  member. DeepSeek's own API documents finish_reason content_filter. The
  cost: in a group with a member behind it, DeepSeek's thinking reaches
  the agent once its text begins (kept alive meanwhile), as Claude's does;
  on the last candidate it streams as before. GLM, Kimi and others are
  unchanged.
- The workbuddy mover's min is 0.2.4 (npm view --prefer-online: 0.2.4).

Run on mote at this tree: go test ./internal/gateway -run
'TestDeepSeekRefusalAfterThinkingFailsOver|TestThinkingHeldFor|
TestRefusalAfterThinkingFailsOver|TestThinkingStreams' ok; go test
./internal/provider ok; gofmt -l clean. The full ./... suite was started at
this tree minus the one-line min and is still running; its result goes on
plugins #540 (owner rule: tag without waiting).

Broken by hand: without the deepseek prefix, TestDeepSeekRefusalAfterThinkingFailsOver/refused
goes red (DeepSeek's reasoning reached the agent, b never asked) and
TestThinkingHeldFor red for the three DeepSeek ids; /answered stays green.

Not tried: a real WorkBuddy refusal (no prompt reproduces it on demand);
the upstream's literal chunking isn't in the issue, so the fixture is
built from its fields (reasoning, content_filter, 0 tokens).
2026-10-31 06:05:29 +08:00
yetone bca0d6d69a claudetui: a turn's images are pasted as files, not sent to claude -p
A request with images ran claude -p, and a turn with one ended the
interactive run. The helper now writes each base64 image to
image-N.<ext> (0600) in a magpie-claude-images-* temp folder and pastes
its path alone, which Claude Code 2.1.314 reads into the message as
[Image #N]; a path inside other words stays words. Claude Code reads the
file after the paste returns, so the helper waits for [Image #N] past the
last one before pasting the next piece. The folder is removed when the
helper ends. Only an image known by its URL still goes to -p
(urlImages), and tuiPromptMost counts words without images.

Run: go test ./internal/claudetui ./internal/cli on mote and in WSL
magpie-desktop, ok; go test -run 'TestClaudeTUI|TestSubscription|
TestClaudePrint' ./internal/gateway on mote, ok; go vet ./..., GOOS=linux
go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, gofmt -l,
ok. Real account (Claude Code 2.1.314, haiku, sandbox HOME) through the
sandbox gateway with tools: a red then a blue square in two turns, 3 of 3
answered red, blue; the transcript has image blocks in both user rows,
entrypoint cli, and the second turn went on in the same run.
Broken by hand: without the wait for [Image #N], TestShimPastesImages
loses the second image.
Not tried: an image over Claude Code's size limit; Linux with a real
account.
2026-10-31 05:00:39 +08:00
yetone 9d4a4bfd3f gateway: a late Claude Code call tells the client after 500ms, not 1s
In Claude Code's interactive mode a call of a client's tool waits callFirst
for its message in the transcript before the call tells the client itself.
Measured on a real account (a probe build logging the time from the MCP call
to the transcript's tool_use), a message written before its call was read
118 to 162ms after the call came in, 8 calls of 8. 500ms leaves it room and
halves what a late message costs.

Run: go test -race -count=3 -run 'TestClaudeTUI|TestSubscription'
./internal/gateway on mote, ok. Real account (claude-haiku-5-5, sandbox
HOME, interactive TUI): 9 runs of the one/two/text scenarios, all ok, every
call told once with its own id; 1 took the late path, none fell back to -p.
Not tried: sonnet/opus, Linux.
2026-10-31 04:35:16 +08:00
yetone e647a1fd54 plugins: an npm registry of the user's own is used for installs and lookups (timwangdev on X)
timwangdev asked on X for plugins to take a custom npm registry. Zero-config
first: Registry() (internal/plugin/registry.go) takes, in order, the one set
in magpie (settings npmRegistry: `magpie plugin registry <url>|default`, or
Plugins › Discover's new npm registry row), BUN_CONFIG_REGISTRY /
NPM_CONFIG_REGISTRY / npm_config_registry in magpie's environment, then the
login shell's (cached probe only, proc.LoginEnvKnown, never waits on a
shell), install.registry in the plugins folder's or the user's .bunfig.toml,
registry= in the plugins folder's or ~/.npmrc, then the 国内镜像 switch's
npmmirror, then npm's own. The switch no longer puts npmmirror over a
registry the user named: before, bun was handed BUN_CONFIG_REGISTRY=npmmirror
whenever it was on, over the user's .npmrc. bun is told the registry only
where it wouldn't find it itself (magpie's setting, the shell's, the
switch's). magpie's own npm questions (latest version for the market,
Update and the hourly check, README, search) go to the same registry, a
package's @scope:registry= to that scope's, with the .npmrc's
//host/path/:_authToken (${VAR} expanded, longest prefix) sent to that host
alone, dropped on a redirect to another host, never logged or shown.
Download counts stay npm's. Only http(s) with a host, no userinfo, query
or fragment is taken; anything else is refused and not saved, and a bad
value hand-written into settings.json is passed over. /api/plugins says
which registry is in use and where it came from.

The GUI row is in registry.js, imported when Discover draws it, so the
core script budget isn't raised (plugins.js is 292 bytes smaller than
before, one long comment there condensed).

Left out: bunfig [install.scopes] for magpie's own lookups (bun reads them
for installs), .npmrc _auth and username/password, NPM_CONFIG_USERCONFIG
and npm's global npmrc, and internal/agent/cliupdate.go's agent CLI update
lookups, which still ask npm's own.

Run (mote and wsl-run). First at this change on 2ac423f4f:
- go test ./internal/plugin/ ./internal/source/ ./internal/gui/
  ./internal/proc/ ./internal/cli/ ./internal/settings/ -timeout 45m:
  plugin, source, cli, settings ok. gui: only the real-window AppKit tests
  killed at their deadline on mote (dock, panel, titlebar, tray; #2645,
  #4125), TestCoreScriptBudget and TestSettingsSaveKeepsWhatItDoesNotSend
  green after the fixes in this commit. proc: TestNoCommandBypassesProc red
  on origin/main itself (internal/claudetui/tui.go:183), filed as #4491.
- gofmt -l internal: clean. GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok.
- GUI (wsl-run, magpie-desktop): plugin-registry.test.cjs in Chromium and
  WebKit, 5 languages each, 980px and 380px; i18n-keys, old-webkit and
  plugin-market (WebKit): 19/19 pass. On mote the browser runs timed out
  launching (#4125).
Again at this tree rebased on fa5e86cf2 (upstream changed app.js and
i18n.js): go build ./...; go test ./internal/gui/ ./internal/cli/
./internal/plugin/ ./internal/settings/: cli, plugin, settings ok, gui only
the same ten AppKit window tests killed on mote (#2645, #4125), the core
budget green; gofmt clean; plugin-registry (Chromium, WebKit), i18n-keys
and old-webkit on WSL: 22/22 pass.
Rebased once more on 45de2ddb9 (app.js and i18n.js again): gofmt clean,
go vet of gui and plugin ok, TestCoreScriptBudget and
TestSettingsSaveKeepsWhatItDoesNotSend ok, i18n-keys 4/4.

Broken by hand, each red, then restored:
- A: old registryEnv (npmmirror whenever the switch is on):
  TestBunTakesTheUsersRegistry red.
- B: lookups always to npm's own: TestLookupsAskTheUsersRegistry red.
- C: no URL check: TestSetRegistryRefusesWhatIsntOne red.
- D: the switch before the user's registry: Precedence, BunTakes and
  Lookups red.
- E: no token sent: Lookups red.
- F: scopes ignored: Lookups red.

Not tried: a real private registry (Verdaccio, GitHub Packages, Nexus) with
a real token; a real bun install through one; Windows (the login shell
probe is a no-op there, so only env, bunfig and .npmrc apply).
2026-10-31 04:24:59 +08:00
yetone 45de2ddb96 provider: a provider the user counts free goes first under Free first (jiabubu on Discord)
jiabubu asked on Discord #help for a way to mark a provider, model or key
as free, so that Free first routing spends it first. Their example is
ModelScope, which has a free daily quota. Until now routes.Seat.Free
came only from the vendor catalog's Free flag, and there was no way for
the user to set it.

Provider.CountFree ("Free for me" in the provider editor's Advanced fold,
`magpie provider set <id> free=yes|no` in the CLI) makes FreeModel true
for every model of that provider. Routing therefore treats it like a
vendor's free model: Free first uses it before paid ones, and Cheapest
first weighs it at nothing, because PriceAt, which only routing reads,
returns 0 for a free model. Prices shown (ListPrice and the model list)
and the costs Usage counts (EffectivePrice) are unchanged. The mark says
what to spend first, not what a call cost, and a quota that runs out
still bills at the listed price. Key and account (subscription)
providers both carry it, through withPicks, the account literal and the
copy merge.

Tests:
- internal/gateway TestFreeFirstSpendsTheProviderTheUserCountsFree:
  - a Free first group [paidv/m, mine/m] sends its first call to mine
    once mine is marked, and the trace row says Free;
  - EffectivePrice is still the listed 3/15;
  - Cheapest picks mine first;
  - unmarked, paidv goes first again.
- internal/gui TestProviderSaveKeepsCountFree: the preset and typed-in
  providers save the mark and clear it, and /api/providers reports it.
- internal/cli TestProviderSetFree: free=yes and free=no work; the value
  shows in `provider <id>`; free=maybe, an empty value and --help are
  refused and change nothing.
- GUI internal/gui/tests/provider-count-free.test.cjs covers the
  ModelScope preset, a custom provider saved with the mark, and a Codex
  account. It runs chromium and webkit, in en, zh, zh-TW, ja and de, at
  widths 900 and 440. It checks the Advanced fold, the check and save
  POST bodies, that the row fits with no sideways scroll, and that each
  string has a translation in I18N.

Core script budget: rebased on fa5e86cf2, the core's scripts came to
1,538,236 bytes, 880 over coreScriptBudget, which TestCoreScriptBudget
caught. The budget is not raised. countFreeField's comment and five
long comments on the editor's helpers (proxyPicker, concurrencyField,
priceRateField, pluginOptionsField) are cut down, so app.js ends 212
bytes smaller than before this change.

Run (mote via mote-run, at this change's tree on base 8ee75adbf):
- go test of internal/gateway (-run FreeFirst|InOrder), internal/gui,
  internal/cli and internal/provider: ok.
- GUI test: chromium 30/30 on mote. WebKit could not launch on mote at
  all at the time (a bare webkit.launch probe timed out at 60s, and
  other sessions' WebKit launches were stuck there too). WebKit was run
  on Linux instead (wsl-run, magpie-desktop): 30/30.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./... ok; go build for darwin, linux (nogui) and
  windows ok.
- At the pushed head (rebased on fa5e86cf2, comments cut): go test of
  internal/gui, internal/cli, internal/provider and internal/gateway
  -run FreeFirst|CountFree ok (internal/gui was red only on
  TestCoreScriptBudget before the cut); node --check app.js ok; the GUI
  test in chromium 30/30.
- The full Go suite (go test -tags nogui -timeout 45m ./...) is still
  running on mote at ship time, per the owner's ship-at-once rule. Any
  red it finds gets a follow-up commit. The whole GUI suite was not run:
  mote's WebKit cannot launch and the Linux box was running other
  sessions' GUI suites.

Broken by hand:
- With the CountFree line taken out of FreeModel, all three Go tests
  went red, e.g. 'Free first went to "paidv" (free false) first'.
- With `pr.CountFree = in.CountFree` taken out of the preset save
  branch, TestProviderSaveKeepsCountFree went red ("the preset's mark
  wasn't kept").

Not tried:
- A real ModelScope account; the tests use fake upstreams.
- A per-model mark (optional in the request); the mark is
  provider-wide.
- The TUI editor (the CLI setter covers the terminal).
2026-10-31 04:21:21 +08:00
yetone c799934e1b claude: the gateway logs why a run is -p
Finding why the real-account runs went -p (the previous two commits'
end-to-end) took reading a run's stderr by hand: the bridge keeps Claude
Code's stderr for an error only, and claudeTUI said nothing of why it
chose -p.

claudeTUI's conditions move into claudePrintWhy, which names the one
that held ("Claude Code in WSL", "a JSON schema", "the interactive mode
is turned off", ...), and claudeTUI logs "claude: this run is -p: <why>"
(not in the tests' binary, claudeTUIRuns off). lockedWriter logs the
helper's "claude-tui: ...; this run is -p" line (a failed start, an
untrusted folder, the 30-minute mark) as "claude: ...". The rest of
Claude Code's stderr is kept as before and not logged.

Run:
- mote: go test -count=1 -run TestClaudeTUI ./internal/gateway ok:
  TestClaudeTUIChosen now checks each case's reason,
  TestClaudeTUIFallbackLogged the helper's line logged and nothing else.
  go vet ./internal/gateway on darwin, linux, windows; gofmt -l clean.
- Real account, sandbox HOME, a gateway on this build: before the trust
  fix, the helper's line is what named the cause ("Claude Code ended
  before it showed its prompt (exit status 1): B").

Broken by hand: the log in lockedWriter taken out:
TestClaudeTUIFallbackLogged red (logged "").

Not tried: the log on Linux.
2026-10-31 04:20:10 +08:00
yetone 123d72be68 claude: a call Claude Code makes before writing its message is the reply
In the interactive mode the bridge learns of a call from the session's
transcript. Claude Code sometimes writes the message holding a client's
tool_use only after that MCP call returns (4 of 8 real runs before this).
The call waits on the client, and the client waits for the call it was
never told of: a deadlock until the run's timeout.

mcpCall now hands each call to run.onCall, which readOutput sets for a
TUI run. If callFirst (1s) after the call it isn't in the transcript yet
and still waits, the call itself becomes the reply: a message with one
tool_use and stop tool_use, with the MCP helper's id, name and arguments
(the id is the transcript's, from _meta "claudecode/toolUseId"). The
message written after such calls is the late one: its rows aren't told
again (lateID), a call in it not yet told is told by its own turn
(written), and its usage is counted in the next reply. Such a reply has
no words or thinking; the model's text before its call is lost to the
client. -p runs don't set onCall and are unchanged.

docs/subsystems/claude-subscription-bridge.md has the paragraph.

Run:
- mote: go test -count=1 -race -run TestClaudeTUI ./internal/gateway ok
  at this tree; earlier, -race -count=5 of the new tests ok.
- TestClaudeTUICallBeforeItsMessage (output 47 = late 40 + answer 7),
  TestClaudeTUICallAfterItsMessage (told once, output 7),
  TestClaudeTUIParallelCallsBeforeTheirMessage (written after both, and
  between).
- mote: go vet ./internal/gateway on darwin, linux, windows; gofmt -l
  clean. go test -timeout 45m ./internal/gateway ./internal/claudetui
  ./internal/claudebridge ok before the previous commit's rebase
  (gateway 522s); a run with all three commits is going.
- Real account, sandbox HOME, a gateway running this build, haiku: "two
  calls in one message" logged "Claude Code called get_secret before
  writing its message; the call is the reply" for both calls, and the
  client got red then blue as two replies and the answer naming both
  secrets. One call, and words then a call: answered from the
  transcript. Every row "entrypoint":"cli".

Broken by hand: onCall never called: the three tests red ("deadlock").
lateID never set: the late message told again, red.

Not tried: sonnet or opus in the real run (haiku only); a call whose
client takes longer than the run's timeout.
2026-10-31 04:20:10 +08:00