gateway: a Claude Code test or /usage run that magpie gives up on ends with what it started, npm's node on Windows too (#1894, heng91)

What changed: magpie runs Claude Code one-off for an account's model test
(askClaude) and for /usage (claudeUsage, read in the background for each
Claude account). Both ran through CommandContext, whose kill on the
timeout ends only the process magpie started. On Windows an npm install's
claude is claude.cmd: cmd.exe running node, and only cmd.exe was killed,
so node went on running with nothing to end it. Elsewhere a CLI that is a
wrapper script left its child the same way.

Now both run in a proc.Tree (a job on Windows, a session elsewhere), as
the Claude subscription's runs do: what is left once the head ends is
ended with it, and on Windows the job ends it if magpie exits mid-run.

Run:
- go test -tags nogui -count=3 -run 'ClaudeRunEnds|WarmClaude|ClaudeUsage|ClaudeTest'
  ./internal/gateway: ok. New TestClaudeRunEndsWhatItStarted: a script
  claude that starts a child and hangs; once it has started the child the
  run is given up on, and the child must be gone. With cmd.Run() put back
  by hand, both subtests (test, usage) go red with the child running.
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui: clean.

Not run on the Windows box: the job path is the one subscription runs
already use. Not found to be the reporter's processes: magpie's other
Claude Code processes are the subscription runs kept for a conversation's
next turn (at most 6, at most an hour, by design).

Reported-by: heng91
This commit is contained in:
yetone
2026-10-13 13:03:26 +08:00
parent c651c2ffd4
commit 1e88598384
2 changed files with 89 additions and 2 deletions
+19 -2
View File
@@ -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 {
+70
View File
@@ -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 >/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)
}
}
})
}
}