High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: auto-switch to tabs opened by click actions
Luigi Agosti9acad3a1b58e
diff --git a/internal/bridge/action_pointer.go b/internal/bridge/action_pointer.goindex c262f07a..68ac579a 100644--- a/internal/bridge/action_pointer.go+++ b/internal/bridge/action_pointer.go@@ -142,13 +142,27 @@ func submitFormIfButton(ctx context.Context, selector string) (bool, error) {return submitted, err}-func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (map[string]any, error) {+func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (result map[string]any, err error) {// Promote to the humanized click path when the caller (or instance// config) opted in via humanize=true.if b.effectiveHumanize(req) {return b.actionHumanizedClick(ctx, req)}+ // Arm popup-aware auto-switch: if this click opens a new tab, we adopt+ // + focus it and surface the new tab ID on the response.+ auto := b.beginAutoSwitch(req)+ defer func() {+ if auto == nil {+ return+ }+ if err == nil {+ result = auto.finish(ctx, result)+ } else {+ auto.cancel(ctx)+ }+ }()+// Arm a one-shot dialog auto-handler if the caller expects the click// to open a native JS dialog. Without this, the click would hang// waiting for the dialog to be handled from a separate request.@@ -179,6 +193,9 @@ func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (map[string// Run click in goroutine so we can poll for dialogsgo func() {var err error+ if auto != nil {+ auto.prepareWindowOpenCapture(clickCtx)+ }if req.Selector != "" {// For submit buttons, use requestSubmit() to fire constraint validation,// JS submit handlers, and actual submission in one shot (issue #411).@@ -195,8 +212,14 @@ func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (map[stringresultCh <- clickResult{err: nodeErr}return}+ if auto != nil {+ auto.prepareNode(clickCtx, int64(node.BackendNodeID))+ }err = clickByNodeIDWithJSFallback(clickCtx, int64(node.BackendNodeID))} else if req.NodeID > 0 {+ if auto != nil {+ auto.prepareNode(clickCtx, req.NodeID)+ }err = clickByNodeIDWithJSFallback(clickCtx, req.NodeID)} else if req.HasXY {err = ClickByCoordinate(clickCtx, req.X, req.Y)@@ -236,9 +259,9 @@ func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (map[string}// Wait for click result (dialog-action was provided or no tab ID)- result := <-resultCh- if result.err != nil {- return nil, result.err+ res := <-resultCh+ if res.err != nil {+ return nil, res.err}if armedDialog {waitForArmedDialogSettle(dm, req.TabID, dialogAutoHandleTimeout)@@ -272,17 +295,36 @@ func waitForArmedDialogSettle(dm *DialogManager, tabID string, timeout time.Dura_ = dm.TakeAutoHandler(tabID)}-func (b *Bridge) actionDoubleClick(ctx context.Context, req ActionRequest) (map[string]any, error) {- var err error+func (b *Bridge) actionDoubleClick(ctx context.Context, req ActionRequest) (result map[string]any, err error) {+ auto := b.beginAutoSwitch(req)+ defer func() {+ if auto == nil {+ return+ }+ if err == nil {+ result = auto.finish(ctx, result)+ } else {+ auto.cancel(ctx)+ }+ }()if req.Selector != "" {node, nodeErr := firstNodeBySelector(ctx, req.Selector)if nodeErr != nil {return nil, nodeErr}+ if auto != nil {+ auto.prepareNode(ctx, int64(node.BackendNodeID))+ }err = doubleClickByNodeIDWithJSFallback(ctx, int64(node.BackendNodeID))} else if req.NodeID > 0 {+ if auto != nil {+ auto.prepareNode(ctx, req.NodeID)+ }err = doubleClickByNodeIDWithJSFallback(ctx, req.NodeID)} else if req.HasXY {+ if auto != nil {+ auto.prepareWindowOpenCapture(ctx)+ }err = DoubleClickByCoordinate(ctx, req.X, req.Y)} else {return nil, fmt.Errorf("need selector, ref, nodeId, or x/y coordinates")@@ -498,17 +540,34 @@ func (b *Bridge) actionDrag(ctx context.Context, req ActionRequest) (map[string]return nil, fmt.Errorf("need selector, ref, or nodeId")}-func (b *Bridge) actionHumanizedClick(ctx context.Context, req ActionRequest) (map[string]any, error) {+func (b *Bridge) actionHumanizedClick(ctx context.Context, req ActionRequest) (result map[string]any, err error) {+ auto := b.beginAutoSwitch(req)+ defer func() {+ if auto == nil {+ return+ }+ if err == nil {+ result = auto.finish(ctx, result)+ } else {+ auto.cancel(ctx)+ }+ }()var backendNodeID cdp.BackendNodeIDswitch {case req.NodeID > 0:backendNodeID = cdp.BackendNodeID(req.NodeID)+ if auto != nil {+ auto.prepareNode(ctx, req.NodeID)+ }case req.Selector != "":node, err := firstNodeBySelector(ctx, req.Selector)if err != nil {return nil, err}backendNodeID = node.BackendNodeID+ if auto != nil {+ auto.prepareNode(ctx, int64(node.BackendNodeID))+ }default:return nil, fmt.Errorf("need selector, ref, or nodeId")}diff --git a/internal/bridge/action_request.go b/internal/bridge/action_request.goindex 186dfe8b..5c5e7739 100644--- a/internal/bridge/action_request.go+++ b/internal/bridge/action_request.go@@ -78,6 +78,13 @@ type ActionRequest struct {// straight-to-target dispatch.Humanize *bool `json:"humanize,omitempty"`+ // AutoSwitch, when explicitly set to false, disables the popup-aware+ // auto-switch behavior on click actions. nil or true = on (default). When+ // on, a click that opens a new tab adopts + focuses it and surfaces the+ // new tab ID on the response as "switchedToTab". Only click/dblclick+ // honor this field.+ AutoSwitch *bool `json:"autoSwitch,omitempty"`+// DialogAction arms a one-shot dialog auto-handler before the action// executes. Used when clicking a button/link that opens a JS dialog// (alert/confirm/prompt). Values: "accept" or "dismiss". When set, thediff --git a/internal/bridge/tab_adopt.go b/internal/bridge/tab_adopt.gonew file mode 100644index 00000000..41727cfd--- /dev/null+++ b/internal/bridge/tab_adopt.go@@ -0,0 +1,144 @@+package bridge++import (+ "context"+ "fmt"+ "log/slog"+ "time"++ "github.com/chromedp/cdproto/target"+ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/ids"+)++func (tm *TabManager) browserGuardsActive() bool {+ if tm == nil {+ return false+ }+ tm.mu.RLock()+ defer tm.mu.RUnlock()+ return tm.guardActive+}++func (tm *TabManager) tabBlockPatterns() []string {+ if tm == nil || tm.config == nil {+ return nil+ }+ var blockPatterns []string+ if tm.config.BlockAds {+ blockPatterns = CombineBlockPatterns(blockPatterns, AdBlockPatterns)+ }+ if tm.config.BlockMedia {+ blockPatterns = CombineBlockPatterns(blockPatterns, MediaBlockPatterns)+ } else if tm.config.BlockImages {+ blockPatterns = CombineBlockPatterns(blockPatterns, ImageBlockPatterns)+ }+ return blockPatterns+}++func (tm *TabManager) setupManagedTarget(ctx context.Context, tabID, rawCDPID string) bool {+ if tm.onTabSetup != nil {+ tm.onTabSetup(ctx)+ }+ if blockPatterns := tm.tabBlockPatterns(); len(blockPatterns) > 0 {+ if err := SetResourceBlocking(ctx, blockPatterns); err != nil {+ slog.Warn("resource blocking setup failed", "tabId", tabID, "err", err)+ }+ }+ if tm.netMonitor != nil {+ if err := tm.netMonitor.StartCapture(ctx, tabID); err != nil {+ slog.Warn("eager network capture failed", "tab", tabID, "err", err)+ }+ }+ if tm.dialogMgr != nil {+ autoAccept := tm.config != nil && tm.config.DialogAutoAccept+ ListenDialogEvents(ctx, tabID, tm.dialogMgr, autoAccept)+ if err := EnableDialogEvents(ctx); err != nil {+ slog.Warn("enable dialog events failed", "tabId", tabID, "err", err)+ }+ }+ consoleEnabled := tm.shouldEagerlyCaptureConsole()+ if consoleEnabled {+ tm.setupConsoleCapture(ctx, rawCDPID)+ }+ return consoleEnabled+}++func (tm *TabManager) enforceAdoptTabLimit() error {+ if tm == nil || tm.config == nil || tm.config.MaxTabs <= 0 {+ return nil+ }+ tm.mu.RLock()+ managedCount := len(tm.tabs)+ tm.mu.RUnlock()+ if managedCount < tm.config.MaxTabs {+ return nil+ }+ switch tm.config.TabEvictionPolicy {+ case "close_oldest":+ if err := tm.closeOldestTab(); err != nil {+ return fmt.Errorf("eviction failed: %w", err)+ }+ case "reject":+ return &TabLimitError{Current: managedCount, Max: tm.config.MaxTabs}+ default:+ if err := tm.closeLRUTab(); err != nil {+ return fmt.Errorf("eviction failed: %w", err)+ }+ }+ return nil+}++func (tm *TabManager) adoptExistingTarget(targetID target.ID, enforceLimit bool) (string, error) {+ if tm == nil {+ return "", fmt.Errorf("tab manager not initialized")+ }+ if tm.browserCtx == nil {+ return "", fmt.Errorf("no browser context available")+ }+ rawCDPID := string(targetID)+ if rawCDPID == "" {+ return "", fmt.Errorf("target id required")+ }+ if tm.idMgr == nil {+ tm.idMgr = ids.NewManager()+ }+ tabID := tm.idMgr.TabIDFromCDPTarget(rawCDPID)++ tm.mu.RLock()+ entry, tracked := tm.tabs[tabID]+ tm.mu.RUnlock()+ if tracked {+ if entry == nil || entry.Ctx == nil {+ return "", fmt.Errorf("tab %s has no active context", tabID)+ }+ tm.markAccessed(tabID)+ return tabID, nil+ }++ if enforceLimit {+ if err := tm.enforceAdoptTabLimit(); err != nil {+ return "", err+ }+ }++ ctx, cancel := chromedp.NewContext(tm.browserCtx, chromedp.WithTargetID(targetID))+ consoleEnabled := tm.setupManagedTarget(ctx, tabID, rawCDPID)+ now := time.Now()++ tm.mu.Lock()+ tm.tabs[tabID] = &TabEntry{+ Ctx: ctx,+ Cancel: cancel,+ CDPID: rawCDPID,+ CreatedAt: now,+ LastUsed: now,+ ConsoleCaptureEnabled: consoleEnabled,+ }+ tm.accessed[tabID] = true+ tm.currentTab = tabID+ tm.mu.Unlock()++ tm.startTabPolicyWatcher(tabID, ctx)+ return tabID, nil+}diff --git a/internal/bridge/tab_auto_switch.go b/internal/bridge/tab_auto_switch.gonew file mode 100644index 00000000..b8b544e4--- /dev/null+++ b/internal/bridge/tab_auto_switch.go@@ -0,0 +1,363 @@+package bridge++import (+ "context"+ "encoding/json"+ "log/slog"+ "strings"+ "time"++ "github.com/chromedp/cdproto/target"+ "github.com/chromedp/chromedp"+)++// autoSwitchGraceTimeout is a short grace period after a click returns for the+// popup target-created event to reach the browser guard. Popup events normally+// arrive during the click itself; this keeps ordinary clicks from paying a+// long no-popup timeout.+const autoSwitchGraceTimeout = 100 * time.Millisecond++// pendingClickSlot records that a click is in flight for a specific opener tab+// and provides a one-shot channel the popup guard uses to hand the newly+// created target back to the click action.+type pendingClickSlot struct {+ captured chan target.ID+}++// markPendingClick registers an in-flight click for the given opener CDP+// target ID and returns a slot the caller will read from after the click. Any+// existing slot for the same opener is replaced (the previous one is+// abandoned — its receiver will hit its own timeout).+func (tm *TabManager) markPendingClick(openerCDP target.ID) *pendingClickSlot {+ if tm == nil || openerCDP == "" {+ return nil+ }+ slot := &pendingClickSlot{captured: make(chan target.ID, 1)}+ tm.mu.Lock()+ if tm.pendingClicks == nil {+ tm.pendingClicks = make(map[target.ID]*pendingClickSlot)+ }+ tm.pendingClicks[openerCDP] = slot+ tm.mu.Unlock()+ return slot+}++// clearPendingClick removes the slot for openerCDP if it still points at slot.+// It returns any popup target that was already claimed but not yet consumed by+// the action. Idempotent.+func (tm *TabManager) clearPendingClick(openerCDP target.ID, slot *pendingClickSlot) (target.ID, bool) {+ if tm == nil || openerCDP == "" {+ return "", false+ }+ tm.mu.Lock()+ defer tm.mu.Unlock()+ cur, ok := tm.pendingClicks[openerCDP]+ if !ok || (slot != nil && cur != slot) {+ return "", false+ }+ delete(tm.pendingClicks, openerCDP)+ select {+ case targetID := <-cur.captured:+ return targetID, true+ default:+ return "", false+ }+}++// claimPendingPopup is called by the popup guard for every popup target. If a+// click is pending for the opener, the popup is claimed (the guard must not+// close it) and the target ID is delivered on the click's slot. Returns true+// if the popup was claimed.+func (tm *TabManager) claimPendingPopup(openerCDP, newTargetID target.ID) bool {+ if tm == nil || openerCDP == "" {+ return false+ }+ tm.mu.Lock()+ defer tm.mu.Unlock()+ slot := tm.pendingClicks[openerCDP]+ if slot == nil {+ return false+ }+ select {+ case slot.captured <- newTargetID:+ return true+ default:+ // Slot already holds a popup; any second popup from the same click+ // is unexpected — let the guard close it.+ return false+ }+}++// lookupCDPID returns the raw CDP target ID for the given tab ID, if tracked.+func (tm *TabManager) lookupCDPID(tabID string) (target.ID, bool) {+ if tm == nil || tabID == "" {+ return "", false+ }+ tm.mu.RLock()+ defer tm.mu.RUnlock()+ entry, ok := tm.tabs[tabID]+ if !ok || entry.CDPID == "" {+ return "", false+ }+ return target.ID(entry.CDPID), true+}++// autoSwitchSession tracks a pending-click and turns a captured popup target+// into an adopted, focused tab once the click finishes.+type autoSwitchSession struct {+ tm *TabManager+ openerCDP target.ID+ slot *pendingClickSlot++ anchorURL string+ captureInstalled bool+}++// beginAutoSwitch arms popup-guard cooperation for a click on req.TabID. Returns+// nil if the tab isn't tracked (e.g. unit-test contexts) — callers must+// tolerate a nil session.+func (b *Bridge) beginAutoSwitch(req ActionRequest) *autoSwitchSession {+ if b == nil || b.TabManager == nil || req.TabID == "" {+ return nil+ }+ if req.AutoSwitch != nil && !*req.AutoSwitch {+ return nil+ }+ if !b.browserGuardsActive() {+ return nil+ }+ openerCDP, ok := b.lookupCDPID(req.TabID)+ if !ok {+ return nil+ }+ slot := b.markPendingClick(openerCDP)+ if slot == nil {+ return nil+ }+ return &autoSwitchSession{tm: b.TabManager, openerCDP: openerCDP, slot: slot}+}++func (s *autoSwitchSession) prepareWindowOpenCapture(ctx context.Context) {+ if s == nil || s.captureInstalled {+ return+ }+ const script = `(function() {+ if (window.__pinchtabAutoSwitchOpen && window.__pinchtabAutoSwitchOpen.active) return true;+ var state = {+ active: true,+ original: window.open,+ urls: []+ };+ Object.defineProperty(window, "__pinchtabAutoSwitchOpen", {+ value: state,+ configurable: true+ });+ window.open = function(url, target, features) {+ try {+ var raw = (url == null || url === "") ? "about:blank" : String(url);+ state.urls.push({+ url: new URL(raw, window.location.href).href,+ target: target == null ? "" : String(target)+ });+ } catch (e) {}+ return state.original.apply(this, arguments);+ };+ return true;+ })()`+ var installed bool+ if err := chromedp.Run(ctx, chromedp.Evaluate(script, &installed)); err != nil {+ slog.Debug("auto-switch: window.open capture install failed", "err", err)+ return+ }+ s.captureInstalled = installed+}++func (s *autoSwitchSession) prepareNode(ctx context.Context, backendNodeID int64) {+ if s == nil || backendNodeID <= 0 {+ return+ }+ if s.anchorURL == "" {+ if href, err := popupAnchorURL(ctx, backendNodeID); err == nil {+ s.anchorURL = href+ } else {+ slog.Debug("auto-switch: popup anchor lookup failed", "err", err)+ }+ }+ s.prepareWindowOpenCapture(ctx)+}++func popupAnchorURL(ctx context.Context, backendNodeID int64) (string, error) {+ var resolved json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": backendNodeID,+ }, &resolved); err != nil {+ return "", err+ }+ var obj struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(resolved, &obj); err != nil {+ return "", err+ }+ if obj.Object.ObjectID == "" {+ return "", nil+ }++ const script = `function() {+ var el = this;+ while (el && el.nodeType === 1) {+ if (el.tagName === "A" && el.hasAttribute("href")) {+ var target = (el.getAttribute("target") || "").trim().toLowerCase();+ if (target === "_blank") return el.href || "";+ return "";+ }+ el = el.parentElement;+ }+ return "";+ }`+ var raw json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": script,+ "objectId": obj.Object.ObjectID,+ "returnByValue": true,+ }, &raw); err != nil {+ return "", err+ }+ var out struct {+ Result struct {+ Value string `json:"value"`+ } `json:"result"`+ }+ if err := json.Unmarshal(raw, &out); err != nil {+ return "", err+ }+ return strings.TrimSpace(out.Result.Value), nil+}++func (s *autoSwitchSession) restoreWindowOpenAndFallbackURL(ctx context.Context) string {+ if s == nil || !s.captureInstalled {+ return ""+ }+ const script = `(function() {+ var state = window.__pinchtabAutoSwitchOpen;+ if (!state || !state.active) return "";+ try {+ window.open = state.original;+ delete window.__pinchtabAutoSwitchOpen;+ } catch (e) {}+ for (var i = state.urls.length - 1; i >= 0; i--) {+ var item = state.urls[i] || {};+ var target = String(item.target || "").trim().toLowerCase();+ if (target === "" || target === "_blank") return String(item.url || "");+ }+ return "";+ })()`+ var url string+ if err := chromedp.Run(ctx, chromedp.Evaluate(script, &url)); err != nil {+ slog.Debug("auto-switch: window.open capture restore failed", "err", err)+ return ""+ }+ return strings.TrimSpace(url)+}++func (s *autoSwitchSession) fallbackPopupURL(ctx context.Context) string {+ if s == nil {+ return ""+ }+ if url := s.restoreWindowOpenAndFallbackURL(ctx); url != "" {+ return url+ }+ return strings.TrimSpace(s.anchorURL)+}++// cancel releases the pending-click slot without adopting any popup. Safe to+// call multiple times.+func (s *autoSwitchSession) cancel(ctx context.Context) {+ if s == nil {+ return+ }+ s.restoreWindowOpenAndFallbackURL(ctx)+ if targetID, ok := s.tm.clearPendingClick(s.openerCDP, s.slot); ok && s.tm.browserCtx != nil {+ s.tm.closePopupTarget(targetID, s.openerCDP, "")+ }+}++// finish waits briefly for a popup target created by the click, adopts it,+// focuses it, and annotates result with "switchedToTab". If no popup arrives+// within autoSwitchGraceTimeout, result is returned unchanged.+func (s *autoSwitchSession) finish(ctx context.Context, result map[string]any) map[string]any {+ if s == nil {+ return result+ }+ cancelUnadopted := func() {+ if targetID, ok := s.tm.clearPendingClick(s.openerCDP, s.slot); ok && s.tm.browserCtx != nil {+ s.tm.closePopupTarget(targetID, s.openerCDP, "")+ }+ }++ waitCtx, cancel := context.WithTimeout(context.Background(), autoSwitchGraceTimeout)+ defer cancel()++ var newTargetID target.ID+ select {+ case newTargetID = <-s.slot.captured:+ case <-waitCtx.Done():+ cancelUnadopted()+ return s.createFallbackTab(ctx, result)+ case <-ctx.Done():+ // Honour the parent context too, but drain the channel non-blockingly+ // in case the popup arrived right at cancellation.+ select {+ case newTargetID = <-s.slot.captured:+ default:+ cancelUnadopted()+ return result+ }+ }+ s.tm.clearPendingClick(s.openerCDP, s.slot)+ s.restoreWindowOpenAndFallbackURL(ctx)++ newTabID, err := s.tm.adoptExistingTarget(newTargetID, true)+ if err != nil {+ slog.Warn("auto-switch: adopt popup failed", "tabId", newTabID, "err", err)+ if s.tm.browserCtx != nil {+ s.tm.closePopupTarget(newTargetID, s.openerCDP, "")+ }+ return result+ }+ if err := s.tm.FocusTab(newTabID); err != nil {+ slog.Warn("auto-switch: focus popup failed", "tabId", newTabID, "err", err)+ return result+ }++ if result == nil {+ result = map[string]any{}+ }+ result["switchedToTab"] = newTabID+ slog.Debug("auto-switch: focused popup", "openerCDP", string(s.openerCDP), "newTabId", newTabID)+ return result+}++func (s *autoSwitchSession) createFallbackTab(ctx context.Context, result map[string]any) map[string]any {+ url := s.fallbackPopupURL(ctx)+ if url == "" {+ return result+ }+ newTabID, _, _, err := s.tm.CreateTab(url)+ if err != nil {+ slog.Warn("auto-switch: fallback popup create failed", "url", url, "err", err)+ return result+ }+ if err := s.tm.FocusTab(newTabID); err != nil {+ slog.Warn("auto-switch: fallback popup focus failed", "tabId", newTabID, "err", err)+ return result+ }+ if result == nil {+ result = map[string]any{}+ }+ result["switchedToTab"] = newTabID+ slog.Debug("auto-switch: focused fallback popup", "newTabId", newTabID, "url", url)+ return result+}diff --git a/internal/bridge/tab_auto_switch_test.go b/internal/bridge/tab_auto_switch_test.gonew file mode 100644index 00000000..6f9837b3--- /dev/null+++ b/internal/bridge/tab_auto_switch_test.go@@ -0,0 +1,124 @@+package bridge++import (+ "context"+ "errors"+ "testing"+ "time"++ "github.com/chromedp/cdproto/target"+ "github.com/pinchtab/pinchtab/internal/config"+)++func TestPendingClick_ClaimsPopupForOpener(t *testing.T) {+ tm := &TabManager{}+ opener := target.ID("OPENER123")+ newTarget := target.ID("POPUP456")++ slot := tm.markPendingClick(opener)+ if slot == nil {+ t.Fatal("markPendingClick returned nil")+ }++ if !tm.claimPendingPopup(opener, newTarget) {+ t.Fatal("expected popup to be claimed when click is pending")+ }++ select {+ case got := <-slot.captured:+ if got != newTarget {+ t.Fatalf("captured target = %q, want %q", got, newTarget)+ }+ default:+ t.Fatal("captured channel had no value")+ }+}++func TestPendingClick_DoesNotClaimWithoutPending(t *testing.T) {+ tm := &TabManager{}+ if tm.claimPendingPopup(target.ID("OPENER"), target.ID("POPUP")) {+ t.Fatal("claimPendingPopup should return false with no pending click")+ }+}++func TestPendingClick_DoesNotClaimForOtherOpener(t *testing.T) {+ tm := &TabManager{}+ tm.markPendingClick(target.ID("OPENER_A"))+ if tm.claimPendingPopup(target.ID("OPENER_B"), target.ID("POPUP")) {+ t.Fatal("claimPendingPopup should ignore mismatched opener")+ }+}++func TestPendingClick_SecondPopupNotClaimed(t *testing.T) {+ tm := &TabManager{}+ opener := target.ID("OPENER")+ tm.markPendingClick(opener)++ if !tm.claimPendingPopup(opener, target.ID("POPUP1")) {+ t.Fatal("first popup should be claimed")+ }+ if tm.claimPendingPopup(opener, target.ID("POPUP2")) {+ t.Fatal("second popup should not be claimed — guard must close it")+ }+}++func TestPendingClick_ClearReleasesSlot(t *testing.T) {+ tm := &TabManager{}+ opener := target.ID("OPENER")+ slot := tm.markPendingClick(opener)+ if targetID, ok := tm.clearPendingClick(opener, slot); ok || targetID != "" {+ t.Fatalf("clearPendingClick returned target %q, %v; want none", targetID, ok)+ }+ if tm.claimPendingPopup(opener, target.ID("POPUP")) {+ t.Fatal("cleared slot should not claim popups")+ }+}++func TestPendingClick_ClearReturnsClaimedPopup(t *testing.T) {+ tm := &TabManager{}+ opener := target.ID("OPENER")+ popup := target.ID("POPUP")+ slot := tm.markPendingClick(opener)++ if !tm.claimPendingPopup(opener, popup) {+ t.Fatal("expected pending click to claim popup")+ }++ targetID, ok := tm.clearPendingClick(opener, slot)+ if !ok || targetID != popup {+ t.Fatalf("clearPendingClick returned %q, %v; want %q, true", targetID, ok, popup)+ }+ if tm.claimPendingPopup(opener, target.ID("LATE_POPUP")) {+ t.Fatal("cleared slot should not claim late popups")+ }+}++func TestAutoSwitchFinish_NoPopupReturnsWithinGrace(t *testing.T) {+ tm := &TabManager{}+ opener := target.ID("OPENER")+ slot := tm.markPendingClick(opener)+ session := &autoSwitchSession{tm: tm, openerCDP: opener, slot: slot}++ start := time.Now()+ result := session.finish(context.Background(), map[string]any{"clicked": true})+ if elapsed := time.Since(start); elapsed > 500*time.Millisecond {+ t.Fatalf("finish without popup took %s, want under 500ms", elapsed)+ }+ if _, ok := result["switchedToTab"]; ok {+ t.Fatal("finish without popup should not set switchedToTab")+ }+}++func TestAdoptExistingTarget_EnforcesRejectTabLimit(t *testing.T) {+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{+ MaxTabs: 1,+ TabEvictionPolicy: "reject",+ }, nil, nil, nil)+ tm.tabs["existing"] = &TabEntry{Ctx: context.Background(), CDPID: "existing"}++ _, err := tm.adoptExistingTarget(target.ID("new-target"), true)+ var limitErr *TabLimitError+ if !errors.As(err, &limitErr) {+ t.Fatalf("adoptExistingTarget error = %v, want TabLimitError", err)+ }+}diff --git a/internal/bridge/tab_lookup.go b/internal/bridge/tab_lookup.goindex 839e0fe8..a827eca3 100644--- a/internal/bridge/tab_lookup.go+++ b/internal/bridge/tab_lookup.go@@ -7,7 +7,6 @@ import ("time""github.com/chromedp/cdproto/target"- "github.com/chromedp/chromedp")func (tm *TabManager) markAccessed(tabID string) {@@ -91,28 +90,14 @@ func (tm *TabManager) TabContext(tabID string) (context.Context, string, error)for _, t := range targets {raw := string(t.TargetID)if tm.idMgr.TabIDFromCDPTarget(raw) == tabID {- ctx, cancel := chromedp.NewContext(tm.browserCtx, chromedp.WithTargetID(target.ID(raw)))- if tm.onTabSetup != nil {- tm.onTabSetup(ctx)+ if _, adoptErr := tm.adoptExistingTarget(target.ID(raw), false); adoptErr != nil {+ slog.Warn("adopt target failed", "tabId", tabID, "err", adoptErr)+ break}- if tm.netMonitor != nil {- if err := tm.netMonitor.StartCapture(ctx, tabID); err != nil {- slog.Warn("eager network capture failed", "tab", tabID, "err", err)- }- }- if tm.dialogMgr != nil {- autoAccept := tm.config != nil && tm.config.DialogAutoAccept- ListenDialogEvents(ctx, tabID, tm.dialogMgr, autoAccept)- if err := EnableDialogEvents(ctx); err != nil {- slog.Warn("enable dialog events failed", "tabId", tabID, "err", err)- }- }- tm.RegisterTabWithCancel(tabID, raw, ctx, cancel)-tm.mu.RLock()entry = tm.tabs[tabID]tm.mu.RUnlock()- ok = true+ ok = entry != nilbreak}}diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.goindex 028339ae..958e51a8 100644--- a/internal/bridge/tab_manager.go+++ b/internal/bridge/tab_manager.go@@ -34,7 +34,13 @@ type TabManager struct {currentTab string // ID of the most recently used tabexecutor *TabExecutorguardOnce sync.Once+ guardActive boolmu sync.RWMutex++ // pendingClicks tracks in-flight click actions that may open a popup.+ // Keyed by the opener tab's raw CDP target ID. Read by the popup guard+ // to decide whether to suppress closing the newly created tab.+ pendingClicks map[target.ID]*pendingClickSlot}func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgr *ids.Manager, logStore *ConsoleLogStore, onTabSetup TabSetupFunc) *TabManager {@@ -155,19 +161,7 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Catm.onTabSetup(ctx)}- var blockPatterns []string-- if tm.config != nil && tm.config.BlockAds {- blockPatterns = CombineBlockPatterns(blockPatterns, AdBlockPatterns)- }-- if tm.config != nil && tm.config.BlockMedia {- blockPatterns = CombineBlockPatterns(blockPatterns, MediaBlockPatterns)- } else if tm.config != nil && tm.config.BlockImages {- blockPatterns = CombineBlockPatterns(blockPatterns, ImageBlockPatterns)- }-- if len(blockPatterns) > 0 {+ if blockPatterns := tm.tabBlockPatterns(); len(blockPatterns) > 0 {_ = SetResourceBlocking(ctx, blockPatterns)}diff --git a/internal/bridge/tab_popup_guard.go b/internal/bridge/tab_popup_guard.goindex 4b2ab5f0..3ec4e972 100644--- a/internal/bridge/tab_popup_guard.go+++ b/internal/bridge/tab_popup_guard.go@@ -32,7 +32,6 @@ func (tm *TabManager) StartBrowserGuards() {slog.Warn("browser popup guard unavailable", "err", err)return}-chromedp.ListenBrowser(tm.browserCtx, func(ev any) {created, ok := ev.(*target.EventTargetCreated)if !ok || !shouldBlockPopupTarget(created.TargetInfo) {@@ -40,8 +39,17 @@ func (tm *TabManager) StartBrowserGuards() {}info := created.TargetInfo+ // If a click is in flight for this opener, hand the new target+ // to the click action (auto-switch) instead of closing it.+ if tm.claimPendingPopup(info.OpenerID, info.TargetID) {+ return+ }go tm.closePopupTarget(info.TargetID, info.OpenerID, info.URL)})++ tm.mu.Lock()+ tm.guardActive = true+ tm.mu.Unlock()})}diff --git a/internal/handlers/action_execution.go b/internal/handlers/action_execution.goindex 4d1e2556..17ce78e9 100644--- a/internal/handlers/action_execution.go+++ b/internal/handlers/action_execution.go@@ -54,6 +54,13 @@ func (h *Handlers) executeAction(ctx context.Context, req bridge.ActionRequest)return result, "", err}+func switchedTabFromActionResult(result map[string]any) string {+ if switched, ok := result["switchedToTab"].(string); ok {+ return strings.TrimSpace(switched)+ }+ return ""+}+func (h *Handlers) shouldUseLiteAction(req bridge.ActionRequest) bool {kind := bridge.CanonicalActionKind(req.Kind)if h.effectiveActionHumanize(req) && (kind == bridge.ActionClick || kind == bridge.ActionType || kind == bridge.ActionKeyboardType) {diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex e1951c40..5eb433b2 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -107,6 +107,11 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {req.DismissBanners = b}}+ if v := q.Get("autoSwitch"); v != "" {+ if b, err := strconv.ParseBool(v); err == nil {+ req.AutoSwitch = &b+ }+ }if vals, ok := q["deltaX"]; ok && len(vals) > 0 {if n, err := strconv.Atoi(vals[0]); err == nil {req.DeltaX = n@@ -337,6 +342,13 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {h.dismissBanners(tCtx, resolvedTabID, true)}}+ // If the click opened (and auto-switched to) a new tab, point the+ // request-scoped current tab at it so the next action lands there.+ if switched := switchedTabFromActionResult(result); switched != "" {+ h.setCurrentTabForRequest(r, switched)+ w.Header().Set(activity.HeaderPTTabID, switched)+ h.recordResolvedTab(r, switched)+ }w.Header().Set("X-Engine", engineName)h.recordEngine(r, engineName)resp := map[string]any{"success": true, "result": result}@@ -601,6 +613,19 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re}}tCancel()+ if err == nil && !allLite {+ if switched := switchedTabFromActionResult(actionRes); switched != "" {+ nextCtx, nextTabID, switchErr := h.tabContext(r, switched)+ if switchErr != nil {+ err = fmt.Errorf("auto-switch tab %s: %w", switched, switchErr)+ } else {+ ctx = nextCtx+ resolvedTabID = nextTabID+ w.Header().Set(activity.HeaderPTTabID, nextTabID)+ h.recordResolvedTab(r, nextTabID)+ }+ }+ }if err != nil {errMsg := fmt.Sprintf("action %s: %v", action.Kind, err)@@ -806,6 +831,19 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {}}cancel()+ if err == nil && !allLiteMacro {+ if switched := switchedTabFromActionResult(res); switched != "" {+ nextCtx, nextTabID, switchErr := h.tabContext(r, switched)+ if switchErr != nil {+ err = fmt.Errorf("auto-switch tab %s: %w", switched, switchErr)+ } else {+ ctx = nextCtx+ resolvedTabID = nextTabID+ w.Header().Set(activity.HeaderPTTabID, nextTabID)+ h.recordResolvedTab(r, nextTabID)+ }+ }+ }if err != nil {errMsg := err.Error()var dialogErr *bridge.ErrDialogBlockingdiff --git a/internal/handlers/actions_test.go b/internal/handlers/actions_test.goindex 8391d828..f5d7aeee 100644--- a/internal/handlers/actions_test.go+++ b/internal/handlers/actions_test.go@@ -38,6 +38,26 @@ type handoffRecordingBridge struct {has bool}+type autoSwitchActionBridge struct {+ mockBridge+ actionTabs []string+}++func (m *autoSwitchActionBridge) TabContext(tabID string) (context.Context, string, error) {+ if tabID == "" {+ tabID = "tab1"+ }+ return context.Background(), tabID, nil+}++func (m *autoSwitchActionBridge) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {+ m.actionTabs = append(m.actionTabs, req.TabID)+ if len(m.actionTabs) == 1 {+ return map[string]any{"clicked": true, "switchedToTab": "tab2"}, nil+ }+ return map[string]any{"ok": true, "tabId": req.TabID}, nil+}+func (m *liteActionBridge) AvailableActions() []string {return []string{bridge.ActionClick, bridge.ActionType, bridge.ActionPress}}@@ -224,6 +244,44 @@ func TestHandleActions_NoTabError(t *testing.T) {}}+func TestHandleActions_FollowsAutoSwitchedTab(t *testing.T) {+ b := &autoSwitchActionBridge{}+ h := New(b, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)++ body := `{"actions":[{"kind":"click"},{"kind":"type","text":"after"}]}`+ req := httptest.NewRequest("POST", "/actions", bytes.NewReader([]byte(body)))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()++ h.HandleActions(w, req)++ if w.Code != 200 {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got, want := strings.Join(b.actionTabs, ","), "tab1,tab2"; got != want {+ t.Fatalf("action tabs = %s, want %s", got, want)+ }+}++func TestHandleMacro_FollowsAutoSwitchedTab(t *testing.T) {+ b := &autoSwitchActionBridge{}+ h := New(b, &config.RuntimeConfig{ActionTimeout: time.Second, AllowMacro: true}, nil, nil, nil)++ body := `{"steps":[{"kind":"click"},{"kind":"type","text":"after"}]}`+ req := httptest.NewRequest("POST", "/macro", bytes.NewReader([]byte(body)))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()++ h.HandleMacro(w, req)++ if w.Code != 200 {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got, want := strings.Join(b.actionTabs, ","), "tab1,tab2"; got != want {+ t.Fatalf("action tabs = %s, want %s", got, want)+ }+}+func TestHandleTabActions_MissingTabID(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("POST", "/tabs//actions", bytes.NewReader([]byte(`{"actions":[{"kind":"click"}]}`)))diff --git a/tests/e2e/fixtures/target-blank.html b/tests/e2e/fixtures/target-blank.htmlnew file mode 100644index 00000000..d46a2680--- /dev/null+++ b/tests/e2e/fixtures/target-blank.html@@ -0,0 +1,13 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>E2E Test - target=_blank</title>+</head>+<body>+ <h1 id="opener">Opener page</h1>+ <a id="blank-link" href="/index.html" target="_blank">Open index in new tab</a>+ <button id="window-open" onclick="window.open('/buttons.html', '_blank')">Open buttons via window.open</button>+ <a id="same-tab" href="/index.html">Same-tab navigation</a>+</body>+</html>diff --git a/tests/e2e/scenarios/api/auto-switch-smoke.sh b/tests/e2e/scenarios/api/auto-switch-smoke.shnew file mode 100755index 00000000..d1514d80--- /dev/null+++ b/tests/e2e/scenarios/api/auto-switch-smoke.sh@@ -0,0 +1,120 @@+#!/bin/bash+# auto-switch-smoke.sh — Verify click on target=_blank auto-switches the+# current tab to the newly opened popup, and that autoSwitch=false disables it.++GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+source "${GROUP_DIR}/../../helpers/api.sh"++wait_for_tab_count_at_most() {+ local max="$1"+ local desc="$2"+ local attempts="${3:-20}"+ local actual=""++ for _ in $(seq 1 "$attempts"); do+ actual=$(get_tab_count)+ if [ "$actual" -le "$max" ]; then+ echo -e " ${GREEN}✓${NC} ${desc} (${actual} <= ${max})"+ ((ASSERTIONS_PASSED++)) || true+ return 0+ fi+ sleep 0.2+ done++ echo -e " ${RED}✗${NC} ${desc} (tab count ${actual} > ${max})"+ ((ASSERTIONS_FAILED++)) || true+ return 1+}++# ─────────────────────────────────────────────────────────────────+start_test "click on target=_blank auto-switches current tab"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/target-blank.html\"}"+OPENER_TAB_ID=$(get_tab_id)+BEFORE=$(get_tab_count)++pt_post /action -d '{"kind":"click","selector":"#blank-link"}'+assert_ok "click target=_blank link"++NEW_TAB_ID=$(echo "$RESULT" | jq -r '.result.switchedToTab // empty')+if [ -z "$NEW_TAB_ID" ]; then+ echo -e " ${RED}✗${NC} result.switchedToTab missing"+ ((ASSERTIONS_FAILED++)) || true+else+ echo -e " ${GREEN}✓${NC} switchedToTab returned: $NEW_TAB_ID"+ ((ASSERTIONS_PASSED++)) || true+fi++if [ "$NEW_TAB_ID" = "$OPENER_TAB_ID" ]; then+ echo -e " ${RED}✗${NC} switchedToTab equals opener tab"+ ((ASSERTIONS_FAILED++)) || true+fi++AFTER=$(get_tab_count)+if [ "$AFTER" -le "$BEFORE" ]; then+ echo -e " ${RED}✗${NC} expected tab count to increase, before=${BEFORE} after=${AFTER}"+ ((ASSERTIONS_FAILED++)) || true+else+ echo -e " ${GREEN}✓${NC} tab count increased (${BEFORE} → ${AFTER})"+ ((ASSERTIONS_PASSED++)) || true+fi++pt_get /text+assert_ok "unscoped /text after auto-switch"+assert_json_contains "$RESULT" ".url" "index.html" "current tab URL is the opened tab"+assert_json_contains "$RESULT" ".text" "Welcome to the E2E test fixtures" "current tab text is from the opened tab"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "window.open auto-switches current tab"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/target-blank.html\"}"+pt_post /action -d '{"kind":"click","selector":"#window-open"}'+assert_ok "click window.open button"+assert_json_exists "$RESULT" '.result.switchedToTab' "switchedToTab set for window.open"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "regular same-tab click is unaffected"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/target-blank.html\"}"+pt_post /action -d '{"kind":"click","selector":"#same-tab","waitNav":true}'+assert_ok "same-tab click"++SWITCHED=$(echo "$RESULT" | jq -r '.result.switchedToTab // empty')+if [ -n "$SWITCHED" ]; then+ echo -e " ${RED}✗${NC} unexpected switchedToTab on same-tab click: $SWITCHED"+ ((ASSERTIONS_FAILED++)) || true+else+ echo -e " ${GREEN}✓${NC} no switchedToTab on same-tab click"+ ((ASSERTIONS_PASSED++)) || true+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "autoSwitch=false disables auto-switch"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/target-blank.html\"}"+BEFORE_DISABLED=$(get_tab_count)+pt_post /action -d '{"kind":"click","selector":"#blank-link","autoSwitch":false}'+assert_ok "click with autoSwitch=false"++SWITCHED=$(echo "$RESULT" | jq -r '.result.switchedToTab // empty')+if [ -n "$SWITCHED" ]; then+ echo -e " ${RED}✗${NC} switchedToTab set despite autoSwitch=false: $SWITCHED"+ ((ASSERTIONS_FAILED++)) || true+else+ echo -e " ${GREEN}✓${NC} no switchedToTab when autoSwitch=false (popup guard closes the popup)"+ ((ASSERTIONS_PASSED++)) || true+fi++wait_for_tab_count_at_most "$BEFORE_DISABLED" "popup was closed when autoSwitch=false"++pt_get /text+assert_ok "unscoped /text after autoSwitch=false"+assert_contains "$RESULT" "Opener page" "current tab remains on the opener"++end_testdiff --git a/tests/e2e/scenarios/manifest.json b/tests/e2e/scenarios/manifest.jsonindex 4331e644..57f74778 100644--- a/tests/e2e/scenarios/manifest.json+++ b/tests/e2e/scenarios/manifest.json@@ -22,6 +22,9 @@"ready": ["E2E_SERVER", "E2E_AUTOCLOSE_SERVER"],"tags": ["tabs", "autoclose", "lifecycle", "smoke"]},+ "api/auto-switch-smoke.sh": {+ "tags": ["tabs", "actions", "auto-switch", "smoke"]+ },"api/network-route-extended.sh": {"services": ["pinchtab", "pinchtab-full", "fixtures"],"ready": ["E2E_SERVER", "E2E_FULL_SERVER"],diff --git a/tests/tools/runner/internal/e2e/e2e_test.go b/tests/tools/runner/internal/e2e/e2e_test.goindex c65333de..a8ae5b98 100644--- a/tests/tools/runner/internal/e2e/e2e_test.go+++ b/tests/tools/runner/internal/e2e/e2e_test.go@@ -633,7 +633,7 @@ func TestDryRunSmokePlan(t *testing.T) {`Skipping plugin-smoke: filter "" has no matching scenarios`,"docker compose -f tests/e2e/docker-compose-multi.yml up -d pinchtab pinchtab-secure pinchtab-autoclose pinchtab-medium pinchtab-full fixtures","E2E_SUMMARY_TITLE=PinchTab E2E API Smoke Suite",- "runner-api /bin/bash /e2e/run.sh scenario=network-route-smoke.sh scenario=tabs-autoclose-smoke.sh",+ "runner-api /bin/bash /e2e/run.sh scenario=auto-switch-smoke.sh scenario=network-route-smoke.sh scenario=tabs-autoclose-smoke.sh","E2E_SUMMARY_TITLE=PinchTab E2E CLI Smoke Suite","runner-cli /bin/bash /e2e/run.sh scenario=system-smoke.sh scenario=tabs-smoke.sh","docker compose -f tests/e2e/docker-compose-multi.yml restart pinchtab",