High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(bridge): stop an attached instance wedging when the user closes the adopted tab
Luigi Agostia59c753df469
diff --git a/internal/bridge/lifecycle_remote_cdp.go b/internal/bridge/lifecycle_remote_cdp.goindex f08be11e..2006f864 100644--- a/internal/bridge/lifecycle_remote_cdp.go+++ b/internal/bridge/lifecycle_remote_cdp.go@@ -6,7 +6,6 @@ import ("log/slog""github.com/chromedp/cdproto/target"- "github.com/chromedp/chromedp"bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime""github.com/pinchtab/pinchtab/internal/config"internalurls "github.com/pinchtab/pinchtab/internal/urls"@@ -43,12 +42,13 @@ func (b *Bridge) ensureRemoteCDPLocked(cfg *config.RuntimeConfig) error {}func (b *Bridge) ensureAtLeastOnePageTarget(browserCtx context.Context) error {- var targets []*target.Info- err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {- var listErr error- targets, listErr = target.GetTargets().Do(ctx)- return listErr- }))+ // Target.getTargets is browser-level; issuing it on browserCtx's own CDP+ // session ties it to whichever tab chromedp adopted from the remote browser.+ execCtx, err := browserExecutorContext(browserCtx)+ if err != nil {+ return err+ }+ targets, err := target.GetTargets().Do(execCtx)if err != nil {return fmt.Errorf("list targets: %w", err)}diff --git a/internal/bridge/tab_cleanup.go b/internal/bridge/tab_cleanup.goindex 75e642d2..371e408c 100644--- a/internal/bridge/tab_cleanup.go+++ b/internal/bridge/tab_cleanup.go@@ -61,38 +61,66 @@ func (tm *TabManager) CleanStaleTabs(ctx context.Context, interval time.Durationreturncase <-ticker.C:}+ tm.dropTabsTheBrowserNoLongerHas()+ }+}- targets, err := tm.ListTargets()- if err != nil {- continue- }+// dropTabsTheBrowserNoLongerHas removes tracked tabs whose CDP target is gone.+//+// A tab can die without PinchTab hearing about it. Target.targetDestroyed is+// delivered over the CDP session of the tab chromedp adopted for the+// browser-level context, so once that tab dies the event stops arriving for+// every other tab too. That is routine for an attached browser, where the tabs+// belong to the user and PinchTab adopted one of them. A dead entry keeps a+// context that no longer has a session behind it, so calls on it block until+// their deadline rather than failing, and tab selection keeps choosing it.+//+// Target.getTargets is a browser-level command, so what it reports stays true+// whichever tab has died.+func (tm *TabManager) dropTabsTheBrowserNoLongerHas() {+ if tm == nil {+ return+ }+ tm.mu.RLock()+ tracked := len(tm.tabs)+ tm.mu.RUnlock()+ if tracked == 0 {+ return+ }- alive := make(map[string]bool, len(targets))- for _, t := range targets {- alive[string(t.TargetID)] = true- }+ targets, err := tm.ListTargets()+ if err != nil {+ // Without a target list nothing is proven dead. Dropping the set here+ // would evict live tabs every time the browser is briefly busy.+ return+ }+ alive := make(map[string]bool, len(targets))+ for _, t := range targets {+ alive[string(t.TargetID)] = true+ }- type staleTab struct {- tabID string- cdpID string+ type staleTab struct {+ tabID string+ cdpID string+ }+ var staleTabs []staleTab+ tm.mu.RLock()+ for id, entry := range tm.tabs {+ // Only an entry that records which CDP target it belongs to can be+ // missing from the listing. RegisterTab binds a context without one,+ // and for those absence proves nothing, so they are left alone.+ if entry == nil || entry.CDPID == "" {+ continue}- var staleTabs []staleTab- tm.mu.RLock()- for id, entry := range tm.tabs {- if !alive[id] {- cdpID := entry.CDPID- if cdpID == "" {- cdpID = id- }- staleTabs = append(staleTabs, staleTab{tabID: id, cdpID: cdpID})- }+ if !alive[entry.CDPID] {+ staleTabs = append(staleTabs, staleTab{tabID: id, cdpID: entry.CDPID})}- tm.mu.RUnlock()+ }+ tm.mu.RUnlock()- for _, stale := range staleTabs {- tm.purgeTrackedTabState(stale.tabID, stale.cdpID)- slog.Info("cleaned stale tab", "id", stale.tabID)- }+ for _, stale := range staleTabs {+ tm.purgeTrackedTabState(stale.tabID, stale.cdpID)+ slog.Info("cleaned stale tab", "id", stale.tabID)}}diff --git a/internal/bridge/tab_lookup.go b/internal/bridge/tab_lookup.goindex 0aba28af..af20f8f3 100644--- a/internal/bridge/tab_lookup.go+++ b/internal/bridge/tab_lookup.go@@ -77,10 +77,37 @@ func (tm *TabManager) AccessedTabIDs() map[string]bool {return out}+// staleSweepInterval bounds how often resolving a tab pays for a target list.+// The sweep exists to stop a dead tab being handed out forever, not to make+// every action re-check the browser.+const staleSweepInterval = 2 * time.Second++// sweepStaleTabsIfDue drops tabs the browser no longer has, at most once per+// staleSweepInterval. Tab selection runs on every request, so an unthrottled+// sweep would add a CDP round trip to each one.+func (tm *TabManager) sweepStaleTabsIfDue() {+ if tm == nil {+ return+ }+ tm.mu.Lock()+ if len(tm.tabs) == 0 || time.Since(tm.lastStaleSweep) < staleSweepInterval {+ tm.mu.Unlock()+ return+ }+ tm.lastStaleSweep = time.Now()+ tm.mu.Unlock()++ tm.dropTabsTheBrowserNoLongerHas()+}+func (tm *TabManager) TabContext(tabID string) (context.Context, string, error) {if tm == nil {return nil, "", fmt.Errorf("tab manager not initialized")}+ // Selecting a tab that is already gone returns a context whose calls block+ // until their deadline, which is how an attached instance used to wedge for+ // good once the user closed the wrong tab (issue #690).+ tm.sweepStaleTabsIfDue()if tabID == "" {tm.mu.RLock()tabID = tm.selectCurrentTrackedTab()diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.goindex e6d12653..bf813d6d 100644--- a/internal/bridge/tab_manager.go+++ b/internal/bridge/tab_manager.go@@ -46,6 +46,7 @@ type TabManager struct {onTabRemovedHooks []func(tabID string)netMonitor *NetworkMonitorcurrentTab string // ID of the most recently used tab+ lastStaleSweep time.Timeexecutor *TabExecutorguardOnce sync.OnceguardActive bool@@ -202,19 +203,25 @@ func (tm *TabManager) createTab(url, browserContextID string) (string, context.C// leaving the browser window's OS focus unchanged. Do not set background=true:// heavy headed SPAs can suspend that target before DOM/AX reads. newWindow// remains false, so no additional OS window is created.+ //+ // Target.createTarget is a browser-level command, so it is issued on the+ // browser connection rather than through tm.browserCtx's own CDP session.+ // When PinchTab attaches to a browser that is already running, chromedp+ // binds that session to a tab the user owns; routing this call through it+ // makes every later tab creation block until the user's tab happens to+ // outlive the instance.+ browserExecCtx, err := browserExecutorContext(tm.browserCtx)+ if err != nil {+ return "", nil, nil, err+ }var targetID target.ID- createCtx, createCancel := context.WithTimeout(tm.browserCtx, tabCreateTimeout)- if err := chromedp.Run(createCtx,- chromedp.ActionFunc(func(ctx context.Context) error {- params := target.CreateTarget("about:blank").WithFocus(false)- if browserContextID != "" {- params = params.WithBrowserContextID(cdp.BrowserContextID(browserContextID))- }- var err error- targetID, err = params.Do(ctx)- return err- }),- ); err != nil {+ createCtx, createCancel := context.WithTimeout(browserExecCtx, tabCreateTimeout)+ params := target.CreateTarget("about:blank").WithFocus(false)+ if browserContextID != "" {+ params = params.WithBrowserContextID(cdp.BrowserContextID(browserContextID))+ }+ targetID, err = params.Do(createCtx)+ if err != nil {createCancel()if errors.Is(err, context.DeadlineExceeded) {return "", nil, nil, fmt.Errorf("create tab: browser did not open a new tab within %s — it may be out of memory or overloaded (close tabs or restart the instance)", tabCreateTimeout)diff --git a/internal/bridge/tab_manager_attached_browser_test.go b/internal/bridge/tab_manager_attached_browser_test.gonew file mode 100644index 00000000..22b31ae5--- /dev/null+++ b/internal/bridge/tab_manager_attached_browser_test.go@@ -0,0 +1,217 @@+package bridge++import (+ "context"+ "encoding/json"+ "fmt"+ "net"+ "net/http"+ "os"+ "os/exec"+ "testing"+ "time"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/testbrowser"+)++// startUserOwnedBrowser launches a browser the way the reporter's i3 session+// does: externally, with a debugging port, owning its own tabs. PinchTab never+// launches or owns this process.+func startUserOwnedBrowser(t *testing.T) (wsURL string, devtoolsPort int) {+ t.Helper()+ chromePath := testbrowser.Path(t)+ profile := testbrowser.ProfileDir(t)++ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ devtoolsPort = listener.Addr().(*net.TCPAddr).Port+ if err := listener.Close(); err != nil {+ t.Fatal(err)+ }++ cmd := exec.Command(chromePath,+ fmt.Sprintf("--remote-debugging-port=%d", devtoolsPort),+ "--user-data-dir="+profile,+ "--headless=new",+ "--no-sandbox",+ "--no-first-run",+ "--no-default-browser-check",+ "about:blank",+ )+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ _ = cmd.Process.Kill()+ _, _ = cmd.Process.Wait()+ _ = os.RemoveAll(profile)+ })++ deadline := time.Now().Add(30 * time.Second)+ for time.Now().Before(deadline) {+ resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/json/version", devtoolsPort))+ if err == nil {+ var info struct {+ WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"`+ }+ decodeErr := json.NewDecoder(resp.Body).Decode(&info)+ _ = resp.Body.Close()+ if decodeErr == nil && info.WebSocketDebuggerURL != "" {+ return info.WebSocketDebuggerURL, devtoolsPort+ }+ }+ time.Sleep(200 * time.Millisecond)+ }+ t.Fatal("user-owned browser never exposed a devtools endpoint")+ return "", 0+}++// closeTabOutOfBand closes a tab the way the user does: in their own browser,+// with no involvement from PinchTab's CDP session.+func closeTabOutOfBand(t *testing.T, devtoolsPort int, targetID string) {+ t.Helper()+ resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/json/close/%s", devtoolsPort, targetID))+ if err != nil {+ t.Fatalf("close tab out of band: %v", err)+ }+ _ = resp.Body.Close()+}++// Attaching to a browser that is already running binds PinchTab's browser-level+// context to a tab that the user owns, because chromedp's first context adopts+// an existing target instead of creating one. Closing that particular tab must+// not take the instance down with it: the tab was never PinchTab's to depend on.+//+// Before the fix, CreateTab issued Target.createTarget over that dead tab's CDP+// session, so every later call blocked for the full tabCreateTimeout and the+// instance stayed wedged until it was stopped and re-attached (issue #690).+func TestCreateTabSurvivesUserClosingTheAdoptedBrowserContextTab(t *testing.T) {+ wsURL, devtoolsPort := startUserOwnedBrowser(t)++ allocCtx, allocCancel := chromedp.NewRemoteAllocator(context.Background(), wsURL)+ browserCtx, browserCancel := chromedp.NewContext(allocCtx)+ t.Cleanup(func() {+ browserCancel()+ allocCancel()+ })+ if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(context.Context) error { return nil })); err != nil {+ t.Fatalf("attach to user-owned browser: %v", err)+ }++ chromeCtx := chromedp.FromContext(browserCtx)+ if chromeCtx == nil || chromeCtx.Target == nil {+ t.Fatal("attached browser context has no target")+ }+ adoptedUserTab := chromeCtx.Target.TargetID.String()++ tm := NewTabManager(browserCtx, &config.RuntimeConfig{}, nil, nil, nil)++ if _, _, _, err := tm.CreateTab("about:blank"); err != nil {+ t.Fatalf("baseline CreateTab against the attached browser failed: %v", err)+ }++ closeTabOutOfBand(t, devtoolsPort, adoptedUserTab)+ time.Sleep(1500 * time.Millisecond)++ done := make(chan error, 1)+ start := time.Now()+ go func() {+ _, _, _, err := tm.CreateTab("about:blank")+ done <- err+ }()++ select {+ case err := <-done:+ if err != nil {+ t.Fatalf("CreateTab failed after the user closed the adopted tab %s: %v", adoptedUserTab, err)+ }+ t.Logf("CreateTab recovered in %v", time.Since(start).Round(time.Millisecond))+ case <-time.After(tabCreateTimeout - time.Second):+ t.Fatalf("CreateTab wedged for %v after the user closed the adopted tab %s; "++ "the browser-level call is still routed through that tab's dead CDP session",+ time.Since(start).Round(time.Millisecond), adoptedUserTab)+ }+}++// The reported failure was on the shorthand read routes: every one of them+// returned "resolve topmost dialog: resolve top frame: context deadline+// exceeded" until the instance was stopped and re-attached.+//+// Target.targetDestroyed arrives over the CDP session of the tab chromedp+// adopted for the browser-level context. Once the user closes that tab the+// event stops arriving for every other tab too, so a tab that dies afterwards+// is never dropped, and tab selection keeps handing out its dead context.+func TestTabSelectionDropsATabThatDiedAfterTheDestroyedEventStopped(t *testing.T) {+ wsURL, devtoolsPort := startUserOwnedBrowser(t)++ allocCtx, allocCancel := chromedp.NewRemoteAllocator(context.Background(), wsURL)+ browserCtx, browserCancel := chromedp.NewContext(allocCtx)+ t.Cleanup(func() {+ browserCancel()+ allocCancel()+ })+ if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(context.Context) error { return nil })); err != nil {+ t.Fatalf("attach to user-owned browser: %v", err)+ }++ chromeCtx := chromedp.FromContext(browserCtx)+ if chromeCtx == nil || chromeCtx.Target == nil {+ t.Fatal("attached browser context has no target")+ }+ adoptedUserTab := chromeCtx.Target.TargetID.String()++ tm := NewTabManager(browserCtx, &config.RuntimeConfig{}, nil, nil, nil)+ workTabID, _, _, err := tm.CreateTab("about:blank")+ if err != nil {+ t.Fatalf("create the tab under test: %v", err)+ }+ tm.mu.RLock()+ workTabCDPID := tm.tabs[workTabID].CDPID+ tm.mu.RUnlock()++ baselineCtx, _, err := tm.TabContext("")+ if err != nil {+ t.Fatalf("baseline tab selection: %v", err)+ }+ if _, _, err := TopmostModalNodeID(baselineCtx, ""); err != nil {+ t.Fatalf("baseline dialog resolution: %v", err)+ }++ // The user closes the adopted tab, which silences targetDestroyed, and then+ // the tab PinchTab was working in. Nothing tells PinchTab either is gone.+ closeTabOutOfBand(t, devtoolsPort, adoptedUserTab)+ time.Sleep(500 * time.Millisecond)+ closeTabOutOfBand(t, devtoolsPort, workTabCDPID)+ time.Sleep(staleSweepInterval + time.Second)++ type result struct {+ err error+ }+ done := make(chan result, 1)+ start := time.Now()+ go func() {+ selected, _, selectErr := tm.TabContext("")+ if selectErr != nil {+ // A named error is a correct outcome: the caller can act on it.+ done <- result{err: nil}+ return+ }+ _, _, resolveErr := TopmostModalNodeID(selected, "")+ done <- result{err: resolveErr}+ }()++ select {+ case res := <-done:+ if res.err != nil {+ t.Fatalf("tab selection returned a context that could not be read: %v", res.err)+ }+ t.Logf("tab selection recovered in %v", time.Since(start).Round(time.Millisecond))+ case <-time.After(15 * time.Second):+ t.Fatalf("tab selection handed out the dead tab %s and the read wedged for %v",+ workTabCDPID, time.Since(start).Round(time.Millisecond))+ }+}