Commit Graph
57 Commits
Author SHA1 Message Date
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
yetone 98236edd77 agent: Codex installed by install.ps1 on Windows shows its newest version and offers codex update, and its version is read again after each update (xiaoxiaofeixz on Discord: 不会自动检测最新的版本)
Codex's install.ps1 puts %LOCALAPPDATA%\Programs\OpenAI\Codex\bin on PATH.
That folder is a junction to ~\.codex\packages\standalone\current\bin, and
current is a junction to releases\<version>-<target>, retargeted by each
update. filepath.EvalSymlinks leaves junctions alone since Go 1.23, so
magpie saw the binary only as ...\Programs\OpenAI\Codex\bin\codex.exe:

- howInstalled didn't find .codex/packages/standalone in its path, so the
  Agents page showed the version with no newest version and no update.
- installedVersion's stamp was that unchanged path plus size and mtime.
  npm's archive, which install.ps1's legacy layout copies from, gives every
  version's codex.exe the same 1985 mtime. So a new release was asked again
  only if its size happened to differ, else after the 24h memo.

proc.RealPath is now the path Windows opens (GetFinalPathNameByHandle),
junctions followed, and filepath.EvalSymlinks elsewhere. cliupdate's
howInstalled and installedVersion and proc.Version use it.

TestCodexInstallPs1Junctions (Windows) builds install.ps1's layout with
mklink /J, two releases whose codex.exe have the same bytes and mtime. It
checks that codex is recognized as self-updated (codex update) and that
retargeting current makes the version asked again. On the Windows box
(10.0.0.132, sandboxed USERPROFILE/APPDATA/LOCALAPPDATA) it fails on the old
code (howInstalled nil; "0.161.0" after the update) and passes on the new.
The rest of the agent package fails on Windows with the same 17 tests
before and after (TestFolderVarsAreListed, TestAside*, TestVSCodium, ...),
which CI never runs there. `codex update` on Windows is in codex.exe 0.162.0
(win32-x64): it runs install.ps1. The layout was read from
https://chatgpt.com/codex/install.ps1.

Not tried with a real install.ps1 install (it rewrites the user's PATH in
the registry). go test -tags nogui ./internal/agent ./internal/proc
./internal/provider ./internal/library (macOS), gofmt, and go vet for
GOOS=linux and windows pass.
2026-10-09 13:44:50 +08:00
yetone 1831ac4b63 proc: a CLI probe or agent run that is killed leaves nothing of itself running on Mac and Linux, even a launcher that keeps calling itself: its process group is signalled until it is empty, not once (#1278, JJ-Lin)
An old ~/.local/bin/cursor-agent that runs `cursor agent`, which (Cursor's
own bin/cursor) first runs ~/.local/bin/cursor-agent --min-version=... status,
calls itself without end. magpie asks cursor-agent who is signed in (about,
10s timeout) and kills the probe's session on the timeout with one SIGKILL
to the group. On macOS that one signal can miss a process being forked as it
goes out; the miss lives on, in the same group, adopted by init, and keeps
calling itself until the user can start no process (JJ-Lin: ~4800 bash
processes in one chain whose root's parent is PID 1). group.kill now sends
SIGKILL to the group again every 5ms, behind the caller, until the group is
gone (ESRCH) or 10s pass. The group keeps its id while any of it lives, so
nothing else is signalled. It covers ProbeContext's timeout and EndProbes,
and StartTree's Kill and sweep.

Verified:
- red without the change: TestProbeKillEndsWhatTheSignalMissed (the first
  group signal is made to miss, as the race does) fails with
  "what the probe started (pid 95576) outlived a kill that missed it once";
  passes with it (-count=5).
- reproduced the leak with the real Cursor 3.12.6 launcher script
  (/Applications/Cursor.app/.../bin/cursor, read only) and JJ-Lin's 87-byte
  wrapper in a sandbox HOME, under ulimit -u: ProbeContext(cursor-agent about)
  with a 10s timeout peaked at 311-700 processes; before the change 1 of 3
  runs left a chain behind (root ppid 1, same pgid, args
  "agent --min-version=2025.10.01 status"), after it 0 of 6. A fake
  launcher (60 parallel self-calling chains, killed at 500ms) left survivors
  4 of 30 runs before, 0 of 30 after.
- the same through provider.askCursorStatus with the real launcher, 5 runs:
  no cursor process left after each.
- go test -tags nogui ./internal/proc/ in a sandbox HOME; go vet -tags nogui
  of proc for darwin, linux and windows.
2026-10-08 18:18:15 +08:00
yetone 9fcd332b6c proc: a .cmd or .bat is run through cmd.exe with each argument quoted for it, so npm.cmd under C:\Program Files\nodejs (nvm-windows) no longer runs "C:\Program" when magpie updates Claude Code (wztlink1013 on Discord)
Windows starts a batch file as `cmd.exe /c <line>`, and Go builds that
line for a program's parser: with more than two quotes cmd.exe drops the
first and last, so `"C:\Program Files\nodejs\npm.cmd" install -g --prefix
"C:\Program Files\nodejs" …` ran C:\Program. An argument with & or | was
also left unquoted and split into a second command. Every command magpie
runs is made by proc.Command/CommandContext, so the fix is there:
cmd.exe /d /e:ON /v:OFF /s /c "<script> <args>", each argument quoted as
Rust's std does for batch files (doubled ", % broken up).

TestBatchFileInFolderWithSpace (windows) runs npm.cmd, a .bat and npm via
PATH under "Program Files" with the reporter's arguments plus & | % ^ and
trailing-\ cases, through a script that hands %* to a real program. On the
old code it fails on the Windows box with "'…\Program' 不是内部或外部命令".
On the Windows box (Windows 11, zh-CN) magpie's own updater
(howInstalled + runUpdate) on a real npm install of Claude Code 2.0.50
under "…\Program Files\nodejs": old code failed with the reporter's error,
new code updated it to 2.1.293.
2026-10-08 15:04:24 +08:00
forever c2020e0bb3 proc tests: TestAskShellOwnSession reads magpie's session with x/sys/unix, so the package's tests build on Linux (#1219)
bbf99143's test called syscall.Getsid, which Go's syscall package has on
macOS and the BSDs but not on Linux: go vet ./... (and every test run) on
Linux stopped at "undefined: syscall.Getsid", so the ubuntu Test job failed
at Vet on main and on every PR. golang.org/x/sys/unix, already required,
has Getsid on every Unix.

Verified: GOOS=linux, darwin, freebsd and android go vet ./internal/proc;
go test -run TestAskShellOwnSession ./internal/proc on macOS. Linux is run
by this PR's ubuntu job; there is no Linux machine here.
2026-10-08 04:44:10 +08:00
yetone bbf9914307 proc: the login shell magpie asks for its PATH runs in a session of its own, so it can't take the terminal from magpie (DD on Discord: magpie web → zsh: suspended (tty input))
askShell ran `$SHELL -ilc` (and ReadCLI's zsh, bash and fish, for Settings › Command line; LoginPath for Library › RTK) in magpie's own session and process group. An interactive zsh puts itself in the terminal's foreground, so while it ran, magpie's group was in the background of the terminal it was started from: Ctrl-C no longer reached `magpie web`, and anything left in magpie's group that touched the terminal — the bash asked beside it, whose profile runs in magpie's group without job control, or another child — had the kernel send SIGTTIN to the whole group, stopping magpie ("zsh: suspended (tty input)"). Run with `&`, the user's own shell then got EIO reading the terminal and exited. A timeout also killed only the shell, leaving what its profile started holding the terminal.

The shell is now a probe (ProbeContext): it leads a session with no controlling terminal, and its timeout and EndProbes end its whole group. It still answers with its PATH and variables.

TestAskShellOwnSession (a fake shell answering with its process group; a real zsh still gives a PATH) fails without the change: "the login shell ran in magpie's process group …". Reproduced on a pty under an interactive zsh -f, temp HOME, MAGPIE_ADDR 127.0.0.1:47811, magpie web on 47812, ~/.zshrc `sleep 2`, ~/.bash_profile reading /dev/tty, GET /api/cli: the old build prints "zsh: suspended (tty input)  magpie web" in the foreground and "[1] + suspended (tty input)" with `&` (then "zsh: error on TTY read"); with a plain profile it loses the foreground (ps S+ → S). The fixed build stays S+ / running in both, and /api/cli still says zsh and bash are known. go vet -tags nogui ./..., GOOS=linux go build -tags nogui, GOOS=windows go build, and go test -tags nogui of internal/proc, internal/update, internal/library and internal/gui under a temp HOME pass; -race -count=10 of the new test passes. Not tried with DD's own profile, or on Linux.
2026-10-08 03:45:32 +08:00
yetone 06420a7121 tests: a fake program is a file macOS has already let run (testenv.Program), so a fake's first start no longer eats a test's wait under load
macOS checks a newly written executable before its first exec: 0.27s
alone, 2-5s while other new programs start (a go test ./... starting its
test binaries). The same file again takes 0.009s, and the pass is kept
across a rename and an in-place rewrite. 108852b4 worked round this for one
test with /bin/sh -c; the class was every test that writes a `#!/bin/sh`
fake and times its answer.

testenv.Program(t, path, script) replaces os.WriteFile(path, script, 0o755)
for fakes. On macOS it renames a file that has run once from a pool to path
and writes the script into it in place; at the test's cleanup the file goes
back to the pool (only a path the test created; a stand-in it wrote over
stays). Fakes still end with their tests: nothing about how they are
started or waited on changed. Run (and gateway's TestMain) remove the pool
at the end. TestMain's PATH stand-ins are run once in the background
(testenv.StandIns). Other systems write the file as before.

Converted every `#!/bin/sh` fake written by tests under internal/ (agent,
gateway, gui, library, plugin, proc, provider, update). Windows, binary
and node/bun fakes are unchanged.

Under the same load (3 loops each starting 8 freshly written scripts at a
time), 4 rounds each, before (108852b4 / origin/main) vs after:
- provider TestSavedButSignedOutClaudeServed: 4/4 fail (8.01s) -> 4/4 pass
- provider TestClaudeSignInOverStaleCredentials: 4/4 fail (5.00s) -> 4/4 pass
- provider TestDevinSignedInOnlyInMagpie: 3/4 fail ("CLI's own []") -> 4/4 pass
- gateway TestClaudeRunEndsWhenTheClientLeaves: 4/4 fail -> 4/4 pass
  (and 3/3 fail -> 3/3 pass at a third of that load)
- gateway TestClientGoneRecordedAsCanceled: 4/4 fail -> 4/4 pass
- gui TestProvidersAnswerWhileListsComeIn ("cursor found false" at 3.03s):
  4/4 fail -> 4/4 pass. The same class, not bfe8bcaf's test order.
- proc TestUserPath (login shell's PATH never came, 7.01s): 4/4 fail ->
  4/4 pass
Unloaded, every touched package passes; no pool directory or process is
left after a run.
2026-10-07 03:00:47 +08:00
TryWorld 3cc017cd11 proc: IsMagpie knows the name an update leaves a running exe under (#963)
An update moves the running exe aside to exe.old, and when that name is still
held to exe.old-2, -3 (internal/update/update.go, oldName; two of the Windows
install tests assert .old-2 is where the running exe ended up). IsMagpie stripped
".old" and then ".exe", in that order, which unwraps exe.old but not exe.old-2:
".old" is not a suffix of "magpie.exe.old-2", so nothing came off and the name
matched neither magpie nor dial.

So the Gateway card's "Quit magpie and take over" refused to end the user's own
magpie: quitMagpieOnPort takes the "not-magpie" reason and the window says
"which isn't magpie, so magpie leaves it alone", with no way to end it from
there. startHere reads the same function, so it also misreports a magpie that
took the port back as something else.

The tail is now recognised as the count an update appends. Another program's
own name is still left alone: ".old-2" without a number is not ours, and
"magpie.old-backup" is not an update's.

Unchanged: every name IsMagpie already accepted, and the rule that only magpie's
own programs are ended — nothing else is ever touched.

TestIsMagpie's four new paths fail without the change (magpie.exe.old-2,
magpie.exe.old-3, magpie.old-2, dial.old-4 all read as not magpie) and pass
with it; the two negatives are checked in the same table. go vet ./... and the
builds for darwin, GOOS=linux and GOOS=windows pass, and internal/proc passes
-race -count=20.
2026-10-06 11:28:04 +08:00
yetone 0ef7066915 gui, proc: a magpie in a container holding the gateway's port is said as a container's to stop, Settings can move this magpie's gateway past it, and the take-over button is bordered in dark mode (leslie_luo on Discord)
An old magpie (v0.1.552) running in OrbStack held 3425, forwarded on the
Mac by OrbStack Helper. The Gateway card's take-over named OrbStack Helper
as a program that isn't magpie and said to move the gateway to another
port in Settings, and Settings refused the move because another magpie
served the gateway, so there was no way out. proc.IsForwarder tells the
programs that hold a port for a container or a VM (OrbStack, Docker
Desktop, docker-proxy, vpnkit, gvproxy, Lima, WSL's relay); the take-over
then answers reason container, said as the magpie inside it to stop (docker
ps, docker stop, or OrbStack / Docker Desktop) or this magpie's port to
move. setPort refuses only when a magpie program of this user's listens on
the port (magpieOnPort): one in a container, or one this user can't see,
is left on its port and this magpie serves on the new one, the agents it
connected moved with it. The take-over/restart button is text action, a
bordered button, as a plain text button read as words on the dark card.

TestGatewayHeldByAContainer runs a copy of the test binary named OrbStack
Helper answering as magpie on a port of the test's own: the take-over says
container and leaves it running, and setPort moves the gateway to a new
port where it answers as this one's; a copy named magpie still has its
port set there. TestIsForwarder covers the names. gateway-takeover.test.cjs
checks the container message in English and Chinese and the button's
border in dark mode. Both fail without the change. go vet, go build
(GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp
HOME pass.
2026-10-05 22:20:45 +08:00
yetone d6daa40ce3 update, gui: Settings › About › Command line says what magpie runs in a new terminal and adds it (PAMI on Discord) — the app downloaded from the site, and every Windows one, left terminals without the magpie command, and nothing in the GUI said whether it was there. A Command line row now asks each shell installed (zsh, bash, fish and the login shell; PowerShell and cmd on Windows) for its PATH and says, with a dot each, whether its magpie runs this app, another copy (with that copy's version, read from its .app's Info.plist or Homebrew Cellar folder, never by running it), or none. Add to PATH links this app's program (Homebrew's opt link, the AppImage) into the folder on the default shell's PATH whose magpie runs first, else ~/.local/bin or the like when on PATH, replacing another copy there as install.sh's ln -sf does; on Windows it puts the app's folder first in HKCU\Environment Path and broadcasts WM_SETTINGCHANGE. A shell whose PATH lacks that folder gets its own button naming its profile (~/.zshrc, ~/.bash_profile on the Mac or ~/.bashrc, fish's config.fish), which links into ~/.local/bin and adds that folder with one marked line, once; no profile is written otherwise. A translocated or disk-image app is told to move first and gets no button. It says new terminals take the change (on Windows: new PowerShell/cmd windows, restart Windows Terminal). GET/POST /api/cli; en/zh/ja/de. TestCLIOnPath (temp HOME, stubbed shells: link, fish profile once, a shadowing copy replaced, no folder → zsh's profile kept and appended, an unknown shell refused, plist version, translocated refused) and TestPathFirst are new; cli-path.test.cjs (WebKit, en and zh: per-shell dots, Add posts {} and turns green, fish's button posts fish alone, Windows lists PowerShell and cmd, translocated gets no button, no scroll, no select, no left border, translations) fails without the change; cli-behind and update-auto pass. Not tried on a real Windows machine. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass (TestOTelWholeWaterfallFallback and TestDevinSignedInOnlyInMagpie failed once each under load and pass alone). 2026-10-05 17:49:20 +08:00
yetone 2c801b6f9a gui, proc: the Gateway card quits an older magpie serving the gateway and takes it over, or restarts the gateway (leslie_luo on Discord) — the card said an older magpie served the gateway and to quit it, with no way to tell which process that was. With an older magpie on the port it now has "Quit magpie {v} and take over": the process listening on the gateway's port is found (lsof on a Mac, /proc on Linux, Get-NetTCPConnection on Windows), its program path checked to be magpie's (magpie, magpie-*, dial, .exe/.old), asked to quit (SIGTERM, then SIGKILL after 5 s; TerminateProcess on Windows) and this magpie serves the gateway at once instead of within 15 s. Otherwise the card has "Restart gateway" ("Start gateway" when none runs); a magpie of this version or newer gets no button. Anything else on the port is never ended: a program that isn't magpie, one of another user or an administrator, one that won't quit, or a magpie a LaunchAgent/systemd unit/scheduled task starts again is said under the button with its path and pid, in en/zh/ja/de. TestGatewayFixQuitsOnlyAMagpie (copies of the test binary on a port of its own: one named other-server answering as magpie is left running, one named magpie is quit and the gateway is served here, then restarted) and gateway-takeover.test.cjs (WebKit and Chromium, en and zh, no scroll, no left border) fail without the change; TestListeningOn/TestIsMagpie pass on macOS and in a Linux container. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass. 2026-10-05 15:05:31 +08:00
yetone 4183f516bf agent, provider: a CLI whose --version fails isn't run again until it changes, and an npm CLI's version is read from its package (#864) — macOS put up 「已阻止恶意软件:未打开 "codex"」 each time magpie's window opened: the codex magpie finds was asked its version every ten minutes (the model list's client version) and again with the Agents page (a failure retried after ten minutes), and macOS stops a program XProtect flags with that alert on every start. proc.Version is the one way both ask now: an npm CLI (…/node_modules/@openai/codex/bin/codex.js) has its package.json's version read and isn't run at all; any other is run with --version, and a run that ran and said nothing, or couldn't start, isn't made again until the binary's path, size or mtime changes (a reinstall); one cut off by the timeout is. A CLI that answered is asked as before. TestCodexVersionNotRerun (a codex that exits 137 run once over three ten-minute refreshes; an npm codex's version read, not run) fails on the old code (run 3 times); TestVersionRunsOnce. TestUpdateCLI and the agent and provider tests pass. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass but for TestClientGoneRecordedAsCanceled, which passes alone (-count=3). 2026-10-05 13:24:01 +08:00
yetone 72c6b85b0d provider: Claude Code installed off magpie's PATH is found on Windows too, so its sign-in no longer says to install it (EZN7L2C3, #839) — claudeExecutable looked on PATH, then at ~/.local/bin/claude, /usr/local/bin/claude and /opt/homebrew/bin/claude; on Windows the installer's binary is ~/.local/bin/claude.exe, and a magpie started before Claude Code was installed hasn't its folder on PATH, so the Claude sign-in said "install Claude Code first" while the Agents page, which reads ~/.claude, listed it. proc.FindTool now finds a CLI as a terminal would: on PATH, in the folders users' tools go in (UserBinDirs: npm's, ~/.local/bin, bun's, volta's, pnpm's, …) as name.exe, name.cmd or name on Windows, then on the PATH the registry has now; the sign-in and the gateway's Claude runs both use it. TestClaudeFoundInLocalBin fails on the old code on Windows (built for windows/amd64 and run on the Windows 11 test box: claude ""), passes there and here; TestToolIn. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-05 07:42:57 +08:00
tobitege 21702d01ff Add German translation; harden paths against unset env vars (#770)
* Add German translation and harden paths against unset env vars

Add a German locale to the GUI, tray menu, usage alerts and website home page, and refuse to start when the home folder is unset or relative so nothing is written under the working folder; the pi plugin no longer adopts the user's PI_CODING_AGENT_DIR, and an inherited APPIMAGE no longer selects portable mode. Scripts refuse to run from the wrong folder or empty a shared out folder, and a new internal/testenv sandboxes every test package from the user's real files, which also fixes the Claude picker and Termux installer tests on Windows.

* Makefile: know magpie's folder by its go.mod, so paths with spaces work

The check compared $(CURDIR) with $(dir $(abspath …)), which make splits on spaces, so a checkout under 'My Projects' or 'John Doe' refused every target. It now reads go.mod relative to the working folder and wants magpie's module there: make -C and a symlinked Makefile work, make -f from another folder still stops before any recipe runs.

* i18n: German for the strings main added since, with a parity test

75 strings main added (group order, patterns, slow-start wait, usage caps, RTK savings …) get their German, and two that main dropped go. gui-de.test.cjs checks, as gui-ja does, that de has every zh string with its placeholders and tags, and that the window reads in German when picked or on a German system.

* appdir: ignore relative folder variables when reading, keep them for children

CheckEnv no longer unsets anything. magpie reads the XDG folders, APPDATA/LOCALAPPDATA and every agent's folder variable through appdir.Getenv/LookupEnv, which pass over a relative value; the environment stays as it is, so the agents magpie starts get the variable as the user set it. That covers what proc.UserPath lends from the login shell too, which is set after main's check and reached the desktop app unchecked. On Windows a path rooted on the current drive (\Users\x, Git Bash's /c/x) counts as usable, and magpie version and help answer without a home, before run makes any folder.

* Sandbox the tests main added since

internal/wslrun gets testenv's TestMain, and four tests main added that set HOME alone set their home with testenv.SetHome, so on Windows they don't read the runner's profile through USERPROFILE.

* agentenv: PI_CONFIG_DIR and OPENCODE_DB take relative names on purpose

omp puts $PI_CONFIG_DIR under the home and OpenCode a relative $OPENCODE_DB in its data folder, so neither depends on the working folder: appdir no longer passes them over.

* i18n: German for the Library's multi-select and System One's decision API

The 19 strings main added since (#791's skill multi-select, the decision API snippets) get their German; the one main replaced (four APIs → five APIs) goes.

* appdir: tidy the import into magpie's group; say what Go makes of /c/x

The appdir import joins the group of magpie's own imports where a file has one. rooted's comment now says that Go takes a Git Bash path like /c/x as \c\x on the current drive, not C:\x.
2026-10-04 23:30:56 +08:00
ylornandylorn 1aef0f3f2d proc: the login-shell probe asks nushell through /bin/sh, and a value the shell printed instead of expanding counts as unset (#738: with nushell as the login shell, shellEnv's printf '…' "$PATH" "$CLAUDE_CONFIG_DIR" … came back as the text "$PATH", "$CLAUDE_CONFIG_DIR", … — a double-quoted string is literal in nushell — and setUnset exported every one of agentenv.Vars with its own name as the value; Claude sign-in then failed with "mkdir $CLAUDE_CONFIG_DIR: read-only file system" (putClaudeLogin's MkdirAll of that relative name under the GUI's cwd /), and the account lapsed minutes later as "Claude Code is no longer signed in", its sign-in looked for under that folder; Codex, Pi, omp and the rest were pointed at "$CODEX_HOME", "$PI_CODING_AGENT_DIR", "$OMP_PROFILE" the same way, in the GUI alone, which is the one caller of UserPath) — shellProbe builds the command: for a shell named nu it is ^/bin/sh -c '<the same printf>' (nushell has no POSIX quoting to ask with and its PATH is a list, while a child of it gets the environment as any child does, PATH joined back into one string, and sh expands the references; the outer string in nushell's single quotes where a backslash is a backslash, the format in sh's double quotes where \0 reaches printf), any other shell keeps the printf it had; and parseShellEnv takes a value that is the variable's own reference ("$CODEX_HOME", or "$PATH" for PATH) for unset, so a login shell with other quoting than POSIX leaves a variable alone rather than setting it to its name. TestShellEnvNushell runs the probe through a nushell on the machine (skipped where there is none) and checks the command's shape anyway; TestParseShellEnvUnexpanded feeds the unexpanded answer. Verified against nushell 0.116.0: PATH comes back, CODEX_HOME from the environment reaches sh, unset variables are "". (#739)
Co-authored-by: ylorn <ylorn@icloud.com>
2026-10-04 11:13:50 +08:00
yetone a27bd9ec96 proc: the desktop app takes the agents' folder variables from the login shell, as it does PATH (atie on Discord: PI_CODING_AGENT_DIR set in the shell, magpie still wrote Pi's config to ~/.pi/agent/models.json) — magpie reads PI_CODING_AGENT_DIR, CODEX_HOME, CLAUDE_CONFIG_DIR and the rest with os.Getenv, but an app opened from the Finder, the Dock or the login item gets launchd's environment, with nothing a shell profile exports, so every agent was wired into its default folder in the home. proc.UserPath already asked the login shell for its PATH (sh -ilc printf with markers); the same single call now prints PATH and every variable in agentenv.Vars between the markers, parted by NULs, and each one magpie's environment doesn't have and the shell gives a non-empty value is set with os.Setenv; one magpie was started with is kept. These are read as soon as the app starts (the library is synced into the agents at once, the backend wires them), so UserPath now waits for the shell's answer up to 2 s instead of not at all; a slower profile still doesn't hold the window up longer, and what it says later is still taken. LoginPath uses the same call. Windows is unchanged (an app gets the user's environment from the registry there). Only the GUI's runGUI/runPanel call UserPath; no test but proc's own does. TestUserPathTakesAgentVars (a fake $SHELL whose profile exports PI_CODING_AGENT_DIR with a space, CODEX_HOME and an empty GROK_HOME) fails on the old code (nothing taken) and passes: Pi's folder is set by the time UserPath returns, magpie's own CODEX_HOME is kept, the empty and absent ones stay unset. Tried with a built binary calling proc.UserPath under env -i (launchd's PATH, a temp HOME): with /bin/zsh, .zshrc's PI_CODING_AGENT_DIR="$HOME/my pi" and CLAUDE_CONFIG_DIR came through, CODEX_HOME=/kept stayed, .zprofile's PATH folder was added, in 19 ms; with /bin/bash, .bash_profile's value came through. go vet, builds (darwin, GOOS=linux -tags nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass but TestClaudeSignedOut, TestClaudeAccountNamedAsItsLogin, TestClaudeIdentityServedWhileAsked and TestDevinSignedInOnlyInMagpie, timing tests on fake CLIs (5 s waits) that pass when the package is rerun; none of them reaches UserPath. 2026-10-03 22:34:36 +08:00
yetone 9848a9062a library: RTK says when rtk isn't on the PATH the agents get, and puts it there when asked (#601, Moody-Sin: magpie好像没有正确安装RTK — Pi said "RTK disabled: rtk binary not found in PATH" while the Library showed RTK working) — rtk's hooks run it by name (Pi's extension probes rtk --version and turns itself off when that fails; Claude Code's and Codex's are rtk hook …; the commands they rewrite to are rtk git status and so on), but magpie looked for rtk in more places than an agent's PATH: ~/.local/bin and ~/.cargo/bin, which the app adds to its own PATH whether the user's shell has them or not (rtk's own install.sh puts it in ~/.local/bin and only warns when that isn't on PATH), and WinGet\Links on Windows, which winget doesn't always link into. So rtk was "installed", the agents were switched on with it by its whole path, and none of them could run it. Now the PATH a terminal opened now has is read — the login shell's (proc.LoginPath, the one UserPath already asks for, kept a minute) or on Windows the registry's (moved from provider's registryPath) — and when rtk isn't in it the RTK card says so, with what Put RTK on PATH will do, and each agent that has rtk is tagged Not on PATH (不在 PATH 中). Put RTK on PATH (magpie library rtk path) links rtk into the first of ~/.local/bin, ~/bin, /opt/homebrew/bin, /usr/local/bin, linuxbrew's bin, ~/.cargo/bin that is on that PATH and writable, or on Windows adds rtk's own folder to the user's PATH in the registry (a link needs Developer Mode, and a copy is left behind when winget upgrades rtk; winget's package folder doesn't change across upgrades) and tells Explorer; with no such folder it says which folder to add to PATH in the shell profile — shell profiles are never edited. rtk is also found in winget's package folder (WinGet\Packages\rtk-ai.rtk_*), and rtk's script upgrades a linked rtk where the link points, not over the link. TestRTKOffPath and library-rtk-path.test.cjs (en, zh) fail without the change. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build and vet, go test -tags nogui -count=1 ./... under a temp HOME pass but the known TestFXInState flake. The Windows registry path is built, not run on Windows. 2026-10-03 02:38:17 +08:00
AronnaxandClaude Opus 5.5 ec4ee5a3a4 fix(proc): end what a CLI probe started, on its timeout and when magpie exits (#414)
* fix(proc): end what a CLI probe started, on its timeout and when magpie exits

The probes that ask an agent's CLI something (claude auth status,
cursor-agent about/models/status, the --version checks) ran through
proc.CommandContext, which on its timeout kills only the command itself.
A CLI that is a script (a version manager's wrapper, a shim) left what it
had started running, adopted by init; and a probe still asking when magpie
exited (a one-shot command, an update, a restart) was left whole, with
nothing to end it. With Omarchy's mise wrappers stuck in their exec loop
(omacom/omarchy#7234) that was five processes holding about half a core
each for up to six hours.

proc.ProbeContext gives such a probe a session of its own on Unix, as
StartTree does, and its context ending kills the whole group. Probes still
running are listed, and proc.EndProbes kills them when magpie exits (after
run in main) or puts a new version in its place (update.Reexec). On
Windows a probe is killed alone, as before, a job being joined only once
the command has started.

TestProbeTimeoutEndsWhatItStarted and TestEndProbes fail without the
change.

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

* fix(proc): end probes on a terminal's signals and on a Mac's quit

Review of the first change: a probe leading its own session no longer
gets the Ctrl+C, hang-up or SIGTERM sent to magpie's terminal or service,
and magpie ending on the signal never reached EndProbes, so the probe was
left to init where before it died with magpie. main now catches SIGINT,
SIGTERM and SIGHUP, ends the probes and exits as the signal would have
(128+n). A signal magpie was started ignoring (nohup, a background job)
stays ignored. The account sign-in and plugin commands, which end
themselves on Ctrl+C, go through interruptContext and are left to do so.

On a Mac the desktop app's quit ([NSApp terminate:], also the restart to
update) exits without returning to main, so OnShutdown ends the probes.

TestProbeTimeoutEndsWhatItStarted ended its probe on a 500ms timeout,
which on a Mac could come before the script had written its child's pid
(6 of 10 runs failed in review). It now ends the context once that pid is
read, the same Cancel path.

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

* fix: let the app and the TUI quit on a signal their own way

Review of the signal handling: endProbesOnSignal exited ahead of Wails
and bubbletea, which quit on SIGINT and SIGTERM themselves. `magpie tray`
exited 143 without OnShutdown (no downloaded update installed, and
sessions.Saved skipped in main), and `magpie tui` left the terminal on its
alternate screen with the cursor hidden. The app's and the TUI's entry
points now hand the signals back (ownSignals): the app's OnShutdown ends
the probes, and the TUI comes back to main, which ends them too. A
one-shot command keeps the handler.

TestOwnSignalsHandsThemBack fails without the change (magpie exited 143
before the command could quit its own way); TestSignalExits keeps the
one-shot behavior.

childPid waited 3s for a script just written to start its child, which a
busy Mac can exceed (2 of 3 full runs failed in review). It waits 30s now
and, should the probe end first, says the probe's error rather than "the
script started nothing".

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

* fix: keep SIGHUP for the app and the TUI, and die of the signal

ownSignals handed SIGHUP back along with SIGINT and SIGTERM, but neither
Wails nor bubbletea handles it: the terminal closing under the TUI or an
app started from a shell ended magpie on the spot, and its probes, in a
session of their own, out of the hang-up's reach, kept running (before
this PR they were in the terminal's group and ended with it). SIGHUP now
stays with endProbesOnSignal. A tray under a pty whose terminal closes
left 2 processes before, none now.

The handler asked whether a command was ending itself on Ctrl+C only
after EndProbes, which can take up to a second; a sign-in done in the
meantime got magpie ended in the middle of its own cleanup. It is asked
first.

It exited 128+n, which a shell takes for a child that handled the signal:
a loop running magpie went on to the next run on Ctrl+C. It now dies of
the signal (handling reset, the signal sent again); Windows, which can't
send one, still exits with the code.

agentProbe and agentCommand share withProxy; the Windows probeGroup
comment no longer says EndProbes ends what a shim started.

TestOwnSignalsKeepsHangUp and TestInterruptWhileEndingProbes fail without
the change.

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

* fix: hand signals to the TUI and the app only once they listen

Review: runTUI handed SIGINT and SIGTERM back before tui.Run, whose
newModel asks agents' CLIs (claude auth status, up to 5s) before
bubbletea listens for signals. Ctrl+C, SIGTERM or SIGINT while it loaded
ended magpie by Go's default and left the probe and its child running.
tui.Run now takes ready, called once the model is made, and runTUI passes
ownSignals.

The app had the same window: runGUI handed them back before gui.Run,
which starts the backend (probes included) before Wails' Run starts
listening. ownSignals is now gui.Started, called on ApplicationStarted,
which Wails emits after its signal handler is set up. A tray sent SIGTERM
0.05s after starting, a probe under way, left 2 processes before and
none now; one sent it once started still quits through OnShutdown
(exit 0).

TestTUIKeepsSignalsWhileLoading fails without the change.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 00:42:48 +08:00