diff --git a/internal/gateway/claude_warmup.go b/internal/gateway/claude_warmup.go index 6ebf1bfd9..330791aff 100644 --- a/internal/gateway/claude_warmup.go +++ b/internal/gateway/claude_warmup.go @@ -6,10 +6,12 @@ import ( "encoding/json" "errors" "os" + "os/exec" "slices" "strings" "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/provider" ) @@ -51,7 +53,7 @@ func askClaude(ctx context.Context, configDir, model string) error { cmd.Env = binary.env(netproxy.EnvWith(claudeProxy(ctx), cleanClaudeEnv(os.Environ())), configDir) var out, stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &stderr - runErr := cmd.Run() + runErr := runClaudeTree(cmd) if res, ok := claudeResult(out.Bytes()); ok && res.IsError { return errors.New("Claude Code: " + clip(res.Result)) } @@ -102,7 +104,7 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) { cmd.Env = binary.env(netproxy.EnvWith(claudeProxy(ctx), env), configDir) var out, stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &stderr - runErr := cmd.Run() + runErr := runClaudeTree(cmd) if res, ok := claudeResult(out.Bytes()); ok { if res.IsError { return "", errors.New("Claude Code: " + clip(res.Result)) @@ -119,6 +121,21 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) { return "", errors.New("Claude Code: " + clip(msg)) } +// runClaudeTree runs a one-off Claude Code (a test, a /usage) and ends, +// with it, whatever it started: its context ending kills only the +// process magpie started, and on Windows that is cmd.exe running npm's +// claude.cmd, whose node went on running with nobody waiting for it +// (#1894). In a tree, a job on Windows and a session elsewhere, what is +// left once the head is gone is ended with it, and on Windows when magpie +// exits mid-run. +func runClaudeTree(cmd *exec.Cmd) error { + t, err := proc.StartTree(cmd) + if err != nil { + return err + } + return t.Wait() +} + // claudeRun is the result Claude Code prints for a -p run with // --output-format json. type claudeRun struct { diff --git a/internal/gateway/claude_warmup_test.go b/internal/gateway/claude_warmup_test.go index d2bdd18d0..04f23b85d 100644 --- a/internal/gateway/claude_warmup_test.go +++ b/internal/gateway/claude_warmup_test.go @@ -4,10 +4,13 @@ import ( "context" "encoding/json" "os" + "os/exec" "path/filepath" "runtime" + "strconv" "strings" "testing" + "time" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/testenv" @@ -198,3 +201,70 @@ func TestClaudeVerboseOutput(t *testing.T) { t.Fatalf("got %v", err) } } + +// heng91 on #1894: claude processes in Task Manager with no Claude session +// open. A test or /usage run of Claude Code that outlives its time is +// killed, and what it started goes with it: npm's claude.cmd is cmd.exe +// running node, and only cmd.exe was killed. A script stands in, which +// starts a child and hangs; once the run is given up on, the child is gone. +func TestClaudeRunEndsWhatItStarted(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for Claude Code") + } + for _, run := range []struct { + name string + f func(ctx context.Context) error + }{ + {"test", func(ctx context.Context) error { return askClaude(ctx, "", "haiku") }}, + {"usage", func(ctx context.Context) error { _, err := claudeUsage(ctx, ""); return err }}, + } { + t.Run(run.name, func(t *testing.T) { + dir := t.TempDir() + pidFile := filepath.Join(dir, "child") + testenv.Program(t, filepath.Join(dir, "claude"), "#!/bin/sh\nsleep 300 /dev/null 2>&1 &\necho $! > "+pidFile+"\nsleep 300\n") + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + var pid int + t.Cleanup(func() { + if pid > 0 { + if p, err := os.FindProcess(pid); err == nil { + p.Kill() + } + } + }) + // given up on once it has started its child, however busy the + // machine: a timeout that came first had nothing to leave behind + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + go func() { + for ctx.Err() == nil { + if b, _ := os.ReadFile(pidFile); strings.HasSuffix(string(b), "\n") { + cancel() + return + } + time.Sleep(10 * time.Millisecond) + } + }() + if err := run.f(ctx); err == nil { + t.Fatal("a run that never answered passed") + } + b, err := os.ReadFile(pidFile) + if err != nil { + t.Fatal(err) + } + pid, _ = strconv.Atoi(strings.TrimSpace(string(b))) + if pid <= 0 { + t.Fatalf("pid %q", b) + } + // gone, or a zombie waiting for init to reap it + for end := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) { + out, _ := exec.Command("ps", "-o", "stat=", "-p", strconv.Itoa(pid)).Output() + if st := strings.TrimSpace(string(out)); st == "" || strings.HasPrefix(st, "Z") { + break + } + if time.Now().After(end) { + t.Fatalf("what Claude Code started is still running (%d)", pid) + } + } + }) + } +}