agent: an npm update on Windows lets go of magpie's own claude and codex first
CLJY (Discord) had %APPDATA%\npm with only the 308-byte sh shim of claude: no claude.cmd, no claude.ps1 and no codex at all, and `npm i -g @anthropic-ai/claude-code` ended in "npm warn cleanup ... EPERM ... unlink ...\.claude-code-<rand>\...\claude-code-win32-x64\claude.exe". On Windows a running program's file can't be removed. npm moves the old package aside, takes the old shims away, and stops partway when a claude.exe of that package is still running; the sh shim is what is left. magpie keeps such processes running itself: - the Claude subscription bridge keeps up to 6 Claude Code runs waiting for their conversations' next turns, for up to an hour; - Codex's app-server daemon has no idle exit, and magpie restarts it. Its Update button ran npm with both still up. - agent.UpdateCLI, on Windows through npm, bun or pnpm, first lets go of them: gateway.LetGoIdleClaudeCode ends every waiting run (its session shelved for the next turn, as a run let go past idleMost is) and returns once each has exited; provider.StopIdleCodexDaemon stops the daemon when no codex session is on it. Runs in a turn and sessions are left. - An update on Windows that leaves the CLI's file gone fails, saying to quit it and reinstall, instead of "updated". - proc's toolIn (FindTool) and codexExecutable no longer take the bare extensionless file on Windows, which CreateProcess can't run. Beside name.exe and name.cmd, the sh shim alone stands for the .exe it runs (Claude Code's bin\claude.exe), read from cmd-shim's exec line and kept inside its folder; a node shim (codex) or any other script is skipped. The testdata shims are cmd-shim 7's bytes, made with cmd-shim@7 on the Windows box. Run at this head (rebased on origin/main; after the rebase, vet on all three systems and the changed tests again: ok on Windows and macOS): - gofmt -l internal/: clean. go vet of proc, agent, provider and gateway on macOS (mote), Windows (win-run) and Linux (wsl-run): ok. - Windows (win-run): internal/proc ok; TestToolInNPMShShimAlone, TestLetGoIdleClaudeCodeFreesTheExe and the TestClaudeIdle* tests pass. internal/agent, internal/provider and internal/gateway (-run "Claude|LetGo|Codex") have Windows reds, and the same run at origin/mainc9d253e4ahas the same ones (26 in agent, 15 in provider, 2 in gateway), except TestUsageReadAndReadAgain, a clock-tick flake filed as #4796. - macOS (mote): internal/proc, internal/agent, internal/provider and internal/gateway (-run "Claude|LetGo|Codex") ok. - Linux (wsl-run): internal/proc and internal/provider ok; internal/agent red only in TestGrokInstalled, red the same on origin/mainc9d253e4a(3 of 3), filed as #3548. Broken by hand: - toolIn taking the bare name again: TestToolInNPMShShimAlone red on Windows (6 cases). - letGoIdle not waiting for the trees: TestLetGoIdleClaudeCodeFreesTheExe red on Windows, and with that check off the removal fails with "Access is denied" - the user's EPERM. - no let-go call and no gone check: TestUpdateCLIOnWindowsLetsGoFirst red; StopIdleCodexDaemon ignoring sessions: TestStopIdleCodexDaemon red. Not tried: a real npm update of Claude Code or Codex on the Windows box with magpie running; the Windows-only path is tested with updateGOOS = "windows" on macOS, and the process lock with a copy of the test binary. Reported-by: CLJY (Discord)
This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -30,8 +31,10 @@ import (
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/desktopdir"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/source"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
)
|
||||
@@ -1081,6 +1084,32 @@ func updateEnv(u *updater) []string {
|
||||
return append(env, "NONINTERACTIVE=1", "HOMEBREW_NO_ENV_HINTS=1", "NO_COLOR=1", "CLINE_NO_AUTO_UPDATE=1")
|
||||
}
|
||||
|
||||
// letGoBeforeUpdate ends what magpie itself keeps running of the agent
|
||||
// id's CLI, before a package manager on Windows replaces its package: a
|
||||
// program running from it can't be removed there (EPERM), and npm, which
|
||||
// takes the old shims away first, stopped partway and left none (CLJY on
|
||||
// Discord: %APPDATA%\npm with only the sh shim of claude, no claude.cmd,
|
||||
// and no codex at all). The Claude subscription bridge's runs kept for
|
||||
// their conversations' next turns, and Codex's app-server daemon with no
|
||||
// session on it; a var so tests can see it asked.
|
||||
var letGoBeforeUpdate = func(ctx context.Context, id string) {
|
||||
switch id {
|
||||
case "claude":
|
||||
if n := gateway.LetGoIdleClaudeCode(); n > 0 {
|
||||
log.Printf("claude: ended %d Claude Code runs waiting for their next turn, to update it", n)
|
||||
}
|
||||
case "codex":
|
||||
if stopped, err := provider.StopIdleCodexDaemon(ctx); err != nil {
|
||||
log.Println("codex: before its update:", err)
|
||||
} else if stopped {
|
||||
log.Println("codex: stopped its app-server daemon, to update it")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// updateGOOS is runtime.GOOS; a var so tests can be Windows.
|
||||
var updateGOOS = runtime.GOOS
|
||||
|
||||
// updateTimeout bounds an update: a download, or Homebrew updating itself first.
|
||||
var updateTimeout = 10 * time.Minute
|
||||
|
||||
@@ -1110,6 +1139,9 @@ func (a *Agent) UpdateCLI() (CLI, error) {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), updateTimeout)
|
||||
defer cancel()
|
||||
if updateGOOS == "windows" && (u.via == "npm" || u.via == "bun" || u.via == "pnpm") {
|
||||
letGoBeforeUpdate(ctx, a.ID)
|
||||
}
|
||||
run := runUpdate
|
||||
if u.admin {
|
||||
run = runAdmin
|
||||
@@ -1135,6 +1167,13 @@ func (a *Agent) UpdateCLI() (CLI, error) {
|
||||
}
|
||||
return c, fmt.Errorf("%s: %s", u.shown(), msg)
|
||||
}
|
||||
if updateGOOS == "windows" && !isFile(bin) {
|
||||
// npm took the old shims away and stopped before it wrote the new
|
||||
// ones: a file of the old package's was still running (EPERM), and
|
||||
// what is left of claude is npm's sh shim, which Windows can't run
|
||||
// (CLJY on Discord)
|
||||
return c, fmt.Errorf("%s was updated, but %s is gone (a copy of it still running keeps %s from finishing): quit it, and %s", a.Name, bin, u.via, mendHint(u, c.Version))
|
||||
}
|
||||
if c.Update && c.Version == before {
|
||||
return c, fmt.Errorf("%s is still %s after %s; %s is out", a.Name, c.Version, u.shown(), c.Latest)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// CLJY (Discord): on Windows npm can't replace Claude Code while a copy of
|
||||
// its claude.exe runs, and an update stopped partway and left only the sh
|
||||
// shim, which Windows can't run. Before an npm update there, magpie lets go
|
||||
// of what it keeps running of that CLI; and an update that leaves the CLI
|
||||
// gone is a failure that says to quit it and reinstall, not "updated".
|
||||
func TestUpdateCLIOnWindowsLetsGoFirst(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("shell scripts as the CLI")
|
||||
}
|
||||
tmp, _ := filepath.EvalSymlinks(t.TempDir())
|
||||
prefix := filepath.Join(tmp, "npm")
|
||||
pkgDir := filepath.Join(prefix, "lib/node_modules/@anthropic-ai/claude-code")
|
||||
pkgJSON := filepath.Join(pkgDir, "package.json")
|
||||
file(t, pkgJSON, `{"name":"@anthropic-ai/claude-code","version":"2.1.298"}`)
|
||||
file(t, filepath.Join(pkgDir, "bin/claude.exe"), "#!/bin/sh\necho '2.1.298 (Claude Code)'\n")
|
||||
file(t, filepath.Join(prefix, "bin/npm"), "#!/bin/sh\nexit 1\n")
|
||||
shim := filepath.Join(prefix, "bin/claude")
|
||||
link(t, "../lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe", shim)
|
||||
t.Setenv("PATH", filepath.Join(prefix, "bin"))
|
||||
t.Setenv("HOME", filepath.Join(tmp, "home"))
|
||||
|
||||
oldRun, oldLetGo, oldGOOS := runUpdate, letGoBeforeUpdate, updateGOOS
|
||||
t.Cleanup(func() {
|
||||
runUpdate, letGoBeforeUpdate, updateGOOS = oldRun, oldLetGo, oldGOOS
|
||||
versions, latests = memo{}, memo{}
|
||||
})
|
||||
versions, latests = memo{}, memo{}
|
||||
latests.get("npm:@anthropic-ai/claude-code", "", 1<<40, 1<<40, func() (string, error) { return "2.1.299", nil })
|
||||
updateGOOS = "windows"
|
||||
var order []string
|
||||
letGoBeforeUpdate = func(_ context.Context, id string) { order = append(order, "let go of "+id) }
|
||||
runUpdate = func(_ context.Context, u *updater) ([]byte, error) {
|
||||
order = append(order, u.via)
|
||||
// npm's reify: the old shims removed, the new ones never written
|
||||
os.Remove(shim)
|
||||
os.WriteFile(pkgJSON, []byte(`{"name":"@anthropic-ai/claude-code","version":"2.1.299"}`), 0o644)
|
||||
return []byte("npm warn cleanup Failed to remove some directories\nchanged 1 package in 3s"), nil
|
||||
}
|
||||
a := &Agent{ID: "claude", Name: "Claude Code", Bin: "claude"}
|
||||
if c, ok := a.CLI(); !ok || c.Via != "npm" {
|
||||
t.Fatalf("before: %+v", c)
|
||||
}
|
||||
_, err := a.UpdateCLI()
|
||||
if got := strings.Join(order, ", "); got != "let go of claude, npm" {
|
||||
t.Errorf("ran %q; want magpie's own runs let go of before npm", got)
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), "is gone") {
|
||||
t.Fatalf("an update that left no claude to run: %v", err)
|
||||
}
|
||||
|
||||
// elsewhere a running program doesn't hold its file: nothing let go of
|
||||
updateGOOS = "darwin"
|
||||
order = nil
|
||||
file(t, pkgJSON, `{"name":"@anthropic-ai/claude-code","version":"2.1.298"}`)
|
||||
link(t, "../lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe", shim)
|
||||
versions = memo{}
|
||||
runUpdate = func(_ context.Context, u *updater) ([]byte, error) {
|
||||
order = append(order, u.via)
|
||||
os.WriteFile(pkgJSON, []byte(`{"name":"@anthropic-ai/claude-code","version":"2.1.299"}`), 0o644)
|
||||
return nil, nil
|
||||
}
|
||||
a.UpdateCLI()
|
||||
if got := strings.Join(order, ", "); !strings.HasPrefix(got, "npm") || strings.Contains(got, "let go") {
|
||||
t.Errorf("ran %q off Windows", got)
|
||||
}
|
||||
}
|
||||
@@ -7388,3 +7388,67 @@ func allowedTools(req *Request) map[string]bool {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LetGoIdleClaudeCode ends the Claude Code runs every subscription bridge
|
||||
// keeps waiting for their conversations' next turns, each one's session
|
||||
// shelved for that turn as a run let go past idleMost is, and waits for
|
||||
// them to have exited. It says how many it ended. An update of Claude
|
||||
// Code by npm on Windows asks it first (agent.UpdateCLI): a run holds the
|
||||
// package's claude.exe for up to idleLongest, which npm can't remove
|
||||
// while it runs (EPERM), so the update stopped partway and left
|
||||
// %APPDATA%\npm without claude.cmd (CLJY on Discord). A run in a turn is
|
||||
// left to finish it.
|
||||
func LetGoIdleClaudeCode() int {
|
||||
var runs []*subscriptionRun
|
||||
bridges.Range(func(b, _ any) bool {
|
||||
runs = append(runs, b.(*subscriptionBridge).letGoIdle("Claude Code is being updated")...)
|
||||
return true
|
||||
})
|
||||
// Windows' Stop kills the tree and returns; the process has exited,
|
||||
// and let go of its files, once exited closes
|
||||
gone := time.After(stopGrace + time.Second)
|
||||
for _, r := range runs {
|
||||
r.mu.Lock()
|
||||
exited := r.exited
|
||||
r.mu.Unlock()
|
||||
if exited == nil {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-exited:
|
||||
case <-gone:
|
||||
return len(runs)
|
||||
}
|
||||
}
|
||||
return len(runs)
|
||||
}
|
||||
|
||||
// letGoIdle ends b's runs waiting for their next turn, for why, waits
|
||||
// until each tree is ended, and says which they were.
|
||||
func (b *subscriptionBridge) letGoIdle(why string) []*subscriptionRun {
|
||||
var drop []*subscriptionRun
|
||||
b.mu.Lock()
|
||||
for key, run := range b.idle {
|
||||
if run.idleKey == key {
|
||||
b.shelve(run)
|
||||
}
|
||||
delete(b.idle, key)
|
||||
run.idleKey = ""
|
||||
if !slices.Contains(drop, run) {
|
||||
drop = append(drop, run)
|
||||
}
|
||||
}
|
||||
b.mu.Unlock()
|
||||
stops := make([]<-chan struct{}, 0, len(drop))
|
||||
for _, run := range drop {
|
||||
run.abortFor(why)
|
||||
}
|
||||
for _, run := range drop {
|
||||
stops = append(stops, run.abort())
|
||||
}
|
||||
for _, s := range stops {
|
||||
<-s
|
||||
}
|
||||
claudeRoom.nudge()
|
||||
return drop
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
)
|
||||
|
||||
// CLJY (Discord): npm couldn't remove claude.exe while a Claude Code run
|
||||
// magpie kept for a conversation's next turn still ran it (EPERM), so an
|
||||
// update stopped partway and left %APPDATA%\npm with the sh shim alone.
|
||||
// LetGoIdleClaudeCode, which an npm update on Windows asks first, ends
|
||||
// every waiting run and returns once its process has exited: the exe it
|
||||
// ran can then be removed. Its conversation is shelved for its next turn;
|
||||
// a run in a turn is left to finish it.
|
||||
func TestLetGoIdleClaudeCodeFreesTheExe(t *testing.T) {
|
||||
const child = "MAGPIE_TEST_LETGO_CHILD"
|
||||
if os.Getenv(child) != "" {
|
||||
time.Sleep(2 * time.Minute) // a Claude Code waiting for its next turn
|
||||
return
|
||||
}
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
exe := filepath.Join(dir, "claude"+filepath.Ext(self))
|
||||
body, err := os.ReadFile(self)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(exe, body, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
b := idleTestBridge()
|
||||
start := func() *subscriptionRun {
|
||||
cmd := proc.Command(exe, "-test.run=^TestLetGoIdleClaudeCodeFreesTheExe$", "-test.timeout=3m")
|
||||
cmd.Env = append(os.Environ(), child+"=1")
|
||||
tree, err := proc.StartTree(cmd)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exited := make(chan struct{})
|
||||
r := &subscriptionRun{bridge: b, cmd: cmd, tree: tree, exited: exited, pending: map[string]chan mcpToolResult{}}
|
||||
go func() {
|
||||
tree.Wait()
|
||||
r.mu.Lock()
|
||||
close(exited)
|
||||
r.mu.Unlock()
|
||||
}()
|
||||
t.Cleanup(func() { <-tree.Stop(0) })
|
||||
return r
|
||||
}
|
||||
waiting := start()
|
||||
waiting.sessionID, waiting.sessions = "s1", []string{filepath.Join(dir, "project")}
|
||||
b.keepIdle(waiting, "conversation", "conversation")
|
||||
b.runs["waiting"] = waiting
|
||||
busy := &subscriptionRun{bridge: b, pending: map[string]chan mcpToolResult{}}
|
||||
b.runs["busy"] = busy
|
||||
t.Cleanup(func() {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
for _, s := range b.shelf {
|
||||
if s.timer != nil {
|
||||
s.timer.Stop()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
bridges.Store(b, true)
|
||||
t.Cleanup(func() { bridges.Delete(b) })
|
||||
if n := LetGoIdleClaudeCode(); n < 1 {
|
||||
t.Fatalf("let go of %d runs; one was waiting", n)
|
||||
}
|
||||
select {
|
||||
case <-waiting.exited:
|
||||
default:
|
||||
t.Fatal("LetGoIdleClaudeCode returned before the waiting run's Claude Code exited")
|
||||
}
|
||||
if len(b.idle) != 0 {
|
||||
t.Fatalf("%d runs still kept for a next turn", len(b.idle))
|
||||
}
|
||||
if s := b.shelf["conversation"]; s == nil || s.session != "s1" {
|
||||
t.Fatal("the waiting run's conversation was not shelved for its next turn")
|
||||
}
|
||||
busy.mu.Lock()
|
||||
closed := busy.closed
|
||||
busy.mu.Unlock()
|
||||
if closed {
|
||||
t.Fatal("a run in a turn was ended")
|
||||
}
|
||||
// the exe npm replaces: on Windows a running copy refuses this (EPERM)
|
||||
if err := os.Remove(exe); err != nil {
|
||||
t.Fatalf("the exe can't be removed after the let-go (%s): %v", runtime.GOOS, err)
|
||||
}
|
||||
}
|
||||
+50
-2
@@ -3,6 +3,7 @@ package proc
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
@@ -61,12 +62,22 @@ func SystemDirs(paths ...string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// ToolIn is name's program in the first of dirs that has one, as toolIn
|
||||
// finds it on this system.
|
||||
func ToolIn(name string, dirs []string) string { return toolIn(name, runtime.GOOS, dirs) }
|
||||
|
||||
// toolIn is name's program in the first of dirs that has one: on Windows
|
||||
// name.exe, name.cmd or name, as npm's shim or an installer's binary.
|
||||
// name.exe or name.cmd, as an installer's binary or npm's shim, else the
|
||||
// program npm's sh shim name runs, when that is a Windows program
|
||||
// (npmShimExe). A file with no extension is never run on Windows itself:
|
||||
// CreateProcess refuses it ("%1 is not a valid Win32 application"), and
|
||||
// what npm left of its shims when an install failed partway is that sh
|
||||
// one alone (CLJY on Discord: %APPDATA%\npm\claude, 308 bytes, with no
|
||||
// claude.cmd beside it, was what magpie ran).
|
||||
func toolIn(name, goos string, dirs []string) string {
|
||||
names := []string{name}
|
||||
if goos == "windows" {
|
||||
names = []string{name + ".exe", name + ".cmd", name}
|
||||
names = []string{name + ".exe", name + ".cmd"}
|
||||
}
|
||||
for _, d := range dirs {
|
||||
if d == "" {
|
||||
@@ -78,6 +89,43 @@ func toolIn(name, goos string, dirs []string) string {
|
||||
return p
|
||||
}
|
||||
}
|
||||
if goos == "windows" {
|
||||
if p := npmShimExe(filepath.Join(d, name)); p != "" {
|
||||
return p
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// npmShimLine is the line of npm's sh shim (cmd-shim) that runs a program
|
||||
// of its package's directly: exec "$basedir/node_modules/<pkg>/<bin>" "$@".
|
||||
// A shim of a node script names node first, and isn't matched.
|
||||
var npmShimLine = regexp.MustCompile(`(?m)^\s*exec "\$basedir/([^"$]+\.exe)"\s+"\$@"`)
|
||||
|
||||
// npmShimExe is the Windows program the npm sh shim at path runs, where it
|
||||
// is: Claude Code's is node_modules\@anthropic-ai\claude-code\bin\claude.exe.
|
||||
// "" when path is no such shim or its program is gone.
|
||||
func npmShimExe(path string) string {
|
||||
st, err := os.Stat(path)
|
||||
if err != nil || st.IsDir() || st.Size() > wrapperMax {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
m := npmShimLine.FindSubmatch(b)
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
rel := filepath.FromSlash(string(m[1]))
|
||||
if !filepath.IsLocal(rel) {
|
||||
return ""
|
||||
}
|
||||
exe := filepath.Join(filepath.Dir(path), rel)
|
||||
if st, err := os.Stat(exe); err != nil || st.IsDir() {
|
||||
return ""
|
||||
}
|
||||
return exe
|
||||
}
|
||||
|
||||
@@ -74,3 +74,57 @@ func TestSystemDirsLieInTheTestsHome(t *testing.T) {
|
||||
t.Errorf("SystemDirs outside a test = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// What npm leaves of a package's shims when an install stops partway on
|
||||
// Windows is its sh shim alone, which Windows can't run: a folder holding
|
||||
// only that is given as the program it names, when that is a Windows one
|
||||
// still there, and passed over otherwise (CLJY on Discord: %APPDATA%\npm
|
||||
// had the 308-byte claude and no claude.cmd, and magpie ran the sh file).
|
||||
// The shims are cmd-shim 7's own bytes, made on the Windows box.
|
||||
func TestToolInNPMShShimAlone(t *testing.T) {
|
||||
read := func(name string) []byte {
|
||||
b, err := os.ReadFile(filepath.Join("testdata", name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
d := t.TempDir()
|
||||
npm, later := filepath.Join(d, "npm"), filepath.Join(d, "later")
|
||||
os.MkdirAll(later, 0o755)
|
||||
exe := filepath.Join(npm, "node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe")
|
||||
os.MkdirAll(filepath.Dir(exe), 0o755)
|
||||
os.WriteFile(filepath.Join(npm, "claude"), read("npm-sh-shim-claude"), 0o644)
|
||||
os.WriteFile(filepath.Join(npm, "codex"), read("npm-sh-shim-codex"), 0o644)
|
||||
os.WriteFile(filepath.Join(npm, "gemini"), []byte("#!/bin/sh\nexec gemini \"$@\"\n"), 0o644)
|
||||
|
||||
// the package's program is gone too: the shim is no tool
|
||||
if got := toolIn("claude", "windows", []string{npm}); got != "" {
|
||||
t.Errorf("shim of a missing program: %q", got)
|
||||
}
|
||||
os.WriteFile(exe, []byte("MZ"), 0o755)
|
||||
if got := toolIn("claude", "windows", []string{npm, later}); got != exe {
|
||||
t.Errorf("claude: %q, want %q", got, exe)
|
||||
}
|
||||
// a shim that runs node, or anything but npm's, is passed over, for a
|
||||
// runnable one in a later folder
|
||||
if got := toolIn("codex", "windows", []string{npm}); got != "" {
|
||||
t.Errorf("codex's node shim: %q", got)
|
||||
}
|
||||
if got := toolIn("gemini", "windows", []string{npm}); got != "" {
|
||||
t.Errorf("a script that isn't npm's: %q", got)
|
||||
}
|
||||
os.WriteFile(filepath.Join(later, "codex.exe"), []byte("MZ"), 0o755)
|
||||
if got := toolIn("codex", "windows", []string{npm, later}); got != filepath.Join(later, "codex.exe") {
|
||||
t.Errorf("codex in a later folder: %q", got)
|
||||
}
|
||||
// a shim naming a program outside its folder is not followed
|
||||
os.WriteFile(filepath.Join(npm, "evil"), []byte("exec \"$basedir/../../x.exe\" \"$@\"\n"), 0o644)
|
||||
if got := toolIn("evil", "windows", []string{npm}); got != "" {
|
||||
t.Errorf("a shim leaving its folder: %q", got)
|
||||
}
|
||||
// elsewhere the sh shim is the tool, as before
|
||||
if got := toolIn("claude", "linux", []string{npm}); got != filepath.Join(npm, "claude") {
|
||||
t.Errorf("linux: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
exec "$basedir/node_modules/@anthropic-ai/claude-code/bin/claude.exe" "$@"
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/node_modules/@openai/codex/bin/codex.js" "$@"
|
||||
else
|
||||
exec node "$basedir/node_modules/@openai/codex/bin/codex.js" "$@"
|
||||
fi
|
||||
@@ -621,3 +621,35 @@ func CodexPIDs(ctx context.Context) []int {
|
||||
}
|
||||
return pids
|
||||
}
|
||||
|
||||
// StopIdleCodexDaemon stops Codex's app-server daemon for the Codex home
|
||||
// magpie signs Codex in through, when it runs with no codex session on it,
|
||||
// and says whether it did. An update of Codex by npm on Windows asks it
|
||||
// first (agent.UpdateCLI): the daemon, which has no idle exit and which
|
||||
// magpie restarts (KeepCodexDaemonCurrent), holds the package's codex.exe,
|
||||
// which npm can't remove while it runs (EPERM), and the update stopped
|
||||
// partway. The next codex started starts it again. One with sessions on it
|
||||
// is left: they hold codex.exe too.
|
||||
func StopIdleCodexDaemon(ctx context.Context) (bool, error) {
|
||||
home := codexHome()
|
||||
ps, err := listProcesses(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if findCodexDaemon(ps, home) == 0 || codexClients(ps, home) > 0 {
|
||||
return false, nil
|
||||
}
|
||||
codexRestarting.Lock()
|
||||
defer codexRestarting.Unlock()
|
||||
cmd, err := codexDaemonCommand(ctx, home, "stop")
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
if msg := lastLine(out); msg != "" {
|
||||
return false, errors.New("codex app-server daemon stop: " + msg)
|
||||
}
|
||||
return false, errors.New("codex app-server daemon stop: " + err.Error())
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
@@ -680,3 +680,47 @@ func TestCodexPIDsFindsOpenCodex(t *testing.T) {
|
||||
t.Fatalf("a failed list gave %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// CLJY (Discord): before npm updates Codex on Windows, magpie stops the
|
||||
// app-server daemon when no codex session is on it, since it holds the
|
||||
// package's codex.exe, which npm can't remove while it runs. One with a
|
||||
// session on it, or none running, is left.
|
||||
func TestStopIdleCodexDaemon(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a shell script stands in for codex")
|
||||
}
|
||||
fakeDaemon(t)
|
||||
out := fakeCodex(t, 0)
|
||||
home := codexHome()
|
||||
clients, daemon := 0, true
|
||||
listProcesses = func(context.Context) ([]proc.Process, error) {
|
||||
var ps []proc.Process
|
||||
if daemon {
|
||||
ps = append(ps, proc.Process{PID: 50, Args: home + "/packages/app-server-daemon/releases/0.162.0/bin/codex app-server --listen unix:///x --managed-daemon"})
|
||||
}
|
||||
for i := range clients {
|
||||
ps = append(ps, proc.Process{PID: 100 + i, Args: "codex"})
|
||||
}
|
||||
return ps, nil
|
||||
}
|
||||
ran := func() string {
|
||||
b, _ := os.ReadFile(out + ".args")
|
||||
os.Remove(out + ".args")
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
ctx := context.Background()
|
||||
if stopped, err := StopIdleCodexDaemon(ctx); !stopped || err != nil || ran() != "app-server daemon stop" {
|
||||
t.Fatalf("idle daemon: stopped %t, %v", stopped, err)
|
||||
}
|
||||
if b, _ := os.ReadFile(out + ".home"); strings.TrimSpace(string(b)) != home {
|
||||
t.Errorf("CODEX_HOME %q, want %q", b, home)
|
||||
}
|
||||
clients = 1
|
||||
if stopped, err := StopIdleCodexDaemon(ctx); stopped || err != nil || ran() != "" {
|
||||
t.Fatalf("a session on it: stopped %t, %v", stopped, err)
|
||||
}
|
||||
clients, daemon = 0, false
|
||||
if stopped, err := StopIdleCodexDaemon(ctx); stopped || err != nil || ran() != "" {
|
||||
t.Fatalf("no daemon: stopped %t, %v", stopped, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,6 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -230,19 +228,9 @@ var codexExecutable = func() string {
|
||||
if p, err := proc.LookPath("codex"); err == nil {
|
||||
return p
|
||||
}
|
||||
names := []string{"codex"}
|
||||
if runtime.GOOS == "windows" {
|
||||
names = []string{"codex.cmd", "codex.exe", "codex"}
|
||||
}
|
||||
for _, d := range proc.UserBinDirs() {
|
||||
for _, n := range names {
|
||||
p := filepath.Join(d, n)
|
||||
if st, err := os.Stat(p); err == nil && !st.IsDir() {
|
||||
return p
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
// on Windows npm's codex.cmd, never the sh shim npm leaves alone when
|
||||
// an install fails partway, which Windows can't run (CLJY on Discord)
|
||||
return proc.ToolIn("codex", proc.UserBinDirs())
|
||||
}
|
||||
|
||||
// parseCodexModels reads the backend's list, the listed ones in its order.
|
||||
|
||||
Reference in New Issue
Block a user