Skip to content

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

refactor: extract TabManager from Bridge

Mario80b6993558cd
diff --git a/TODO.md b/TODO.md
index cb5caf94..2c7db331 100644
--- a/TODO.md
+++ b/TODO.md
@@ -35,7 +35,7 @@ P2 (K11 file path, blockImages on CreateTab) — all resolved.
- [ ] **Randomized window sizes** — Avoid automation fingerprint.
### Code Quality
-- [ ] **Extract TabManager from Bridge** — Bridge is a semi-god object. Split tabs + snapshots management into its own `TabManager` struct.
+- [x] **Extract TabManager from Bridge** — Tabs, snapshots, and ref cache in own struct with setup hook.
- [ ] **installStableBinary streaming** — Use `io.Copy` with file streams instead of reading entire binary into memory.
- [x] **Interfaces for ProfileManager/Orchestrator** — `ProfileService` and `OrchestratorService` interfaces with compile-time checks.
- [ ] **proxy_ws.go proper HTTP** — Replace raw `backend.Write` of HTTP headers with proper request construction.
diff --git a/bridge.go b/bridge.go
index a68b5cc7..a0b9f0c7 100644
--- a/bridge.go
+++ b/bridge.go
@@ -2,14 +2,9 @@ package main
import (
"context"
- "fmt"
"log/slog"
- "sync"
- "time"
- cdp "github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/page"
- "github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
)
@@ -26,12 +21,10 @@ type refCache struct {
type Bridge struct {
allocCtx context.Context
browserCtx context.Context
- tabs map[string]*TabEntry
- snapshots map[string]*refCache
+ *TabManager
stealthScript string
actions map[string]ActionFunc
locks *lockManager
- mu sync.RWMutex
}
func (b *Bridge) injectStealth(ctx context.Context) {
@@ -48,190 +41,15 @@ func (b *Bridge) injectStealth(ctx context.Context) {
}
}
-func (b *Bridge) TabContext(tabID string) (context.Context, string, error) {
- if tabID == "" {
- targets, err := b.ListTargets()
- if err != nil {
- return nil, "", fmt.Errorf("list targets: %w", err)
- }
- if len(targets) == 0 {
- return nil, "", fmt.Errorf("no tabs open")
- }
- tabID = string(targets[0].TargetID)
- }
-
- b.mu.RLock()
- if entry, ok := b.tabs[tabID]; ok && entry.ctx != nil {
- b.mu.RUnlock()
- return entry.ctx, tabID, nil
- }
- b.mu.RUnlock()
-
- b.mu.Lock()
- defer b.mu.Unlock()
-
- if entry, ok := b.tabs[tabID]; ok && entry.ctx != nil {
- return entry.ctx, tabID, nil
- }
-
- if b.browserCtx == nil {
- return nil, "", fmt.Errorf("no browser connection")
- }
-
- ctx, cancel := chromedp.NewContext(b.browserCtx,
- chromedp.WithTargetID(target.ID(tabID)),
- )
- if err := chromedp.Run(ctx); err != nil {
- cancel()
- return nil, "", fmt.Errorf("tab %s not found: %w", tabID, err)
- }
-
+// tabSetup is the hook called by TabManager on new tab contexts.
+func (b *Bridge) tabSetup(ctx context.Context) {
b.injectStealth(ctx)
if cfg.NoAnimations {
b.injectNoAnimations(ctx)
}
-
- b.tabs[tabID] = &TabEntry{ctx: ctx, cancel: cancel}
- return ctx, tabID, nil
-}
-
-func (b *Bridge) CleanStaleTabs(ctx context.Context, interval time.Duration) {
- ticker := time.NewTicker(interval)
- defer ticker.Stop()
-
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- }
-
- targets, err := b.ListTargets()
- if err != nil {
- continue
- }
-
- alive := make(map[string]bool, len(targets))
- for _, t := range targets {
- alive[string(t.TargetID)] = true
- }
-
- b.mu.Lock()
- for id, entry := range b.tabs {
- if !alive[id] {
- if entry.cancel != nil {
- entry.cancel()
- }
- delete(b.tabs, id)
- delete(b.snapshots, id)
- slog.Info("cleaned stale tab", "id", id)
- }
- }
- b.mu.Unlock()
- }
-}
-
-func (b *Bridge) GetRefCache(tabID string) *refCache {
- b.mu.RLock()
- defer b.mu.RUnlock()
- return b.snapshots[tabID]
-}
-
-func (b *Bridge) SetRefCache(tabID string, cache *refCache) {
- b.mu.Lock()
- defer b.mu.Unlock()
- b.snapshots[tabID] = cache
}
-func (b *Bridge) DeleteRefCache(tabID string) {
- b.mu.Lock()
- defer b.mu.Unlock()
- delete(b.snapshots, tabID)
-}
-
-func (b *Bridge) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
- if b.browserCtx == nil {
- return "", nil, nil, fmt.Errorf("no browser context available")
- }
- ctx, cancel := chromedp.NewContext(b.browserCtx)
-
- b.injectStealth(ctx)
-
- if cfg.NoAnimations {
- b.injectNoAnimations(ctx)
- }
-
- if cfg.BlockMedia {
- _ = setResourceBlocking(ctx, mediaBlockPatterns)
- } else if cfg.BlockImages {
- _ = setResourceBlocking(ctx, imageBlockPatterns)
- }
-
- navURL := "about:blank"
- if url != "" {
- navURL = url
- }
- if err := navigatePage(ctx, navURL); err != nil {
- cancel()
- return "", nil, nil, fmt.Errorf("new tab: %w", err)
- }
-
- newTargetID := string(chromedp.FromContext(ctx).Target.TargetID)
- b.mu.Lock()
- b.tabs[newTargetID] = &TabEntry{ctx: ctx, cancel: cancel}
- b.mu.Unlock()
-
- return newTargetID, ctx, cancel, nil
-}
-
-func (b *Bridge) CloseTab(tabID string) error {
- b.mu.Lock()
- entry, tracked := b.tabs[tabID]
- b.mu.Unlock()
-
- if tracked && entry.cancel != nil {
- entry.cancel()
- }
-
- closeCtx, closeCancel := context.WithTimeout(b.browserCtx, 5*time.Second)
- defer closeCancel()
-
- if err := target.CloseTarget(target.ID(tabID)).Do(cdp.WithExecutor(closeCtx, chromedp.FromContext(closeCtx).Browser)); err != nil {
-
- if !tracked {
- return nil
- }
- slog.Debug("close target CDP", "tabId", tabID, "err", err)
- }
-
- b.mu.Lock()
- delete(b.tabs, tabID)
- delete(b.snapshots, tabID)
- b.mu.Unlock()
-
- return nil
-}
-
-func (b *Bridge) ListTargets() ([]*target.Info, error) {
- if b.browserCtx == nil {
- return nil, fmt.Errorf("no browser connection")
- }
- var targets []*target.Info
- if err := chromedp.Run(b.browserCtx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- var err error
- targets, err = target.GetTargets().Do(ctx)
- return err
- }),
- ); err != nil {
- return nil, fmt.Errorf("get targets: %w", err)
- }
-
- pages := make([]*target.Info, 0)
- for _, t := range targets {
- if t.Type == targetTypePage {
- pages = append(pages, t)
- }
- }
- return pages, nil
+// InitTabManager creates and wires the TabManager into the Bridge.
+func (b *Bridge) InitTabManager() {
+ b.TabManager = NewTabManager(b.browserCtx, b.tabSetup)
}
diff --git a/bridge_test.go b/bridge_test.go
index d5194285..734840bb 100644
--- a/bridge_test.go
+++ b/bridge_test.go
@@ -6,10 +6,7 @@ import (
)
func TestRefCacheConcurrency(t *testing.T) {
- b := &Bridge{
- tabs: make(map[string]*TabEntry),
- snapshots: make(map[string]*refCache),
- }
+ b := newTestBridgeWithTabs()
// Simulate concurrent reads/writes to snapshot cache
var wg sync.WaitGroup
@@ -37,10 +34,7 @@ func TestRefCacheConcurrency(t *testing.T) {
}
func TestRefCacheLookup(t *testing.T) {
- b := &Bridge{
- tabs: make(map[string]*TabEntry),
- snapshots: make(map[string]*refCache),
- }
+ b := newTestBridgeWithTabs()
b.mu.RLock()
cache := b.snapshots["tab1"]
diff --git a/handler_actions_test.go b/handler_actions_test.go
index 560f13a5..f9aab80a 100644
--- a/handler_actions_test.go
+++ b/handler_actions_test.go
@@ -29,9 +29,7 @@ func TestHandleActions_EmptyArray(t *testing.T) {
}
func TestHandleActions_NoTabError(t *testing.T) {
- b := &Bridge{
- tabs: make(map[string]*TabEntry),
- }
+ b := newTestBridgeWithTabs()
body := `{
"actions": [
@@ -51,9 +49,7 @@ func TestHandleActions_NoTabError(t *testing.T) {
}
func TestHandleGetCookies_NoTab(t *testing.T) {
- b := &Bridge{
- tabs: make(map[string]*TabEntry),
- }
+ b := newTestBridgeWithTabs()
req := httptest.NewRequest("GET", "/cookies", nil)
w := httptest.NewRecorder()
@@ -104,9 +100,7 @@ func TestHandleSetCookies_EmptyCookies(t *testing.T) {
}
func TestHandleStealthStatus_NoTabs(t *testing.T) {
- b := &Bridge{
- tabs: make(map[string]*TabEntry),
- }
+ b := newTestBridgeWithTabs()
req := httptest.NewRequest("GET", "/stealth/status", nil)
w := httptest.NewRecorder()
@@ -137,9 +131,7 @@ func TestHandleStealthStatus_NoTabs(t *testing.T) {
}
func TestHandleFingerprintRotate_NoTab(t *testing.T) {
- b := &Bridge{
- tabs: make(map[string]*TabEntry),
- }
+ b := newTestBridgeWithTabs()
body := `{"os": "windows", "browser": "chrome"}`
req := httptest.NewRequest("POST", "/fingerprint/rotate", bytes.NewReader([]byte(body)))
diff --git a/handler_cookies_test.go b/handler_cookies_test.go
index 7098d509..f10dc2fd 100644
--- a/handler_cookies_test.go
+++ b/handler_cookies_test.go
@@ -21,7 +21,7 @@ func TestHandleSetCookies_InvalidJSON(t *testing.T) {
func TestHandleSetCookies_NoTab(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
body := `{"url":"https://example.com","cookies":[{"name":"a","value":"b"}],"tabId":"nonexistent"}`
req := httptest.NewRequest("POST", "/cookies", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
@@ -36,7 +36,7 @@ func TestHandleSetCookies_NoTab(t *testing.T) {
func TestHandleGetCookies_NameFilter(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
req := httptest.NewRequest("GET", "/cookies?name=session_id&tabId=nonexistent", nil)
w := httptest.NewRecorder()
diff --git a/handler_stealth_test.go b/handler_stealth_test.go
index 94d3b46a..36a7e82b 100644
--- a/handler_stealth_test.go
+++ b/handler_stealth_test.go
@@ -8,7 +8,7 @@ import (
func TestHandleStealthStatus_NoTab_ReturnsStatic(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
req := httptest.NewRequest("GET", "/stealth/status", nil)
w := httptest.NewRecorder()
@@ -118,7 +118,7 @@ func TestGetStealthRecommendations_Partial(t *testing.T) {
func TestSendStealthResponse_HighScore(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
features := map[string]bool{
"a": true, "b": true, "c": true, "d": true, "e": true,
}
@@ -136,7 +136,7 @@ func TestSendStealthResponse_HighScore(t *testing.T) {
func TestSendStealthResponse_LowScore(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
features := map[string]bool{
"a": true, "b": false, "c": false, "d": false, "e": false,
"f": false, "g": false, "h": false, "i": false, "j": false,
@@ -152,7 +152,7 @@ func TestSendStealthResponse_LowScore(t *testing.T) {
func TestSendStealthResponse_MediumScore(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
features := map[string]bool{
"a": true, "b": true, "c": true, "d": true, "e": true,
diff --git a/handler_test.go b/handler_test.go
index 70a3a96a..4a822a00 100644
--- a/handler_test.go
+++ b/handler_test.go
@@ -8,12 +8,17 @@ import (
// newTestBridge creates a Bridge with initialized maps (no Chrome).
func newTestBridge() *Bridge {
- return &Bridge{
+ b := &Bridge{}
+ b.TabManager = &TabManager{
tabs: make(map[string]*TabEntry),
snapshots: make(map[string]*refCache),
}
+ return b
}
+// newTestBridgeWithTabs is an alias used across test files.
+var newTestBridgeWithTabs = newTestBridge
+
func TestHandleNavigate_MissingURL(t *testing.T) {
b := newTestBridge()
body := `{"url": ""}`
diff --git a/handlers_extra_test.go b/handlers_extra_test.go
index 378b9c1f..9366a654 100644
--- a/handlers_extra_test.go
+++ b/handlers_extra_test.go
@@ -12,7 +12,7 @@ import (
func TestHandleHealth_Response(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
req := httptest.NewRequest("GET", "/health", nil)
w := httptest.NewRecorder()
b.handleHealth(w, req)
@@ -224,10 +224,12 @@ func TestLoadConfig_ConfigFileAllFields(t *testing.T) {
// handler dispatch logic without needing Chrome.
func newBridgeWithFakeTab() *Bridge {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
- b.snapshots = make(map[string]*refCache)
+ b.TabManager = &TabManager{
+ tabs: make(map[string]*TabEntry),
+ snapshots: make(map[string]*refCache),
+ }
ctx, cancel := context.WithCancel(context.Background())
_ = cancel
- b.tabs["tab1"] = &TabEntry{ctx: ctx, cancel: cancel}
+ b.RegisterTab("tab1", ctx)
return b
}
diff --git a/integration_test.go b/integration_test.go
index 91f2950c..2ce96a86 100644
--- a/integration_test.go
+++ b/integration_test.go
@@ -47,12 +47,11 @@ func testBridge(t *testing.T) (*Bridge, func()) {
b := &Bridge{
allocCtx: allocCtx,
browserCtx: browserCtx,
- tabs: make(map[string]*TabEntry),
- snapshots: make(map[string]*refCache),
}
+ b.InitTabManager()
initID := string(chromedp.FromContext(browserCtx).Target.TargetID)
- b.tabs[initID] = &TabEntry{ctx: browserCtx}
+ b.RegisterTab(initID, browserCtx)
return b, func() {
browserCancel()
diff --git a/main.go b/main.go
index d306bdef..f6f32ed3 100644
--- a/main.go
+++ b/main.go
@@ -95,8 +95,7 @@ func main() {
applyTimezone(browserCtx)
bridge.browserCtx = browserCtx
- bridge.tabs = make(map[string]*TabEntry)
- bridge.snapshots = make(map[string]*refCache)
+ bridge.InitTabManager()
bridge.initActionRegistry()
bridge.locks = newLockManager()
@@ -106,7 +105,7 @@ func main() {
orchestrator := NewOrchestrator(profilesDir)
initTargetID := chromedp.FromContext(browserCtx).Target.TargetID
- bridge.tabs[string(initTargetID)] = &TabEntry{ctx: browserCtx}
+ bridge.RegisterTab(string(initTargetID), browserCtx)
slog.Info("initial tab", "id", string(initTargetID))
if !cfg.Headless {
diff --git a/snapshot_extra_test.go b/snapshot_extra_test.go
index ca0ba0f2..49c876f2 100644
--- a/snapshot_extra_test.go
+++ b/snapshot_extra_test.go
@@ -227,7 +227,7 @@ func TestRawAXValue_String_NonString(t *testing.T) {
func TestHandleSnapshot_InvalidFilter(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
req := httptest.NewRequest("GET", "/snapshot?filter=bogus", nil)
w := httptest.NewRecorder()
b.handleSnapshot(w, req)
@@ -238,7 +238,7 @@ func TestHandleSnapshot_InvalidFilter(t *testing.T) {
func TestHandleScreenshot_RawParam(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
req := httptest.NewRequest("GET", "/screenshot?raw=true&tabId=nonexistent", nil)
w := httptest.NewRecorder()
b.handleScreenshot(w, req)
@@ -249,7 +249,7 @@ func TestHandleScreenshot_RawParam(t *testing.T) {
func TestHandleNavigate_WithTimeout(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
body := `{"url":"https://example.com","timeout":5,"tabId":"nonexistent"}`
req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
@@ -261,7 +261,7 @@ func TestHandleNavigate_WithTimeout(t *testing.T) {
func TestHandleNavigate_WithBlockImages(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
body := `{"url":"https://example.com","blockImages":true,"tabId":"nonexistent"}`
req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
@@ -273,7 +273,7 @@ func TestHandleNavigate_WithBlockImages(t *testing.T) {
func TestHandleNavigate_WaitTitle(t *testing.T) {
b := &Bridge{}
- b.tabs = make(map[string]*TabEntry)
+ b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
body := `{"url":"https://example.com","waitTitle":true,"tabId":"nonexistent"}`
req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
diff --git a/stealth_test.go b/stealth_test.go
index a5dc4a06..ab8ff49a 100644
--- a/stealth_test.go
+++ b/stealth_test.go
@@ -152,9 +152,7 @@ func TestGenerateFingerprint(t *testing.T) {
}
func TestHandleStealthStatus(t *testing.T) {
- b := &Bridge{
- tabs: make(map[string]*TabEntry),
- }
+ b := newTestBridgeWithTabs()
req := httptest.NewRequest("GET", "/stealth/status", nil)
w := httptest.NewRecorder()
diff --git a/tab_manager.go b/tab_manager.go
new file mode 100644
index 00000000..2a386c7a
--- /dev/null
+++ b/tab_manager.go
@@ -0,0 +1,235 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "sync"
+ "time"
+
+ cdp "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+)
+
+// TabSetupFunc is called after a new tab context is created (stealth, animations, etc.).
+type TabSetupFunc func(ctx context.Context)
+
+// TabManager manages browser tabs, their contexts, and ref caches.
+type TabManager struct {
+ browserCtx context.Context
+ tabs map[string]*TabEntry
+ snapshots map[string]*refCache
+ onTabSetup TabSetupFunc
+ mu sync.RWMutex
+}
+
+// NewTabManager creates a TabManager with the given browser context and setup hook.
+func NewTabManager(browserCtx context.Context, onTabSetup TabSetupFunc) *TabManager {
+ return &TabManager{
+ browserCtx: browserCtx,
+ tabs: make(map[string]*TabEntry),
+ snapshots: make(map[string]*refCache),
+ onTabSetup: onTabSetup,
+ }
+}
+
+// TabContext returns or creates a context for the given tab ID.
+// If tabID is empty, the first available page target is used.
+func (tm *TabManager) TabContext(tabID string) (context.Context, string, error) {
+ if tabID == "" {
+ targets, err := tm.ListTargets()
+ if err != nil {
+ return nil, "", fmt.Errorf("list targets: %w", err)
+ }
+ if len(targets) == 0 {
+ return nil, "", fmt.Errorf("no tabs open")
+ }
+ tabID = string(targets[0].TargetID)
+ }
+
+ tm.mu.RLock()
+ if entry, ok := tm.tabs[tabID]; ok && entry.ctx != nil {
+ tm.mu.RUnlock()
+ return entry.ctx, tabID, nil
+ }
+ tm.mu.RUnlock()
+
+ tm.mu.Lock()
+ defer tm.mu.Unlock()
+
+ if entry, ok := tm.tabs[tabID]; ok && entry.ctx != nil {
+ return entry.ctx, tabID, nil
+ }
+
+ if tm.browserCtx == nil {
+ return nil, "", fmt.Errorf("no browser connection")
+ }
+
+ ctx, cancel := chromedp.NewContext(tm.browserCtx,
+ chromedp.WithTargetID(target.ID(tabID)),
+ )
+ if err := chromedp.Run(ctx); err != nil {
+ cancel()
+ return nil, "", fmt.Errorf("tab %s not found: %w", tabID, err)
+ }
+
+ if tm.onTabSetup != nil {
+ tm.onTabSetup(ctx)
+ }
+
+ tm.tabs[tabID] = &TabEntry{ctx: ctx, cancel: cancel}
+ return ctx, tabID, nil
+}
+
+// CreateTab opens a new tab, optionally navigating to url.
+func (tm *TabManager) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
+ if tm.browserCtx == nil {
+ return "", nil, nil, fmt.Errorf("no browser context available")
+ }
+ ctx, cancel := chromedp.NewContext(tm.browserCtx)
+
+ if tm.onTabSetup != nil {
+ tm.onTabSetup(ctx)
+ }
+
+ if cfg.BlockMedia {
+ _ = setResourceBlocking(ctx, mediaBlockPatterns)
+ } else if cfg.BlockImages {
+ _ = setResourceBlocking(ctx, imageBlockPatterns)
+ }
+
+ navURL := "about:blank"
+ if url != "" {
+ navURL = url
+ }
+ if err := navigatePage(ctx, navURL); err != nil {
+ cancel()
+ return "", nil, nil, fmt.Errorf("new tab: %w", err)
+ }
+
+ newTargetID := string(chromedp.FromContext(ctx).Target.TargetID)
+ tm.mu.Lock()
+ tm.tabs[newTargetID] = &TabEntry{ctx: ctx, cancel: cancel}
+ tm.mu.Unlock()
+
+ return newTargetID, ctx, cancel, nil
+}
+
+// CloseTab closes a tab by ID.
+func (tm *TabManager) CloseTab(tabID string) error {
+ tm.mu.Lock()
+ entry, tracked := tm.tabs[tabID]
+ tm.mu.Unlock()
+
+ if tracked && entry.cancel != nil {
+ entry.cancel()
+ }
+
+ closeCtx, closeCancel := context.WithTimeout(tm.browserCtx, 5*time.Second)
+ defer closeCancel()
+
+ if err := target.CloseTarget(target.ID(tabID)).Do(cdp.WithExecutor(closeCtx, chromedp.FromContext(closeCtx).Browser)); err != nil {
+ if !tracked {
+ return nil
+ }
+ slog.Debug("close target CDP", "tabId", tabID, "err", err)
+ }
+
+ tm.mu.Lock()
+ delete(tm.tabs, tabID)
+ delete(tm.snapshots, tabID)
+ tm.mu.Unlock()
+
+ return nil
+}
+
+// ListTargets returns all page-type targets from the browser.
+func (tm *TabManager) ListTargets() ([]*target.Info, error) {
+ if tm.browserCtx == nil {
+ return nil, fmt.Errorf("no browser connection")
+ }
+ var targets []*target.Info
+ if err := chromedp.Run(tm.browserCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ var err error
+ targets, err = target.GetTargets().Do(ctx)
+ return err
+ }),
+ ); err != nil {
+ return nil, fmt.Errorf("get targets: %w", err)
+ }
+
+ pages := make([]*target.Info, 0)
+ for _, t := range targets {
+ if t.Type == targetTypePage {
+ pages = append(pages, t)
+ }
+ }
+ return pages, nil
+}
+
+// GetRefCache returns the ref cache for a tab.
+func (tm *TabManager) GetRefCache(tabID string) *refCache {
+ tm.mu.RLock()
+ defer tm.mu.RUnlock()
+ return tm.snapshots[tabID]
+}
+
+// SetRefCache sets the ref cache for a tab.
+func (tm *TabManager) SetRefCache(tabID string, cache *refCache) {
+ tm.mu.Lock()
+ defer tm.mu.Unlock()
+ tm.snapshots[tabID] = cache
+}
+
+// DeleteRefCache removes the ref cache for a tab.
+func (tm *TabManager) DeleteRefCache(tabID string) {
+ tm.mu.Lock()
+ defer tm.mu.Unlock()
+ delete(tm.snapshots, tabID)
+}
+
+// RegisterTab registers an externally-created tab (e.g., the initial Chrome tab).
+func (tm *TabManager) RegisterTab(tabID string, ctx context.Context) {
+ tm.mu.Lock()
+ defer tm.mu.Unlock()
+ tm.tabs[tabID] = &TabEntry{ctx: ctx}
+}
+
+// CleanStaleTabs periodically removes tabs that no longer exist in Chrome.
+func (tm *TabManager) CleanStaleTabs(ctx context.Context, interval time.Duration) {
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ }
+
+ targets, err := tm.ListTargets()
+ if err != nil {
+ continue
+ }
+
+ alive := make(map[string]bool, len(targets))
+ for _, t := range targets {
+ alive[string(t.TargetID)] = true
+ }
+
+ tm.mu.Lock()
+ for id, entry := range tm.tabs {
+ if !alive[id] {
+ if entry.cancel != nil {
+ entry.cancel()
+ }
+ delete(tm.tabs, id)
+ delete(tm.snapshots, id)
+ slog.Info("cleaned stale tab", "id", id)
+ }
+ }
+ tm.mu.Unlock()
+ }
+}