High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(bridge): semantic CDP IDs and tab eviction policies
Bosch23df1719cb2d
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.goindex 155785e3..46b05c24 100644--- a/internal/bridge/bridge.go+++ b/internal/bridge/bridge.go@@ -15,10 +15,12 @@ import ()type TabEntry struct {- Ctx context.Context- Cancel context.CancelFunc- Accessed bool- CDPID string // raw CDP target ID; set when this entry is a hash-alias+ Ctx context.Context+ Cancel context.CancelFunc+ Accessed bool+ CDPID string // raw CDP target ID+ CreatedAt time.Time // when the tab was first created/registered+ LastUsed time.Time // last time the tab was accessed via TabContext}type RefCache struct {diff --git a/internal/bridge/bridge_test.go b/internal/bridge/bridge_test.goindex 88c3d5fb..98af11ed 100644--- a/internal/bridge/bridge_test.go+++ b/internal/bridge/bridge_test.go@@ -119,52 +119,65 @@ func TestTabContext_RejectsRawCDPID(t *testing.T) {}}-func TestCreateTab_ReturnsHashFormat(t *testing.T) {- // Verify CreateTab returns hash-format IDs (tab_XXXXXXXX)- // Note: This test can't actually create tabs without Chrome,- // but we can test the ID format logic directly+func TestCreateTab_ReturnsRawCDPID(t *testing.T) {+ // Verify TabIDFromCDPTarget returns raw CDP ID (no prefix)tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)- // CreateTab will fail (no browser), but we can test the idMgrif tm.idMgr == nil {t.Error("TabManager should have idMgr initialized")}- // Test the ID generation format- hashID := tm.idMgr.TabIDFromCDPTarget("A25658CE1BA82659EBE9C93C46CEE63A")- if len(hashID) < 4 || hashID[:4] != "tab_" {- t.Errorf("expected hash ID to start with 'tab_', got %s", hashID)- }- if len(hashID) != 12 { // tab_ + 8 hex chars- t.Errorf("expected hash ID length 12, got %d (%s)", len(hashID), hashID)+ rawCDP := "A25658CE1BA82659EBE9C93C46CEE63A"+ tabID := tm.idMgr.TabIDFromCDPTarget(rawCDP)++ if tabID != rawCDP {+ t.Errorf("expected %s, got %s", rawCDP, tabID)}}-func TestTabContext_AcceptsRegisteredHashID(t *testing.T) {- // TabContext should accept hash IDs that are properly registered+func TestTabContext_AcceptsRegisteredID(t *testing.T) {tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)- // Manually register a tab entry (simulating what CreateTab does internally)- hashID := "tab_abc12345"rawCDPID := "RAWCDPID123456789012345678901234"ctx := context.Background()- tm.tabs[hashID] = &TabEntry{+ tm.tabs[rawCDPID] = &TabEntry{Ctx: ctx,CDPID: rawCDPID,}- // TabContext should find and return it- returnedCtx, resolvedID, err := tm.TabContext(hashID)+ returnedCtx, resolvedID, err := tm.TabContext(rawCDPID)if err != nil {- t.Errorf("TabContext should accept registered hash ID: %v", err)+ t.Errorf("TabContext should accept registered ID: %v", err)}if returnedCtx != ctx {t.Error("TabContext should return the registered context")}- // resolvedID should be the raw CDP ID for internal consistencyif resolvedID != rawCDPID {- t.Errorf("resolvedID should be raw CDP ID, got %s", resolvedID)+ t.Errorf("resolvedID should be tab ID, got %s", resolvedID)+ }+}++func TestTabContext_EmptyID_UsesCurrentTrackedTab(t *testing.T) {+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)++ ctx := context.Background()+ tabID := "SOMECDPID"++ tm.mu.Lock()+ tm.tabs[tabID] = &TabEntry{Ctx: ctx, CDPID: tabID}+ tm.currentTab = tabID+ tm.mu.Unlock()++ returnedCtx, resolvedID, err := tm.TabContext("")+ if err != nil {+ t.Fatalf("TabContext(\"\") should resolve to current tab: %v", err)+ }+ if returnedCtx != ctx {+ t.Error("should return the current tab's context")+ }+ if resolvedID != tabID {+ t.Errorf("expected %s, got %s", tabID, resolvedID)}}diff --git a/internal/bridge/errors.go b/internal/bridge/errors.gonew file mode 100644index 00000000..998f6f4f--- /dev/null+++ b/internal/bridge/errors.go@@ -0,0 +1,15 @@+package bridge++import "fmt"++// TabLimitError is returned when a new tab cannot be created because+// the configured limit has been reached and the eviction policy is "reject".+// HTTP handlers should map this to 429 Too Many Requests.+type TabLimitError struct {+ Current int+ Max int+}++func (e *TabLimitError) Error() string {+ return fmt.Sprintf("tab limit reached (%d/%d)", e.Current, e.Max)+}diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.goindex 977d782f..3eb587bb 100644--- a/internal/bridge/tab_manager.go+++ b/internal/bridge/tab_manager.go@@ -24,6 +24,7 @@ type TabManager struct {accessed map[string]boolsnapshots map[string]*RefCacheonTabSetup TabSetupFunc+ currentTab string // ID of the most recently used tabmu sync.RWMutex}@@ -45,9 +46,44 @@ func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgrfunc (tm *TabManager) markAccessed(tabID string) {tm.mu.Lock()tm.accessed[tabID] = true+ if entry, ok := tm.tabs[tabID]; ok {+ entry.LastUsed = time.Now()+ }+ tm.currentTab = tabIDtm.mu.Unlock()}+// selectCurrentTrackedTab returns the current tab ID, falling back to the most+// recently used tab if the explicit pointer is stale or unset.+func (tm *TabManager) selectCurrentTrackedTab() string {+ // Prefer explicit current tab if still tracked+ if tm.currentTab != "" {+ if _, ok := tm.tabs[tm.currentTab]; ok {+ return tm.currentTab+ }+ }++ // Fallback: pick the tab with the most recent LastUsed+ var best string+ var bestTime time.Time+ for id, entry := range tm.tabs {+ if entry.LastUsed.After(bestTime) {+ best = id+ bestTime = entry.LastUsed+ }+ }+ // If no LastUsed set, fall back to most recent CreatedAt+ if best == "" {+ for id, entry := range tm.tabs {+ if entry.CreatedAt.After(bestTime) {+ best = id+ bestTime = entry.CreatedAt+ }+ }+ }+ return best+}+// AccessedTabIDs returns the set of tab IDs that were accessed this session.func (tm *TabManager) AccessedTabIDs() map[string]bool {tm.mu.RLock()@@ -61,17 +97,23 @@ func (tm *TabManager) AccessedTabIDs() map[string]bool {func (tm *TabManager) TabContext(tabID string) (context.Context, string, error) {if tabID == "" {- // Auto-select first tab when no ID provided- 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")+ // Resolve to current tracked tab+ tm.mu.RLock()+ tabID = tm.selectCurrentTrackedTab()+ tm.mu.RUnlock()++ if tabID == "" {+ // No tracked tabs — try to find one from CDP targets+ 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")+ }+ rawID := string(targets[0].TargetID)+ tabID = tm.idMgr.TabIDFromCDPTarget(rawID)}- // Convert raw CDP ID to hash and look it up- rawID := string(targets[0].TargetID)- tabID = tm.idMgr.TabIDFromCDPTarget(rawID)}tm.mu.RLock()@@ -88,13 +130,51 @@ func (tm *TabManager) TabContext(tabID string) (context.Context, string, error)tm.markAccessed(tabID)- // Return the canonical raw CDP ID so that operations like ref-cache- // lookups are consistent regardless of which ID form was used.- resolvedID := tabID- if entry.CDPID != "" {- resolvedID = entry.CDPID+ return entry.Ctx, tabID, nil+}++// closeOldestTab evicts the tab with the earliest CreatedAt timestamp.+func (tm *TabManager) closeOldestTab() error {+ tm.mu.RLock()+ var oldestID string+ var oldestTime time.Time+ for id, entry := range tm.tabs {+ if oldestID == "" || entry.CreatedAt.Before(oldestTime) {+ oldestID = id+ oldestTime = entry.CreatedAt+ }+ }+ tm.mu.RUnlock()++ if oldestID == "" {+ return fmt.Errorf("no tabs to evict")+ }+ slog.Info("evicting oldest tab", "id", oldestID, "createdAt", oldestTime)+ return tm.CloseTab(oldestID)+}++// closeLRUTab evicts the tab with the earliest LastUsed timestamp.+func (tm *TabManager) closeLRUTab() error {+ tm.mu.RLock()+ var lruID string+ var lruTime time.Time+ for id, entry := range tm.tabs {+ t := entry.LastUsed+ if t.IsZero() {+ t = entry.CreatedAt+ }+ if lruID == "" || t.Before(lruTime) {+ lruID = id+ lruTime = t+ }+ }+ tm.mu.RUnlock()++ if lruID == "" {+ return fmt.Errorf("no tabs to evict")}- return entry.Ctx, resolvedID, nil+ slog.Info("evicting LRU tab", "id", lruID, "lastUsed", lruTime)+ return tm.CloseTab(lruID)}func (tm *TabManager) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {@@ -112,7 +192,18 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca// If check fails due to timeout, log warning but allow creation to proceedslog.Warn("tab count check timed out, proceeding with creation", "error", err)} else if len(targets) >= tm.config.MaxTabs {- return "", nil, nil, fmt.Errorf("tab limit reached (%d/%d) — close a tab first", len(targets), tm.config.MaxTabs)+ switch tm.config.TabEvictionPolicy {+ case "close_oldest":+ if evictErr := tm.closeOldestTab(); evictErr != nil {+ return "", nil, nil, fmt.Errorf("eviction failed: %w", evictErr)+ }+ case "close_lru":+ if evictErr := tm.closeLRUTab(); evictErr != nil {+ return "", nil, nil, fmt.Errorf("eviction failed: %w", evictErr)+ }+ default: // "reject"+ return "", nil, nil, &TabLimitError{Current: len(targets), Max: tm.config.MaxTabs}+ }}}@@ -162,17 +253,17 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca_ = SetResourceBlocking(ctx, blockPatterns)}- // Compute hash-based tab ID and store only that entry.- // Raw CDP ID is kept internal in the CDPID field.rawCDPID := string(targetID)- hashTabID := tm.idMgr.TabIDFromCDPTarget(rawCDPID)+ tabID := tm.idMgr.TabIDFromCDPTarget(rawCDPID)+ now := time.Now()tm.mu.Lock()- tm.tabs[hashTabID] = &TabEntry{Ctx: ctx, Cancel: cancel, CDPID: rawCDPID}- tm.accessed[hashTabID] = true+ tm.tabs[tabID] = &TabEntry{Ctx: ctx, Cancel: cancel, CDPID: rawCDPID, CreatedAt: now, LastUsed: now}+ tm.accessed[tabID] = true+ tm.currentTab = tabIDtm.mu.Unlock()- return hashTabID, ctx, cancel, nil+ return tabID, ctx, cancel, nil}func (tm *TabManager) CloseTab(tabID string) error {@@ -193,7 +284,7 @@ func (tm *TabManager) CloseTab(tabID string) error {entry.Cancel()}- // Resolve hash alias → raw CDP target ID for the actual CDP close call+ // Resolve to raw CDP target ID for the actual CDP close callcdpTargetID := tabIDif tracked && entry.CDPID != "" {cdpTargetID = entry.CDPID@@ -292,18 +383,20 @@ func (tm *TabManager) DeleteRefCache(tabID string) {}func (tm *TabManager) RegisterTab(tabID string, ctx context.Context) {+ now := time.Now()tm.mu.Lock()defer tm.mu.Unlock()- tm.tabs[tabID] = &TabEntry{Ctx: ctx}+ tm.tabs[tabID] = &TabEntry{Ctx: ctx, CreatedAt: now, LastUsed: now}+ tm.currentTab = tabID}-// RegisterHashTab registers a hash-based tab ID (e.g. "tab_XXXXXXXX") as an alias-// for the given raw CDP target ID. This allows callers to use the hash ID for all-// subsequent operations (action, snapshot, close) without knowing the raw CDP ID.-func (tm *TabManager) RegisterHashTab(hashID, rawCDPID string, ctx context.Context, cancel context.CancelFunc) {+// RegisterTabWithCancel registers a tab ID with its context and cancel function.+func (tm *TabManager) RegisterTabWithCancel(tabID, rawCDPID string, ctx context.Context, cancel context.CancelFunc) {+ now := time.Now()tm.mu.Lock()defer tm.mu.Unlock()- tm.tabs[hashID] = &TabEntry{Ctx: ctx, Cancel: cancel, CDPID: rawCDPID}+ tm.tabs[tabID] = &TabEntry{Ctx: ctx, Cancel: cancel, CDPID: rawCDPID, CreatedAt: now, LastUsed: now}+ tm.currentTab = tabID}func (tm *TabManager) CleanStaleTabs(ctx context.Context, interval time.Duration) {diff --git a/internal/config/config.go b/internal/config/config.goindex 765dd634..86cabd0d 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -34,6 +34,7 @@ type RuntimeConfig struct {UserAgent stringNoAnimations boolStealthLevel string+ TabEvictionPolicy string // "reject" (default), "close_oldest", "close_lru"ActionTimeout time.DurationNavigateTimeout time.DurationShutdownTimeout time.Duration@@ -247,6 +248,7 @@ func Load() *RuntimeConfig {UserAgent: envMigrate("PINCHTAB_USER_AGENT", "BRIDGE_USER_AGENT"),NoAnimations: envBoolOrMigrate("PINCHTAB_NO_ANIMATIONS", "BRIDGE_NO_ANIMATIONS", false),StealthLevel: envOrMigrate("PINCHTAB_STEALTH", "BRIDGE_STEALTH", "light"),+ TabEvictionPolicy: envOr("PINCHTAB_TAB_EVICTION_POLICY", "reject"),ActionTimeout: 30 * time.Second,NavigateTimeout: 60 * time.Second,ShutdownTimeout: 10 * time.Second,diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.goindex 8d07db33..3e2964e9 100644--- a/internal/handlers/health_tabs.go+++ b/internal/handlers/health_tabs.go@@ -95,13 +95,14 @@ func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {tabs := make([]map[string]any, 0, len(targets))for _, t := range targets {+ tabID := string(t.TargetID)entry := map[string]any{- "id": string(t.TargetID),+ "id": tabID,"url": t.URL,"title": t.Title,"type": t.Type,}- if lock := h.Bridge.TabLockInfo(string(t.TargetID)); lock != nil {+ if lock := h.Bridge.TabLockInfo(tabID); lock != nil {entry["owner"] = lock.Ownerentry["lockedUntil"] = lock.ExpiresAt.Format(time.RFC3339)}diff --git a/internal/idutil/idutil.go b/internal/idutil/idutil.goindex 508643b4..ceed261e 100644--- a/internal/idutil/idutil.go+++ b/internal/idutil/idutil.go@@ -37,12 +37,10 @@ func (m *Manager) TabID(instanceID string, tabIndex int) string {return hashID("tab", data)}-// TabIDFromCDPTarget converts a CDP target ID to a hash-based tab ID-// Used when creating tabs dynamically via CDP-// Format: tab_XXXXXXXX (12 chars total)+// TabIDFromCDPTarget returns the CDP target ID as-is.+// Raw CDP IDs are used directly — no prefixing or hashing.func (m *Manager) TabIDFromCDPTarget(cdpTargetID string) string {- // Hash the CDP target ID to create a stable, shorter tab ID- return hashID("tab", cdpTargetID)+ return cdpTargetID}// hashID creates a short hash-based ID with the given prefixdiff --git a/internal/idutil/idutil_test.go b/internal/idutil/idutil_test.gonew file mode 100644index 00000000..fae37673--- /dev/null+++ b/internal/idutil/idutil_test.go@@ -0,0 +1,12 @@+package idutil++import "testing"++func TestTabIDFromCDPTarget_Passthrough(t *testing.T) {+ m := NewManager()+ cdpID := "A25658CE1BA82659EBE9C93C46CEE63A"+ got := m.TabIDFromCDPTarget(cdpID)+ if got != cdpID {+ t.Errorf("TabIDFromCDPTarget(%q) = %q, want %q", cdpID, got, cdpID)+ }+}diff --git a/scripts/check.sh b/scripts/check.shindex d51f2c4f..c6237296 100755--- a/scripts/check.sh+++ b/scripts/check.sh@@ -37,10 +37,19 @@ unformatted=$(gofmt -l .)if [ -n "$unformatted" ]; thenfail "gofmt" "Files not formatted:"echo "$unformatted" | while read f; do hint " $f"; done- hint "Run: gofmt -w ."- exit 1+ echo ""+ printf " Fix formatting now? (Y/n) "+ read -r answer+ if [ "$answer" != "n" ] && [ "$answer" != "N" ]; then+ gofmt -w .+ ok "gofmt (fixed)"+ else+ hint "Run: gofmt -w ."+ exit 1+ fi+else+ ok "gofmt"fi-ok "gofmt"# ── Vet ──────────────────────────────────────────────────────────────diff --git a/tests/integration/orchestrator_test.go b/tests/integration/orchestrator_test.goindex 6158ce0a..1d1755f7 100644--- a/tests/integration/orchestrator_test.go+++ b/tests/integration/orchestrator_test.go@@ -114,8 +114,8 @@ func TestOrchestrator_HashBasedIDs(t *testing.T) {t.Fatalf("navigate failed: %d: %s", navStatus, string(navBody))}- if !strings.HasPrefix(tabID, "tab_") || len(tabID) != 12 {- t.Fatalf("invalid tab ID format: %s", tabID)+ if tabID == "" {+ t.Fatalf("expected non-empty tab ID")}// Cleanup@@ -330,8 +330,8 @@ func TestOrchestrator_ProxyRouting(t *testing.T) {t.Fatalf("proxy navigate failed: %d: %s", status, string(body))}- if !strings.HasPrefix(tabID, "tab_") {- t.Fatalf("invalid tab ID from proxy: %s", tabID)+ if tabID == "" {+ t.Fatalf("expected non-empty tab ID")}// Test snapshot via orchestrator proxy@@ -504,8 +504,8 @@ func TestOrchestrator_FirstRequestLazyChrome(t *testing.T) {t.Fatalf("navigate failed: %d: %s", status, string(body))}- if !strings.HasPrefix(tabID, "tab_") {- t.Fatalf("invalid tab ID: %s", tabID)+ if tabID == "" {+ t.Fatalf("expected non-empty tab ID")}t.Logf("✓ Instance reached running state with lazy Chrome init; navigate succeeded: tabId=%s", tabID)diff --git a/tests/integration/tabs_test.go b/tests/integration/tabs_test.goindex 5244aa2b..e7fbd6ed 100644--- a/tests/integration/tabs_test.go+++ b/tests/integration/tabs_test.go@@ -165,21 +165,21 @@ func TestTabs_IDFormat(t *testing.T) {t.Fatal("expected tabId in response")}- // Verify hash format: tab_XXXXXXXX (12 chars total)- if len(tabID) != 12 || tabID[:4] != "tab_" {- t.Errorf("expected hash format tab_XXXXXXXX, got %s", tabID)+ // Verify tab ID is a non-empty raw CDP ID+ if tabID == "" {+ t.Errorf("expected non-empty tab ID")}// Clean up_, _ = httpPost(t, "/tab", map[string]string{"action": "close", "tabId": tabID})}-// TB8: Raw CDP ID rejection - security test-func TestTabs_RejectsRawCDPID(t *testing.T) {- // Raw CDP target IDs (32-char hex) should be rejected+// TB8: Nonexistent tab ID rejection+func TestTabs_RejectsNonexistentID(t *testing.T) {+ // A tab ID that doesn't correspond to any open tab should return 404rawCDPID := "A25658CE1BA82659EBE9C93C46CEE63A"- // Try to navigate using raw CDP ID - should fail with 404+ // Try to navigate using nonexistent tab ID - should fail with 404code, _ := httpPost(t, "/tabs/"+rawCDPID+"/navigate", map[string]string{"url": "https://example.com",})