Skip to content

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

fix: reap orphan tab targets at browser launch, not on the create path

Luigi Agostie7a9c6c852d3
diff --git a/internal/bridge/tab_budget.go b/internal/bridge/tab_budget.go
new file mode 100644
index 00000000..793fcc87
--- /dev/null
+++ b/internal/bridge/tab_budget.go
@@ -0,0 +1,99 @@
+package bridge
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ cdp "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+)
+
+func (tm *TabManager) trackedCDPIDs() map[string]bool {
+ tm.mu.RLock()
+ defer tm.mu.RUnlock()
+ out := make(map[string]bool, len(tm.tabs))
+ for _, entry := range tm.tabs {
+ if entry != nil && entry.CDPID != "" {
+ out[entry.CDPID] = true
+ }
+ }
+ return out
+}
+
+func selectOrphanTargets(tracked map[string]bool, pages []*target.Info, limit int) []target.ID {
+ orphans := make([]target.ID, 0)
+ for i := len(pages) - 1; i >= 0; i-- {
+ t := pages[i]
+ if t == nil || t.Type != TargetTypePage {
+ continue
+ }
+ if tracked[string(t.TargetID)] {
+ continue
+ }
+ orphans = append(orphans, t.TargetID)
+ if limit > 0 && len(orphans) >= limit {
+ break
+ }
+ }
+ return orphans
+}
+
+func (tm *TabManager) closeTarget(id target.ID) bool {
+ closeCtx, cancel := context.WithTimeout(tm.browserCtx, 5*time.Second)
+ defer cancel()
+ c := chromedp.FromContext(closeCtx)
+ if c == nil || c.Browser == nil {
+ return false
+ }
+ if err := target.CloseTarget(id).Do(cdp.WithExecutor(closeCtx, c.Browser)); err != nil {
+ slog.Debug("tab budget: orphan close failed", "targetId", id, "err", err)
+ return false
+ }
+ return true
+}
+
+func (tm *TabManager) reconcileTabBudget() {
+ if tm == nil || tm.config == nil || tm.config.MaxTabs <= 0 || tm.browserCtx == nil {
+ return
+ }
+
+ pages, err := tm.ListTargets()
+ if err != nil {
+ slog.Debug("tab budget: launch reconcile skipped", "err", err)
+ return
+ }
+ if len(pages) <= tm.config.MaxTabs {
+ return
+ }
+
+ orphans := selectOrphanTargets(tm.trackedCDPIDs(), pages, len(pages)-tm.config.MaxTabs)
+ closed := 0
+ for _, id := range orphans {
+ if !tm.closeTarget(id) {
+ continue
+ }
+ closed++
+ }
+ if closed == 0 {
+ return
+ }
+
+ deadline := time.Now().Add(5 * time.Second)
+ live := len(pages)
+ for {
+ remaining, err := tm.ListTargets()
+ if err != nil {
+ break
+ }
+ live = len(remaining)
+ if live <= tm.config.MaxTabs || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(25 * time.Millisecond)
+ }
+
+ slog.Info("tab budget: reaped untracked targets on browser launch",
+ "closed", closed, "live", live, "maxTabs", tm.config.MaxTabs)
+}
diff --git a/internal/bridge/tab_budget_integration_test.go b/internal/bridge/tab_budget_integration_test.go
new file mode 100644
index 00000000..73cfcaf8
--- /dev/null
+++ b/internal/bridge/tab_budget_integration_test.go
@@ -0,0 +1,91 @@
+package bridge
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/testbrowser"
+)
+
+func TestReconcileTabBudgetBoundsUntrackedTargets(t *testing.T) {
+ chromePath := testbrowser.Path(t)
+ profile := testbrowser.ProfileDir(t)
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancel := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancel()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+
+ if err := chromedp.Run(ctx, chromedp.Navigate("about:blank")); err != nil {
+ t.Fatalf("start browser: %v", err)
+ }
+
+ const maxTabs = 3
+ tm := NewTabManager(ctx, &config.RuntimeConfig{
+ MaxTabs: maxTabs,
+ TabEvictionPolicy: "close_lru",
+ }, nil, nil, nil)
+
+ exec, err := browserExecutorContext(ctx)
+ if err != nil {
+ t.Fatalf("browser executor: %v", err)
+ }
+
+ var firstCreated target.ID
+ for i := 0; i < 6; i++ {
+ id, err := target.CreateTarget("about:blank").Do(exec)
+ if err != nil {
+ t.Fatalf("create untracked target %d: %v", i, err)
+ }
+ if i == 0 {
+ firstCreated = id
+ }
+ }
+
+ tm.mu.Lock()
+ tm.tabs["managed"] = &TabEntry{CDPID: string(firstCreated)}
+ tm.mu.Unlock()
+
+ before, err := tm.ListTargets()
+ if err != nil {
+ t.Fatalf("list targets: %v", err)
+ }
+ if len(before) <= maxTabs {
+ t.Fatalf("precondition: expected more than %d page targets before reconcile, got %d", maxTabs, len(before))
+ }
+
+ tm.reconcileTabBudget()
+
+ after, err := tm.ListTargets()
+ if err != nil {
+ t.Fatalf("list targets after reconcile: %v", err)
+ }
+ if len(after) > maxTabs {
+ t.Fatalf("reconcile did not bound live page targets to MaxTabs: got %d, want <= %d", len(after), maxTabs)
+ }
+
+ survived := false
+ for _, tg := range after {
+ if tg.TargetID == firstCreated {
+ survived = true
+ }
+ }
+ if !survived {
+ t.Fatalf("reconcile reaped the tracked/managed target %s", firstCreated)
+ }
+}
diff --git a/internal/bridge/tab_budget_test.go b/internal/bridge/tab_budget_test.go
new file mode 100644
index 00000000..3f23760f
--- /dev/null
+++ b/internal/bridge/tab_budget_test.go
@@ -0,0 +1,73 @@
+package bridge
+
+import (
+ "testing"
+
+ "github.com/chromedp/cdproto/target"
+)
+
+func pageTarget(id string) *target.Info {
+ return &target.Info{TargetID: target.ID(id), Type: TargetTypePage}
+}
+
+func TestSelectOrphanTargets_PicksUntrackedOldestFirst(t *testing.T) {
+ tracked := map[string]bool{"t-managed": true}
+ pages := []*target.Info{pageTarget("t-new"), pageTarget("t-managed"), pageTarget("t-old")}
+
+ got := selectOrphanTargets(tracked, pages, 0)
+ if len(got) != 2 {
+ t.Fatalf("expected 2 orphans, got %d (%v)", len(got), got)
+ }
+ if got[0] != target.ID("t-old") {
+ t.Fatalf("expected oldest orphan first, got %v", got)
+ }
+ for _, id := range got {
+ if id == target.ID("t-managed") {
+ t.Fatal("a tracked target must never be reaped as an orphan")
+ }
+ }
+}
+
+func TestSelectOrphanTargets_RespectsLimit(t *testing.T) {
+ pages := []*target.Info{pageTarget("a"), pageTarget("b"), pageTarget("c")}
+ got := selectOrphanTargets(map[string]bool{}, pages, 2)
+ if len(got) != 2 {
+ t.Fatalf("expected limit of 2, got %d", len(got))
+ }
+}
+
+func TestSelectOrphanTargets_LimitSparesNewest(t *testing.T) {
+ pages := []*target.Info{pageTarget("in-flight"), pageTarget("mid"), pageTarget("oldest")}
+ got := selectOrphanTargets(map[string]bool{}, pages, 1)
+ if len(got) != 1 || got[0] != target.ID("oldest") {
+ t.Fatalf("expected only the oldest target, got %v", got)
+ }
+ for _, id := range got {
+ if id == target.ID("in-flight") {
+ t.Fatal("a bounded reconcile must not reap the newest (in-flight) target")
+ }
+ }
+}
+
+func TestSelectOrphanTargets_IgnoresNonPageTargets(t *testing.T) {
+ pages := []*target.Info{
+ {TargetID: target.ID("worker"), Type: "service_worker"},
+ nil,
+ pageTarget("page"),
+ }
+ got := selectOrphanTargets(map[string]bool{}, pages, 0)
+ if len(got) != 1 || got[0] != target.ID("page") {
+ t.Fatalf("expected only the page target, got %v", got)
+ }
+}
+
+func TestTrackedCDPIDs(t *testing.T) {
+ tm := &TabManager{tabs: map[string]*TabEntry{
+ "tab_1": {CDPID: "raw1"},
+ "tab_2": {CDPID: ""},
+ }}
+ got := tm.trackedCDPIDs()
+ if !got["raw1"] || len(got) != 1 {
+ t.Fatalf("unexpected tracked set: %v", got)
+ }
+}
diff --git a/internal/bridge/tab_popup_guard.go b/internal/bridge/tab_popup_guard.go
index 3ec4e972..610a144d 100644
--- a/internal/bridge/tab_popup_guard.go
+++ b/internal/bridge/tab_popup_guard.go
@@ -50,6 +50,8 @@ func (tm *TabManager) StartBrowserGuards() {
tm.mu.Lock()
tm.guardActive = true
tm.mu.Unlock()
+
+ tm.reconcileTabBudget()
})
}