High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: improving locking of profile for start and restart
Luigi Agostidaa77a5c9f54
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.goindex 478240c6..711fc213 100644--- a/internal/bridge/bridge.go+++ b/internal/bridge/bridge.go@@ -4,6 +4,7 @@ import ("context""fmt""log/slog"+ "os""sync""time"@@ -116,7 +117,31 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {return nil // Already has browser context}+ slog.Debug("ensure chrome called", "headless", cfg.Headless, "profile", cfg.ProfileDir)+// Initialize Chrome if not already done+ if err := AcquireProfileLock(cfg.ProfileDir); err != nil {+ if cfg.Headless {+ // If we are in headless mode, we are more flexible.+ // Instead of failing, we can use a unique temporary profile dir.+ uniqueDir, tmpErr := os.MkdirTemp("", "pinchtab-profile-*")+ if tmpErr == nil {+ slog.Warn("profile in use; using unique temporary profile for headless instance",+ "requested", cfg.ProfileDir, "using", uniqueDir, "reason", err.Error())+ cfg.ProfileDir = uniqueDir+ // Re-acquire lock for the new temp dir (should always succeed)+ _ = AcquireProfileLock(cfg.ProfileDir)+ } else {+ slog.Error("cannot acquire profile lock and failed to create temp dir", "profile", cfg.ProfileDir, "err", err.Error(), "tmpErr", tmpErr.Error())+ return fmt.Errorf("profile lock: %w (temp dir failed: %v)", err, tmpErr)+ }+ } else {+ slog.Error("cannot acquire profile lock; another pinchtab may be active", "profile", cfg.ProfileDir, "err", err.Error())+ return fmt.Errorf("profile lock: %w", err)+ }+ }++ slog.Info("starting chrome with confirmed profile", "headless", cfg.Headless, "profile", cfg.ProfileDir)allocCtx, allocCancel, browserCtx, browserCancel, err := InitChrome(cfg)if err != nil {return fmt.Errorf("failed to initialize chrome: %w", err)diff --git a/internal/bridge/init.go b/internal/bridge/init.goindex d9e875c5..426f2d38 100644--- a/internal/bridge/init.go+++ b/internal/bridge/init.go@@ -244,10 +244,16 @@ func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfiselect {case res := <-runCh:err = res.err+ if err != nil {+ slog.Debug("chrome initial action failed", "error", err.Error())+ } else {+ slog.Debug("chrome initial action succeeded")+ }case <-time.After(chromeStartupTimeout):// Chrome started (ExecAllocator launched the process) but never announced// its DevTools URL via stderr. Wrap as DeadlineExceeded so isStartupTimeout// recognises it, then fall through to the cleanup + fallback logic below.+ slog.Debug("chrome startup timed out", "timeout", chromeStartupTimeout)err = fmt.Errorf("chrome startup timeout after %v: %w", chromeStartupTimeout, context.DeadlineExceeded)}@@ -257,8 +263,10 @@ func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfiallocCancel()errMsg := err.Error()+ slog.Debug("evaluating chrome startup error", "error", errMsg)if !retriedProfileLock && isChromeProfileLockError(errMsg) {+ slog.Debug("detected chrome profile lock error", "profile", cfg.ProfileDir)recovered, recoverErr := clearStaleChromeProfileLock(cfg.ProfileDir, errMsg)if recoverErr != nil {slog.Warn("failed to recover chrome profile lock", "profile", cfg.ProfileDir, "err", recoverErr)diff --git a/internal/bridge/profile_lock.go b/internal/bridge/profile_lock.goindex ecc30dbb..ba962d66 100644--- a/internal/bridge/profile_lock.go+++ b/internal/bridge/profile_lock.go@@ -25,6 +25,8 @@ import (var chromeProfileProcessLister = findChromeProfileProcessesvar chromePIDIsRunning = isChromePIDRunning+var killChromeProfileProcesses = killProcesses+var isProfileOwnedByRunningPinchtabMock = isProfileOwnedByRunningPinchtabvar chromeSingletonFiles = []string{"SingletonLock",@@ -58,8 +60,13 @@ func clearStaleChromeProfileLock(profileDir, errMsg string) (bool, error) {if err != nil {slog.Warn("failed to probe chrome lock pid; falling back to process listing", "profile", profileDir, "pid", pid, "err", err)} else if running {- slog.Warn("chrome profile lock appears active; leaving singleton files in place", "profile", profileDir, "pid", pid)- return false, nil+ // If we find the PID from the error message is still running,+ // check if it's actually managed by another active PinchTab.+ if owned, ptPid := isProfileOwnedByRunningPinchtabMock(profileDir); owned {+ slog.Warn("chrome profile lock appears active and owned by another pinchtab; leaving singleton files in place", "profile", profileDir, "pid", pid, "pinchtab_pid", ptPid)+ return false, nil+ }+ slog.Warn("chrome profile lock appears active but pinchtab owner is dead; proceeding with stale cleanup", "profile", profileDir, "pid", pid)}}@@ -72,12 +79,21 @@ func clearStaleChromeProfileLock(profileDir, errMsg string) (bool, error) {}}if len(processes) > 0 {- pids := make([]string, 0, len(processes))- for _, proc := range processes {- pids = append(pids, proc.PID)+ if owned, ptPid := isProfileOwnedByRunningPinchtabMock(profileDir); owned {+ pids := make([]string, 0, len(processes))+ for _, proc := range processes {+ pids = append(pids, proc.PID)+ }+ slog.Warn("chrome profile lock appears active and owned by another pinchtab; leaving singleton files in place", "profile", profileDir, "pids", strings.Join(pids, ","), "pinchtab_pid", ptPid)+ return false, nil+ }++ // If no other PinchTab owns this profile, we can safely kill the stale Chrome processes.+ slog.Warn("chrome profile lock appears active but no pinchtab owner found; killing stale processes", "profile", profileDir)+ if err := killChromeProfileProcesses(processes); err != nil {+ slog.Error("failed to kill stale chrome processes", "profile", profileDir, "err", err)+ return false, nil}- slog.Warn("chrome profile lock appears active; leaving singleton files in place", "profile", profileDir, "pids", strings.Join(pids, ","))- return false, nil}removed := false@@ -98,6 +114,59 @@ func clearStaleChromeProfileLock(profileDir, errMsg string) (bool, error) {return removed, nil}+func isProfileOwnedByRunningPinchtab(profileDir string) (bool, int) {+ pidFile := filepath.Join(profileDir, "pinchtab.pid")+ data, err := os.ReadFile(pidFile)+ if err != nil {+ if !os.IsNotExist(err) {+ slog.Debug("failed to read pinchtab pid file", "path", pidFile, "err", err)+ }+ return false, 0+ }++ var pid int+ if _, err := fmt.Sscanf(string(data), "%d", &pid); err != nil {+ slog.Debug("failed to parse pinchtab pid file", "path", pidFile, "err", err)+ return false, 0+ }++ if pid == os.Getpid() {+ return false, pid // It's us+ }++ running, err := chromePIDIsRunning(pid)+ if err == nil && running {+ // Even if the PID is running, check if it's actually a pinchtab process+ // to handle PID reuse.+ if isPinchTabProcess(pid) {+ slog.Debug("profile is owned by another active pinchtab", "profile", profileDir, "pid", pid)+ return true, pid+ }+ slog.Debug("PID in lockfile is running but not a pinchtab process (PID reuse)", "profile", profileDir, "pid", pid)+ } else {+ slog.Debug("PID in lockfile is not running", "profile", profileDir, "pid", pid, "err", err)+ }++ return false, 0+}++func AcquireProfileLock(profileDir string) error {+ if profileDir == "" {+ return nil+ }+ if err := os.MkdirAll(profileDir, 0755); err != nil {+ return fmt.Errorf("mkdir profile dir: %w", err)+ }++ if owned, pid := isProfileOwnedByRunningPinchtab(profileDir); owned {+ return fmt.Errorf("profile %s is already in use by pinchtab process %d", profileDir, pid)+ }++ pidFile := filepath.Join(profileDir, "pinchtab.pid")+ slog.Debug("acquiring profile lock", "profile", profileDir, "pid", os.Getpid())+ return os.WriteFile(pidFile, []byte(fmt.Sprintf("%d", os.Getpid())), 0644)+}+func extractChromeProfileLockPID(msg string) (int, bool) {if msg == "" {return 0, falsediff --git a/internal/bridge/profile_lock_pid_other.go b/internal/bridge/profile_lock_pid_other.goindex 96922891..d0b465f3 100644--- a/internal/bridge/profile_lock_pid_other.go+++ b/internal/bridge/profile_lock_pid_other.go@@ -4,7 +4,11 @@ package bridgeimport ("errors"+ "fmt"+ "os/exec"+ "strings""syscall"+ "time")func isChromePIDRunning(pid int) (bool, error) {@@ -23,3 +27,37 @@ func isChromePIDRunning(pid int) (bool, error) {}return false, err}++func killProcesses(processes []chromeProfileProcess) error {+ for _, proc := range processes {+ var pid int+ if _, err := fmt.Sscanf(proc.PID, "%d", &pid); err != nil {+ continue+ }+ if pid <= 0 {+ continue+ }+ // Try SIGTERM first, then SIGKILL if it doesn't work?+ // Given we are in a "stale recovery" path, being aggressive is often better+ // to ensure the next startup succeeds.+ _ = syscall.Kill(pid, syscall.SIGKILL)+ }+ // Give a small amount of time for processes to actually exit+ time.Sleep(100 * time.Millisecond)+ return nil+}++func isPinchTabProcess(pid int) bool {+ if pid <= 0 {+ return false+ }+ // On Linux/macOS, we can check the process name or args.+ // A simple check is to see if the command contains "pinchtab".+ cmd := exec.Command("ps", "-p", fmt.Sprintf("%d", pid), "-o", "args=")+ out, err := cmd.Output()+ if err != nil {+ return false+ }+ line := strings.ToLower(string(out))+ return strings.Contains(line, "pinchtab")+}diff --git a/internal/bridge/profile_lock_pid_windows.go b/internal/bridge/profile_lock_pid_windows.goindex fe4ae15c..1c3c2174 100644--- a/internal/bridge/profile_lock_pid_windows.go+++ b/internal/bridge/profile_lock_pid_windows.go@@ -6,3 +6,13 @@ func isChromePIDRunning(pid int) (bool, error) {_ = pidreturn false, nil}++func killProcesses(processes []chromeProfileProcess) error {+ _ = processes+ return nil+}++func isPinchTabProcess(pid int) bool {+ _ = pid+ return true // Better to assume true on Windows for now to avoid accidental deletions+}diff --git a/internal/bridge/profile_lock_test.go b/internal/bridge/profile_lock_test.goindex a62df91a..e79100fa 100644--- a/internal/bridge/profile_lock_test.go+++ b/internal/bridge/profile_lock_test.go@@ -58,15 +58,20 @@ func TestClearStaleChromeProfileLockRemovesSingletonFiles(t *testing.T) {orig := chromeProfileProcessListerorigPID := chromePIDIsRunning+ origMock := isProfileOwnedByRunningPinchtabMockchromeProfileProcessLister = func(string) ([]chromeProfileProcess, error) {return nil, nil}chromePIDIsRunning = func(int) (bool, error) {return false, nil}+ isProfileOwnedByRunningPinchtabMock = func(string) (bool, int) {+ return false, 0+ }t.Cleanup(func() {chromeProfileProcessLister = origchromePIDIsRunning = origPID+ isProfileOwnedByRunningPinchtabMock = origMock})removed, err := clearStaleChromeProfileLock(profileDir, "")@@ -93,15 +98,20 @@ func TestClearStaleChromeProfileLockLeavesActiveProfileUntouched(t *testing.T) {orig := chromeProfileProcessListerorigPID := chromePIDIsRunning+ origMock := isProfileOwnedByRunningPinchtabMockchromeProfileProcessLister = func(string) ([]chromeProfileProcess, error) {return []chromeProfileProcess{{PID: "36", Command: "/usr/bin/chromium-browser --user-data-dir=" + profileDir}}, nil}chromePIDIsRunning = func(int) (bool, error) {return false, nil}+ isProfileOwnedByRunningPinchtabMock = func(string) (bool, int) {+ return true, 1234+ }t.Cleanup(func() {chromeProfileProcessLister = origchromePIDIsRunning = origPID+ isProfileOwnedByRunningPinchtabMock = origMock})removed, err := clearStaleChromeProfileLock(profileDir, "")@@ -125,6 +135,7 @@ func TestClearStaleChromeProfileLockFallsBackToPIDProbe(t *testing.T) {orig := chromeProfileProcessListerorigPID := chromePIDIsRunning+ origMock := isProfileOwnedByRunningPinchtabMockchromeProfileProcessLister = func(string) ([]chromeProfileProcess, error) {return nil, os.ErrPermission}@@ -134,9 +145,13 @@ func TestClearStaleChromeProfileLockFallsBackToPIDProbe(t *testing.T) {}return false, nil}+ isProfileOwnedByRunningPinchtabMock = func(string) (bool, int) {+ return false, 0+ }t.Cleanup(func() {chromeProfileProcessLister = origchromePIDIsRunning = origPID+ isProfileOwnedByRunningPinchtabMock = origMock})removed, err := clearStaleChromeProfileLock(profileDir, "another Chromium process (36)")diff --git a/internal/profiles/handlers.go b/internal/profiles/handlers.goindex 8ebdac26..7719bc06 100644--- a/internal/profiles/handlers.go+++ b/internal/profiles/handlers.go@@ -135,9 +135,9 @@ func (pm *ProfileManager) handleImport(w http.ResponseWriter, r *http.Request) {func (pm *ProfileManager) handleUpdateMeta(w http.ResponseWriter, r *http.Request) {var req struct {- Name string `json:"name"`- Description string `json:"description"`- UseWhen string `json:"useWhen"`+ Name string `json:"name"`+ Description *string `json:"description"`+ UseWhen *string `json:"useWhen"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {web.Error(w, 400, err)@@ -149,11 +149,11 @@ func (pm *ProfileManager) handleUpdateMeta(w http.ResponseWriter, r *http.Reques}updates := make(map[string]string)- if req.Description != "" {- updates["description"] = req.Description+ if req.Description != nil {+ updates["description"] = *req.Description}- if req.UseWhen != "" {- updates["useWhen"] = req.UseWhen+ if req.UseWhen != nil {+ updates["useWhen"] = *req.UseWhen}if err := pm.UpdateMeta(req.Name, updates); err != nil {@@ -250,9 +250,9 @@ func (pm *ProfileManager) handleUpdateByID(w http.ResponseWriter, r *http.Reques}var req struct {- Name string `json:"name"`- UseWhen string `json:"useWhen"`- Description string `json:"description"`+ Name *string `json:"name"`+ UseWhen *string `json:"useWhen"`+ Description *string `json:"description"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {web.Error(w, 400, fmt.Errorf("invalid JSON"))@@ -260,8 +260,8 @@ func (pm *ProfileManager) handleUpdateByID(w http.ResponseWriter, r *http.Reques}finalName := name- if req.Name != "" && req.Name != name {- if err := pm.Rename(name, req.Name); err != nil {+ if req.Name != nil && *req.Name != name {+ if err := pm.Rename(name, *req.Name); err != nil {if strings.Contains(err.Error(), "already exists") {web.Error(w, 409, err)} else if strings.Contains(err.Error(), "cannot contain") || strings.Contains(err.Error(), "cannot be empty") {@@ -271,15 +271,15 @@ func (pm *ProfileManager) handleUpdateByID(w http.ResponseWriter, r *http.Reques}return}- finalName = req.Name+ finalName = *req.Name}updates := make(map[string]string)- if req.Description != "" {- updates["description"] = req.Description+ if req.Description != nil {+ updates["description"] = *req.Description}- if req.UseWhen != "" {- updates["useWhen"] = req.UseWhen+ if req.UseWhen != nil {+ updates["useWhen"] = *req.UseWhen}if len(updates) > 0 {if err := pm.UpdateMeta(finalName, updates); err != nil {diff --git a/internal/profiles/profiles_test.go b/internal/profiles/profiles_test.goindex ddb6c6d7..fb7b1368 100644--- a/internal/profiles/profiles_test.go+++ b/internal/profiles/profiles_test.go@@ -364,6 +364,43 @@ func TestProfileUpdateMeta(t *testing.T) {}}+func TestProfileUpdateByIDCanClearMetadata(t *testing.T) {+ pm := NewProfileManager(t.TempDir())+ mux := http.NewServeMux()+ pm.RegisterHandlers(mux)++ if err := pm.CreateWithMeta("clearable", ProfileMeta{+ UseWhen: "Used for work",+ Description: "Has metadata",+ }); err != nil {+ t.Fatal(err)+ }++ body := `{"useWhen":"","description":""}`+ req := httptest.NewRequest("PATCH", "/profiles/"+profileID("clearable"), strings.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != 200 {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }++ profiles, err := pm.List()+ if err != nil {+ t.Fatal(err)+ }+ if len(profiles) != 1 {+ t.Fatalf("expected 1 profile, got %d", len(profiles))+ }+ if profiles[0].UseWhen != "" {+ t.Errorf("expected empty useWhen after clear, got %q", profiles[0].UseWhen)+ }+ if profiles[0].Description != "" {+ t.Errorf("expected empty description after clear, got %q", profiles[0].Description)+ }+}+func TestProfileCreateWithUseWhen(t *testing.T) {pm := NewProfileManager(t.TempDir())mux := http.NewServeMux()diff --git a/internal/server/bridge.go b/internal/server/bridge.goindex eed7fb61..d27f78e6 100644--- a/internal/server/bridge.go+++ b/internal/server/bridge.go@@ -44,6 +44,16 @@ func RunBridgeServer(cfg *config.RuntimeConfig) {doShutdown := func() {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")+ }+ }})}h.RegisterRoutes(mux, doShutdown)