Commit Graph
74 Commits
Author SHA1 Message Date
yetone 0052c860e0 library: billion-context installed with bun is found on Windows (Zerenjie on X)
biliPath looked for bili.cmd on PATH and in %APPDATA%\npm only. bun add -g
puts bili.exe (with a bili.bunx) in the bin of BUN_INSTALL or ~\.bun\bin,
so a bun install was never found. It now asks proc.FindTool, which tries
.exe and .cmd in every folder a user's tools are installed in. proc's
UserBinDirs also takes BUN_INSTALL's bin (Windows and elsewhere), and
Kiro Crew's adapter search gets ~/.bun/bin, BUN_INSTALL's bin and, on
Windows, %APPDATA%\npm, its siblings that had the same hole.

Run: on xiaomi-gpu (Windows 11) really `bun add -g billion-context` into a
sandbox BUN_INSTALL with PATH holding no bun bin. Before the fix biliPath
was "" ; after, it was bili.exe and `bili --version` answered 0.1.213. go
vet and go test -run Bili|KiroCrew|ToolIn|UserPath for library, agent and
proc passed on Windows and in WSL (magpie-desktop). The three new tests
fail on the old code in WSL (broken by hand with the sources stashed).
Not run: the full suite, a darwin vet and a mote run (mote's disk was
full, 226Mi free), the GUI suites (no GUI file touched).
2026-11-11 14:04:37 +08:00
yetone f03ec97b8f proc: a PATH folder that doesn't answer is left out of every look (ifccod7391564 on X)
Started with `open -a`, magpie ran but took over 60s to write
"started", while the same binary run from a shell started in 1s. The
reporter's trace: startUp → agent.RenameLegacy → onMachine →
vscodePortableData → binAt("code-insiders"). Without Insiders,
exec.LookPath walks all of PATH, and a folder on a mount that no longer
answers holds open()/stat() until it does, before applog.Start.

The block isn't binAt's alone: startUp builds every agent through
local() in RenameLegacy and again in moveEfforts (Cursor's and
Antigravity's), each asking for its command through binAt/proc, all
walking the same PATH, and lookStamp stats every PATH folder first. So
the bound is where all of them pass, in proc (reach.go): each PATH
folder is asked (a stat and an open) in a goroutine of its own, all at
once, and one that hasn't answered in 1s is left out of the stamp and of
the look until its probe returns; a probe still out isn't started again,
so later looks skip the folder at once. With such a folder, the command
is looked for in the others, each as a path (exec.LookPath on dir/name).
An answer is trusted for a minute. findMise and FindShell's last resort
used exec.LookPath directly and now go through Look.

Test: TestHungPathFolderIsLeftOut puts a folder whose probe never
returns before the folder with the tool: three looks find the tool, PATH
is never walked whole, the folder is probed once; once it answers, PATH
is walked as before.

Run: go test ./internal/proc ./internal/claudetui on mote ok; go vet for
darwin, linux and windows ok; the proc look tests on the Windows box
(win-run) ok.
Broken by hand: with lookPath not asking hungDirs, the test is red
("PATH was walked 3 times", wsl-run).
Not tried: a real dead network mount on PATH; the test fakes it at the
probe. Direct exec.LookPath calls outside proc (daemon, library, update)
aren't on the startup path and are unchanged.
2026-11-10 18:33:35 +08:00
yetone e4197144a8 perf: every package's package-level regexps compile on first use
v0.1.3516 made gateway's and redact's patterns lazy. The other 299
package-level regexp.MustCompile calls, in 148 files across agent,
provider, gui, library, codexcat, sessions, usage, plugin and the rest,
now go through lazyre.New too, so a launch that never reaches them
(`magpie statusline`, run by Claude Code on every message) doesn't
compile them. Fields, maps and params that held them are *lazyre.RE.

Measured on mote (M5 Pro), sandbox HOME, v0.1.3516-equivalent build
(t42) against this one (t43):
- GODEBUG=inittrace=1 sum: 7.39 MB / 69,837 allocs -> 4.62 MB / 46,765
- `magpie statusline`, 3 runs each: instructions retired ~212M -> ~176M,
  peak memory footprint 19.2-19.4 MB -> 16.8-17.0 MB

Run: go vet ./... (darwin) ok; GOOS=windows go vet on each of the 30
changed packages ok; GOOS=linux go vet ok except ., internal/cli and
internal/gui, which stop in wails v3's cgo files when cross-compiled
(the same at main). New TestAllLazyPatternsCompile at the root compiles
all 574 registered patterns (ok), so a bad pattern fails a test rather
than a first use.
Not run before push: the changed packages' own test suites; they run
on mote after it.
2026-11-10 12:54:39 +08:00
yetone 77076eef47 agent: an npm update on Windows lets go of magpie's own claude and codex first
CLJY (Discord) had %APPDATA%\npm with only the 308-byte sh shim of claude:
no claude.cmd, no claude.ps1 and no codex at all, and `npm i -g
@anthropic-ai/claude-code` ended in "npm warn cleanup ... EPERM ...
unlink ...\.claude-code-<rand>\...\claude-code-win32-x64\claude.exe".
On Windows a running program's file can't be removed. npm moves the old
package aside, takes the old shims away, and stops partway when a
claude.exe of that package is still running; the sh shim is what is left.

magpie keeps such processes running itself:
- the Claude subscription bridge keeps up to 6 Claude Code runs waiting
  for their conversations' next turns, for up to an hour;
- Codex's app-server daemon has no idle exit, and magpie restarts it.
Its Update button ran npm with both still up.

- agent.UpdateCLI, on Windows through npm, bun or pnpm, first lets go of
  them: gateway.LetGoIdleClaudeCode ends every waiting run (its session
  shelved for the next turn, as a run let go past idleMost is) and returns
  once each has exited; provider.StopIdleCodexDaemon stops the daemon when
  no codex session is on it. Runs in a turn and sessions are left.
- An update on Windows that leaves the CLI's file gone fails, saying to
  quit it and reinstall, instead of "updated".
- proc's toolIn (FindTool) and codexExecutable no longer take the bare
  extensionless file on Windows, which CreateProcess can't run. Beside
  name.exe and name.cmd, the sh shim alone stands for the .exe it runs
  (Claude Code's bin\claude.exe), read from cmd-shim's exec line and kept
  inside its folder; a node shim (codex) or any other script is skipped.
  The testdata shims are cmd-shim 7's bytes, made with cmd-shim@7 on the
  Windows box.

Run at this head (rebased on origin/main; after the rebase, vet on all
three systems and the changed tests again: ok on Windows and macOS):
- gofmt -l internal/: clean. go vet of proc, agent, provider and gateway
  on macOS (mote), Windows (win-run) and Linux (wsl-run): ok.
- Windows (win-run): internal/proc ok;
  TestToolInNPMShShimAlone, TestLetGoIdleClaudeCodeFreesTheExe and the
  TestClaudeIdle* tests pass. internal/agent, internal/provider and
  internal/gateway (-run "Claude|LetGo|Codex") have Windows reds, and
  the same run at origin/main c9d253e4a has the same ones (26 in agent,
  15 in provider, 2 in gateway), except TestUsageReadAndReadAgain, a
  clock-tick flake filed as #4796.
- macOS (mote): internal/proc, internal/agent, internal/provider and
  internal/gateway (-run "Claude|LetGo|Codex") ok.
- Linux (wsl-run): internal/proc and internal/provider ok; internal/agent
  red only in TestGrokInstalled, red the same on origin/main c9d253e4a
  (3 of 3), filed as #3548.

Broken by hand:
- toolIn taking the bare name again: TestToolInNPMShShimAlone red on
  Windows (6 cases).
- letGoIdle not waiting for the trees: TestLetGoIdleClaudeCodeFreesTheExe
  red on Windows, and with that check off the removal fails with "Access
  is denied" - the user's EPERM.
- no let-go call and no gone check: TestUpdateCLIOnWindowsLetsGoFirst red;
  StopIdleCodexDaemon ignoring sessions: TestStopIdleCodexDaemon red.

Not tried: a real npm update of Claude Code or Codex on the Windows box
with magpie running; the Windows-only path is tested with
updateGOOS = "windows" on macOS, and the process lock with a copy of the
test binary.

Reported-by: CLJY (Discord)
2026-11-09 12:56:42 +08:00
yetone e6cdeac9c6 proc: with no WSL distro registered, or after wsl.exe asks to be updated, magpie starts no wsl.exe (TraderX219 on X)
TraderX219 on Windows: while magpie ran, a console window "WSL 必须更新到
最新版本……按任意键安装" came up every 20 to 30 seconds. magpie asked
wsl.exe for its distros (the running list retries every 30s after a
failure), and Windows' inbox wsl.exe answers each run on a computer
without a current WSL package by starting `wsl.exe --update --confirm
--prompt-before-exit` in a console of its own.

proc.Command, CommandContext and ProbeContext are where every wsl.exe
magpie runs is made (agent's wslRun/wslExec, wslrun, claudetui, the
library's rtk and MCP checks, the gateway's TUI helper), so both gates
sit in wslOff beside #1264's ErrWSLOff:

- The registry is read first (HKCU\...\CurrentVersion\Lxss, one subkey
  with a DistributionName per distro). With the key there or gone and no
  distro in it, wsl.exe isn't started: ErrNoWSLDistro. agent's wslList
  and wslrun's running list read that as "no distros", not as a failure
  or a hang, so nothing is retried every 30s. It is read at every start,
  so a distro installed later is seen at once. A read that fails is
  unknown: wsl.exe is asked as before.
- When a run's output (UTF-16LE or UTF-8, stdout and stderr) says WSL
  must be updated or installed, proc.WSLSaid writes settings' wsl-update
  mark (atomic, like wsl-hung) and no magpie process starts wsl.exe for
  6h: ErrWSLNeedsUpdate. The mark holds the WSL package version (HKLM
  Lxss\MSI Version) and the registered distros; a change to either
  clears it. A refused listing is unknown, so wsl.seen, WSLKept values
  and links are kept, never removed.

docs/subsystems/agent-wiring.md describes both.

Run:
- mote: gofmt -l (clean); go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...; go build for darwin, linux (nogui),
  windows: all ok.
- mote: go test -count=1 of internal/proc, agent, wslrun, library,
  sessions, claudetui at base 191f3c0af: all ok.
- mote, full suite through suite.lock (go test -count=1 -timeout 45m
  ./...) at base 191f3c0af: 88 packages ok, none failed.
- xiaomi-gpu (Windows 11, win-run): go test -count=1 ./internal/agent/...
  ./internal/proc/... ./internal/wslrun/...: proc and wslrun ok;
  agent has 25 reds, the same 25 by name on untouched origin/main
  191f3c0af. 24 were filed (#4115, #4786, #5068 and others);
  TestCodexOwnModelsFollowPicks wasn't, now #5605.
- xiaomi-gpu, read-only: TestWSLRegistryLive (MAGPIE_WSL_REGISTRY_LIVE=1)
  read the real Lxss key (magpie-fedora, Ubuntu, docker-desktop,
  magpie-3896, magpie-desktop; package 2.6.1.0) and ran `wsl.exe -l -q`
  (docker-desktop, magpie-fedora, Ubuntu, magpie-desktop): every listed
  distro is registered, so the gate never reads none while wsl.exe has
  some. magpie-3896 is registered in State 4 (uninstalling) and not
  listed, which only keeps wsl.exe being asked. No distro was stopped or
  changed.
- At the pushed head (rebased on f13d5f16f, which touches gateway and
  provider only), mote: go test of proc, wslrun, provider ok. agent's
  TestWSLMoreAgentsPick failed with "no space left on device" (mote's
  data volume was at 100%). Rerun: -count=3 -run 'TestWSLMoreAgents|WSL'
  ./internal/agent/ ok, and -run History ./internal/gateway/ ok. abe7b0063 (gateway) and
  e4fdf9ed3 (gui) landed after that run and were rebased onto unrun; they
  touch no file this change does.

Broken by hand, each red:
- registry check off: TestNoWSLDistroStartsNoWSL ("wsl.exe wasn't
  refused") and TestNoWSLDistroRunsNoWSL ("no distro registered read as
  wsl.exe failing").
- WSLSaid left out of agent's wslRun: TestWSLUpdateKeepsDistros ("wsl.exe
  -l -q was started: exit status 1").
- wslList's ErrNoWSLDistro as listed: TestNoWSLDistroRunsNoWSL.
- wslUpdateLately always false: TestWSLUpdateBacksOff ("wsl.exe run again
  after it asked for an update").

Not tried:
- The stub's window itself: xiaomi-gpu has a current WSL and distros, so
  it doesn't pop there. The fix wasn't run on the reporter's machine.
- The registry key missing (ErrNotExist) on a real Windows without WSL.
- The stub's real exit code and stdout: the update text is matched from
  the inbox wsl.exe's .mui strings (en, zh-CN) and the reporter's words.
- A wsl.exe that times out is not taken as asking for an update; the
  existing wsl-hung back-off still covers it.
2026-11-07 17:51:51 +08:00
yetoneandvincent f4068ccc25 proc: with Detect agents in WSL off, no wsl.exe is started on any path (#4872)
With Settings' Detect agents in WSL off (noWSLAgents), every Claude
request still reached wsl.exe: wslReady (wslClaudeStandIn,
wslCodexStandIn) and wslClaudeClassifier listed the running distros
without asking wslLooks, the gate #1264 put on wslAgents, wslHomes and
WSLRunning. wslrun's Up, In and running weren't gated either (only
Find was). On a computer without WSL, Windows' inbox wsl.exe answers
each ask with a window offering to install WSL, one per request.

The fix is at the one choke point every command magpie starts goes
through (TestNoCommandBypassesProc): proc.Command and CommandContext
(and so ProbeContext, wslrun.Tool.Command/Probe, the Claude TUI
helper's ConPTY start, which checks cmd.Err) refuse wsl.exe by any
name or path (wsl, WSL.EXE, C:\Windows\System32\wsl.exe) with
proc.ErrWSLOff while the setting is off, as a probe of an app's own
program is refused. The paths that reach it: agent's wslRun/wslExec
(lists, probes, links, chmod, reach), wslrun.Run/Find/In/Up/Stop,
library's cmdvars, mcp_wsl, mcp_check and rtk_wsl, claudetui's
wslread, the gateway's Claude Code in WSL. The settings read is
settings.Shared() and only for a wsl name. Not gated: the Sessions
page's resume line for a WSL session (a string a terminal runs on the
user's click), whose sessions aren't listed with detection off.
skygunner/vincent's stand-in fix is kept as well, so the stand-in and
classifier return before taking wsl's lock or recording a failed list.

Run:
- mote-run: go vet ./internal/proc ./internal/agent ./internal/wslrun;
  GOOS=windows go vet of proc, agent, wslrun, claudetui, library,
  gateway; GOOS=linux go vet of proc, agent, wslrun, claudetui: clean.
  go test -count=1 ./internal/proc ./internal/wslrun ./internal/claudetui:
  ok; -run 'WSL|Wsl|Dsh' ./internal/agent ./internal/library
  ./internal/sessions: ok. gofmt -l: nothing.
- win-run on xiaomi-gpu (Windows 11, real wsl.exe present): the four new
  tests plus TestWSLDetectionOff, TestWSLClaudeStandIn,
  TestWSLCodexStandIn, TestNoCommandBypassesProc: ok; -v shows each new
  test PASS; go test ./internal/proc ./internal/wslrun whole: ok.
  TestWSLRunnerRefusedWhenOff runs agent's real wslRun there.

Broken by hand (wslOff's check made `if false && …`, agent/wsl.go at
origin/main, new tests kept), on mote: TestWSLOffStartsNoWSL red for
every name and maker, TestRunRefusedWhenOff "Run ran wsl.exe: exit
status 1", TestWSLRunnerRefusedWhenOff red, TestWSLStandInAsksNothing
WhenOff red with three "-l --running -q" asks.

Not tried: the reporter's own Windows without WSL (the install window
itself); the full suite runs after the push under the suite lock.

Reported-by: 陌离 (Discord)
Co-authored-by: vincent <vincent@users.noreply.github.com>
2026-11-06 21:28:24 +08:00
yetone f9e6061b85 claude: claude-magpie runs Claude Code through magpie, a plain claude left on the user's account
baranwang on X (11-06): `claude` stays on the user's own Claude account,
`claude-magpie` goes through magpie, and nothing is switched back and
forth.

`claude-magpie` runs `magpie claude run [args…]`. That writes a settings
file of magpie's own, <config>/claude-launch/settings.json, connected as
Connect connects Claude Code (the gateway, its key, the shared LAN key when
sharing is on, the model, the tiers) and starts
`claude --settings <file> args…`. Claude Code puts a --settings file's env
and model over the user's settings.json, a claude.ai sign-in and the
shell's variables (tried on 2.1.318), so ~/.claude/settings.json is never
rewritten. ANTHROPIC_API_KEY and the cloud switches (Bedrock, Vertex…) are
blanked in the file, so neither the user's file nor the shell can take a
request past magpie. The file is the agent `claude#launch`, listed nowhere:
the Agents page, Check and Notice see only the user's file. It is set again
when the gateway moved or its key changed.

- /model in a claude-magpie session saves to the user's settings.json
  (Claude Code never writes a --settings file). After the session a magpie
  model picked there moves into the launch file, for the next claude-magpie,
  and the user's file gets its model back. A Claude alias (sonnet) stays.
- Claude Code's own one-time `opus` -> `opus[1m]` rewrite of the user's
  file (migration_opus_to_opus1m), which the launch file's 1M opus tier sets
  off, is undone the same way. Found in the end-to-end run below.
- claude runs as a child so that can happen: on Unix a stopped child stops
  magpie too (^Z, fg; proc.WaitFollowingStops reaps it with WUNTRACED, as
  cmd.Wait can't see a stop), and claude's exit code is magpie's. On Windows magpie
  ignores Ctrl+C while claude has it.
- The command: a launcher beside the `magpie` command. Settings › Command
  line (AddCLI) writes it; `magpie claude launcher [add|remove]` adds it for
  a command put there before. It is a `#!/bin/sh` exec of magpie's stable
  path, or on Windows a .cmd running "%~dp0magpie". A file by that name
  without "written by magpie" is never written over.
- Docs: agent-wiring.md, and the start page in en/zh/ja.

Run at this commit (rebased on origin/main 218b38c59):
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build for darwin, linux (nogui), windows;
  go test ./... -timeout 45m: 85 packages ok; red only
  TestMainWindowCorners (#3949) and TestRenewLoginsKeepsClaudeReading
  (#5481), both red alone on origin/main b020ae102. The run before at
  f22a9ae61 also had proc's TestEveryStartedCommandIsWaited red on this
  change's own Wait4 loop, fixed here by moving it into proc.
- Windows (xiaomi-gpu): go test ./internal/update ./internal/cli: cli ok;
  update red only in TestPackagedByDpkg, red the same on origin/main
  f47390bf3, filed as #4603.
- Real Claude Code 2.1.318 in WSL (magpie-desktop), sandbox HOME, a built
  magpie (`serve` on its own port), a fake Anthropic upstream:
  - `magpie claude run -p "say hi"`: PONG, exit 0; upstream got
    claude-opus-4-6 with the provider's key. A user settings.json with its
    own ANTHROPIC_API_KEY and "model": "opus" kept both values.
  - Interactive in tmux under bash -i: `/model fakeco/glm-4.6` then /exit:
    the user's file is back on opus, the launch file on fakeco/glm-4.6.
    ^Z stops both magpie and claude (T), fg resumes both.
  - `magpie claude launcher add` wrote ~/bin/claude-magpie, and running it
    answered PONG.
- Real Claude Code 2.1.281 on Windows: claude-magpie.cmd beside a built
  magpie.exe, `claude-magpie --version` printed the version through
  `claude --settings <launch file>`, exit 0.

Broken by hand, each red: the blanks dropped; the launch dir override; the
stale-address check; ClaudeLaunchAfter returning early; the opus[1m]
rewrite check; WaitFollowingStops answering 0 for a signal; "$@" turned into $* in the launcher; the model mark check;
AddCLI's launcher loop; --settings dropped from the args; the restore call
dropped.

Not tried: macOS with a real Claude Code (the Unix path ran in WSL only);
Windows interactive (Ctrl+C, /model restore); a real Claude subscription or
API key upstream (a fake upstream only). Known limits: a session that ends
by a crash or kill skips the restore; managed settings (policy) outrank
--settings; magpie has to be running (claude-magpie warns when it isn't);
Claude Code itself reformats the user's settings.json when it runs its
opus migration, values kept.
2026-11-06 17:31:04 +08:00
yetoneandbaijiu666 5055349922 plugin: a host ended ends what its plugin started, at any depth (#5402)
A plugin host was ended with cmd.Process.Kill(), the host alone. A
plugin that starts a browser or a daemon (magpie-magicrew-auth's
headless Edge behind a WAF) left it running with no parent: 620
msedge.exe (6.8GB) and 382 temp profiles (57GB) in an hour on one
Windows machine. Bun's own job ends its direct children with it on
Windows, but lets their children out, so Edge's gpu/renderer processes
lived on. On macOS and Linux nothing ended them at all.

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

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

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

Co-authored-by: baijiu666 <198813975+baijiu666@users.noreply.github.com>
2026-11-06 00:34:42 +08:00
yetone 9d0c9b41ea serve: follow an update put in where it runs from; a replaced magpie.real is magpie
acezan on Discord (Linux 5.15, 0.1.2959 to 0.1.2960): `magpie web` as a
system unit updated /root/.local/bin/magpie.real, and the user unit's
`magpie serve` (`magpie daemon install`) ran on for good from "magpie.real
(deleted)". The panel said an older magpie served the gateway, and its
"close it here" then said the port holder "isn't magpie" and left it.

Why serve stayed old: the app and `magpie web` follow the program they
started from (gui's followReplaced) and restart into an update; plain
`magpie serve` had no such look, and answered `magpie update`'s restart
ask (gateway.RestartPath) "unsupported". Nothing else can restart it
reliably: a system unit doesn't reach the user's `systemctl --user`, and
on a Mac the launch agent's serve (#4335) is the same serve. So serve now
looks itself (internal/cli/serve_follow.go): every 5s it checks its
program with update.Replaced; once replaced, it waits until the gateway
is idle (nothing in flight, 10s since the last end, as gui's idle rule;
after an hour, nothing in flight is enough), ends the plugin hosts and
runs the new program in its own place (update.Reexec: exec in place on
Unix, same PID, so systemd and launchd keep tracking it; a new process
on Windows). The restart ask now answers restarting/waiting/current. A
build that isn't a release never does it.

Why "not magpie": proc.IsMagpie judged the file name, and "magpie.real"
(the program the installer's wrapper script runs) didn't match. It now
trims ".real". And proc.RunsMagpie, used by the takeover and the port
check, also reads Go's build info of the running program (on Linux
through /proc/<pid>/exe, which still reads after the file is replaced)
and calls it magpie when its main package is github.com/yetone/magpie.
A process that isn't magpie is still never ended (the existing
"other-server" case passes unchanged).

Tests, each red on the old code:
- cli TestServeRestartsIntoAnUpdate: a copy of the test binary named
  magpie.real runs `serve` on a free port; a script renamed over it is
  run in its place with the same pid and args, and the old port stops
  answering. Old code: "serve ran on as the old version" after 40s.
- cli TestServeFollowWaitsForIdle: current / waiting / tool-chain gap /
  waitMost with a request in flight / idle / non-release.
- gui TestGatewayFixQuitsAReplacedMagpieReal: a fake older gateway named
  magpie.real, its file removed after start, is quit and the gateway
  served here. Old code: {OK:false Reason:not-magpie}, acezan's case.
- proc TestIsMagpie magpie.real case; TestRunsMagpieByItsBuild: a copy
  named server.real, its file removed, is told by its build (Linux
  /proc/<pid>/exe), and is not magpie with the real main path.

Run: the targeted tests above on Linux (wsl-run, magpie-desktop, -tags
nogui) and macOS (mote-run), all pass. Broken by hand on Linux: dropped
the ".real" trim, made RunsMagpie only IsMagpie, and set serve's follow
to nil; all four new tests went red (output above), restored after.
gofmt -l clean; go vet (darwin, GOOS=linux -tags nogui, GOOS=windows)
and builds on mote.

Not tried: a real systemd user unit or launch agent with a real update;
the Windows restart path (Reexec starts a new process) beyond vet; the
macOS TCC part of #4335 (this restarts the launch agent's serve into the
new bundle path only if that path is where it started from). #4335 stays
open, and ggbdpq's daemon.RestartReplaced patch there is not applied.
2026-11-04 23:55:14 +08:00
yetone 1987fe220c agent restart: a script run on the app's own executable is not the app (WorkBuddy's sidecar)
Northes (Discord #feedback, 11-04): WorkBuddy's Agents row kept "重启
WorkBuddy 后生效" after they quit and reopened it, and its Restart quit
WorkBuddy and never opened it again. #3700 (Raters0) is the second half on
WorkBuddy AI.

Cause, from WorkBuddy 5.5.6's app.asar (read only) and its processes on the
Windows box: WorkBuddy starts a sidecar as `<its own executable>
.../app.asar/main/sidecar-entry.js --token ...` (ELECTRON_RUN_AS_NODE,
detached). The sidecar outlives the app's quit and the next start reuses
it, and its prewarm and `--serve` CLIs run as `<executable>
.../cli/bin/codebuddy ...`. The daemon is `WorkBuddy.exe ...
daemon-app-server-entry.js --stdio`. All of them match the running check's
`Contents/MacOS/<exe>` pattern (and WorkBuddy.exe's image on Windows), so:
- (a) findRestartable took the oldest match, the sidecar, as the app's
  start, so magpie's change was always "after" it and the row never
  cleared, however often the app restarted. On Windows the earliest start
  was used too.
- (b) reopenBundle waited for every process under Contents/ to end; the
  sidecar never does, so after 30s it said "still open" and never ran
  `open`.

Fix: runsScript(cmd, exe) tells a script run on the app's executable (a
.js/.cjs/.mjs argument, or a first non-flag argument that is an absolute
path) from the app itself and its helpers (--type=..., /prefetch:,
-psn_, a deep link). The macOS running check and the reopen's wait skip
such processes (appProcs), and the Windows check reads each process's
command line (proc.CommandLine, new) and skips them too. The reopen still
waits for real helpers (renderer, GPU). This is shared by every restartable
app: Claude desktop, WorkBuddy, WorkBuddy AI and the Codex app.

Tests (red on the old code: a copy of the base with runsScript returning
false failed all three, since = the sidecar's 2h, the Windows since the
sidecar's, and 6 RunsScript rows):
- TestWorkBuddySidecarOutlivesQuitOnMac (WorkBuddy and WorkBuddy AI, a
  space in the bundle): a 2h-old sidecar and prewarm beside the app; the
  row is behind by the app's start, a manual reopen clears it, the
  sidecar alone is not "running", Restart quits then opens.
- TestWorkBuddySidecarOutlivesQuitOnWindows: same, and Restart closes and
  ends only the app's tree, then opens it.
- TestRunsScript: real Windows command lines from WorkBuddy on the box,
  macOS ones, and #3700's `codebuddy --serve` line.

Run at this head (rebased on d6d3e6cc8):
- mote: gofmt -l clean; GOOS=windows, linux and darwin go vet
  ./internal/agent ./internal/proc; go test -count=1 ./internal/agent
  ./internal/proc ok.
- xiaomi-gpu (win-run): go test ./internal/agent ./internal/proc -run
  'Restart|Sidecar|RunsScript|WorkBuddy|List': the new tests pass; red are
  TestWorkBuddyRestartOnMac and TestWorkBuddyOwnSaveAfterStartIsNoChange/
  darwin (red the same at origin/main d6d3e6cc8, #4115) and
  TestWithViaKeepsTheJoinedList (#4786). The new mac test skips on Windows
  for #4115's reason.
- Real processes, uncommitted tests: on mote a fake "WorkBuddy AI.app"
  (Go sleeper as Electron) with a sidecar started first, through real
  pgrep and sysctl: since is the app's (0.66s), the sidecar alone is not
  running. On xiaomi-gpu a fake WorkBuddy.exe sidecar and app:
  readWinProc's command lines are the real ones and runsScript tells
  them apart.

Not tried: the real WorkBuddy or WorkBuddy AI (not run, ~/.workbuddy not
touched); a real Restart end to end through osascript/open or on Windows
(the quit/open steps are faked); Linux (no restartable app there).

Refs #3700
2026-11-04 14:25:43 +08:00
yetone 1cb346f2dc gui: on Linux the folder and Backups buttons start the opener and return (pkh1585)
pkh1585 on Discord: on Linux, clicking the Library's folder / Backups
button froze magpie and the file manager that opened closed by itself.

Cause: Linux openFolder was Wails' OpenFileManager, which runs the desktop's
file manager (the inode/directory .desktop Exec, or xdg-open) with cmd.Run
under a 10 second context. A file manager that isn't running yet stays in
the foreground, so the click waited the full 10 seconds and then the
context killed the window that had just opened. Windows had the same shape
and was fixed earlier (folder_windows.go); macOS's `open` returns at once.

Fix: proc.OpenFolder (Linux) starts xdg-open (else gio open, exo-open) with
no stdio and a session of its own, reaps it in a goroutine, and returns. All
callers go through Host.OpenFolder (Library folder, Backups reveal, usage
and backup saves, logs/config reveals, browser reveal), so every sibling is
reached. macOS keeps Wails' way (folder_other.go is now !linux).

Run:
- mote-run go test ./internal/proc, wsl-run (magpie-desktop) go test
  ./internal/proc: ok. New TestOpenFolderDoesNotWaitForTheFileManager: with
  the Wait made synchronous it fails on WSL (waited 1m0s); with Setsid off
  it fails (shares magpie's session); green with the fix, -count=3.
- Real XFCE (magpie-desktop, DISPLAY :0, real Thunar): the old way
  (`timeout 10 thunar dir`) blocked 10s and killed Thunar (rc 124, no
  thunar left); `setsid xdg-open dir` returned at once and Thunar stayed up
  12s later.
- gofmt clean; go vet ./internal/proc for linux, windows (mote), linux (wsl);
  go vet ./internal/gui on macOS.

Not tried: a built Linux magpie GUI clicking the real button (WSL has no
gtk4/webkitgtk-6.0, so internal/gui can't build there, and linux gui vet
wasn't run); Omarchy/Hyprland; AppImage env (LD_LIBRARY_PATH) leaking into
the opener, which is unchanged; the full go test ./... suite and GUI tests
(no GUI or JS file changed).
2026-11-04 04:47:02 +08:00
vincentandJoeyWu-tech 62f612fd44 proc: recheck tools installed within a directory clock tick
Adapt JoeyWu-tech f9d7eac9: do not retain lookup answers or directory listings while their timestamps are fresh. Freeze the clock in the same-tick regression so scheduler delays cannot age the fixture. Keep the settled/future directory cache and document the 100ms resolution limit.

Validation: the same-tick regression fails with both old layers, only the stamp fixed, and only the listing fixed. Restored proc lookup and four affected agent tests pass five race runs.

Batch run, at tree 104d75f0a (the twelve coffemon ports together, on
origin/main 7d022bdb6), mote, macOS, go1.26.8:
- go test -tags nogui -count=1 -timeout 45m on the packages the batch
  changes (agent, autostart, daemon, gateway, library, proc, provider,
  sessions, testenv, tui, gui): ok each.
- GUI, node --test with Playwright 1.62.0, Chromium and WebKit:
  library-*.test.cjs and i18n-keys.test.cjs, 1044 of 1044 pass.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... and go build ./...: ok at cdd7c8e46, the same
  batch on origin/main 00098f12b one rebase before.
- The whole go test ./... at cdd7c8e46: 86 packages ok, one red,
  internal/cli TestEveryRouteHasACommandOrIsNamed (GET
  /api/context/reply has no command), red on main too (#5026).
- Linux (wsl-run, Ubuntu 24.04, at 339055896, the batch on f4c664a09):
  proc, autostart, testenv, tui ok; agent: only TestGrokInstalled red
  (#3548); #4033's proc.Look reds (Zed, Copilot, Qoder, Cursor, Omp)
  pass.
- Windows (win-run, Windows 11, at 339055896): proc, autostart, testenv,
  tui ok; library and agent red in the same tests as on origin/main
  f4c664a09 (#4115, #1827, #4786; #5068, #5069, #5070 filed now).
- Rebased onto origin/main fb1f4856a (three commits, no file in
  common with the batch) and run again at the pushed tree: gofmt -l
  nothing, go build ./... and go vet ./... ok; go test -tags nogui
  sessions, agent, autostart, tui, proc, testenv ok; i18n-keys and
  library-* 1044 of 1044 pass.
- Not run before the push: the whole GUI suite (a run at cdd7c8e46 was
  cut off at 1170 of ~1174 tests when mote rebooted; it runs again after
  the tag and any red is filed).

Co-authored-by: JoeyWu-tech <joey110551567@gmail.com>
2026-11-03 20:38:11 +08:00
yetone a9a8f11e7f plugin, proc: a plugin host is waited for when it ends, not when its stdout does
acezan on Discord (v0.1.2819, Linux x86_64, a systemd service): after
47 hours, 57 <defunct> magpie-bun children of magpie, growing toward the
unit's TasksMax until a restart.

One cause: the plugin host's only cmd.Wait ran in host.read after its
stdout reached EOF. A program a plugin started that kept a copy of the
host's stdout (Bun.spawn given Bun.stdout, which host.js's spawn guard
doesn't catch, #5063; a daemon left behind) held that pipe open past the
host's end, so EOF never came, Wait never ran, the host was never marked
dead, and every host stopped (Restart, a moved proxy, hostStale) stayed a
zombie until magpie quit. Reproduced on Linux (WSL magpie-desktop,
Bun 1.4.2): one more Z-state bun under the test process per Restart,
1, 2, 3, 4 over four rounds. The other cause, magpie web's restart to
update leaving the running host behind its exec (#3285), is the next
commit.

- proc.Output (new, internal/proc/output.go) gives a command's stdout and
  stderr pipes of magpie's own and waits for the command the moment it
  ends. Its readers then have OutputGrace (2s) to read the last lines;
  the pipes are closed after that, which ends a read held up by a
  grandchild. startOn uses it, and a reap goroutine fails the host when
  its child ends. host.read no longer calls Wait. The tests' fake hosts
  (no child) keep cmd.Wait.
- Every other start that wasn't waited for now goes through
  proc.StartReaped (Start, then go cmd.Wait()). Process.Release doesn't
  reap on Unix: codexrelay.Start (a relay that can end while magpie
  runs), tui serveInBackground, uninstall's startAfter, update's
  runAfterExit and OpenBeside (no Wait at all), and Windows' Reexec.
- TestEveryStartedCommandIsWaited (internal/proc) parses every non-test
  .go file. In each function, an x.Start() on a command needs an
  x.Wait(), or x handed on (a call's argument, a struct field), and
  .Process.Release() is refused. It found exactly the sites above.
- docs/subsystems/provider-plugins.md says how the host is reaped.

Checked and left as they are (each waits): the StartTree callers
(provider/install, library mcp_run and mcp_check, gateway claude_warmup
and claude_subscription), pii/serve, provider grok and claude_signin,
claudetui child_unix and wslread, awake, every other bun start (bun.go,
bunupdate, store, dist use Output/CombinedOutput).

Run at 82460a2f9 (on origin/main 40a287b21):
- mote (macOS): gofmt -l clean; go vet on the touched packages,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.
  go test -count=1 -timeout 45m ./internal/plugin ./internal/proc
  ./internal/codexrelay ./internal/tui ./internal/uninstall
  ./internal/update: all ok. -race -count=3 of the new proc tests: ok.
- WSL magpie-desktop (Linux): the same six packages ok, including
  TestHostReapedWhileItsChildHoldsStdout with a real Bun host; -race
  -count=3 of it and the Output tests: ok.
- Windows (xiaomi-gpu), at the tree before the rebase (base 5ee5274bd):
  proc and codexrelay ok. plugin and update had TestPiPackage,
  TestLoadConcurrentWithSavesAndEdits and TestPackagedByDpkg red; each
  fails the same at untouched origin/main 40a287b21 on that box, 3 of 3,
  and is filed (#4115, #1827, #4603).

Broken by hand, each red:
- host.go back to StdoutPipe with Wait only after EOF:
  TestHostReapedWhileItsChildHoldsStdout fails on Linux ("the host isn't
  marked ended 15s after Restart").
- Output.Start waiting for the readers before Wait:
  TestOutputWaitsPastWhatHoldsIt fails (not waited for in 10s).
- codexrelay back to Process.Release: TestEveryStartedCommandIsWaited
  names relay.go:89 and :92.

Not tried: a full go test ./... (mote and WSL were each running other
sessions' package runs, load 39 and 110); a real magpie serve or web
running for hours on Linux; the host test on macOS (no /proc; the
Output test runs there). Not changed: killing what a host left behind
(its process group) when it is stopped; an orphan like the sleep above
stays in the service's cgroup until it ends on its own.

Reported by acezan on Discord.
2026-11-03 17:58:31 +08:00
yetone b2f7818d2e proc: a probe never runs a Windows GUI program, so asking opencode's version doesn't open OpenCode there either (saint carol)
saint carol, on Windows with OpenCode's desktop app: opening magpie,
often right after an update, brings up OpenCode. af0cd09c9 covered only a
Mac's app bundles.

OpenCode's desktop app installs per user, to
%LOCALAPPDATA%\Programs\ai.opencode.desktop\OpenCode.exe (electron-builder
NSIS; @opencodedesktop before), with its CLI at
resources\opencode-cli.exe. The installer puts nothing on PATH, and
"Install CLI" is Mac-only. With that folder on PATH, `opencode` finds
OpenCode.exe, since Windows looks names up without case and PATHEXT adds
.exe. magpie's `opencode --version` at each start and after a CLI update
(proc.Version, library openCodeVersion, cliupdate runCheck) then started
the Electron app. Nothing else in magpie starts OpenCode on Windows: no
App Paths lookup, no opencode:// link, and scoop's opencode-desktop gives
a shortcut, not a shim.

ProbeContext now also refuses (cmd.Err, nothing started) a program whose
PE header names the GUI subsystem (guiExe: e_lfanew, PE signature,
optional header Subsystem == 2). Console programs run as before: CLIs,
bun's, npm's and WinGet's shims, opencode-cli.exe. Anything that isn't a
PE, or whose header can't be read, also runs as before. On the Windows
box, every program magpie probes that is installed there is console
(claude.exe, codex.exe, git.exe). The GUI ones on PATH are system32
tools, git-gui, gitk and Codex's codex-command-runner, which no probe
asks.

Tests:
- TestGuiPE: GUI PE32 and PE32+ headers are a window's program; console,
  a bad magic, a cut-short header, a script and empty bytes are not.
- TestProbeNeverOpensAWindowsApp (Windows): the install's layout is made
  from copies of the test binary, which notes that it ran (TestMain's
  MAGPIE_PROC_RAN). OpenCode.exe is patched to the GUI subsystem as
  Electron's is. With the folder on PATH, `opencode` resolves to
  OpenCode.exe and isn't run, and Version is "". opencode-cli.exe still
  answers 2.2.5.

Broken by hand on xiaomi-gpu: with guiExe out of ProbeContext,
TestProbeNeverOpensAWindowsApp goes red ("OpenCode.exe was run and said
2.2.5").

Run at 4b407bb79 plus this change (go test -count=1 -timeout 45m):
- mote (macOS): internal/proc, library, agent, provider, wslrun ok;
  GOOS=windows go vet ./... ok, GOOS=linux go vet -tags nogui ./... ok;
  gofmt -l empty.
- xiaomi-gpu (Windows, win-run): internal/proc ok. internal/library red
  on TestGoneAgentListedToTakeOut and TestCheckMixedServerEachSide, the
  same at 4b407bb79 without this change, both listed in #4115.
- magpie-desktop (Linux, wsl-run): internal/proc ok.

Not tried: the real OpenCode desktop app on Windows (not installed on the
test box; the layout is from OpenCode's electron-builder config and NSIS
include), the reporter's PATH, and a .cmd or .ps1 the user wrote that
starts OpenCode.exe (still run).
2026-11-02 16:24:51 +08:00
yetone af0cd09c9d proc: a probe never runs a macOS app's own program, so asking opencode's version doesn't open OpenCode (saint carol)
saint carol on Discord: opening magpie, often right after an update,
brings up OpenCode, which they never asked for.

magpie asks `opencode --version` at every start and after a CLI update
(proc.Version for the agents' CLI info, library/rtk.go openCodeVersion,
agent/cliupdate.go runCheck), all through proc.ProbeContext. When the
`opencode` on PATH is OpenCode.app's own program (a link to
OpenCode.app/Contents/MacOS/OpenCode, or the bundle's MacOS folder on
PATH, where a case-insensitive disk finds OpenCode as opencode), running
it with any arguments opens the app's window. A GUI app never answers
--version, and a timeout isn't cached, so it happened again at each
start. Nothing else in magpie opens OpenCode: no `open -a`, no
opencode:// URL, and the Sessions menu's Open/Terminal actions are a
user's click.

ProbeContext now refuses (cmd.Err, nothing started) a program that is
the main executable of an outermost .app bundle, after links: the
CFBundleExecutable of an XML Info.plist, or the program named as the
bundle when the plist can't be read (binary, as Kiro CLI.app's is). Every
probe goes through it: version, auth status, Grok's agentProbe. A
bundle's other programs still run (OpenCode's opencode-cli, Kiro CLI's
kiro-cli beside kiro_cli_desktop), and so does a bundle inside another
app's: ChatGPT.app's codex is CodexCLI.app's main executable (plist
checked on this Mac, ChatGPT 26.1027).

Tests (internal/proc/appmain_test.go, not on Windows): a fake
OpenCode.app whose programs record that they ran.
- TestProbeNeverOpensAnApp: a link to OpenCode is not run, Version is "",
  `opencode` found in the bundle's folder by PATH is refused, the
  bundled opencode-cli still answers.
- TestProbeUnreadPlistByName: no plist / a binary one: OpenCode is not
  run, opencode-cli is.
- TestProbeRunsANestedAppsCLI: CodexCLI.app's codex inside ChatGPT.app,
  with that app's plist keys, answers.
- TestAppMainOnlyBundles: paths that only look like a bundle.

Broken by hand: with the guard off, TestProbeNeverOpensAnApp and
TestProbeUnreadPlistByName go red (OpenCode ran); with the nested check
off, TestProbeRunsANestedAppsCLI and TestAppMainOnlyBundles go red.

Run on mote at a8d6a861a plus this change (go test -count=1 -timeout 45m):
internal/proc, library, wslrun, agent, provider ok. internal/cli red on
TestEveryRouteHasACommandOrIsNamed (POST /api/usage/checkin-account has
no command), which is #4826 from e87140242 and not touched here.
GOOS=windows go vet ./... ok; GOOS=linux go vet -tags nogui ./... ok
(wails' Linux GUI doesn't cross-vet from a Mac); gofmt -l empty.

Not tried: the real OpenCode desktop app (the cause is read from its
bundle layout and magpie's code, not reproduced), the reporter's PATH or
link, and a shell wrapper that execs the GUI program (still run).
2026-11-02 15:53:25 +08:00
yetone b3eb26400c library: a ${NAME} only the login shell exports reaches the MCP server magpie starts or calls
Cyrus on Discord: once a Library MCP server's token was written as
${NAME}, the Library listed no tools for it. magpie expanded the
reference from its own environment only, and a magpie opened from the
Finder or the Dock has none of the profile's variables, so a token
exported in .zshrc was "not set" for the tool-list check, and the
router (dialHub) and Codex's run through the gateway (specOf) didn't
start the server either.

expandAll, the one place all three expand a reference, now takes a
variable magpie's environment hasn't from proc.LoginVars: what the
login shell (and fish or nushell, as shellEnv asks them) exports, read
through /bin/sh as the existing PATH probe is, each answer kept a
minute. On Windows it reads the registry's user then machine variables
(one set with setx after magpie started). The value is only in memory
at call time: never set in magpie's environment, never written to
library.json or an agent's file, never logged. A variable set nowhere
is still novar, naming it ("NAME not set" on the page, unchanged). The
library only documents ${NAME} (no ${NAME:-default}), so nothing else
is parsed.

Run at this head (90d554db1 rebased on 46a13f837), on mote:
- go test -tags nogui ./internal/proc ./internal/library: ok
- GOOS=linux and GOOS=windows go vet ./internal/proc ./internal/library: ok
- gofmt -l: clean
- wsl-run (magpie-desktop): TestLoginVars, TestEnvRefs*, TestCheckStdio,
  TestCheckHTTP, TestShellEnv*, TestLoginEnv*: ok
- ./internal/cli before the rebase: only TestEveryRouteHasACommandOrIsNamed
  red, POST /api/usage/checkin-account, already filed as #4826.
- By hand on mote: LoginVars with the real /bin/zsh (.zshrc) and
  /bin/bash (.bash_profile) in a temp HOME read the exported token and
  left an unset name unset.

TestEnvRefsFromLoginShell: a fake login shell exports CYRUS_TOKEN,
magpie's environment hasn't it; a fake stdio server that exits without
the right token and an http one that answers 401 without it are each
checked (ok, with tools) and dialled by the router, Codex's run spec has
the value, a variable set nowhere is novar, and after SaveServer, a
check and a Sync no file in the sandbox HOME holds the token.
TestLoginVars: exported, exported-empty, unexported and unset names, bad
names never asked, the minute's cache and a new SHELL asked again.

Broken by hand: loginVars returning nothing made TestEnvRefsFromLoginShell
red (command and url both novar CYRUS_TOKEN, the reporter's case);
parseNamed ignoring the set flag made TestLoginVars red.

Not tried: the Windows registry read (compiled by vet only, no run on
xiaomi-gpu); a real Finder-launched magpie.app with a real token; the
GUI suite (no GUI file changed).
2026-11-02 11:01:51 +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 51aa4c0ef3 codex: a turn left open by a gone app-server doesn't hold an account switch back (danzi002)
蛋仔 (danzi002 on Discord, 10-29 and 10-30) switched the Codex app's
used-up account in magpie, auth.json changed, and the app stayed grey
until it was quit and opened: "如果打开了 codex 再不点击任何会话的时候,
我手动切换账号它会重启,如果点了会话再切换账号就重启不了". dd9828f2b
made a switch restart every one of the app's own app-servers once no
Codex turn runs. This one never ran.

Why. Codex reads auth.json once; a 401 reloads it only for the same
account id (codex-rs/login/src/auth/manager.rs, reload_if_account_id_
matches), so only a new app-server takes up a switched account.
codexAppStep waits while any session file written to in the last 30
minutes ends in task_started. Tried with the real codex
0.164.0-alpha.11.1 (ChatGPT.app's), sandbox HOME/CODEX_HOME, a fake
Responses server holding a turn open:
- SIGTERM or stdin closed mid-turn: turn_aborted is written.
- SIGKILL (force quit, crash): the file ends in task_started for good.
- thread/resume in a new app-server, which is what opening the thread
  in the app does, appends thread_settings_applied and moves the mtime
  each time, nothing else changed.
- a 429 usage_limit_reached ends the turn with task_complete, so being
  out of credit doesn't leave one open.
So a thread whose turn a killed app-server left open reads as running
for as long as the user keeps opening it, and the switch waits forever.

Change. proc.Started(pid) reads when a process started (darwin
kern.proc.pid P_starttime, Linux /proc/<pid>/stat starttime + btime,
Windows GetProcessTimes; ErrNoStart elsewhere). codexAppStep and
RestartCodexAppWhenIdle pass the oldest start of the app-servers they
would end; an open turn whose task_started line's timestamp is more
than 2s before it can't be running in them and no longer counts. A
start or a timestamp that can't be read counts the turn as running, as
before. A turn started in a running app-server still holds it: no turn
is cut short.

Run (mote-run unless said):
- gofmt -l internal/proc internal/provider: clean.
- go vet ./internal/proc ./internal/provider on darwin, GOOS=linux
  -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m ./internal/proc ./internal/provider:
  ok (6.2s, 110s).
- wsl-run (magpie-desktop) and win-run (xiaomi-gpu): TestStarted,
  TestCodexTurnOpen, TestCodexApp*: ok.
- The real killed-turn rollout above, copied into a temp test: open
  with since unknown, not open with since after the kill, open with
  since before the turn.
Broken by hand:
- codexAppStep passing a zero since (the old behaviour):
  TestCodexAppSwitchPastATurnItsServerNeverRan red ("ended [], want
  [60]").
- sessionTurnOpen ignoring since: TestCodexTurnOpen red too.
Not tried: the reporter's own app on a real account switch; whether
their app-server was in fact killed (force quit or crash) is not known.
A restarted app-server with the thread left open was not watched
ungreying Send in the real app.
2026-10-30 01:22:45 +08:00
yetone 7fe98c2afd proc: the /bin/sh tests of CombinedOutputOwn skip on Windows
TestCombinedOutputOwnRuns and TestCombinedOutputOwnContext (531b44a9a)
run /bin/sh, which Windows lacks, so internal/proc was red on the
Windows box at origin/main (exec: "/bin/sh": executable file not found
in %PATH%). Windows CI only compiles tests, so nothing showed it. They
skip there now, as TestCombinedOutputOwnAnswersForItself already does
off macOS.

What was run (this tree):
- win-run go test -count=1 ./internal/proc/: ok 8.6s (red at
  origin/main with the two tests above).
- mote: go test -run 'TestCombinedOutputOwn|TestTreeRSS' -v
  ./internal/proc/: all four pass, none skipped.
2026-10-28 18:26:59 +08:00
yetone b569d1ab77 proc: TestTreeRSS reads on past a first 0 kB under WSL2 (#4033)
Under WSL2 (magpie-desktop, kernel 5.15) a sleep's /proc/<pid>/status
says "VmRSS: 0 kB" on the read right after its exec, before the loader
maps anything. parseKiB counts 0 as no reading, and the test's wait loop
stopped on the first !ok, so it failed at 0.00s every run there. A read
a few ms later says 1792 kB. The loop now waits while there is no
reading too, within the same 10s.

Product code is unchanged: the one caller (claude_rss.go's oversized)
reads a Claude Code after a whole turn, and a 0 there skips the check.

What was run (this tree):
- wsl-run go test -count=20 -run TestTreeRSS ./internal/proc/: ok
  (red 3 of 3 at origin/main before).
- go test ./internal/proc/: ok on mote (6.1s) and on WSL (2.7s).
  Windows: TestTreeRSS passes; TestCombinedOutputOwnRuns and
  TestCombinedOutputOwnContext are red there at origin/main too
  (/bin/sh), fixed in the next commit.

Refs #4033
2026-10-28 18:26:59 +08:00
JoeyWu-tech 759b3b8c49 proc, provider: the env tests wait for their helper to be running (#3906)
TestEnvOfChild (internal/proc) and TestCodexAppServersOnHome
(internal/provider) are red on Linux since 8b0132b3, on ubuntu CI at
e056779a (run 40492644859): "EnvOf = map[], want map[CODEX_HOME:/sand
box/h/.codex HOME:/sand box/h]" and "HOME's .codex: not counted". Each
starts this test binary as a helper with a HOME (and CODEX_HOME) of its
own, and reads them back (proc.EnvOf, which codexAppHomeIs asks) the
moment cmd.Start returns. On Linux EnvOf reads /proc/<pid>/environ.
Start returns once the exec has put the new program's memory in place,
before the kernel has set where its environment lies in it, and environ
read in that window is empty. On macOS EnvOf runs ps -E, and macOS CI
has neither red.

Each helper now writes "running" to its stdout once its test runs, and
the tests read that line before anything else, as filelock's
TestLockAcrossProcesses waits for "locked". TestEndExitsClean waited
200ms for the same helper before ending it, "so the signal isn't taken
before its handlers"; it waits for the line too.

The wait has a cost the old timing hid. A helper is given no
testenv.Marker, so its TestMain makes a test home of its own in TMPDIR,
and once killed at its test's end it never removes it. At e056779a each
helper was killed before it got that far; waiting for it to run, every
helper would leave its home in the machine's temporary folder. Each
helper's TMPDIR is now a folder of its test's own (t.TempDir), removed
after the helper is ended. The other tests that start this binary again
hand it os.Environ(), testenv.Marker included, and make no home.

Not changed: EnvOf. magpie reads it of the Codex app-servers it finds
running; one read in that window would have no HOME, so codexAppHomeIs
says no and the app-server is left running, not restarted.

What was run (tree d20d0362, on origin/main e056779a, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- -count=100 -v: at e056779a TestEnvOfChild red 53 times and
  TestCodexAppServersOnHome 95 (80 at HOME's .codex, 15 at CODEX_HOME),
  TestEndExitsClean never. Here 300 PASS, in a TMPDIR of the run's own,
  with no test home left in it.
- Broken by hand, the helpers' TMPDIR a folder of its own instead of the
  test's, to count what they leave: -count=20 left 20 test homes from
  TestEnvOfChild's helpers and 40 from TestCodexAppServersOnHome's. The
  same at e056779a, without the wait: none, each helper killed before it
  made one. Here: none.
- -race -count=30 over the three: ok.
- The window itself, outside magpie: a Go program starting a child with
  a HOME and reading /proc/<pid>/environ the moment Start returns read
  it empty 510 times in 1000 for /bin/sleep and 58 in 1000 for a
  statically linked Go binary.
- internal/proc whole: ok (at e056779a TestEnvOfChild red).
  internal/provider whole but TestUnreadLoginsWriteErrorsKeepCredentials
  (#3632's crash), Bun 1.4.2: TestCodexAppServersOnHome passes, and
  #3854's three tests are red, as at e056779a.
- go test -tags nogui -count=1 -timeout 45m ./... outside graftcp, umask
  077, Bun 1.4.2 (log kept): 70 packages ok, internal/proc among them,
  and 6 red, none in what this changes. In internal/provider
  TestCodexAppServersOnHome passes before #3632's crash ends the
  package. The reds: agent TestFolderVarsAreListed (#3884, main's CI
  red), TestCodexDriftReached (#3398), TestInstalledVersion,
  TestHowInstalled, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir (#3141),
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask 077,
  #3640); gateway TestPluginToldWhereTheAgentWorks (#3675); gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie (#3649);
  provider's "close of synctest channel from outside bubble" from
  TestUnreadLoginsWriteErrorsKeepCredentials (#3632, main's CI red).
- gofmt -l clean. go vet -tags nogui and go build -tags nogui for linux,
  windows and darwin, and go vet and go build for windows without the
  tag: exit 0 each. go vet and go build without the tag on linux: exit 1
  (this box has no GTK or WebKitGTK dev packages).

Not tried: Windows, where TestEndExitsClean wants code 0, and macOS.

Merged from JoeyWu-tech's branch, cherry-picked onto origin/main d6c459c79 with the other of #3906/#3854. Run on mote (macOS) at that tree:
- go test ./internal/proc/ ./internal/provider/: ok, both whole (provider's first whole pass since #3632).
- the six tests these two touch, -count=20: ok. Each was red on main before.
- GOOS=linux and GOOS=windows go vet ./internal/proc/ ./internal/provider/: ok.
Not run here: Linux, where #3906 was red; its record is the author's above and the CI run of this push.
2026-10-28 07:10:09 +08:00
yetone c89284ae66 library: a server turned off everywhere has its running processes ended (#3885)
Turning MCP servers off in the Library rewrote the agents' configs, but
Codex, the Codex app and Claude Code read them only at start, so the
servers they had started kept running. With every server turned off, the
reporter's machine still held 17.75 GB of node processes for them.

A change, and the sync at start, now record each stdio server it took out
of an agent's config as that config had it. Once no agent's config runs
that command and those arguments (another agent's entry, or the user's own
under another name, keeps it), proc.EndTrees ends every process whose
command line runs it, with all it started: the cmd /d /s /c "npx -y x"
wrapper, the node npx-cli.js under it and the server under that. magpie
and what it runs under are never picked, and a process under one picked
goes with that one. An interpreter with nothing after it (node, npx) is
never matched. It runs after the change lets go of the Library lock and
before it returns, so magpie library mcp ends them too before it exits.

On Windows the processes come from a Toolhelp snapshot with their command
lines (no PowerShell); elsewhere from ps -o pid=,ppid=,args=.

Run at base e54a7d50b, before the rebase onto 34d38ed66:
- gofmt -l internal/: clean; go vet -tags nogui for linux, windows, darwin
  on internal/proc, internal/library, internal/cli: ok
- go test -count=1 -timeout 45m ./internal/proc ./internal/library
  ./internal/cli: ok (28s, 197s, 66s)
- the proc test binary on the Windows box: TestParseFamily, TestPicks,
  TestEndTreesEndsWhatItStarted, TestEnd*, TestList*: PASS
- broken by hand: endFamily ending the picked process alone on macOS made
  TestEndTreesEndsWhatItStarted red (its child ran 20s on); dropping the
  dropped-server record made TestDroppedServerEndedOnceNoAgentRunsIt red
- real, on the Windows box in a sandbox USERPROFILE, with Node 22.11.0
  (SHA-256 checked against nodejs.org's SHASUMS256): magpie library mcp add
  fs npx -y @modelcontextprotocol/server-filesystem <dir>
  agents=codex,claude; a stand-in agent started it as Codex does, through
  cmd with stdin held open: cmd -> node npx-cli.js -> cmd -> node
  index.js, 4 processes. Off for Codex only (Claude Code still has it): 4
  left. Off for every agent: "ended 1 process trees of fs", 0 left, the
  stand-in agent still running.

Not tried: a real Codex or Claude Code session holding the server (no
signed-in agent may be copied to the sandbox). Not done here, from the
same issue: writing the installed bin instead of npx, the opencode.json
servers stub, and an applied.json record of MCP changes.

At the rebased head (base 34d38ed66): go build ./..., GOOS=linux/windows/darwin
go vet -tags nogui ./internal/proc ./internal/library ok; TestParseFamily,
TestPicks, TestEndTrees*, TestDroppedServer*, TestLaunchedBy ok. The
rebase brought no proc or library changes.
2026-10-28 00:19:24 +08:00
yetone bafdf14923 proc: End on Windows ends what the process started too
The Codex app restart on Windows (df8374921, 3aead9c62) ends codex.exe
app-server through proc.End, which was TerminateProcess on codex.exe
alone. Where SIGTERM lets Codex end its own MCP servers, TerminateProcess
does not, so node.exe under npx, uvx and the rest were left running with
no parent, one more set each restart (liam_8829, 10-27).

End now lists pid's descendants while it is alive (killtree_windows.go's
descendants, the walk cancelTree already uses), ends pid with exit code 0
as before (the app reads 0 as a clean exit and starts it again), then
TerminateProcess's each descendant. Unix is unchanged (endTree = end).

Run:
- TestEndEndsWhatItStarted (new, Windows): cmd.exe /c ping -n 60; End(cmd)
  must leave cmd exited 0 and the ping gone. On the Windows box
  (10.0.0.132): the old proc test binary fails it ("process 52016 ...
  still runs after End"), the new one passes.
- The whole proc package on the Windows box (TestNoCommandBypassesProc
  skipped: it walks the source from the cwd): only
  TestCombinedOutputOwnRuns and TestCombinedOutputOwnContext red, which
  need /bin/sh and fail the same on the old binary.
- go test -count=1 -timeout 45m ./internal/library ./internal/proc
  ./internal/provider:
  library ok (312s), proc ok (40s) at b67c7eaa0 (rebased on origin/main
  14e4d8040). provider red only in tests already filed: with
  -skip TestUnreadLoginsWriteErrorsKeepCredentials (the synctest crash in
  filememo.Forget, #3632, on main since 091153bf), its only reds are
  TestFetchAsksOneListOnceForTwoBasesOfIt, TestFetchUnionsProtocolLists-
  WithoutChat and TestFetchAsksASharedBaseOnce (#3854, on main since
  6eb510f78). Neither touches this change.
- gofmt -l internal/ clean; go vet darwin, GOOS=linux -tags nogui,
  GOOS=windows on library, proc and provider.

Not tried: the real Codex app on Windows with real MCP servers under it.
MCP servers codex.exe itself loses while it runs are Codex's own.
2026-10-27 18:52:15 +08:00
yetone 8b0132b3d2 codex: the Codex app sends again on every system as soon as magpie takes a used-up ChatGPT account over, and gets it back at the reset
Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540. The Codex app greys
Send for every model, magpie's too, while the ChatGPT account it is signed in
to is used up. Its composer's gate (ChatGPT.app 26.1013) reads authMethod
"chatgpt" plus rate limit allowed=false, and it asks account/read only when its
app-server starts. ef37b6fb7 (v0.1.1381) could fail in practice:
- (a) The reopen was macOS-only, ran once per time out, only from the GUI
  process. A Windows or Linux user, a magpie without its window, or a second
  time out stayed greyed.
- Switch-back: the app stayed on magpie (authMethod null, no cloud tasks or
  Log out) after the reset. Nothing restarted it.
- (c) Detection lag: the account was read every 5 minutes.
- The notice sat on the Providers page, not on Codex's Agents row.

Now:
- The gateway process (`provider.KeepCodexAppOnItsProvider`, every 3s, on
  every OS) ends the Codex app's own app-server each time `Agent.AppOut`
  flips, both ways. The app starts another at once and reads account/read
  afresh. Its window, threads and drafts stay.
- It never ends an app-server while a Codex request is in flight through
  magpie or ended in the last 10s (`Server.CodexBusy`, Codex's requests only),
  or while a session under the Codex home has a turn open (`codexTurnOpen`).
- It ends only the app's own app-server. That one runs on stdio; one another
  program starts with `--listen` is left alone (Miyi Helper runs one on this
  Mac). It must also run on magpie's Codex home (`proc.EnvOf`: ps -E on macOS,
  /proc on Linux; Windows can't tell).
- The exit is clean (`proc.End`: SIGTERM, or TerminateProcess with code 0 on
  Windows). The app shows any other exit as a crash.
- A listing that fails is taken up again at the next look. One that outlives
  3 ends, or is denied, makes the row say to quit and reopen.
- The active account is read every minute while it is held or a window is at
  90% or more (`codexLookEvery`).
- Codex's Agents row says "On magpie until <reset> · ChatGPT allowance used
  up". Hovering it, or opening the row, says what is off until then (cloud
  tasks, the usage meter, Log out) and that it all comes back on its own. In
  en, zh, zh-TW, ja and de.
- Removed: gui's keepCodexAppSending/codexAppOut, provider's episode
  bookkeeping, and the Providers-page notice.

Not changed, by design:
- A Codex own model that no magpie account serves stays as it is: magpie
  can't serve that turn.
- Account discovery off and "Only switch Codex's sign-in" (login=chatgpt) are
  the user's own choices, and are left alone.

Full suite green at cff1a9686 (on origin/main 6ce0f14b9), below. At
4541b3e97 (rebased on 430e3050d, which touched gateway.go, app.js and
i18n.js beside this) ran: gofmt -l, go build ./..., go vet on darwin,
linux (-tags nogui ./...) and windows; go test -run Codex ./internal/provider
./internal/agent ok; GUI codex-app-out (22 ok) and codex-app-stale (20 ok),
chromium and webkit. Pushed rebased on b92cb2f59 (two more commits,
neither in these files), built, not rerun.

Run at this commit (cff1a9686, on origin/main 6ce0f14b9), with a private
GOCACHE (another session ran go clean -cache mid-run):
- gofmt -l: clean. go build ./...: ok.
- go vet: darwin (touched packages); GOOS=linux -tags nogui ./...;
  GOOS=windows (touched packages).
- go test -count=1 -timeout 45m: internal/proc, internal/provider,
  internal/agent, internal/gateway, internal/gui all ok, skipping four
  tests red on main without this change, each already filed:
  TestUnreadLoginsWriteErrorsKeepCredentials (#3632, a synctest crash
  since 091153bf) and TestFetchAsksOneListOnceForTwoBasesOfIt,
  TestFetchUnionsProtocolListsWithoutChat, TestFetchAsksASharedBaseOnce
  (#3854, since 6eb510f78). All three of the latter fail the same at
  origin/main 6ce0f14b9 and at 353519f55 without this commit.
- GUI at cff1a9686, chromium and webkit, 231 cases ok: codex-app-out (5 languages, 980 and 440px),
  i18n-keys, gui-de/ja/zh-tw, codex-app-stale, codex-accounts-via,
  agent-stale-copies, agent-app-restart, agent-failover, agent-connect,
  agent-layout, agent-expand-steady, agent-connected-unfolded,
  agent-notice-lang and codex-signin-always.
- Windows box (cross-built test binaries): proc and provider's Codex app
  tests pass. TestEndExitsClean passes there and goes red with exit code 1.
- Broken by hand, each went red:
  - Codex-only busy: TestCodexBusy.
  - The 90% cadence: TestCodexLookEvery.
  - The retry after a failed listing: TestCodexAppServerUnknown.
  - The turn guard: TestCodexAppServerRestartedEachWay.
  - The --listen exclusion: TestCodexAppOwnServer.
  - Code 0 on Windows: TestEndExitsClean.
  - The row's notice: codex-app-out.test.cjs, 4 of 4.
- Real app: ChatGPT.app 26.1013 in a sandbox HOME/CODEX_HOME, with this
  build serving on 3492/3493. Codex was put on magpie as Sync does for a held
  account (model_provider = "magpie", codex.out in stash.json). OpenAI's usage
  reading to the app was never faked.
  - The first listing ran out at load ~200, so the timeout is now 30s. The
    next look ended the app-server, and the app started another 12s later.
    Its profile went from "Pro · Usage · Log out" to "magpie" with no reopen,
    and /api/state carried appOut.
  - Undoing it ended the app-server again, and the profile came back to Pro,
    Usage and Log out.
  - The owner's own ChatGPT app (its app-server on ~/.codex) was never
    touched.
- One webkit codex-app-out run at load 291 had one red subtest, name lost.
  It passed 3 of 3 alone and in two full webkit runs.

Not tried:
- The Windows Store app (not installed on the box), and a real Codex app
  on Linux.
- A real used-up account.
- A turn running in the real app while the switch happens (unit-tested
  only).
2026-10-27 15:57:41 +08:00
yetone 531b44a9a8 codex: the daemon magpie restarts asks macOS for folders in its own name, not magpie's (reformed9448 on Discord)
The first `codex --yolo` in a terminal had macOS say magpie wanted files
in the Desktop folder. magpie keeps Codex's managed app-server daemon
current (KeepCodexDaemonCurrent restarts it with `codex app-server daemon
restart` when no session is attached). On macOS a process is the TCC
"responsible process" of whoever started it, so the daemon that restart
leaves running answered to magpie. Every codex run in a terminal attaches
to that daemon, which works in the run's folder, so ~/Desktop was asked
for under magpie's name.

proc.CombinedOutputOwn runs a command through posix_spawn with
responsibility_spawnattrs_setdisclaim (looked up with dlsym, as it has no
header), so the command and what it leaves running answer for themselves.
Only stdio is passed on, stdin is /dev/null, signals are reset, and the
context's end kills it as CommandContext would. restartCodexDaemon uses it.
Elsewhere, and in a build without cgo (the CLI), it is cmd.CombinedOutput.

Run (darwin/arm64, Go 1.26.8, at f51ab771f + this):
- go test -count=1 ./internal/proc/: ok (TestCombinedOutputOwnAnswersForItself,
  TestCombinedOutputOwnRuns, TestCombinedOutputOwnContext)
- go test -count=1 ./internal/provider/: ok with
  -skip TestUnreadLoginsWriteErrorsKeepCredentials; that test crashes with
  "close of synctest channel from outside bubble" in filememo.Forget on
  main too, which is #3632 (open, a patch is under review there)
- gofmt -l clean; go vet for darwin, linux and windows on proc and provider;
  CGO_ENABLED=0 -tags nogui build, the GUI build, linux nogui and windows
  builds
Broken by hand:
- the disclaim call turned off: TestCombinedOutputOwnAnswersForItself red
  ("the sleep answers to 2201, this process to 2201")
- restartCodexDaemon back on cmd.CombinedOutput:
  TestRestartedCodexDaemonIsNotMagpies red ("the daemon answers to 2201,
  magpie to 2201")
Not tried: a real TCC prompt (the tests check the responsible pid macOS
reports, which is what the prompt names; it can't be shown in a sandbox).
The CLI build, without cgo, still starts the daemon as its own child; it
is the GUI that keeps the daemon current for most users.
2026-10-27 12:28:06 +08:00
yetoneandEdward4226 5b4da5bee3 proc: magpie on Windows finds fnm's node and npx (#2685)
What changed
- fnm puts its Node on a terminal's PATH from the shell profile
  (`fnm env | Invoke-Expression`), never in the registry, so magpie
  started from the Start menu had no node: a Library MCP server run by
  bare npx was "notfound", and one run by npx.cmd's full path (the
  reporter's C:\Users\...\fnm\aliases\default\npx.cmd, alone or under
  `cmd /c`) exited 1 with cmd's "'node' is not recognized", since the
  package npx fetched runs node by name.
- Windows UserPath (no-op before) adds the folder fnm's default alias
  names, after what PATH has. UserBinDirs (FindTool) gets each fnm
  Node: the default alias first, then installations newest by number.
- fnm's Windows layout, checked against Schniz/fnm master (config.rs,
  directories.rs, version.rs, fs.rs, commands/env.rs): root FNM_DIR,
  else etcetera's Windows data_dir\fnm (home\AppData\Roaming, APPDATA),
  else legacy ~\.fnm; versions in node-versions\<v>\installation with
  node.exe/npx.cmd directly in it (no bin on Windows); aliases\default
  a junction to an installation folder; the "system" alias points at
  Z:\_fnm_\..., read as none. XDG vars on Windows only move fnm's
  multishell links, not its versions. LOCALAPPDATA isn't used for them.
- The shared node-version helpers (nodeVersions, parseNodeVersion,
  nodeVersionLess, isDir) and addPath moved from the !windows files to
  nodever.go unchanged; fnmWin* there take home/APPDATA/FNM_DIR as
  arguments so the tests run them on every OS.
- The Library check (checkStdioAt, this machine only) starts a bare
  command PATH lacks from where proc.FindTool finds it and puts that
  folder on the child's PATH (stdioProgram, withPath), as the owner's
  plan on the issue said. Docs: agent-wiring.md, library.md.

Run
- macOS: go test -count=1 ./internal/proc/ ./internal/library/ ok
  (TestNoCommandBypassesProc and the other proc guards included);
  gofmt -l clean; go vet GOOS=windows/darwin for proc, library, cli,
  daemon; GOOS=linux vet proc, library and (-tags nogui) cli, daemon;
  GOOS=windows test binaries for proc and library build.
- Windows box (Win 11 x64), cross-compiled amd64 test binaries:
  TestUserPathFnmNode (real junction via mklink /J, npx.cmd that runs
  node by name) red on origin/main 4a1cd7765's code ("PATH after
  UserPath = [C:\windows\System32], want fnm's default alias"), green
  here; TestFnmWin* green.
- Real fnm 1.39.0 + Node v24.22.1 installed into a sandbox
  (USERPROFILE/APPDATA under C:\Users\yeton\fnm-2685, no FNM_DIR,
  registry PATH without node). A throwaway probe calling UserPath then
  library.CheckServer on chrome-devtools-mcp@latest:
  4a1cd7765: npx -> notfound; ...\aliases\default\npx.cmd -> exited 1;
  cmd /c ...npx.cmd -> exited 1 (the reporter's case).
  This commit: all three ok, 32 tools.
- Broken by hand: stdioProgram without FindTool ->
  TestStdioProgramFindsWhatPathLacks red; fnmWinBins without the
  default alias -> TestFnmWinBins red; Windows UserPath as before ->
  TestUserPathFnmNode red (above).
- Windows full proc/library binaries: TestNoCommandBypassesProc,
  TestGoneAgentListedToTakeOut, TestCheckMixedServerEachSide,
  TestCheckKeepsToolNames and TestRTKNoHookIssuesAreEachAgents fail
  the same with 4a1cd7765's binaries run the same way; the guard and
  two of them read the source tree, which a binary run outside a
  checkout doesn't have; the other two are in #1827.

Not tried
- The desktop GUI on Windows with the reporter's fnm (the probe runs
  the same UserPath and CheckServer calls the app does).
- magpie serve/web/tui on Windows don't call UserPath (as on macOS), so
  there an absolute npx.cmd still lacks node on PATH; a bare npx is
  covered by the check's FindTool.
- Agents magpie starts get the new PATH only from the GUI/daemon.

Refs #2685

Co-authored-by: Edward4226 <234070868+Edward4226@users.noreply.github.com>
2026-10-27 06:45:37 +08:00
yetoneandskygunner cec54c1d01 proc: main's two reds, the TUI's serve start through proc.Command (#3567) and an RSS read before the loader ran
Test (ubuntu, macos) on main has been red since 75e78a5a0 on two tests.

TestNoCommandBypassesProc: internal/tui/keep.go's serveInBackground
started `magpie serve` with os/exec. It is proc.Command now, the fix
skygunner gave on #3567 (64bd29fa on their fork). Off Windows
proc.Command is exec.Command, and this path runs on Linux only, so
nothing else changes.

TestTreeRSS (ubuntu only): the test read sleep's VmRSS right after
StartTree and wanted at least 64 KiB. Just after its exec a command
holds a few pages until its loader maps libc: CI read 16384 bytes. The
test now reads again until it holds 64 KiB, for up to 10s. Tree.RSS
itself is unchanged.

Run at this head:
- golang:1.26 docker (Linux, CI's Go): TestTreeRSS -count=50,
  old test red 13 of 50 ("a running sleep holds ..."), new 50 of 50 ok.
- macOS: go test -count=3 ./internal/proc ./internal/tui ok (the old
  keep.go is the guard's red on CI's runs 40199986992 and earlier).
- GOOS=linux and GOOS=windows go vet -tags nogui on both packages,
  gofmt clean.
Not run: the full suite.

Co-authored-by: skygunner <skygunner@users.noreply.github.com>
2026-10-25 23:15:45 +08:00
yetone a093e9c3a5 claude: a Claude Code run holding over its memory budget is let go after its turn, its session resumed (#3256)
claudeRoom bounded how many Claude Code processes run, not how large
each one is. A run is kept for its conversation's next turn, turn after
turn, and on a service never restarted one grew for days: a
node-MainThread in magpie.service reached 8 GiB RSS on a 31 GiB host and
the OOM killer took the machine down (#3256).

Now each time a run's reply ends, its process tree's resident memory is
read (proc.Tree.RSS: /proc VmRSS on Linux, ps on macOS, the working sets
of its job's processes on Windows, so an npm claude.cmd's node counts)
and logged with its pid. Over the budget (an eighth of memLimit on
Linux, of the computer's memory elsewhere, 1 GiB at least, 4 GiB if
unknown), a whole turn's run is not kept idle: its session is shelved
and the next turn resumes it in a new Claude Code with --resume, told
only the new messages. A run parked on tool calls is let go past 1.5x
the budget (no session to shelve there; its results start a new run).
Each Claude Code also logs pid and model at start, and run time, how it
ended and peak RSS (ru_maxrss) at its end, so an OOM pid can be found in
magpie's log. Budget on the reporter's 31 GiB host: 3.9 GiB.

Run (worktree at 99de8e1ad + this change, macOS arm64):
- go test -timeout 45m ./internal/gateway -run
  'Claude|Subscription|Room|Park|Idle|Resume' -count=1: ok (60.5s).
- go test ./internal/proc -count=1: every test ok except
  TestNoCommandBypassesProc, red on origin/main since 75e78a5a0
  (internal/tui/keep.go, filed as #3567, not this change).
- New tests: TestClaudeOversizedRunIsLetGoAndResumes (injected RSS over
  budget: the run ends, the next turn runs --resume s<pid> and is not
  told a1 again), TestClaudeRunWithinBudgetIsKept,
  TestClaudeOversizedParkedRunIsLetGo, TestClaudeRunBudgetScalesWithMemory
  (31 GiB MemTotal -> an eighth; 2 GiB -> the 1 GiB floor), TestTreeRSS
  (a real sleep's RSS read; none once waited for).
- Broken by hand: with both checks turned off, the oversized idle and
  parked tests go red ("the oversized run to end", "a run over its
  budget was kept waiting on its tool calls").
- Real Claude Code 2.1.310 in a sandbox HOME and CLAUDE_CONFIG_DIR,
  stream-json like the bridge, against DeepSeek's Anthropic endpoint
  (deepseek-chat, real key, synthetic 40KB turns): RSS after turns
  1/10/20/30 = 192/244/223/233 MiB, peak 245 MiB over 30 turns and
  ~1.2 MB of conversation. oversized() on that real process with the
  budget 1 MiB under its RSS said over; with the real budget on this
  64 GiB Mac (8192 MiB) it said keep.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags
  nogui ./internal/proc ./internal/gateway clean.

Not tried: a real Claude subscription run through the bridge on Linux
until it crosses the budget (the retire path is shown with injected RSS
on the fake Claude Code, and the RSS read on a real one); the Windows
RSS reader and job listing on the Windows box (vet only); a Linux run of
the /proc reader (macOS reads through ps); the full ./internal/gateway
package.
2026-10-25 17:41:41 +08:00
yetone fc9430e12d proc: Windows lists processes from a Toolhelp snapshot, not a new PowerShell and WMI each time (#3467) 2026-10-24 21:00:05 +08:00
yetone 68a96b67b8 proc: a command's context ending on Windows kills what it started too (#2341)
The Store's WSL runs System32's wsl.exe, which starts Program Files'
wsl.exe and waits on it. When `wsl.exe -l --running -q` hung past its
timeout, CommandContext killed the first only; the second, waiting on
a hung WSL service, was left. With a retry every few seconds that came
to dozens of wsl.exe a day on the reporter's machine. ProbeContext had
the same gap on Windows: Output starts the command out of a job's
reach, so the probe was killed alone.

CommandContext's Cancel on Windows now finds the command's descendants
by parent pid (a Toolhelp snapshot; a reused pid is told apart by a
start before its parent's) and terminates them before the command.
ProbeContext's Windows cancel does the same. wslrun's cancelable kept
its own Cancel and dropped proc's: it now runs proc's after stopping
the run inside the distro, so it gets the tree kill too (and a probe's
end, which it had lost).

Measured on the Windows box (10.0.0.132), cmd.exe running ping as the
two wsl.exe:
  before: 1 child left running per ended context (CommandContext and
          ProbeContext both)
  after:  0 left

Run:
- TestContextEndKillsWhatTheCommandStarted, windows/amd64 test binary
  on the Windows box. With killDescendants commented out in both
  cancels:
    killtree_windows_test.go:71: process 57548 that cmd.exe started still runs after its context ended
    killtree_windows_test.go:71: process 42264 that cmd.exe started still runs after its context ended
    --- FAIL: TestContextEndKillsWhatTheCommandStarted (4.08s)
  With the fix: --- PASS (0.09s), both subtests.
- The whole proc test binary on the Windows box: everything passes but
  TestNoCommandBypassesProc, which walks the source tree from the
  binary's folder and read other checkouts under C:\Users\yeton (the
  binary ran outside a checkout). wslrun's test binary there: PASS.
- macOS, sandbox HOME: go test -count=1 -timeout 45m ./internal/proc/
  ./internal/wslrun/ -> ok proc 54.098s, ok wslrun 2.872s.
- gofmt -l clean; go vet ./internal/proc ./internal/wslrun;
  GOOS=linux and GOOS=windows go vet -tags nogui ./... clean.

Not tried: a real hung WSL service. The box's WSL answers, so the
reporter's hang itself wasn't reproduced; the test's cmd.exe→ping
stands in for System32 wsl.exe→Program Files wsl.exe.
2026-10-20 20:23:51 +08:00
yetone df3734b959 proc: the login shell's variables count only when exported, and Codex's proxy detail names the variable it read (#2627)
ReneXiong: Codex showed the "proxied" drift, "through the proxy at
http://127.0.0.1:7890, set in HTTP_PROXY", while Codex went direct. The
value was fish's universal http_proxy from an old Clash setup, never
exported (`set -S` says "unexported"), so no program fish starts has it.
shellEnv asks fish beside the login shell (zsh), and shellProbe printed
"$http_proxy" in the shell itself, which expands unexported variables too;
mergeShellEnv then filled zsh's empty value with fish's.

Fix at the shared reader: every shell is now asked to run
/bin/sh -c 'printf ... "$PATH" "$CODEX_HOME" ...', the form nushell already
used (still with its ^). A child sees only exported variables, so each
value is what an agent started from that shell gets. This covers every
reader of the probe: Codex's proxy (codexEnv), Claude Code's provider
switches (claudeShellEnv), and agentenv.Vars such as CODEX_HOME and
CLAUDE_CONFIG_DIR that magpie takes into its own environment; an
unexported zsh or bash variable no longer counts either, which matches what
an agent run from that terminal sees. Proxy variables are still merged from
fish when the login shell has none: a fish user who exports one runs Codex
with it from fish, so taking proxies from the login shell only (the
report's other suggestion) would miss that case.

codexProxyFor named HTTP_PROXY (or HTTPS_PROXY, ALL_PROXY) for a value in
the lowercase variable. It now names the one it read, in both the reqwest
and respect_system_proxy paths, and the detail's NO_PROXY advice matches a
lowercase name too (and not "the system's proxy settings").

Other proxy readers checked: the daemon's carried env, wslrun's proxyVars,
netproxy and the plugin host read magpie's own environment, not a shell;
the WSL probe scripts ask for no proxy variable.

Tests: TestLoginEnvUnexportedNotCounted, a login shell with the reporter's
literal values unexported beside an exported NO_PROXY; TestShellEnvRealFish
now writes the reporter's literal fish_variables lines and checks that
http_proxy, https_proxy and all_proxy read empty;
TestCodexProxyNamesItsVariable. Broken by hand, each went red: the old
in-shell printf (unexported values read back, in the fake shell and in real
fish 3.7.1), and env() naming keys[0].

Run: go test ./internal/proc and the codex proxy tests on darwin;
TestShellEnvRealFish, TestShellEnvFishLogin and
TestLoginEnvUnexportedNotCounted on real fish 3.7.1 in an alpine container
(linux/arm64), green with the fix and red without it; gofmt -l clean; go vet
-tags nogui ./... for darwin, linux and windows; the full go test -tags
nogui -timeout 45m ./... under pipefail, both fixes together on
origin/main ec6454395: exit 0, 66 packages ok, no FAIL.

Not tried: the reporter's Mac with fish itself, and nushell (not installed
here; TestShellEnvNushell's real-nu part skipped, its probe-shape check
passes).
2026-10-17 05:35:45 +08:00
yetoneandggbdpq 8820646f7c library, agent: the gone-agent tests pass on Windows, with or without the Codex app installed, and no package's tests read the machine's Store apps (#2254, ggbdpq)
ggbdpq found TestTargetsLeaveGoneAgentsOut and TestGoneAgentKeepsWhatItHas
(from e413512d8) red on a Windows machine with the Codex desktop app.
Their patch (ggbdpq/magpie fix-2254-gone-test, ddd44c36) skipped the
tests when HasApp said so, which proves nothing on such machines, and set
a PATH of the test's own. This takes their hermes fixture fix and makes
the rest hermetic instead:

- agent: windowsStorePackages reads none of the machine's AppX registry
  in a test binary testenv isolated (proc.Isolated), as SystemDirs already
  keeps the machine's folders out. Only agent's own TestMain stood in for
  it before, so library's tests (and any other package's) saw a real
  Codex app, and codex's CLI was never gone there.
- library: the hermes fixture goes where Hermes reads it
  (appdir.HermesHome: %LOCALAPPDATA%\hermes on Windows). In ~/.hermes
  hermes was never detected there, and Takes refused nothing.
- library: TestGoneAgentKeepsWhatItHas uses Pi, which goes on every
  system. On Windows a ~\.codex whose CLI isn't found is never taken for
  a leftover (#1482, by design), so the test with codex failed on every
  Windows machine, Codex app or not. The PATH change in the patch made
  no difference to that.
- TestRTKLeavesGoneAgentsOut keeps codex; it already skips on Windows
  (its fake rtk is a shell script).

Run:
- Windows 11 box, test binaries cross-built (amd64): old main had
  TestTargetsLeaveGoneAgentsOut and TestGoneAgentKeepsWhatItHas FAIL
  (Takes(hermes) <nil>; codex a target), new both PASS. Full library and
  agent packages there: new fails only what old fails too (library:
  TestAgentsSkillsFolders, TestHooksCodexTrustMovesWithTheGroups, filed as
  #2275; TestCheckKeepsToolNames and agent's 10 are from running a test
  .exe away from its source: testdata, ../gui, go and bash not there).
- Broken by hand: TestStorePackagesNotTheMachinesInTests without the
  Isolated check reads the box's 152 Store packages and goes red; with
  Targets' CLIMissing filter removed, both library tests go red on macOS.
- macOS: go test of agent, proc, library; gofmt -l; go vet -tags nogui
  for darwin, linux, windows on the three packages.

Full suite: SUITE_LINE

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 23:08:01 +08:00
yetone 79fec406c6 agent, gui: a Claude Code provider switch (CLAUDE_CODE_USE_BEDROCK, …) steps aside while magpie is wired in and comes back after; one magpie can't take out is said (jw1dev on X)
jw1dev's ~/.claude/settings.json had CLAUDE_CODE_USE_BEDROCK=1. magpie wrote
ANTHROPIC_BASE_URL and its model ids beside it. Bedrock ignores the base URL,
so Claude Code went to AWS, Bedrock refused magpie's model, and magpie still
showed Claude Code as connected.

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

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

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

Not tried:
- A project's .claude/settings.json(.local) isn't read, because magpie
  doesn't know where Claude Code runs.
- WSL and Windows were not run for real; tests only.
- Real Vertex, Foundry and AWS accounts.
- T3 Code and Claude Desktop with a switch, run for real.
- The drift shown in the real app window. The CLI has no drift output.
- The user's own ANTHROPIC_MODEL being lost across connect/disconnect is a
  separate gap, fixed in its own commit.
2026-10-15 07:41:30 +08:00
yetone b25659344f proc: on Windows a port nobody listens on reads as no listener, not "exit status 1", so the take-over doesn't say "stuck" (#2231, JasonBuildAI)
ListeningOn on Windows ran Get-NetTCPConnection with -ErrorAction
SilentlyContinue. When nothing listens the cmdlet fails with
ObjectNotFound, and PowerShell still exits 1 for it, so the read answered
"exit status 1" where lsof and /proc answer no pids and no error. The
Gateway page's take-over waits for exactly that answer to know the older
magpie let the port go; with an error it waited out its deadline and said
"stuck" with the port already free. The command now catches the error and
exits 0 only for ObjectNotFound; any other failure (the cmdlet missing, a
PowerShell cut short) is still an error.

JasonBuildAI's 85a8c8c0 reads "exit 1 with nothing on either stream" as
none found instead. Catching the category keeps a silent failure of
another kind an error, so this takes that route; his separate point that
the darwin reader has no deadline guard is not in this commit.

Run:
- TestNothingListeningIsNoError (new), on the Windows box: old code FAIL
  "nothing listens on 56409: exit status 1", new PASS; TestListeningOn
  passes on both. go test ./internal/proc on macOS: ok.
- TestGatewayFixQuitsOnlyAMagpie (internal/gui) on the Windows box: old
  code FAIL "take-over: {OK:false Reason:stuck ...}" after 12.5s; with
  this change the take-over succeeds (the test's own cleanup failure is
  the next commit). With both, 3 of 3 PASS in ~7s each.
- go test -tags nogui ./... on macOS with this series: every package ok.
- gofmt -l, go vet ./... on darwin, linux (nogui) and windows: clean.
2026-10-15 03:34:58 +08:00
yetoneandXIQIXIQIXIQI b789bcc45d gateway, proc: magpie ends a Claude Code run with SIGTERM and a 5s grace before the kill, so its OAuth refresh lock is let go (#2195, XIQIXIQIXIQI)
subscriptionRun.abort killed Claude Code's process group with SIGKILL at
once. A Claude Code holding ~/.claude/.oauth_refresh.lock at that moment
can't run its exit cleanup, and the lock was left for the next requests to
fail on ("another Claude Code process is refreshing it or exited
mid-refresh").

proc.Tree.Stop(grace) sends SIGTERM to the leader alone, then ends the
tree once it has exited (Wait sweeps the group) or grace has passed
(Kill). A second Stop shares the first's grace. Windows has no such
signal and kills the job at once. abort uses it with stopGrace (5s); the
run still counts as ended at once, and abortAll, as the gateway stops,
waits for every tree. Other agents' trees keep Kill.

Run (macOS, sandbox HOME, pinned caches):
- the real Claude Code 2.1.299 (-p, stream-json in/out, as the bridge
  starts it) under a sandbox HOME/CLAUDE_CONFIG_DIR, no credentials:
  SIGTERM after 4s, it exited in 0.497s with 143.
- go test -race -count=20 -run TestTree ./internal/proc: ok
- go test -race -count=5 -run TestClaudeAbortAllowsLockCleanup
  ./internal/gateway (the reporter's test, trap set before the lock is
  made): ok
- broken by hand: abort back to t.Kill() -> TestClaudeAbortAllowsLockCleanup
  FAIL "Claude abort left refresh lock: <nil>"; Stop killing at once ->
  TestTreeStopLetsItCleanUp FAIL "the command's lock is left after Stop".
- on b9c589ebb plus these commits: gofmt -l (nothing), go vet ./... on
  darwin, GOOS=linux -tags nogui and GOOS=windows, go test -tags nogui ./...:
  every package ok but two filed load flakes, TestMaxRPMWaitsForRoomInTheMinute
  (#1791) and TestCopilotSecretToolUsername (#1627), on a machine at load
  ~200; each passed -count=3 alone.
- rebased onto e98440ae6 (27 more commits on main) and
  run again there: gofmt -l, go vet ./... (darwin, linux nogui, windows),
  go test -tags nogui ./internal/gateway ./internal/proc ./internal/agent.
- then onto af27b70b4 (9 commits; gateway routing.go/gateway.go and agent
  codex.go touched, not these lines): gofmt -l, go vet on the three OSes,
  and the tests named above plus the new remote-magpie and Codex ones.
Not tried: a real OAuth refresh interrupted mid-way (no Claude request was
made); Linux and Windows at runtime.

Co-authored-by: XIQIXIQIXIQI <75725040+XIQIXIQIXIQI@users.noreply.github.com>
2026-10-15 01:22:13 +08:00
yetone 0dc643fdb7 proc, agent: asking Cline's version no longer starts an npm update of Cline (新v学员 on Discord)
Cline checks for an update on every start, `cline --version` too, and
spawns a detached `npm install -g cline@latest` the user never asked for;
新v学员 saw that node process each time magpie read the version.

- proc.Version reads the version from an npm shim before running anything:
  a small file (cline.cmd / cline.ps1 / sh shim, as npm installs on
  Windows, where no symlink reaches node_modules) that names
  node_modules/<pkg>/ gets <pkg>/package.json beside it, scoped packages
  too. Nothing is started.
- Where a binary still has to be run, runVersion sets
  CLINE_NO_AUTO_UPDATE=1 (the switch Cline's own updater reads), and so
  does cliupdate's env, whose --version after an update starts Cline too.

Run:
- go test -count=1 ./internal/proc ./internal/agent: ok (agent 1435s,
  the machine under other sessions' load).
- TestVersionReadsAnNpmShim (cmd, sh and ps1 shims, @openai/codex scoped)
  asks runVersion 0 times; with shimVersion's call taken out it fails
  (runs the binary). TestVersionRunTellsClineNotToUpdate fails without the
  env switch ("cline updates").
- gofmt -l clean; go vet darwin, windows, linux -tags nogui on proc,
  agent, cli.
- The proc test binary built for windows/amd64 on the Windows box: pass.
- The switch's name checked in the cline binary's own strings
  (CLINE_NO_AUTO_UPDATE === "1").
Not tried: the real cline on Windows (no node on the box).
2026-10-15 00:15:25 +08:00
yetone b319657301 gui: a sign-in whose browser didn't open says why and shows its link, and Windows names rundll32 by its path (#2043)
xiaobaifly7: on Windows, signing in to Cloudflare's MCP server (and any
sign-in) opened no browser, and the window said to finish in the
browser until the sign-in timed out. Wails' Browser.OpenURL starts
rundll32 by its bare name, which Go looks up with PATHEXT's extensions;
a PATHEXT without .EXE (WSL passes one on as ".CPL") finds nothing, and
host.OpenURL dropped the error.

- proc.OpenBrowser starts %SystemRoot%\System32\rundll32.exe by its
  path (open / xdg-open / termux-open-url elsewhere) and returns the
  launcher's error. host.OpenURL falls back to it when Wails' fails, and
  the CLI's account sign-in uses it.
- Windows.OpenURL returns the error. /api/signin, the plugin sign-in and
  /api/library/mcp-signin answer it as openError; /api/open fails with
  it, so Open again says why.
- The sign-in card shows "magpie couldn't open your browser: {error}.
  Open the sign-in link below in a browser yourself." where it said
  magpie opened the page, with the link already shown below; the MCP
  editor shows the error with the link and a copy button. Translated
  (zh, zh-TW, ja, de).
- Open again matched its sign-in by identity, so a poll that put a fresh
  copy of the same sign-in in place kept the old error after a
  successful retry; it now matches by id.

Run:
- TestBrowserNamesRundll32ByItsPath, TestMCPSignInSaysTheBrowserDidntOpen
  and the /api/open and /api/signin tests in signin_open_2043_test.go.
  Broken by hand: the bare name back in browserCommand fails the first;
  openError returning "" fails the gui tests.
- On the Windows box (amd64, cmd with PATHEXT=.CPL): exec.Command
  ("rundll32", ...).Start() gave `exec: "rundll32": executable file not
  found in %PATH%`; proc.OpenBrowser started it (nil). The proc test
  binary's TestBrowserNamesRundll32ByItsPath passed there.
- signin-browser-down.test.cjs (new): the card's text, the link, no
  sideways overflow, Open again failing then succeeding, and the MCP
  editor's error and link, in Chromium and WebKit at 1100 and 420 in
  every language: 20/20. The related sign-in GUI tests: 451/452, the
  one a signin-proxy flake also on main (fixed in its own commit).
- gofmt -l clean; go vet darwin, linux -tags nogui, windows; GOOS=linux
  and windows builds; go test -tags nogui ./internal/gui/
  ./internal/proc/ ./internal/cli/.

Not tried: the real Wails app on Windows under PATHEXT=.CPL (the
fallback path is exercised only through proc.OpenBrowser), WSL itself,
the reporter's machine. Not covered: internal/tui/sessions.go and
internal/provider/install.go start `powershell` by its bare name, which
would miss the same way under such a PATHEXT.
2026-10-14 08:36:07 +08:00
yetone 8a4cfe0e4e proc: a command that isn't installed is answered from each PATH folder's listing, not a stat per extension, so a Library change after a start no longer looks for ~100 agents' commands one file at a time on Windows (#1624, Hipple)
On every Library create, switch or delete, Targets() asks agent.Detected for
about a hundred agents. Each one's command is looked up with exec.LookPath,
and on Windows with FindTool's findDirs as well. A command that isn't
installed costs a stat of name+each PATHEXT extension in every folder. The
answers are cached (looked), but that cache is empty after a start and is
dropped whenever any PATH folder's mtime changes. With an antivirus slowing
every stat, that is the slow first change Hipple sees.

Each folder's listing is now read once (lower-cased names, also each name up
to every dot) and read again only when the folder's mtime changes. A
command that no folder has a name for is not found without a stat. One a
folder may hold, and any folder that can't be read, goes to exec.LookPath
and toolIn as before. On Windows the current folder is included unless
NoDefaultCurrentDirectoryInExePath is set, as exec.LookPath does.

Measured on the Windows test box (47 PATH folders, WSL agents off,
library ops through a throwaway test in a sandbox HOME):
- the first create after a start went from 486ms to 285ms; the old CPU
  profile was mostly exec.LookPath/GetFileAttributesEx;
- warm ops ~10ms either way.
With WSL agents on, the first op costs ~3.0s on both builds, about 2.7s of
it in wsl.exe list and probe spawns. This commit doesn't change that. On the
box, wsl -l -q, wsl -l --running -q and a docker-desktop probe each take
40-75ms, so a failed-probe retry every 10 min doesn't explain the report
there. The 5-8s after 10 min idle wasn't reproduced: ops after 4, 8 and 12
min idle took ~120ms.

Run: go test ./internal/proc ./internal/agent ./internal/library (ok);
gofmt -l; GOOS=linux and GOOS=windows go vet on the three packages.
I broke the fix by hand (look.go/find.go back to exec.LookPath, mayBeIn
check off), and TestMissingCommandsReadEachFolderOnce failed: "100 missing
commands were looked for on PATH 200 times, want 0".
2026-10-14 08:08:50 +08:00
yetone 73ce9765f1 proc: EndProbes returns once a killed probe's whole group is gone, so an exit right after can't leave a missed child running (#1278)
JJ-Lin's fault injection on #1278: when the first signal to a probe's
group missed a process being forked, group.kill went on signalling it
from a goroutine nobody waited for, and the probe counted as ended as
soon as the first signal went out. EndProbes returned in ~0.2ms; magpie
then exiting (or Exec'ing the new version) ended that goroutine, and the
missed child lived on with PPID 1.

group.kill now returns a channel closed once none of the group is left
(or killFor has passed). A probe's Cancel marks its kill as begun and
counts the probe ended only when that channel closes. EndProbes waits up
to endWait for each kill to begin (a probe that already answered has
none, as before) and then for the group to be empty, bounded by killFor
plus a second. Every exit path goes through EndProbes: the GUI's
OnShutdown, the CLI's return and signal handler, and update.Reexec.

Windows: the job's TerminateJobObject takes no new process once it is
ending, and a probe is killed alone with TerminateProcess, so there was
no background loop to outlive; kill returns a closed channel there. The
known Windows gap that a shim's children aren't in a job for probes is
unchanged.

Run:
- TestEndProbesThenExitLeavesNothing (new) re-runs the test binary as a
  magpie whose group signals miss for 300ms, which calls EndProbes and
  os.Exit(0) at once. On the old code it fails 3/3 on darwin: "what the
  probe started (pid N) outlived magpie's exit after EndProbes".
- darwin: go test -race ./internal/proc ok; -race -count=10 of the
  probe/EndProbes tests ok.
- linux (docker golang:1.26.8 --init, GOTOOLCHAIN=local): -race -count=5
  of the probe/tree tests ok. Without --init the container's PID 1
  reaps nothing and every group test fails on zombies, on old code too.
- Windows box: new TestEndProbesWindows (ping probe ended, EndProbes
  ~0ms) passes 3/3; the rest of the package passes except
  TestNoCommandBypassesProc, which walks ../.. and found other
  checkouts in C:\Users\yeton since the binary ran outside a tree.
- gofmt -l, go vet (darwin), GOOS=linux vet -tags nogui, GOOS=windows vet.
2026-10-13 05:21:03 +08:00
yetone 7d0c68b187 proc: the mise-hangs test gives up on its fake mise once it has written its pid, not after 300ms a loaded machine passes first (#1838)
What: the context an ask of mise runs under comes from miseAsk (a var;
production keeps miseWait = 5s, now a const). The "hangs" case of
TestFindToolKeepsWrapperWhenMiseDoesntSay cancels it once the fake mise
has written its pid (polled, with a minute's cap), then checks that
FindTool returns the wrapper within 30s of that (the fake sleeps 60s) and
that the fake's process is gone. The other wrapper tests give an
answering fake a minute instead of the production 5s.

Why: the test set miseWait to 300ms; at load average ~20 the fake's shell
hadn't written its pid by then, was killed, and the test said "mise
wasn't asked" though FindTool had asked. Under the same load the "fails"
case took 4.5s of the 5s budget here, so the answering fakes got room too.

Run (go1.26.8, sandbox HOME, private GOCACHE, load avg ~20):
- repro on old code: a 0.5s sleep injected before the fake writes its pid
  -> hangs FAIL "mise wasn't asked".
- new code with a 2s sleep injected: pass (hangs 2.2s). Removed after.
- break check: miseWhich ignoring the context -> FAIL "FindTool returned
  1m0s after mise was given up on". Restored: pass.
- gofmt -l clean; go vet ./... darwin, linux -tags nogui, windows: clean.
- go test -tags nogui ./internal/proc: ok; -race -count=5 -run
  'TestFindTool|TestParseMiseWrapper': ok.
Not run: the full go test ./...; Linux CI's run of this test.
2026-10-12 23:56:20 +08:00
yetone 8bfe33f1f4 agent, proc: where each command is on PATH is looked up once while its folders are unchanged, so a Windows page doesn't stat PATH per agent and per session (#1771)
oxyuan profiled every page's first load on Windows at seconds (4-7s), and
Sessions, Usage → Sessions and Context at 26-45s: 96-98% of the samples
were os.Stat under exec.LookPath and proc.FindTool. A failed lookup stats
every PATHEXT candidate in every PATH folder (111ms there), and the pages
asked once per known agent (Detected → binAt) and once per Pi session
(sessions.carries → ompThere) on every request.

proc.Look (new, look.go) is exec.LookPath with its answers kept. The
proc.LookPath that 1bf722e28 added (exec.LookPath, then Unwrap of a mise
wrapper script) is now Look then Unwrap, and FindTool keeps its PATH
answer the same way before Unwrap. Unwrap keeps its own answer by the
script's size and time, and on Windows it returns at once. The PATH
answers are keyed on PATH and PATHEXT,
and dropped when a looked-in folder's modification time changes (an
install or removal), checked at most every 2s, every time in a test binary
testenv isolated. proc.Forget drops them all and agent.Rescan (the Agents
page's refresh) calls it. Every exec.LookPath that a page or the gateway
reaches now goes through one of them. The sites 1bf722e28 made unwrap keep
LookPath: agent (agent, air, nativemodels) and provider (codex models,
cursor, devin, kiro). The rest keep exec.LookPath's answer as it was,
through Look: agent (agents, cliupdate, the shim, gemini, install,
reasonix, vscode, zed), sessions/carry and library/rtk. Those left
on exec.LookPath run once per user action (update's pkexec, the
secret-tool read, installers, rtk upgrade) or in tests.

Run:
- look_test.go: asks once while folders are unchanged, sees an install and
  a removal, a changed PATH and Forget, concurrent lookups under -race. The
  first goes red with LookPath calling exec.LookPath directly.
- On the Windows box (yeton@10.0.0.132, amd64 probe, sandbox USERPROFILE):
  Detected with 4 agents 252ms → 7ms per call after the first, 297x
  LookPath(omp) 879ms → 1.1ms; drift over Detected 274ms → 42ms; Titles
  for 6 sessions 23ms → 4ms. The first call is the same (it looks).
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., sandboxed go test ./... at the rebased head.
Not run: the reporter's own machine (47 PATH folders, 59 agents).
2026-10-12 22:55:22 +08:00
yetone e4134d1fb7 agent: Codex's proxy is worked out from the login shell's NO_PROXY and HTTP_PROXY and macOS' HTTP entry alone, as its reqwest reads them, so "Codex 经代理连 magpie" no longer shows while Codex goes direct (liu_dyj on X)
liu_dyj: with the VPN on, magpie said Codex reached magpie through a
proxy that didn't pass its requests on; versions before f156d9046 had
no such check, which is why upgrading brought it.

Cause: codexProxyFor didn't read the proxy the way Codex does.
- It read magpie's own environment. Codex in a terminal has the login
  shell's, and the ChatGPT app's Codex too (ChatGPT.app 26.1007 runs
  $SHELL -ilc at start and Object.assign()s its env into process.env).
  magpie opened from the Dock has neither, so a NO_PROXY=127.0.0.1 in
  .zshrc, which keeps Codex direct, wasn't seen, and magpie probed the
  system proxy and warned.
- For the system proxy it took netproxy's one URL (HTTPS over HTTP over
  SOCKS). hyper-util 0.1.20's Matcher::from_system, which reqwest
  0.12.28 uses for Codex, takes only macOS' HTTP entry for an http://
  URL; with only the HTTPS or SOCKS entry set (ShadowsocksX-NG's global
  mode is SOCKS only) Codex goes direct and magpie warned. On Windows
  it takes ProxyServer as one address, which a per-protocol list
  ("http=..;https=..") isn't (http's Authority::parse refuses two
  colons), so Codex goes direct there too.
- With respect_system_proxy on macOS, CFNetwork's SOCKS entry is
  UnsupportedProxyScheme, and Codex falls back to HTTP_PROXY/ALL_PROXY
  with NO_PROXY (codex-rs outbound_proxy.rs resolve_env_proxy_route);
  magpie used the SOCKS URL.
- The probe spoke real SOCKS5 to a socks5:// proxy. Codex's reqwest is
  built without SOCKS (no tokio-socks in codex-rs Cargo.lock) and sends
  an absolute-URI HTTP request to it, so the probe now does the same:
  it passes a Clash mixed port as Codex does and fails a SOCKS-only
  port as Codex does.

So netproxy.Proxy carries the HTTP and SOCKS entries alone beside URL
(parseScutil, parseWindows), proc asks the login shell for the
*_PROXY variables with agentenv.Vars in the same probe and only reads
them (proc.LoginEnv; never set in magpie's env, whose requests use
netproxy), and codexProxyFor uses both. Failover's gate
(codexProxyOK) and the drift share codexProxyFor and proxyProbe, so
both follow. The pill's How to fix now names the shell profile for
NO_PROXY. Clash/mihomo rule mode with a 127.0.0.0/8 DIRECT rule never
warned and still doesn't; global mode or a rule set without it still
warns, rightly (real codex 502s there). TUN mode sets no proxy and
never warned.

Run:
- real codex-cli 0.162.1 in a sandbox HOME/CODEX_HOME against a fake
  gateway and mihomo v1.19.32 (rule, no-LAN-rule, global ports):
  direct, rule, and ALL_PROXY=socks5:// on the rule port reach the
  gateway; no-LAN-rule and global 502; global with NO_PROXY=127.0.0.1
  reaches it. The Go probe agrees on every one.
- go test -tags nogui ./internal/agent, ./internal/netproxy,
  ./internal/proc; gofmt -l; GOOS=linux and GOOS=windows go vet
  -tags nogui on the three packages.
- Broke each part by hand: sys.URL back in codexProxyFor (Windows per
  protocol, macOS HTTPS/SOCKS alone red), the probe's socks->http
  (TestRealProxyProbe red), codexEnv without the login shell
  (TestCodexEnvTakesLoginShell red), the respect-path SOCKS fallback
  (three respect cases red), setUnset of every shell var and the probe
  without ProxyVars (TestLoginEnvProxyVarsNotSet red).

Not tried: the macOS system proxy cases with real Codex (changing the
system's proxy settings is off limits here; read from hyper-util,
reqwest and codex-rs sources), the Windows per-protocol ProxyServer
with real Codex (from the http crate's source; no Windows run), and
the reporter's own app and mode, which are asked on X.
2026-10-12 22:33:50 +08:00
yetone 1bf722e289 proc, provider, agent: a claude (or other agent CLI) that is a mise wrapper script is run as the program mise names, and a Claude sign-in that gets no link says which program it ran (deluxe on Discord)
deluxe (Omarchy Linux, magpie started from the desktop) never saw the
Claude sign-in link. ~/.local/bin/claude was a script ending
`exec mise x "claude" -- "claude" "$@"`; without the shell's mise
environment, `mise x` looks claude up on PATH, finds the same script
(~/.local/bin is before mise's shims) and it runs itself for ever.

What changed:
- proc.Unwrap / proc.LookPath (internal/proc/wrapper.go): a small #!
  script whose line is `[exec] mise|rtx x|exec [opts] [tool] -- <name>`
  is resolved with `mise which <name>` (then `mise which --tool <tool>
  <name>`), run as a probe (process group killed) with a 5s timeout,
  magpie's environment and the home folder as cwd. The answer must be an
  executable file that isn't the wrapper or another wrapper; otherwise,
  or with no mise, the old path is kept. Answers are cached per file
  (path, mtime, size); a failed ask is retried after a minute.
  Windows is unchanged.
- proc.FindTool (claude via claudecode.Find: the sign-in, the gateway's
  Claude subscription, `magpie claude-code`) unwraps what it finds.
- The siblings that looked an agent CLI up with exec.LookPath use
  proc.LookPath: agent.binAt (detection, CLI version/update), codex,
  kiro-cli, devin, cursor-agent, Air's opencode, nativemodels' npm
  package lookup.
- The Claude sign-in already gave up after linkWait (30s) with "claude
  auth login gave no link to open". It now adds the last line the CLI
  printed, or, when it printed nothing, the program it ran and to run
  `<path> auth login` in a terminal to see what it does.

asdf shims (`exec asdf exec "claude" "$@"`) are left alone: asdf exec
resolves the real program itself and doesn't recurse.

Verified (macOS, sandbox HOME, Go caches pinned):
- New tests: internal/proc/wrapper_test.go (wrapper -> mise's program;
  no mise -> wrapper; mise fails / names the wrapper / names a folder /
  hangs -> wrapper, and the hung mise's pid is gone; deluxe's own fixed
  script, a node launcher, a wrapper of another command, a commented
  line -> unchanged and mise never asked; parse cases; --tool retry),
  internal/provider/signin_claude_wrapper_test.go (the full Claude
  sign-in through the wrapper with a fake mise that really recurses:
  link shown, account added; with no `mise which`, the sign-in fails in
  linkWait naming the wrapper).
- Break checks: with find.go put back, TestFindToolUnwrapsMiseWrapper and
  TestFindToolAsksWithWrappersTool FAIL (FindTool = the wrapper), and
  TestClaudeSignInThroughMiseWrapper FAILs with "claude auth login gave
  no link to open: .../local-bin/claude printed nothing in 5s". With the
  old error string, TestClaudeSignInWrapperThatNeverStarts FAILs.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; GOOS=linux go build -tags nogui;
  GOOS=windows go build.
- go test -tags nogui ./...: every package ok except internal/agent and
  internal/gateway, which hit the default 10m timeout with the machine
  at load ~45 (different tests each run, none in the new code). Those
  two were rerun with -timeout 40m; origin/main 217d2f8f2's
  internal/agent alone took 2094s under the same load.
- Rebased on 9964535ad, -timeout 40m: internal/agent ok (1689s),
  internal/proc ok, internal/provider ok (681s), internal/claudecode ok;
  internal/gateway FAIL in one test, TestCodexHeardWithinItsIdleTimeout
  (3.78s against its 3s wall-clock bound, body right, no retry taken).
  Alone with -count=5 it passes 5 of 5. Filed as #1800; unrelated to
  binary lookup.

Not verified: no real mise or the reporter's Omarchy machine; the fake
mise stands in for mise's which/x. The wrapper fixture is the line the
reporter quoted, not their whole file.
2026-10-12 19:52:37 +08:00
yetone e2b3eb7406 agent: an npm -g agent under mise's Node says its version and updates with that Node's npm, not "can't tell how it was installed" (flp on Discord)
On Windows with Node managed by mise, the Agents page read "无法判断安装方式"
for an agent installed with npm install -g. howInstalled decided from the
binary's path, and a mise shim leads nowhere near node_modules: on a Mac
or Linux it is a symlink to the mise binary; on Windows a copy of
mise-shim.exe (exe mode, the default), a .cmd plus a bash script running
`mise x --` (file), or a hard or symbolic link to mise.exe.

A shim is now recognised (a link to mise, or a file in mise's shims
folder: parent "mise", a .mode file, or MISE_DATA_DIR/shims) and mise is
asked which program it runs, `mise which <cmd>` from the home folder; how
it was installed is read from that program. On Windows mise names npm's
extensionless sh script, so the .cmd beside it is used. The update runs
that Node version's own npm with --prefix, then `mise reshim`: on Windows
npm install -g makes no shim for a new command (seen on the box), mise's
Unix npm wrapper reshims itself, so it is harmless there.

Siblings:
- asdf shims (scripts with "# asdf-plugin:" and `exec asdf exec`) are
  asked with `asdf which` the same way; asdf-nodejs's npm reshims itself
  and asdf has no Windows build.
- proc.UserBinDirs on Windows also looks in mise's shims folder
  (MISE_DATA_DIR, else XDG_DATA_HOME\mise, which mise follows on Windows,
  else %LOCALAPPDATA%\mise) for an agent PATH doesn't reach.
- Install side: npmIn accepts npm.exe beside node as well as npm.cmd.
- WSL agents get no update path (CLI skips them) and wsl.go's probe
  already lists mise/asdf shims: unchanged.
- MISE_DATA_DIR and ASDF_DIR join agentenv.Vars, so a test sandbox
  clears them (TestFolderVarsAreListed).

Fixtures are real bytes: internal/agent/testdata/mise-windows from mise
2026.10.7 on the Windows box (file-mode snow.cmd and snow, .mode files,
npm's snow.cmd/snow in the Node folder); the Mac layout and the asdf
shim's text from mise 2026.10.7 and asdf 0.20.2 release binaries in a
sandbox home.

Run:
- flp's own layout (where.exe claude: installs\node\24.20.0\claude,
  claude.cmd, shims\claude.exe; mise which claude names the extensionless
  script): TestMiseShimWindowsFiveAgents covers claude, pi, codex,
  opencode and codebuddy through shims\<cmd>.exe; run on the Windows box,
  red with the fix removed by hand, green restored.
- go test -tags nogui ./internal/agent ./internal/proc -run
  'Shim|HowInstalled|UpdateCLI|NpmIn|InstalledVersion'; with installedAt
  skipping the shim by hand TestMiseShimIsNodesNpm,
  TestUpdateCLIThroughMiseShim and TestAsdfShimIsNodesNpm go red, green
  again restored.
- Real mise on the Mac (sandbox home, mise 2026.10.7, node 22.23.3,
  snow-ai): detection through the real shim and `mise which`, and a real
  update 0.9.1 -> 0.9.2 through UpdateCLI.
- Real mise on Windows (the box, sandbox USERPROFILE/LOCALAPPDATA, mise
  2026.10.7, node 22.23.3, snow-ai): the Windows test binary's unit tests
  (TestMiseShimWindows, TestHowInstalledWindowsShim, TestNpmIn) pass;
  a temporary test through the real shim in exe, file and hardlink modes
  found npm.cmd --prefix <node>, version 0.9.2; after npm install -g
  snow-ai@0.9.1 a real UpdateCLI took it to 0.9.2 and reshimmed; snow.exe
  ran 0.9.2. Symlink mode was not tried (needs developer mode); it is
  the link-to-mise case the Mac covers. flp's own machine was not tried.
- go test -tags nogui -timeout 40m ./...; gofmt -l; GOOS=linux and
  GOOS=windows go vet -tags nogui ./...
2026-10-11 12:45:31 +08:00
ggbdpqandfactory-droid[bot] c409693806 proc: a test's own signalGroup put back no longer races the kill loop still reading it (#1568, ggbdpq)
What changed:
- group.kill's retry loop outlives its caller: it keeps signalling a
  process group every 5ms for up to 10s after the caller (a probe's
  cmd.Cancel on exec's watchCtx goroutine) has gone. It read the package
  var signalGroup on every pass, so a test that swaps the var for its own
  and puts the old one back when it ends (TestProbeKillEndsWhatTheSignal-
  Missed's cleanup) raced the loop's reads: go test -race ./internal/proc/
  went red with "WARNING: DATA RACE" (write at probe_test.go:151, read at
  tree_other.go:43), 5 of 5 runs.
- kill now takes the kill function once at its entry and the loop uses
  that copy. In production nothing changes (the var is never written);
  a test's swap is seen by every kill started after it, and a loop under
  way finishes with the function it was started with, which is the one
  that must answer whether the group is empty.

Run:
- go test -race -tags nogui -count=1 -run TestProbeKillEndsWhatTheSignalMissed
  ./internal/proc/: FAIL with DATA RACE without the change (1 warning,
  5 of 5 runs), ok with it, and -race -count=20 ok.
- go test -race -tags nogui -count=1 and -count=1 ./internal/proc/ ok.
  Nothing else in the tree reads or writes signalGroup (grep).

Review: on main (3f5702421) go test -race -count=5 -run
TestProbeKillEndsWhatTheSignalMissed ./internal/proc reported 4 DATA RACE
warnings: the cleanup's write (probe_test.go:151) and the next run's swap
(probe_test.go:141) against the loop's read (tree_other.go:43), and one
run failed. With the change -race -count=30 is ok and the whole package
is ok under -race.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2026-10-11 12:00:41 +08:00
yetone 6b8dc4cdd8 proc, agent: magpie finds an agent CLI under the Node nvm's default names, not the folder whose name sorts last (v9 after v22)
proc.UserPath added "the newest-looking" nvm Node to magpie's PATH, the
last folder of ~/.nvm/versions/node/*/bin in string order. That isn't
the Node a terminal gets, and string order puts v9.11.2 after v22.12.0
and v22.3.0 after v22.12.0. So magpie could find, run and update a
codex/claude/gemini under a Node the user's terminal doesn't use (found
while answering 悠悠哥 on Discord, 9f407cafa). UserBinDirs (FindTool,
the Codex executable, nodeHere) took every version in reverse name
order, with the same flaw.

Now (internal/proc/nodever_other.go) the nvm folder is $NVM_DIR or
~/.nvm, and its default is resolved as nvm.sh does on load (nvm_auto
use -> nvm_resolve_local_alias default, read from nvm v0.40.3's
source): alias/default and each alias it names in turn (lts/* ->
lts/jod -> v22.x, lts/-N as nvm_normalize_lts counts it, user aliases),
a cycle being none; node/stable the highest installed; a partial
version (22, v20, 22.3) the highest installed it starts; an exact one
when its bin/node is installed. UserPath adds that one; with no usable
default (unset, not installed, cycle, iojs/unstable) the highest
version by number; with "system" none of nvm's, since the terminal then
runs the system Node. UserBinDirs lists the default first, then the
rest highest first.

Siblings:
- mise's installs and fnm's node-versions (UserBinDirs only) were in
  reverse name order too: now by number, fnm's aliases/default first
  (and $FNM_DIR looked in). mise's active Node is reached through its
  shims, which come earlier.
- volta, asdf and mise shims, and n (one copy in /usr/local/bin), pick
  the version themselves: no change.
- Windows (path_windows.go) lists no per-version folder: nvm-windows'
  current Node is its NVM_SYMLINK on the registry PATH. No change.
- The WSL probe's wslbin (internal/agent/wsl.go) globbed
  "$HOME"/.nvm/versions/node/*/bin, first in name order (v18 before the
  default v22). It now asks nvm itself (nvm.sh sourced by bash with
  --no-use, nvm_version default), then the rest highest first.
- NVM_DIR and FNM_DIR join agentenv.Vars: test sandboxes clear them, and
  UserPath takes them from the login shell like the agents' variables.

Run: TestUserPathNvmDefault (15 real nvm layouts: v9 vs v22, lts/*,
lts/iron, lts/-1, 22, v20, exact v9, node, stable, a user alias, a
default not installed, lts/* naming a line not installed, a cycle,
system direct and through an alias), TestFindToolNvmDefaultFirst,
TestUserPathNvmDir, TestUserBinDirsFnmMise, TestWSLProbeNvmDefault.
With the old path_other.go 14 of the 15 nvm cases go red (v9.11.2
picked; the exact-v9 default passes), as do the other three; with the
default ignored by hand 9 go red; with the old probe line all 3 WSL
cases go red. Cross-checked nvmDefault against
nvm v0.40.3's own nvm_version default on 19 alias layouts: same version
each time (nvm says N/A where magpie falls back, and N/A for system
with no system node). The new probe run with the real nvm.sh under
/bin/sh and /bin/dash resolved lts/*, lts/iron and 18 right. go test
./internal/proc ./internal/agent ./internal/agentenv ./internal/provider
./internal/testenv; full go test -tags nogui ./...; gofmt -l; go vet,
GOOS=linux and GOOS=windows go vet -tags nogui on the touched packages.
All under a temp HOME; no real ~/.nvm read.
2026-10-11 06:41:06 +08:00
yetone 81cf081f04 proc: a test that empties PATH means a machine without the tool, not one with Homebrew's (#1525, BUKOWSKIREAL)
TestFindTakesTheMachinesOwnFirst, TestClaudeSubscriptionRunsTheDownloadedClaudeCode
and TestClaudeSubscriptionWithoutClaudeCodeSaysHowToGetIt set PATH to an
empty folder to stand for a machine with no Claude Code, but
proc.FindTool falls back to proc.UserBinDirs, which lists the machine's
own /opt/homebrew/bin and /usr/local/bin. A Mac with
/opt/homebrew/bin/claude made Find() return it instead of the download.

proc.SystemDirs now gives every path of the machine's own that discovery
looks in. Outside tests it gives them as they are. In a test binary
testenv isolated (MAGPIE_TEST_SANDBOX set), each one is under the test's
home, at <home>/system/<path>, so the tests decide what is installed
there. The same leak was in the sibling finders, which now go through
it too:
- proc.UserBinDirs (Homebrew, /usr/local/bin), used by FindTool, the
  agents' install check (proc.FindTool(a.Bin) in internal/agent) and codexExecutable;
- FindTool's and nodeHere's Windows fallback to the registry PATH and
  %ProgramFiles%\nodejs;
- KiroExecutable, CursorExecutable and DevinExecutable's /usr/local/bin,
  /opt/homebrew/bin and /Applications/Kiro CLI.app paths.
Production discovery doesn't change.

Not changed: update's and rtk's choice of a PATH folder to link into
(they only take a folder already on PATH, which the test sets) and
FindShell (a test that runs a shell needs the real one).

Reproduced on this Mac, which has /opt/homebrew/bin/gemini, npm, node and
opencode but no claude there: under testenv with PATH emptied,
FindTool("gemini") gave /opt/homebrew/bin/gemini. The new
TestSystemDirsLieInTheTestsHome checks that no tool is found with an
empty PATH, and that a claude put at SystemDirs("/opt/homebrew/bin") in
the test's home is still found. Making SystemDirs return its paths
unchanged turns it red (gemini, npm, node and opencode found on the
host).

Run: go test -tags nogui -count=1 ./internal/proc ./internal/claudecode
./internal/provider ./internal/agent . (all ok); the three tests from
the issue -run by name in ./internal/claudecode ./internal/gateway (pass);
gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui on the touched
packages.
2026-10-11 00:52:57 +08:00
yetone cc8eb5a742 proc: the login shell's PATH comes when its profile starts tmux or zellij in an interactive shell, or is slow to come up in one (John on Discord)
John on Discord: agents on fish's PATH weren't found, fish being the login
shell (set with chsh). With SHELL=fish and a plain config.fish the probe
already worked (9bad1144's checks), so the difference is in the profile.
Reproduced with real fish 4.9.3 under the probe (ProbeContext, -ilc, no
terminal), a config.fish adding a folder with fish_add_path, plus:
  fish_greeting set              PATH comes
  read -P under is-interactive   PATH comes
  exec tmux under is-interactive no answer: tmux replaces fish
  exec /bin/cat likewise         no answer
  sleep 6 (a slow profile)       no answer after the 5s limit
With no answer magpie got no PATH at all from the login shell.

askShell now asks again as a login shell only (-lc) when the interactive
login shell (-ilc) gives no answer, timed out or not, with the same 5s
limit. fish reads config.fish then too, zsh .zprofile, bash
.bash_profile. MAGPIE_SHELL_PROBE=1 is in the probe's environment both
times, so a profile can skip its auto-start for magpie.

Not the cause, checked: a desktop app and a LaunchAgent get SHELL from
the user record (every launchd job here has SHELL); askShell runs the
absolute $SHELL as it is (/opt/homebrew/bin/fish). A SHELL left from
before chsh until logout is covered by 9bad1144 asking an installed,
set-up fish beside it. The TUI/CLI take the terminal's own PATH.

Tests: TestAskShellProfileExecsOrHangs (fake shells that exec cat or
sleep when interactive) and TestAskShellRealFishAutostart (real fish,
skipped without it) fail on the old askShell:
  slow: PATH = "", vars false: the login shell wasn't asked again
  tmux: PATH = "", want ".../fb" in it
and with the variable taken out: "exec: MAGPIE_SHELL_PROBE didn't reach
the profile". Run: internal/proc and internal/update tests pass (with
fish 4.9.3 on PATH); gofmt -l clean; go vet and GOOS=linux,
GOOS=windows go vet on internal/proc clean.
Real use: sandbox magpie (go build -tags dev, own HOME, ports
3486/3487, PATH=/usr/bin:/bin:/usr/sbin:/sbin, SHELL=<real fish>,
config.fish with fish_add_path to a folder holding a fake claude and
`if status is-interactive; and not set -q TMUX; exec /bin/cat; end`):
origin/main finds no claude in /api/agents/cli or /api/state; this
build finds it (2.1.99, the fake's).
2026-10-10 21:54:38 +08:00
yetone 9bad11449b proc, update: an agent installed in a folder only fish's config adds is found when the terminal opens fish but the login shell is zsh or bash (John on Discord)
John on Discord: 二进制文件没有从用户环境变量找到,我终端环境使用的fish. The desktop
app gets launchd's PATH and asks the login shell ($SHELL) for its own.
fish isn't a POSIX shell, so many keep zsh or bash as the login shell and
have the terminal open fish (its profile setting, or exec fish from
.zshrc). magpie then asked only zsh, and a claude or codex in a folder
config.fish adds (fish_add_path, set -gx PATH) wasn't seen.

The suspected cause, fish joining "$PATH" with spaces, isn't it: PATH is a
path variable in fish and is joined with ':' in double quotes. Checked with
real fish 4.9.3 (macOS), 3.6 and 4.0.2 (Debian, Docker) under -ilc with
the probe's printf and \0: PATH whole, the variables in place. With
SHELL=fish the old code already found the agent.

- shellEnv asks fish and nushell too, in parallel with the login shell,
  when they are installed and their config folder exists (each makes it
  on its first run) and they aren't the login shell. Their PATH folders
  come after the login shell's; a variable of agentenv.Vars the login
  shell leaves empty is taken from them.
- proc.FindShell finds a shell in the system's, Homebrew's, MacPorts',
  Nix's, ~/.local/bin and cargo's folders, then /etc/shells, then PATH.
  Settings > Command line (update.installedShells) uses it too, so a fish
  from MacPorts or Nix is listed there as well.
- The shellProbe comment now says why fish's "$PATH" is right.

Tests: TestShellEnvAsksFishBesideLoginShell (a fake fish answering with
the bytes real fish 4.9.3 printed) and TestShellEnvRealFish (real fish,
skipped where it isn't installed) fail on the old shellEnv:
  PATH = "/from/zsh:/usr/bin:/bin", want the login shell's first and
  fish's folder after
  PATH = "/usr/bin:/bin", want fish's ".../fish bin" in it
TestShellEnvLeavesUnusedFish and TestShellEnvFishLogin cover fish with no
config and fish as the login shell.

Run: internal/proc shell tests on macOS with the downloaded fish 4.9.3 and
on Linux (golang:1.26.8 + Debian fish 4.0.2) all pass; go test ./...
under a temp HOME: all pass except gateway (10m timeout under load; the
failing TestClaudeUnloadableSessionStartsAnew passes alone) and gui
TestOTelPreferencesAPI (TempDir cleanup race, passes alone -count=3),
neither touching this code; gofmt -l clean; go vet and GOOS=linux,
GOOS=windows go vet on internal/proc and internal/update clean.
Real use: a sandbox magpie (go build -tags dev, own HOME, ports
3486/3487, launchd-like PATH=/usr/bin:/bin:/usr/sbin:/sbin, SHELL=/bin/zsh
with no .zshrc, fish at ~/.local/bin/fish, a fake claude only in a folder
config.fish adds with fish_add_path): the old build reports no claude in
/api/agents/cli and /api/state; this one finds it (version 2.1.99 of the
fake). With SHELL=fish both builds find it.
2026-10-10 21:42:00 +08:00
yetone b934d64a4e tests: TestNoCommandBypassesProc leaves out internal/testenv, which only tests import and which can't import proc (its tests import testenv); main was red since 2da8fbe4's testenv.Bun ran bun with os/exec 2026-10-10 10:51:48 +08:00