Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: Chrome process and temp profile cleanup on shutdown (#278)

luigiagent8081834f467d
diff --git a/cmd/pinchtab/cmd_daemon.go b/cmd/pinchtab/cmd_daemon.go
index 0ea8fe55..dd1a81c2 100644
--- a/cmd/pinchtab/cmd_daemon.go
+++ b/cmd/pinchtab/cmd_daemon.go
@@ -643,6 +643,8 @@ func renderLaunchdPlist(execPath, configPath string) string {
<true/>
<key>KeepAlive</key>
<true/>
+ <key>ExitTimeOut</key>
+ <integer>10</integer>
<key>EnvironmentVariables</key>
<dict>
<key>PINCHTAB_CONFIG</key>
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
index 128ef8b5..75e49e5d 100644
--- a/internal/bridge/bridge.go
+++ b/internal/bridge/bridge.go
@@ -44,6 +44,10 @@ type Bridge struct {
// Lazy initialization
initMu sync.Mutex
initialized bool
+
+ // Temp profile cleanup: directories created as fallback when profile lock fails.
+ // These are removed on Cleanup() to prevent Chrome process/disk leaks.
+ tempProfileDir string
}
func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridge {
@@ -129,6 +133,7 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
slog.Warn("profile in use; using unique temporary profile for headless instance",
"requested", cfg.ProfileDir, "using", uniqueDir, "reason", err.Error())
cfg.ProfileDir = uniqueDir
+ b.tempProfileDir = uniqueDir
// Re-acquire lock for the new temp dir (should always succeed)
_ = AcquireProfileLock(cfg.ProfileDir)
} else {
@@ -172,6 +177,47 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
return nil
}
+// Cleanup releases browser resources and removes temporary profile directories.
+// Must be called on shutdown to prevent Chrome process and disk leaks.
+func (b *Bridge) Cleanup() {
+ // Cancel chromedp contexts (kills main Chrome process)
+ if b.BrowserCancel != nil {
+ b.BrowserCancel()
+ slog.Debug("chrome browser context cancelled")
+ }
+ if b.AllocCancel != nil {
+ b.AllocCancel()
+ slog.Debug("chrome allocator context cancelled")
+ }
+
+ // Chrome spawns helpers (GPU, renderer) in their own process groups.
+ // Context cancellation only kills the main process. Kill survivors
+ // by scanning for processes using our profile directory.
+ profileDir := ""
+ if b.tempProfileDir != "" {
+ profileDir = b.tempProfileDir
+ } else if b.Config != nil {
+ profileDir = b.Config.ProfileDir
+ }
+ if profileDir != "" {
+ // Brief wait for context cancel to propagate
+ time.Sleep(200 * time.Millisecond)
+ killed := killChromeByProfileDir(profileDir)
+ if killed > 0 {
+ slog.Info("cleanup: killed surviving chrome processes", "count", killed, "profileDir", profileDir)
+ }
+ }
+
+ if b.tempProfileDir != "" {
+ if err := os.RemoveAll(b.tempProfileDir); err != nil {
+ slog.Warn("failed to remove temp profile dir", "path", b.tempProfileDir, "err", err)
+ } else {
+ slog.Info("removed temp profile dir", "path", b.tempProfileDir)
+ }
+ b.tempProfileDir = ""
+ }
+}
+
func (b *Bridge) SetBrowserContexts(allocCtx context.Context, allocCancel context.CancelFunc, browserCtx context.Context, browserCancel context.CancelFunc) {
b.initMu.Lock()
defer b.initMu.Unlock()
diff --git a/internal/bridge/bridge_cleanup_test.go b/internal/bridge/bridge_cleanup_test.go
new file mode 100644
index 00000000..1e606048
--- /dev/null
+++ b/internal/bridge/bridge_cleanup_test.go
@@ -0,0 +1,38 @@
+package bridge
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestCleanup_RemovesTempProfileDir(t *testing.T) {
+ tmpDir := t.TempDir()
+ profileDir := filepath.Join(tmpDir, "pinchtab-profile-test")
+ if err := os.MkdirAll(profileDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ ctx := context.TODO()
+ b := New(ctx, ctx, &config.RuntimeConfig{})
+ b.tempProfileDir = profileDir
+
+ b.Cleanup()
+
+ if _, err := os.Stat(profileDir); !os.IsNotExist(err) {
+ t.Errorf("expected temp profile dir to be removed, but it still exists")
+ }
+ if b.tempProfileDir != "" {
+ t.Errorf("expected tempProfileDir to be cleared, got %q", b.tempProfileDir)
+ }
+}
+
+func TestCleanup_NoTempDir(t *testing.T) {
+ ctx := context.TODO()
+ b := New(ctx, ctx, &config.RuntimeConfig{})
+ // Should not panic with no temp dir
+ b.Cleanup()
+}
diff --git a/internal/bridge/cleanup.go b/internal/bridge/cleanup.go
new file mode 100644
index 00000000..df1fe838
--- /dev/null
+++ b/internal/bridge/cleanup.go
@@ -0,0 +1,196 @@
+//go:build !windows
+
+package bridge
+
+import (
+ "bytes"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+)
+
+// CleanupOrphanedChromeProcesses kills Chrome processes left behind by
+// previous PinchTab runs and removes temporary profile directories.
+// Call on startup before launching Chrome.
+func CleanupOrphanedChromeProcesses(profileDir string) {
+ // 1. Kill Chrome processes using the configured profile dir
+ // (from a previous crashed run that didn't shut down cleanly)
+ if profileDir != "" {
+ killed := killChromeByProfileDir(profileDir)
+ if killed > 0 {
+ slog.Info("cleanup: killed orphaned chrome processes using profile", "path", profileDir, "count", killed)
+ }
+ }
+
+ // 2. Find and clean up temp profile dirs from previous headless fallbacks
+ tmpDir := os.TempDir()
+ entries, err := os.ReadDir(tmpDir)
+ if err != nil {
+ slog.Debug("cleanup: cannot read temp dir", "path", tmpDir, "err", err)
+ return
+ }
+
+ for _, e := range entries {
+ if !e.IsDir() || !strings.HasPrefix(e.Name(), "pinchtab-profile-") {
+ continue
+ }
+ dir := filepath.Join(tmpDir, e.Name())
+ killChromeByProfileDir(dir)
+ if err := os.RemoveAll(dir); err != nil {
+ slog.Warn("cleanup: failed to remove temp profile dir", "path", dir, "err", err)
+ } else {
+ slog.Info("cleanup: removed orphaned temp profile dir", "path", dir)
+ }
+ }
+}
+
+// KillAllPinchtabChrome kills all Chrome processes spawned by PinchTab.
+// Matches both persistent profiles (--user-data-dir=.../profiles/...) and
+// temp profiles (--user-data-dir=.../pinchtab-profile-*).
+// Called on server shutdown — one ps scan, immediate SIGKILL.
+func KillAllPinchtabChrome() int {
+ // Find Chrome processes using either temp or persistent pinchtab profiles
+ var pids []int
+ tempPids := findPIDsByNeedle("pinchtab-profile")
+ persistPids := findPIDsByNeedle(".pinchtab/profiles")
+
+ seen := make(map[int]bool)
+ for _, pid := range append(tempPids, persistPids...) {
+ if !seen[pid] {
+ seen[pid] = true
+ pids = append(pids, pid)
+ }
+ }
+
+ if len(pids) == 0 {
+ return 0
+ }
+
+ for _, pid := range pids {
+ _ = syscall.Kill(pid, syscall.SIGKILL)
+ }
+ slog.Info("shutdown: killed pinchtab chrome processes", "count", len(pids))
+ return len(pids)
+}
+
+// findChromePIDsByProfileDir returns PIDs of Chrome processes using the given profile directory.
+func findChromePIDsByProfileDir(profileDir string) []int {
+ needle := fmt.Sprintf("--user-data-dir=%s", profileDir)
+ if pids := findPIDsByNeedle(needle); len(pids) > 0 {
+ return pids
+ }
+ return nil
+}
+
+// findPIDsByNeedle searches process command lines for a substring.
+// Tries /proc first (Linux, always available even in minimal containers),
+// then falls back to ps (macOS, BSDs).
+func findPIDsByNeedle(needle string) []int {
+ if pids := findPIDsViaProc(needle); pids != nil {
+ return pids
+ }
+ return findPIDsViaPS(needle)
+}
+
+// findPIDsViaProc reads /proc/*/cmdline to find matching processes.
+// Returns nil (not empty slice) if /proc is not available.
+func findPIDsViaProc(needle string) []int {
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ return nil // /proc not available (macOS, some BSDs)
+ }
+
+ var pids []int
+ self := os.Getpid()
+
+ for _, e := range entries {
+ if !e.IsDir() {
+ continue
+ }
+ pid, err := strconv.Atoi(e.Name())
+ if err != nil || pid <= 0 || pid == self {
+ continue
+ }
+ cmdline, err := os.ReadFile(filepath.Join("/proc", e.Name(), "cmdline"))
+ if err != nil {
+ continue
+ }
+ // /proc/*/cmdline uses null bytes as separators
+ args := string(bytes.ReplaceAll(cmdline, []byte{0}, []byte{' '}))
+ if strings.Contains(args, needle) {
+ pids = append(pids, pid)
+ }
+ }
+ return pids
+}
+
+// findPIDsViaPS uses `ps -axo pid=,args=` to find matching processes.
+func findPIDsViaPS(needle string) []int {
+ cmd := exec.Command("ps", "-axo", "pid=,args=")
+ out, err := cmd.Output()
+ if err != nil {
+ return nil
+ }
+
+ lines := bytes.Split(out, []byte{'\n'})
+ var pids []int
+
+ for _, rawLine := range lines {
+ line := strings.TrimSpace(string(rawLine))
+ if line == "" || !strings.Contains(line, needle) {
+ continue
+ }
+
+ fields := strings.Fields(line)
+ if len(fields) < 2 {
+ continue
+ }
+
+ pid, err := strconv.Atoi(fields[0])
+ if err != nil || pid <= 0 {
+ continue
+ }
+ pids = append(pids, pid)
+ }
+ return pids
+}
+
+// killChromeByProfileDir finds Chrome processes using the given profile
+// directory, sends SIGTERM, waits briefly, then SIGKILL any survivors.
+// Returns the number of processes killed.
+func killChromeByProfileDir(profileDir string) int {
+ pids := findChromePIDsByProfileDir(profileDir)
+ if len(pids) == 0 {
+ return 0
+ }
+
+ // SIGTERM first
+ for _, pid := range pids {
+ _ = syscall.Kill(pid, syscall.SIGTERM)
+ }
+
+ // Give Chrome 500ms to shut down gracefully
+ time.Sleep(500 * time.Millisecond)
+
+ // SIGKILL any survivors
+ killed := 0
+ for _, pid := range pids {
+ if err := syscall.Kill(pid, 0); err != nil {
+ // Process already dead
+ killed++
+ continue
+ }
+ if err := syscall.Kill(pid, syscall.SIGKILL); err == nil {
+ slog.Info("cleanup: force-killed chrome process", "pid", pid)
+ }
+ killed++
+ }
+
+ return killed
+}
diff --git a/internal/bridge/cleanup_windows.go b/internal/bridge/cleanup_windows.go
new file mode 100644
index 00000000..a2ed1f34
--- /dev/null
+++ b/internal/bridge/cleanup_windows.go
@@ -0,0 +1,96 @@
+//go:build windows
+
+package bridge
+
+import (
+ "bytes"
+ "fmt"
+ "log/slog"
+ "os/exec"
+ "strconv"
+ "strings"
+)
+
+// findPIDsByPowerShell finds Chrome PIDs whose command line contains the needle.
+func findPIDsByPowerShell(needle string) []int {
+ escaped := strings.ReplaceAll(needle, `\`, `\\`)
+ cmd := exec.Command("powershell", "-NoProfile", "-Command",
+ fmt.Sprintf(`Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | `+
+ `Where-Object { $_.CommandLine -like '*%s*' } | `+
+ `Select-Object -ExpandProperty ProcessId`, escaped))
+
+ out, err := cmd.Output()
+ if err != nil {
+ return nil
+ }
+
+ var pids []int
+ for _, line := range bytes.Split(out, []byte{'\n'}) {
+ pidStr := strings.TrimSpace(string(line))
+ if pidStr == "" {
+ continue
+ }
+ pid, err := strconv.Atoi(pidStr)
+ if err != nil || pid <= 0 {
+ continue
+ }
+ pids = append(pids, pid)
+ }
+ return pids
+}
+
+// taskkillPIDs force-kills processes and their children via taskkill /F /T.
+func taskkillPIDs(pids []int) int {
+ killed := 0
+ for _, pid := range pids {
+ cmd := exec.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(pid))
+ if cmd.Run() == nil {
+ killed++
+ slog.Info("cleanup: killed chrome process", "pid", pid)
+ }
+ }
+ return killed
+}
+
+// killChromeByProfileDir finds and kills Chrome processes using the given profile directory.
+func killChromeByProfileDir(profileDir string) int {
+ pids := findPIDsByPowerShell(fmt.Sprintf("--user-data-dir=%s", profileDir))
+ if len(pids) == 0 {
+ return 0
+ }
+ return taskkillPIDs(pids)
+}
+
+// KillAllPinchtabChrome kills all Chrome processes spawned by PinchTab.
+func KillAllPinchtabChrome() int {
+ var pids []int
+ seen := make(map[int]bool)
+
+ for _, needle := range []string{"pinchtab-profile", ".pinchtab\\profiles"} {
+ for _, pid := range findPIDsByPowerShell(needle) {
+ if !seen[pid] {
+ seen[pid] = true
+ pids = append(pids, pid)
+ }
+ }
+ }
+
+ if len(pids) == 0 {
+ return 0
+ }
+
+ killed := taskkillPIDs(pids)
+ slog.Info("shutdown: killed pinchtab chrome processes", "count", killed)
+ return killed
+}
+
+// CleanupOrphanedChromeProcesses kills orphaned Chrome processes on Windows.
+func CleanupOrphanedChromeProcesses(profileDir string) {
+ if profileDir == "" {
+ return
+ }
+ killed := killChromeByProfileDir(profileDir)
+ if killed > 0 {
+ slog.Info("cleanup: killed orphaned chrome processes", "count", killed, "profileDir", profileDir)
+ }
+}
diff --git a/internal/bridge/init.go b/internal/bridge/init.go
index 45b26df6..cbb5a6e8 100644
--- a/internal/bridge/init.go
+++ b/internal/bridge/init.go
@@ -160,6 +160,13 @@ func setupAllocator(cfg *config.RuntimeConfig) (context.Context, context.CancelF
}
opts = append(opts, chromedp.CombinedOutput(newPrefixedLogWriter(os.Stdout, "chrome")))
+ // Replace chromedp's default allocateCmdOptions to set Pdeathsig on Linux.
+ // Do NOT set Setpgid — Chrome should inherit the parent's process group
+ // so the orchestrator can kill the entire bridge group at once.
+ opts = append(opts, chromedp.ModifyCmdFunc(func(cmd *exec.Cmd) {
+ configureChromeProcess(cmd)
+ }))
+
ctx, cancel := context.WithCancel(context.Background())
return ctx, cancel, opts, debugPort
}
diff --git a/internal/bridge/proc_linux.go b/internal/bridge/proc_linux.go
new file mode 100644
index 00000000..16bb8e61
--- /dev/null
+++ b/internal/bridge/proc_linux.go
@@ -0,0 +1,18 @@
+//go:build linux
+
+package bridge
+
+import (
+ "os/exec"
+ "syscall"
+)
+
+// configureChromeProcess sets parent death signal on Linux so Chrome dies
+// when the Go process exits unexpectedly.
+// Does NOT set Setpgid — Chrome stays in the parent's process group so the
+// orchestrator can kill the entire bridge group at once.
+func configureChromeProcess(cmd *exec.Cmd) {
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Pdeathsig: syscall.SIGKILL,
+ }
+}
diff --git a/internal/bridge/proc_other.go b/internal/bridge/proc_other.go
new file mode 100644
index 00000000..9b70a477
--- /dev/null
+++ b/internal/bridge/proc_other.go
@@ -0,0 +1,10 @@
+//go:build darwin
+
+package bridge
+
+import "os/exec"
+
+// configureChromeProcess is a no-op on macOS.
+// Chrome inherits the parent's process group. The orchestrator kills the
+// entire bridge group, and in standalone bridge mode, Cleanup() handles it.
+func configureChromeProcess(_ *exec.Cmd) {}
diff --git a/internal/bridge/proc_windows.go b/internal/bridge/proc_windows.go
new file mode 100644
index 00000000..188ef67c
--- /dev/null
+++ b/internal/bridge/proc_windows.go
@@ -0,0 +1,8 @@
+//go:build windows
+
+package bridge
+
+import "os/exec"
+
+// configureChromeProcess is a no-op on Windows.
+func configureChromeProcess(_ *exec.Cmd) {}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index d6c74809..0b915ce7 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -553,6 +553,12 @@ func (o *Orchestrator) markStopped(id string) {
slog.Info("instance stopped and removed", "id", id, "profile", profileName)
+ // Kill any orphaned Chrome processes using this profile's directory.
+ // Chrome spawns helpers (GPU, renderer) in their own process groups,
+ // so killing the bridge process group doesn't reach them.
+ profilePath := filepath.Join(o.baseDir, profileName)
+ bridge.CleanupOrphanedChromeProcesses(profilePath)
+
if strings.HasPrefix(profileName, "instance-") {
profilePath := filepath.Join(o.baseDir, profileName)
if err := os.RemoveAll(profilePath); err != nil {
diff --git a/internal/server/bridge.go b/internal/server/bridge.go
index f493118c..5ef30d27 100644
--- a/internal/server/bridge.go
+++ b/internal/server/bridge.go
@@ -27,6 +27,9 @@ func RunBridgeServer(cfg *config.RuntimeConfig) {
ProfileDir: cfg.ProfileDir,
})
+ // Clean up orphaned Chrome processes from previous crashed runs
+ bridge.CleanupOrphanedChromeProcesses(cfg.ProfileDir)
+
bridgeInstance := bridge.New(context.Background(), nil, cfg)
bridgeInstance.StealthScript = assets.StealthScript
@@ -39,14 +42,7 @@ func RunBridgeServer(cfg *config.RuntimeConfig) {
shutdownOnce.Do(func() {
slog.Info("shutting down bridge...")
if bridgeInstance != nil {
- if bridgeInstance.BrowserCancel != nil {
- bridgeInstance.BrowserCancel()
- slog.Debug("chrome browser context cancelled")
- }
- if bridgeInstance.AllocCancel != nil {
- bridgeInstance.AllocCancel()
- slog.Debug("chrome allocator context cancelled")
- }
+ bridgeInstance.Cleanup()
}
})
}
diff --git a/internal/server/server.go b/internal/server/server.go
index eab11024..3da4029c 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -11,6 +11,7 @@ import (
"syscall"
"time"
+ "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/dashboard"
@@ -29,6 +30,9 @@ import (
)
func RunDashboard(cfg *config.RuntimeConfig, version string) {
+ // Clean up orphaned Chrome processes from previous crashed runs
+ bridge.CleanupOrphanedChromeProcesses(cfg.ProfileDir)
+
dashPort := cfg.Port
if dashPort == "" {
dashPort = "9870"
@@ -180,6 +184,10 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
doShutdown := func() {
shutdownOnce.Do(func() {
slog.Info("shutting down dashboard...")
+ // Kill all Chrome processes under our profiles dir immediately.
+ // This runs before strategy.Stop() to ensure cleanup happens
+ // even if launchd SIGKILL arrives during graceful shutdown.
+ bridge.KillAllPinchtabChrome()
if err := activeStrategy.Stop(); err != nil {
slog.Warn("strategy stop failed", "err", err)
}
@@ -205,6 +213,9 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
sig := make(chan os.Signal, 2)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
+ // Kill Chrome immediately on signal — synchronous, before anything else.
+ // launchd may SIGKILL us shortly after SIGTERM, so this must happen first.
+ bridge.KillAllPinchtabChrome()
go doShutdown()
<-sig
slog.Warn("force shutdown requested")
diff --git a/scripts/pre-commit b/scripts/pre-commit
index 7abc5a79..a6e16385 100755
--- a/scripts/pre-commit
+++ b/scripts/pre-commit
@@ -11,7 +11,7 @@ echo "🔍 Running pre-commit checks..."
staged_go=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$' || true)
if [ -n "$staged_go" ]; then
echo "📦 Checking Go files..."
-
+
# gofmt check
unformatted=$(gofmt -l $staged_go 2>/dev/null || true)
if [ -n "$unformatted" ]; then
@@ -22,16 +22,26 @@ if [ -n "$staged_go" ]; then
fi
# golangci-lint (if available)
+ GOLANGCI_LINT=""
if command -v golangci-lint &>/dev/null; then
+ GOLANGCI_LINT="golangci-lint"
+ elif [ -x "${GOPATH:-$HOME/go}/bin/golangci-lint" ]; then
+ GOLANGCI_LINT="${GOPATH:-$HOME/go}/bin/golangci-lint"
+ elif [ -x "$HOME/go/bin/golangci-lint" ]; then
+ GOLANGCI_LINT="$HOME/go/bin/golangci-lint"
+ fi
+
+ if [ -n "$GOLANGCI_LINT" ]; then
dirs=$(echo "$staged_go" | xargs -n1 dirname | sort -u | sed 's|$|/...|')
- if ! golangci-lint run --timeout=5m $dirs; then
+ if ! $GOLANGCI_LINT run --timeout=5m $dirs; then
echo "❌ golangci-lint: issues found"
exit 1
fi
else
echo "⚠️ golangci-lint not found, skipping Go lint"
+ echo " Install: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest"
fi
-
+
echo "✅ Go checks passed"
fi
@@ -41,9 +51,9 @@ fi
staged_web=$(git diff --cached --name-only --diff-filter=ACM | grep '^dashboard/.*\.\(ts\|tsx\|js\|jsx\|css\)$' || true)
if [ -n "$staged_web" ]; then
echo "🌐 Checking dashboard files..."
-
+
cd dashboard
-
+
# Check if bun is available
if ! command -v bun &>/dev/null; then
echo "⚠️ bun not found, skipping dashboard checks"
@@ -56,7 +66,7 @@ if [ -n "$staged_web" ]; then
cd ..
exit 1
fi
-
+
# ESLint check
echo " → ESLint..."
if ! bun run lint 2>/dev/null; then
@@ -64,7 +74,7 @@ if [ -n "$staged_web" ]; then
cd ..
exit 1
fi
-
+
# Prettier check (on staged files only)
echo " → Prettier..."
staged_rel=$(echo "$staged_web" | sed 's|^dashboard/||')
@@ -74,7 +84,7 @@ if [ -n "$staged_web" ]; then
cd ..
exit 1
fi
-
+
cd ..
echo "✅ Dashboard checks passed"
fi