|
| 1 | +//go:build !windows |
| 2 | + |
| 3 | +package tools |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "strconv" |
| 10 | + "strings" |
| 11 | + "syscall" |
| 12 | + "testing" |
| 13 | + "time" |
| 14 | +) |
| 15 | + |
| 16 | +func processExists(pid int) bool { |
| 17 | + if pid <= 0 { |
| 18 | + return false |
| 19 | + } |
| 20 | + err := syscall.Kill(pid, 0) |
| 21 | + return err == nil || err == syscall.EPERM |
| 22 | +} |
| 23 | + |
| 24 | +func TestShellTool_TimeoutKillsChildProcess(t *testing.T) { |
| 25 | + tool := NewExecTool(t.TempDir(), false) |
| 26 | + tool.SetTimeout(500 * time.Millisecond) |
| 27 | + |
| 28 | + args := map[string]interface{}{ |
| 29 | + // Spawn a child process that would outlive the shell unless process-group kill is used. |
| 30 | + "command": "sleep 60 & echo $! > child.pid; wait", |
| 31 | + } |
| 32 | + |
| 33 | + result := tool.Execute(context.Background(), args) |
| 34 | + if !result.IsError { |
| 35 | + t.Fatalf("expected timeout error, got success: %s", result.ForLLM) |
| 36 | + } |
| 37 | + if !strings.Contains(result.ForLLM, "timed out") { |
| 38 | + t.Fatalf("expected timeout message, got: %s", result.ForLLM) |
| 39 | + } |
| 40 | + |
| 41 | + childPIDPath := filepath.Join(tool.workingDir, "child.pid") |
| 42 | + data, err := os.ReadFile(childPIDPath) |
| 43 | + if err != nil { |
| 44 | + t.Fatalf("failed to read child pid file: %v", err) |
| 45 | + } |
| 46 | + |
| 47 | + childPID, err := strconv.Atoi(strings.TrimSpace(string(data))) |
| 48 | + if err != nil { |
| 49 | + t.Fatalf("failed to parse child pid: %v", err) |
| 50 | + } |
| 51 | + |
| 52 | + deadline := time.Now().Add(2 * time.Second) |
| 53 | + for time.Now().Before(deadline) { |
| 54 | + if !processExists(childPID) { |
| 55 | + return |
| 56 | + } |
| 57 | + time.Sleep(50 * time.Millisecond) |
| 58 | + } |
| 59 | + |
| 60 | + t.Fatalf("child process %d is still running after timeout", childPID) |
| 61 | +} |
0 commit comments