High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: address PR review — race condition, dead code, state backup, remove unrelated commit
op113122f7e73edc5
diff --git a/internal/bridge/api.go b/internal/bridge/api.goindex 19c594c7..2d6c1f1a 100644--- a/internal/bridge/api.go+++ b/internal/bridge/api.go@@ -2,6 +2,7 @@ package bridgeimport ("context"+ "errors""net/http""time"@@ -12,6 +13,8 @@ import ()// BridgeAPI abstracts browser tab operations for handler testing.+var ErrBrowserDraining = errors.New("browser restart in progress; retry shortly")+type BridgeAPI interface {BrowserContext() context.ContextTabContext(tabID string) (ctx context.Context, resolvedID string, err error)diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.goindex b49968be..25e4e22e 100644--- a/internal/bridge/bridge.go+++ b/internal/bridge/bridge.go@@ -55,9 +55,11 @@ type Bridge struct {fingerprintOverlays map[string]boolworkerStealthTargets sync.Map- // Lazy initialization+ // Lazy initialization / restart coordinationinitMu sync.Mutexinitialized bool+ draining bool+ drainUntil time.Time// Temp profile cleanup: directories created as fallback when profile lock fails.// These are removed on Cleanup() to prevent Chrome process/disk leaks.@@ -102,6 +104,22 @@ func (b *Bridge) quietStealthObservers() bool {return b != nil && b.Config != nil && stealth.NormalizeLevel(b.Config.StealthLevel) == stealth.LevelFull}+func (b *Bridge) RestartStatus() (bool, time.Duration) {+ if b == nil {+ return false, 0+ }+ b.initMu.Lock()+ defer b.initMu.Unlock()+ if !b.draining {+ return false, 0+ }+ remaining := time.Until(b.drainUntil)+ if remaining < 0 {+ remaining = 0+ }+ return true, remaining+}+func (b *Bridge) injectStealth(ctx context.Context) {if b.StealthBundle == nil || b.StealthBundle.Script == "" {return@@ -205,6 +223,10 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {b.initMu.Lock()defer b.initMu.Unlock()+ if b.draining {+ return ErrBrowserDraining+ }+if b.initialized && b.BrowserCtx != nil {// Check if browser context is still aliveif b.BrowserCtx.Err() == nil {@@ -310,6 +332,16 @@ func (b *Bridge) RestartBrowser(cfg *config.RuntimeConfig) error {return fmt.Errorf("runtime config is required")}+ const drainWindow = 2 * time.Second++ b.initMu.Lock()+ b.draining = true+ b.drainUntil = time.Now().Add(drainWindow)+ b.initMu.Unlock()++ slog.Info("browser soft restart: draining requests before restart", "drain_window", drainWindow)+ time.Sleep(drainWindow)+b.initMu.Lock()if b.BrowserCancel != nil {@@ -354,11 +386,7 @@ func (b *Bridge) RestartBrowser(cfg *config.RuntimeConfig) error {b.TabManager = nilb.stealthLaunchMode = stealth.LaunchModeUninitialized- if b.LogStore == nil {- b.LogStore = NewConsoleLogStore(1000)- } else {- b.LogStore = NewConsoleLogStore(1000)- }+ b.LogStore = NewConsoleLogStore(1000)b.netMonitor = NewNetworkMonitor(DefaultNetworkBufferSize)if cfg.NetworkBufferSize > 0 {b.netMonitor = NewNetworkMonitor(cfg.NetworkBufferSize)@@ -375,8 +403,15 @@ func (b *Bridge) RestartBrowser(cfg *config.RuntimeConfig) error {b.Actions = nilb.InitActionRegistry()+ b.draining = false+ b.drainUntil = time.Time{}b.initMu.Unlock()- return b.EnsureChrome(cfg)++ if err := b.EnsureChrome(cfg); err != nil {+ return err+ }+ b.CleanupSavedStateBackup()+ return nil}func (b *Bridge) Cleanup() {diff --git a/internal/bridge/observe/snapshot.go b/internal/bridge/observe/snapshot.goindex e3996424..8458a2b0 100644--- a/internal/bridge/observe/snapshot.go+++ b/internal/bridge/observe/snapshot.go@@ -106,11 +106,7 @@ func FetchAXTree(ctx context.Context) ([]RawAXNode, error) {}func fetchAXTreeForFrame(ctx context.Context, frameID string) ([]RawAXNode, error) {- params := map[string]any{- // pierce:true makes the accessibility tree traverse Shadow DOM boundaries,- // exposing content inside shadow roots (issue #381).- "pierce": true,- }+ params := map[string]any{}if frameID != "" {params["frameId"] = frameID}diff --git a/internal/bridge/state.go b/internal/bridge/state.goindex 242389aa..74235207 100644--- a/internal/bridge/state.go+++ b/internal/bridge/state.go@@ -179,8 +179,26 @@ func (b *Bridge) ClearSavedState() {return}path := filepath.Join(b.Config.StateDir, "sessions.json")- if err := os.Remove(path); err != nil && !os.IsNotExist(err) {- slog.Warn("clear saved state", "path", path, "err", err)+ backupPath := path + ".bak"+ if err := os.Remove(backupPath); err != nil && !os.IsNotExist(err) {+ slog.Warn("clear saved state backup", "path", backupPath, "err", err)+ }+ if err := os.Rename(path, backupPath); err != nil {+ if !os.IsNotExist(err) {+ slog.Warn("backup saved state", "path", path, "backup", backupPath, "err", err)+ }+ return+ }+ slog.Info("backed up saved state", "path", path, "backup", backupPath)+}++func (b *Bridge) CleanupSavedStateBackup() {+ if b == nil || b.Config == nil || b.Config.StateDir == "" {+ return+ }+ backupPath := filepath.Join(b.Config.StateDir, "sessions.json.bak")+ if err := os.Remove(backupPath); err != nil && !os.IsNotExist(err) {+ slog.Warn("cleanup saved state backup", "path", backupPath, "err", err)}}diff --git a/internal/bridge/state_test.go b/internal/bridge/state_test.goindex 98570d20..2090ac1f 100644--- a/internal/bridge/state_test.go+++ b/internal/bridge/state_test.go@@ -238,3 +238,43 @@ func TestRetryRemove_Success(t *testing.T) {t.Error("expected file to be removed")}}++func TestClearSavedState_BackupsSessionsFile(t *testing.T) {+ tmp := t.TempDir()+ sessionsPath := filepath.Join(tmp, "sessions.json")+ if err := os.WriteFile(sessionsPath, []byte(`{"tabs":[]}`), 0644); err != nil {+ t.Fatalf("write sessions: %v", err)+ }++ b := newTestBridge()+ b.Config = &config.RuntimeConfig{StateDir: tmp}+ b.ClearSavedState()++ if _, err := os.Stat(sessionsPath); !os.IsNotExist(err) {+ t.Fatalf("expected sessions.json to be renamed away, got err=%v", err)+ }+ backupPath := sessionsPath + ".bak"+ data, err := os.ReadFile(backupPath)+ if err != nil {+ t.Fatalf("read backup: %v", err)+ }+ if string(data) != `{"tabs":[]}` {+ t.Fatalf("backup contents = %q", string(data))+ }+}++func TestCleanupSavedStateBackup_RemovesBackupFile(t *testing.T) {+ tmp := t.TempDir()+ backupPath := filepath.Join(tmp, "sessions.json.bak")+ if err := os.WriteFile(backupPath, []byte(`{"tabs":[]}`), 0644); err != nil {+ t.Fatalf("write backup: %v", err)+ }++ b := newTestBridge()+ b.Config = &config.RuntimeConfig{StateDir: tmp}+ b.CleanupSavedStateBackup()++ if _, err := os.Stat(backupPath); !os.IsNotExist(err) {+ t.Fatalf("expected backup to be removed, got err=%v", err)+ }+}diff --git a/internal/handlers/find.go b/internal/handlers/find.goindex 3bbaf159..343c8285 100644--- a/internal/handlers/find.go+++ b/internal/handlers/find.go@@ -55,6 +55,9 @@ type findResponse struct {// @Response 500 application/json Snapshot or matching errorfunc (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex e82f5d5f..9edd83e7 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -3,7 +3,9 @@ package handlersimport ("context"+ "errors""net/http"+ "strconv""time""github.com/pinchtab/pinchtab/internal/assets"@@ -11,6 +13,7 @@ import ("github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/dashboard""github.com/pinchtab/pinchtab/internal/engine"+ "github.com/pinchtab/pinchtab/internal/httpx""github.com/pinchtab/pinchtab/internal/idpi""github.com/pinchtab/pinchtab/internal/ids""github.com/pinchtab/semantic"@@ -88,11 +91,40 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,return h}+type restartStatusProvider interface {+ RestartStatus() (bool, time.Duration)+}+// ensureChrome ensures Chrome is initialized before handling requests that need itfunc (h *Handlers) ensureChrome() error {return h.Bridge.EnsureChrome(h.Config)}+func (h *Handlers) bridgeRestartStatus() (bool, time.Duration) {+ provider, ok := h.Bridge.(restartStatusProvider)+ if !ok {+ return false, 0+ }+ return provider.RestartStatus()+}++func (h *Handlers) writeBridgeUnavailable(w http.ResponseWriter, err error) bool {+ if !errors.Is(err, bridge.ErrBrowserDraining) {+ return false+ }+ draining, retryAfter := h.bridgeRestartStatus()+ if !draining {+ retryAfter = time.Second+ }+ seconds := int((retryAfter + time.Second - 1) / time.Second)+ if seconds < 1 {+ seconds = 1+ }+ w.Header().Set("Retry-After", strconv.Itoa(seconds))+ httpx.ErrorCode(w, http.StatusServiceUnavailable, "browser_draining", err.Error(), true, map[string]any{"retryAfterSeconds": seconds})+ return true+}+// useLite returns true when the engine router routes this operation to lite.func (h *Handlers) useLite(op engine.Capability, url string) bool {return h.Router != nil && h.Router.UseLite(op, url)diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.goindex 292f0b1c..e069e672 100644--- a/internal/handlers/health_tabs.go+++ b/internal/handlers/health_tabs.go@@ -32,9 +32,21 @@ func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {httpx.JSON(w, 503, map[string]any{"status": "error", "reason": "bridge not initialized"})return}+ if draining, retryAfter := h.bridgeRestartStatus(); draining {+ seconds := int((retryAfter + time.Second - 1) / time.Second)+ if seconds < 1 {+ seconds = 1+ }+ w.Header().Set("Retry-After", fmt.Sprintf("%d", seconds))+ httpx.JSON(w, http.StatusServiceUnavailable, map[string]any{"status": "draining", "retryAfterSeconds": seconds})+ return+ }// Ensure Chrome is initialized before checking healthif err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.JSON(w, 503, map[string]any{"status": "error", "reason": fmt.Sprintf("chrome initialization failed: %v", err)})return}@@ -64,6 +76,9 @@ func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {func (h *Handlers) HandleEnsureChrome(w http.ResponseWriter, r *http.Request) {// Ensure Chrome is initialized for this instanceif err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization failed: %w", err))return}@@ -128,6 +143,15 @@ func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {httpx.Error(w, 503, fmt.Errorf("bridge not initialized"))return}+ if draining, retryAfter := h.bridgeRestartStatus(); draining {+ seconds := int((retryAfter + time.Second - 1) / time.Second)+ if seconds < 1 {+ seconds = 1+ }+ w.Header().Set("Retry-After", fmt.Sprintf("%d", seconds))+ httpx.ErrorCode(w, http.StatusServiceUnavailable, "browser_draining", bridge.ErrBrowserDraining.Error(), true, map[string]any{"retryAfterSeconds": seconds})+ return+ }targets, err := h.Bridge.ListTargets()if err != nil {diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.goindex df654871..c21faea3 100644--- a/internal/handlers/health_tabs_test.go+++ b/internal/handlers/health_tabs_test.go@@ -352,6 +352,8 @@ type MockBridge struct {ensureChromeCalled boolensureChromeErr stringcurrentTabID string+ draining bool+ retryAfter time.Duration}func (m *MockBridge) ListTargets() ([]*target.Info, error) {@@ -429,6 +431,10 @@ func (m *MockBridge) RestartBrowser(cfg *config.RuntimeConfig) error {return nil}+func (m *MockBridge) RestartStatus() (bool, time.Duration) {+ return m.draining, m.retryAfter+}+func (m *MockBridge) StealthStatus() *stealth.Status {return &stealth.Status{Level: stealth.LevelLight,@@ -499,6 +505,38 @@ func TestHandleHealth_Disconnected_Returns503(t *testing.T) {}}+func TestHandleHealth_Draining_Returns503WithRetryAfter(t *testing.T) {+ mb := &MockBridge{draining: true, retryAfter: 1500 * time.Millisecond}+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/health", nil)+ w := httptest.NewRecorder()++ h.HandleHealth(w, req)++ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503, got %d", w.Code)+ }+ if got := w.Header().Get("Retry-After"); got != "2" {+ t.Fatalf("Retry-After = %q, want 2", got)+ }+}++func TestHandleTabs_Draining_Returns503WithRetryAfter(t *testing.T) {+ mb := &MockBridge{draining: true, retryAfter: time.Second}+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs", nil)+ w := httptest.NewRecorder()++ h.HandleTabs(w, req)++ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503, got %d", w.Code)+ }+ if got := w.Header().Get("Retry-After"); got != "1" {+ t.Fatalf("Retry-After = %q, want 1", got)+ }+}+func TestHandleHealth_Connected_Returns200(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("GET", "/health", nil)diff --git a/internal/handlers/network.go b/internal/handlers/network.goindex fe2583c7..a1778e57 100644--- a/internal/handlers/network.go+++ b/internal/handlers/network.go@@ -38,6 +38,9 @@ func parseBufferSize(r *http.Request) int {// @Response 404 application/json Tab not foundfunc (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}@@ -108,6 +111,9 @@ func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {// @Response 404 application/json Request not foundfunc (h *Handlers) HandleNetworkByID(w http.ResponseWriter, r *http.Request) {if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}@@ -220,6 +226,9 @@ func (h *Handlers) HandleNetworkStream(w http.ResponseWriter, r *http.Request) {_ = http.NewResponseController(w).SetWriteDeadline(time.Time{})if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}diff --git a/internal/handlers/network_export.go b/internal/handlers/network_export.goindex 315f4bdd..36c69273 100644--- a/internal/handlers/network_export.go+++ b/internal/handlers/network_export.go@@ -45,6 +45,9 @@ const maxExportBodyBytes = 10 << 20 // 10 MB// @Response 500 application/json Export errorfunc (h *Handlers) HandleNetworkExport(w http.ResponseWriter, r *http.Request) {if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}@@ -252,6 +255,9 @@ func (h *Handlers) writeExportFile(// @Response 423 application/json Tab is lockedfunc (h *Handlers) HandleNetworkExportStream(w http.ResponseWriter, r *http.Request) {if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}diff --git a/internal/handlers/pdf.go b/internal/handlers/pdf.goindex 61b9b0a5..d6c2b6cc 100644--- a/internal/handlers/pdf.go+++ b/internal/handlers/pdf.go@@ -59,6 +59,9 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {// Ensure Chrome is initializedif err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.goindex 1b9ab9c9..54957084 100644--- a/internal/handlers/screenshot.go+++ b/internal/handlers/screenshot.go@@ -23,6 +23,9 @@ import (func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {// Ensure Chrome is initializedif err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex 747fc65d..2c1734ff 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -83,6 +83,9 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {// Ensure Chrome is initializedif err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}diff --git a/internal/handlers/text.go b/internal/handlers/text.goindex 37221610..f0bc80f0 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -35,6 +35,9 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {// Ensure Chrome is initializedif err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))return}